This is an automated email from the ASF dual-hosted git repository.
dengzh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/hive.git
The following commit(s) were added to refs/heads/master by this push:
new 8fcef2c9740 HIVE-27438: Audit leader election event failed in
non-appendable filesystems (#4416) (Zhihua Deng, reviewed by Sai Hemanth
Gantasala)
8fcef2c9740 is described below
commit 8fcef2c97404a6226071a26a8b637bc019db4f45
Author: dengzh <[email protected]>
AuthorDate: Tue Jul 11 14:03:50 2023 +0800
HIVE-27438: Audit leader election event failed in non-appendable
filesystems (#4416) (Zhihua Deng, reviewed by Sai Hemanth Gantasala)
---
.../hadoop/hive/metastore/conf/MetastoreConf.java | 15 +++-
.../hadoop/hive/metastore/HiveMetaStore.java | 17 ++--
.../hive/metastore/leader/AuditLeaderListener.java | 72 +++++++++++++---
.../hive/metastore/leader/CompactorTasks.java | 1 +
.../hive/metastore/leader/HouseKeepingTasks.java | 18 +++-
.../metastore/leader/LeaderElectionContext.java | 3 +-
.../metastore/leader/LeaderElectionFactory.java | 2 +-
.../hive/metastore/leader/LeaseLeaderElection.java | 22 ++---
...aderElection.java => StaticLeaderElection.java} | 10 +--
.../hive/metastore/leader/StatsUpdaterTask.java | 1 +
.../hive/metastore/leader/TestLeaderElection.java | 2 +-
.../hive/metastore/leader/TestLeaderListener.java | 98 ++++++++++++++++++++++
12 files changed, 210 insertions(+), 51 deletions(-)
diff --git
a/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/conf/MetastoreConf.java
b/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/conf/MetastoreConf.java
index c1354341c34..4e0c136fb5d 100644
---
a/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/conf/MetastoreConf.java
+++
b/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/conf/MetastoreConf.java
@@ -568,11 +568,20 @@ public class MetastoreConf {
METASTORE_HOUSEKEEPING_LEADER_ELECTION("metastore.housekeeping.leader.election",
"metastore.housekeeping.leader.election",
"host", new StringSetValidator("host", "lock"),
- "If sets to host, HMS will choose the leader by the configured
metastore.housekeeping.leader.hostname.\n" +
- "When configured to lock, HMS will use hive locks to elect the
leader."),
+ "Set to host, HMS will choose the leader by the configured
metastore.housekeeping.leader.hostname.\n" +
+ "Set to lock, HMS will use the hive lock to elect the leader."),
METASTORE_HOUSEKEEPING_LEADER_AUDITTABLE("metastore.housekeeping.leader.auditTable",
"metastore.housekeeping.leader.auditTable", "",
- "Audit the Metastore leader changes to the target table when
configured."),
+ "Audit the leader election event to a plain json table when
configured."),
+
METASTORE_HOUSEKEEPING_LEADER_NEW_AUDIT_FILE("metastore.housekeeping.leader.newAuditFile",
+ "metastore.housekeeping.leader.newAuditFile", false,
+ "Whether to create a new audit file in response to the new election
event " +
+ "when the metastore.housekeeping.leader.auditTable is not empty.\n" +
+ "True for creating a new file, false otherwise."),
+
METASTORE_HOUSEKEEPING_LEADER_AUDIT_FILE_LIMIT("metastore.housekeeping.leader.auditFiles.limit",
+ "metastore.housekeeping.leader.auditFiles.limit", 10,
+ "Limit the number of small audit files when
metastore.housekeeping.leader.newAuditFile is true.\n" +
+ "If the number of audit files exceeds the limit, then the oldest will
be deleted."),
METASTORE_HOUSEKEEPING_THREADS_ON("metastore.housekeeping.threads.on",
"hive.metastore.housekeeping.threads.on", false,
"Whether to run the tasks under metastore.task.threads.remote on this
metastore instance or not.\n" +
diff --git
a/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStore.java
b/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStore.java
index 4e49b76f6f9..f6980e2fac6 100644
---
a/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStore.java
+++
b/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStore.java
@@ -47,7 +47,6 @@ import org.apache.hadoop.hive.metastore.utils.SecurityUtils;
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.ShutdownHookManager;
-import org.apache.hadoop.util.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.thrift.TProcessor;
@@ -826,28 +825,24 @@ public class HiveMetaStore extends ThriftHiveMetastore {
LeaderElectionContext context = new
LeaderElectionContext.ContextBuilder(conf)
.setHMSHandler(thriftServer.getHandler()).servHost(getServerHostName())
- // always tasks
- .setTType(LeaderElectionContext.TTYPE.ALWAYS_TASKS)
+ .setTType(LeaderElectionContext.TTYPE.ALWAYS_TASKS) // always
tasks
.addListener(new HouseKeepingTasks(conf, false))
- // housekeeping tasks
- .setTType(LeaderElectionContext.TTYPE.HOUSEKEEPING)
+ .setTType(LeaderElectionContext.TTYPE.HOUSEKEEPING) //
housekeeping tasks
.addListener(new CMClearer(conf))
.addListener(new StatsUpdaterTask(conf))
.addListener(new CompactorTasks(conf, false))
.addListener(new CompactorPMF())
.addListener(new HouseKeepingTasks(conf, true))
- // compactor worker
- .setTType(LeaderElectionContext.TTYPE.WORKER)
- .addListener(new CompactorTasks(conf, true),
MetastoreConf.getVar(conf,
-
MetastoreConf.ConfVars.HIVE_METASTORE_RUNWORKER_IN).equals("metastore"))
+ .setTType(LeaderElectionContext.TTYPE.WORKER) // compactor worker
+ .addListener(new CompactorTasks(conf, true),
+ MetastoreConf.getVar(conf,
MetastoreConf.ConfVars.HIVE_METASTORE_RUNWORKER_IN).equals("metastore"))
.build();
if (shutdownHookMgr != null) {
shutdownHookMgr.addShutdownHook(() -> context.close(), 0);
}
context.start();
} catch (Throwable e) {
- LOG.error("Failure when starting the leader tasks, compactions or
housekeeping tasks may not happen, " +
- StringUtils.stringifyException(e));
+ LOG.error("Failure when starting the leader tasks, Compaction or
Housekeeping tasks may not happen", e);
} finally {
startLock.unlock();
}
diff --git
a/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/AuditLeaderListener.java
b/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/AuditLeaderListener.java
index cb18986b719..0270da27f60 100644
---
a/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/AuditLeaderListener.java
+++
b/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/AuditLeaderListener.java
@@ -18,18 +18,25 @@
package org.apache.hadoop.hive.metastore.leader;
+import com.google.common.annotations.VisibleForTesting;
+
import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.TableName;
import org.apache.hadoop.hive.metastore.ColumnType;
import org.apache.hadoop.hive.metastore.HiveMetaStore;
import org.apache.hadoop.hive.metastore.IHMSHandler;
+import org.apache.hadoop.hive.metastore.TableType;
import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.metastore.api.AlreadyExistsException;
import org.apache.hadoop.hive.metastore.api.PrincipalType;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.metastore.client.builder.TableBuilder;
+import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
+import org.apache.hadoop.hive.metastore.utils.FileUtils;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.utils.SecurityUtils;
import java.io.OutputStream;
@@ -38,12 +45,14 @@ import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
import static java.util.Objects.requireNonNull;
public class AuditLeaderListener implements
LeaderElection.LeadershipStateListener {
private final Configuration configuration;
-
private final Path tableLocation;
private final static String SERDE =
"org.apache.hadoop.hive.serde2.JsonSerDe";
@@ -60,15 +69,18 @@ public class AuditLeaderListener implements
LeaderElection.LeadershipStateListen
.setCatName(tableName.getCat())
.setDbName(tableName.getDb())
.setTableName(tableName.getTable())
- .addCol("leader", ColumnType.STRING_TYPE_NAME)
- .addCol("type", ColumnType.STRING_TYPE_NAME)
+ .addCol("leader_host", ColumnType.STRING_TYPE_NAME)
+ .addCol("leader_type", ColumnType.STRING_TYPE_NAME)
.addCol("elected_time", ColumnType.STRING_TYPE_NAME)
.setOwner(SecurityUtils.getUser())
.setOwnerType(PrincipalType.USER)
.setSerdeLib(SERDE)
.setInputFormat(INPUTFORMAT)
.setOutputFormat(OUTPUTFORMAT)
+ .addTableParam("EXTERNAL", "TRUE")
+ .addTableParam(MetaStoreUtils.EXTERNAL_TABLE_PURGE, "TRUE")
.build(handler.getConf());
+ table.setTableType(TableType.EXTERNAL_TABLE.toString());
handler.create_table(table);
} catch (AlreadyExistsException e) {
// ignore
@@ -82,28 +94,64 @@ public class AuditLeaderListener implements
LeaderElection.LeadershipStateListen
String output = table.getSd().getOutputFormat();
if (!SERDE.equals(serde) || !INPUTFORMAT.equals(input)
|| !OUTPUTFORMAT.equals(output)) {
- throw new RuntimeException(tableName + " should be in json + text
format");
+ throw new RuntimeException(tableName + " should be a plain json table");
}
+ }
+ // For testing purpose only
+ @VisibleForTesting
+ public AuditLeaderListener(Path tableLocation, Configuration configuration) {
+ this.tableLocation = tableLocation;
+ this.configuration = configuration;
}
@Override
public void takeLeadership(LeaderElection election) throws Exception {
+ HiveMetaStore.LOG.info("Became the LEADER for {}", election.getName());
String hostName = getHostname();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd
HH:mm:ss");
- String message = "{\"leader\": \"" + hostName + "\", \"type\": \""
+ String message = "{\"leader_host\": \"" + hostName + "\", \"leader_type\":
\""
+ election.getName() + "\", \"elected_time\": \"" +
LocalDateTime.now().format(formatter) + "\"} \n";
- Path path = new Path(tableLocation, "leader_" + election.getName() +
".json");
+
+ Path path = null;
try {
- FileSystem fs = Warehouse.getFs(path, configuration);
- try (OutputStream outputStream = fs.exists(path) ?
- fs.append(path) :
- fs.create(path, false)) {
+ FileSystem fs = Warehouse.getFs(tableLocation, configuration);
+ boolean createNewFile = FileUtils.isS3a(fs) ||
MetastoreConf.getBoolVar(configuration,
+ MetastoreConf.ConfVars.METASTORE_HOUSEKEEPING_LEADER_NEW_AUDIT_FILE);
+ String prefix = "leader_" + election.getName();
+ String fileName = createNewFile ?
+ prefix + "_" + System.currentTimeMillis() + ".json" :
+ prefix + ".json";
+ path = new Path(tableLocation, fileName);
+ // Audit the election event
+ try (OutputStream outputStream = createNewFile ?
+ fs.create(path, false) :
+ (fs.exists(path) ? fs.append(path) : fs.create(path, false))) {
outputStream.write(message.getBytes(StandardCharsets.UTF_8));
outputStream.flush();
}
+ // Trash out small files when the file system cannot support append
+ final int limit = MetastoreConf.getIntVar(configuration,
+
MetastoreConf.ConfVars.METASTORE_HOUSEKEEPING_LEADER_AUDIT_FILE_LIMIT);
+ if (createNewFile && limit > 0) {
+ List<FileStatus> allFileStatuses =
FileUtils.getFileStatusRecurse(tableLocation, fs);
+ List<FileStatus> thisLeaderFiles = new ArrayList<>();
+ // All this leader audit file must start with leader_$name_
+ allFileStatuses.stream().forEach(f -> {
+ if (f.getPath().getName().startsWith(prefix)) {
+ thisLeaderFiles.add(f);
+ }
+ });
+ if (thisLeaderFiles.size() > limit) {
+ thisLeaderFiles.sort((Comparator.comparing(o ->
o.getPath().getName())));
+ // delete the files that beyond the limit
+ for (int i = 0; i < thisLeaderFiles.size() - limit; i++) {
+ FileUtils.moveToTrash(fs, thisLeaderFiles.get(i).getPath(),
configuration, true);
+ }
+ }
+ }
} catch (Exception e) {
- HiveMetaStore.LOG.error("Error while writing the leader info, path: " +
path, e);
+ HiveMetaStore.LOG.error("Error while writing the leader info into file:
" + path, e);
}
}
@@ -118,7 +166,7 @@ public class AuditLeaderListener implements
LeaderElection.LeadershipStateListen
@Override
public void lossLeadership(LeaderElection election) throws Exception {
- // do nothing
+ HiveMetaStore.LOG.info("Lost leadership for {}", election.getName());
}
}
diff --git
a/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/CompactorTasks.java
b/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/CompactorTasks.java
index 80a92db1dfc..684862762fe 100644
---
a/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/CompactorTasks.java
+++
b/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/CompactorTasks.java
@@ -152,6 +152,7 @@ public class CompactorTasks implements
LeaderElection.LeadershipStateListener {
if (thread instanceof Thread) {
((Thread)thread).interrupt();
}
+ HiveMetaStore.LOG.info("Stopped the Compaction task: {}.",
thread.getClass().getName());
});
metastoreThreadsMap = null;
}
diff --git
a/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/HouseKeepingTasks.java
b/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/HouseKeepingTasks.java
index 7f22907a1fb..5db4bba3f4e 100644
---
a/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/HouseKeepingTasks.java
+++
b/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/HouseKeepingTasks.java
@@ -41,6 +41,8 @@ public class HouseKeepingTasks implements
LeaderElection.LeadershipStateListener
private boolean runOnlyRemoteTasks;
+ private List<MetastoreTaskThread> runningTasks;
+
public HouseKeepingTasks(Configuration configuration, boolean
runOnlyRemoteTasks) {
this.configuration = new Configuration(requireNonNull(configuration,
"configuration is null"));
@@ -84,6 +86,7 @@ public class HouseKeepingTasks implements
LeaderElection.LeadershipStateListener
if (metastoreTaskThreadPool != null) {
throw new IllegalStateException("There should be no running tasks before
taking the leadership!");
}
+ runningTasks = new ArrayList<>();
metastoreTaskThreadPool = ThreadPool.initialize(configuration);
if (!runOnlyRemoteTasks) {
List<MetastoreTaskThread> alwaysTasks = new
ArrayList<>(getAlwaysTasks());
@@ -93,7 +96,7 @@ public class HouseKeepingTasks implements
LeaderElection.LeadershipStateListener
// For backwards compatibility, since some threads used to be hard
coded but only run if
// frequency was > 0
if (freq > 0) {
- HiveMetaStore.LOG.info("Scheduling for " +
task.getClass().getCanonicalName() + " service.");
+ runningTasks.add(task);
metastoreTaskThreadPool.getPool().scheduleAtFixedRate(task, freq,
freq, TimeUnit.MILLISECONDS);
}
}
@@ -102,10 +105,14 @@ public class HouseKeepingTasks implements
LeaderElection.LeadershipStateListener
for (MetastoreTaskThread task : remoteOnlyTasks) {
task.setConf(configuration);
long freq = task.runFrequency(TimeUnit.MILLISECONDS);
- HiveMetaStore.LOG.info("Scheduling for " +
task.getClass().getCanonicalName() + " service.");
+ runningTasks.add(task);
metastoreTaskThreadPool.getPool().scheduleAtFixedRate(task, freq,
freq, TimeUnit.MILLISECONDS);
}
}
+
+ runningTasks.forEach(task -> {
+ HiveMetaStore.LOG.info("Scheduling for " +
task.getClass().getCanonicalName() + " service.");
+ });
}
@Override
@@ -114,6 +121,13 @@ public class HouseKeepingTasks implements
LeaderElection.LeadershipStateListener
metastoreTaskThreadPool.shutdown();
metastoreTaskThreadPool = null;
}
+
+ if (runningTasks != null && !runningTasks.isEmpty()) {
+ runningTasks.forEach(task -> {
+ HiveMetaStore.LOG.info("Stopped the Housekeeping task: {}",
task.getClass().getCanonicalName());
+ });
+ runningTasks.clear();
+ }
}
}
diff --git
a/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/LeaderElectionContext.java
b/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/LeaderElectionContext.java
index 426326ad54d..3c01d8030ca 100644
---
a/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/LeaderElectionContext.java
+++
b/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/LeaderElectionContext.java
@@ -156,12 +156,11 @@ public class LeaderElectionContext {
case "lock":
return ttype.getTableName();
default:
- throw new UnsupportedOperationException("Do not support " + method + "
now");
+ throw new UnsupportedOperationException(method + " not supported for
leader election");
}
}
public static class ContextBuilder {
-
private Configuration configuration;
private boolean startAsDaemon;
private String servHost;
diff --git
a/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/LeaderElectionFactory.java
b/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/LeaderElectionFactory.java
index 1cabdcdebb6..51dce28ac50 100644
---
a/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/LeaderElectionFactory.java
+++
b/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/LeaderElectionFactory.java
@@ -31,7 +31,7 @@ public class LeaderElectionFactory {
MetastoreConf.getVar(conf,
MetastoreConf.ConfVars.METASTORE_HOUSEKEEPING_LEADER_ELECTION);
switch (method.toLowerCase()) {
case "host":
- return new HostLeaderElection();
+ return new StaticLeaderElection();
case "lock":
return new LeaseLeaderElection();
default:
diff --git
a/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/LeaseLeaderElection.java
b/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/LeaseLeaderElection.java
index fbbd12b90a7..937174f5d92 100644
---
a/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/LeaseLeaderElection.java
+++
b/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/LeaseLeaderElection.java
@@ -79,7 +79,7 @@ public class LeaseLeaderElection implements
LeaderElection<TableName> {
// For non-leader instances to check the lock periodically to
// see if there is a chance to take over the leadership.
- // At any time, only one of heartbeater and nonLeaderWatcher is alive.
+ // At any time, either heartbeater or nonLeaderWatcher is alive.
private LeaseWatcher nonLeaderWatcher;
// Current lock id
@@ -134,7 +134,6 @@ public class LeaseLeaderElection implements
LeaderElection<TableName> {
} catch (Exception e) {
LOG.error("Error notifying the listener: " + listener +
", leader: " + isLeader, e);
- // throw new LeaderException(e);
}
});
}
@@ -247,7 +246,7 @@ public class LeaseLeaderElection implements
LeaderElection<TableName> {
}
public void perform() {
- LOG.info("Starting " + getClass().getName() + " for leader: " + name);
+ LOG.info("Starting a watcher: {} for {}", getClass().getName(), name);
start();
}
@@ -290,11 +289,9 @@ public class LeaseLeaderElection implements
LeaderElection<TableName> {
}
private class NonLeaderWatcher extends LeaseWatcher {
- private CheckLockRequest request;
-
private long sleep;
-
private int count;
+ private CheckLockRequest request;
NonLeaderWatcher(Configuration conf, TableName table) {
super(conf, table);
@@ -316,12 +313,12 @@ public class LeaseLeaderElection implements
LeaderElection<TableName> {
reclaim();
}
} else {
- // If the leader crashes, the lock it holds will become timeout
eventually.
+ // In case the leader crashes, the lock it holds will become timeout
eventually.
// The AcidHouseKeeperService would not clean the corrupt lock until
a new leader is elected,
- // however the leader candidate should hold that lock firstly in
order to be the new leader,
- // so a deadlock occurs in such case.
- // For non-leader instances, they should try to clean timeout locks
if possible to avoid
- // such problem.
+ // however a leader candidate should hold that lock firstly in order
to be the new leader,
+ // a deadlock occurs in such case.
+ // For all non-leader instances, they should try to clean timeout
locks if possible to
+ // avoid such problem.
store.performTimeOuts();
}
} catch (NoSuchTxnException | TxnAbortedException e) {
@@ -449,7 +446,7 @@ public class LeaseLeaderElection implements
LeaderElection<TableName> {
} catch (NoSuchLockException | TxnOpenException e) {
// ignore
} catch (Exception e) {
- LOG.error("Error while unlocking", e);
+ LOG.error("Error while unlocking: " + lockId, e);
}
}
}
@@ -467,5 +464,4 @@ public class LeaseLeaderElection implements
LeaderElection<TableName> {
public String getName() {
return name;
}
-
}
diff --git
a/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/HostLeaderElection.java
b/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/StaticLeaderElection.java
similarity index 88%
rename from
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/HostLeaderElection.java
rename to
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/StaticLeaderElection.java
index 608beda5109..8a1752bd9a3 100644
---
a/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/HostLeaderElection.java
+++
b/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/StaticLeaderElection.java
@@ -33,9 +33,9 @@ import static java.util.Objects.requireNonNull;
* If the value is empty, means no election happening and all instances are
leaders,
* otherwise the instance matching the configured hostname will be selected as
a leader.
*/
-public class HostLeaderElection implements LeaderElection<String> {
+public class StaticLeaderElection implements LeaderElection<String> {
- private static final Logger LOG =
LoggerFactory.getLogger(HostLeaderElection.class);
+ private static final Logger LOG =
LoggerFactory.getLogger(StaticLeaderElection.class);
private volatile boolean isLeader;
private String name;
private List<LeadershipStateListener> listeners = new ArrayList<>();
@@ -62,8 +62,7 @@ public class HostLeaderElection implements
LeaderElection<String> {
try {
listener.takeLeadership(this);
} catch (Exception e) {
- LOG.warn("Error while notifying the listener: " +
- listener + ", isLeader: " + isLeader, e);
+ LOG.warn("Error while notifying the listener: " + listener, e);
}
});
}
@@ -98,8 +97,7 @@ public class HostLeaderElection implements
LeaderElection<String> {
try {
listener.lossLeadership(this);
} catch (Exception e) {
- LOG.warn("Error while notifying the listener: " +
- listener + ", isLeader: " + isLeader, e);
+ LOG.warn("Error while notifying the listener: " + listener, e);
}
});
}
diff --git
a/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/StatsUpdaterTask.java
b/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/StatsUpdaterTask.java
index 225a318384f..9c3b754d1ab 100644
---
a/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/StatsUpdaterTask.java
+++
b/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/leader/StatsUpdaterTask.java
@@ -90,6 +90,7 @@ public class StatsUpdaterTask implements
LeaderElection.LeadershipStateListener
statsUpdater.ifPresent(statsUpdater -> {
stop.set(true);
((Thread) statsUpdater).interrupt();
+ HiveMetaStore.LOG.info("Stopped the stats updater tasks.");
});
statsUpdater = null;
stop = null;
diff --git
a/standalone-metastore/metastore-server/src/test/java/org/apache/hadoop/hive/metastore/leader/TestLeaderElection.java
b/standalone-metastore/metastore-server/src/test/java/org/apache/hadoop/hive/metastore/leader/TestLeaderElection.java
index 457e85ecb9f..99d13c00b4a 100644
---
a/standalone-metastore/metastore-server/src/test/java/org/apache/hadoop/hive/metastore/leader/TestLeaderElection.java
+++
b/standalone-metastore/metastore-server/src/test/java/org/apache/hadoop/hive/metastore/leader/TestLeaderElection.java
@@ -37,7 +37,7 @@ public class TestLeaderElection {
@Test
public void testConfigLeaderElection() throws Exception {
- LeaderElection election = new HostLeaderElection();
+ LeaderElection election = new StaticLeaderElection();
String leaderHost = "host1.work";
Configuration configuration = MetastoreConf.newMetastoreConf();
election.tryBeLeader(configuration, leaderHost);
diff --git
a/standalone-metastore/metastore-server/src/test/java/org/apache/hadoop/hive/metastore/leader/TestLeaderListener.java
b/standalone-metastore/metastore-server/src/test/java/org/apache/hadoop/hive/metastore/leader/TestLeaderListener.java
new file mode 100644
index 00000000000..768dd03810d
--- /dev/null
+++
b/standalone-metastore/metastore-server/src/test/java/org/apache/hadoop/hive/metastore/leader/TestLeaderListener.java
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hive.metastore.leader;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Pattern;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
+import org.apache.hadoop.hive.metastore.utils.FileUtils;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class TestLeaderListener {
+
+ @Test
+ public void testAuditLeaderListener() throws Exception {
+ Path location = new Path(".", "test_audit_leader_listener_" +
System.currentTimeMillis());
+ Configuration conf = MetastoreConf.newMetastoreConf();
+ FileSystem fileSystem = FileSystem.get(conf);
+ try {
+ MetastoreConf.setBoolVar(conf,
MetastoreConf.ConfVars.METASTORE_HOUSEKEEPING_LEADER_NEW_AUDIT_FILE, true);
+ MetastoreConf.setLongVar(conf,
MetastoreConf.ConfVars.METASTORE_HOUSEKEEPING_LEADER_AUDIT_FILE_LIMIT, 3);
+ // create a new file on the election event
+ AuditLeaderListener listener = new AuditLeaderListener(location, conf);
+ StaticLeaderElection election = new StaticLeaderElection();
+ election.setName("testAuditLeaderListener");
+ listener.takeLeadership(election);
+ List<FileStatus> fileStatuses = FileUtils.getFileStatusRecurse(location,
fileSystem);
+ Pattern pattern =
Pattern.compile("leader_testAuditLeaderListener_[0-9]+\\.json");
+ fileStatuses.forEach(fileStatus ->
Assert.assertTrue(pattern.matcher(fileStatus.getPath().getName()).matches()));
+
+ FileStatus oldestFile = fileStatuses.get(0);
+ listener.takeLeadership(election);
+ fileStatuses = FileUtils.getFileStatusRecurse(location, fileSystem);
+ Assert.assertTrue(fileStatuses.remove(oldestFile));
+ Assert.assertTrue(fileStatuses.size() == 1);
+ FileStatus tmpFileStatus = fileStatuses.get(0);
+
+ listener.takeLeadership(election);
+ fileStatuses = FileUtils.getFileStatusRecurse(location, fileSystem);
+ Assert.assertTrue(fileStatuses.size() == 3);
+ List<FileStatus> tempFileStatuses = new ArrayList<>(fileStatuses);
+ fileStatuses.forEach(fileStatus ->
Assert.assertTrue(pattern.matcher(fileStatus.getPath().getName()).matches()));
+
+ listener.takeLeadership(election);
+ fileStatuses = FileUtils.getFileStatusRecurse(location, fileSystem);
+ Assert.assertTrue(fileStatuses.size() == 3);
+ Assert.assertTrue(tempFileStatuses.remove(oldestFile));
+ Assert.assertTrue(tempFileStatuses.contains(tmpFileStatus));
+ Assert.assertFalse(fileStatuses.contains(oldestFile));
+ tempFileStatuses.removeAll(fileStatuses);
+ Assert.assertTrue(tempFileStatuses.isEmpty());
+
+ listener.takeLeadership(election);
+ fileStatuses = FileUtils.getFileStatusRecurse(location, fileSystem);
+ Assert.assertTrue(fileStatuses.size() == 3);
+ Assert.assertFalse(fileStatuses.contains(tmpFileStatus));
+
+ // only one file
+ fileSystem.delete(location, true);
+ Assert.assertTrue(FileUtils.isDirEmpty(fileSystem, location));
+ MetastoreConf.setBoolVar(conf,
MetastoreConf.ConfVars.METASTORE_HOUSEKEEPING_LEADER_NEW_AUDIT_FILE, false);
+ listener.takeLeadership(election);
+ fileStatuses = FileUtils.getFileStatusRecurse(location, fileSystem);
+ Assert.assertTrue(fileStatuses.size() == 1);
+
Assert.assertTrue(fileStatuses.get(0).getPath().getName().equals("leader_testAuditLeaderListener.json"));
+ listener.takeLeadership(election);
+ listener.takeLeadership(election);
+ fileStatuses = FileUtils.getFileStatusRecurse(location, fileSystem);
+ Assert.assertTrue(fileStatuses.size() == 1);
+
Assert.assertTrue(fileStatuses.get(0).getPath().getName().equals("leader_testAuditLeaderListener.json"));
+ } finally {
+ FileUtils.moveToTrash(fileSystem, location, conf, true);
+ }
+ }
+
+}