This is an automated email from the ASF dual-hosted git repository.
jojochuang pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ozone.git
The following commit(s) were added to refs/heads/master by this push:
new bc6ab73ced2 HDDS-17107. Show startup progress in Datanode web UI
(#11611)
bc6ab73ced2 is described below
commit bc6ab73ced248ac8733334ba2ef0b3db24d95c7a
Author: Siyao Meng <[email protected]>
AuthorDate: Thu Oct 22 13:10:00 2026 -0700
HDDS-17107. Show startup progress in Datanode web UI (#11611)
Generated-by: Claude Opus 5.5 <[email protected]>
---
.../apache/hadoop/ozone/DatanodeStartupPhase.java | 41 +++
.../apache/hadoop/ozone/HddsDatanodeService.java | 13 +
.../states/endpoint/VersionEndpointTask.java | 3 +
.../ozone/container/ozoneimpl/ContainerReader.java | 37 +++
.../ozone/container/ozoneimpl/OzoneContainer.java | 19 +-
.../resources/webapps/hddsDatanode/dn-startup.html | 66 +++++
.../src/main/resources/webapps/hddsDatanode/dn.js | 27 ++
.../main/resources/webapps/hddsDatanode/index.html | 1 +
.../states/datanode/TestRunningDatanodeState.java | 7 +
.../container/ozoneimpl/TestContainerReader.java | 18 ++
.../apache/hadoop/hdds/server/StartupProgress.java | 300 +++++++++++++++++++++
.../hadoop/hdds/server/StartupProgressMXBean.java | 85 ++++++
.../hadoop/hdds/server/TestStartupProgress.java | 168 ++++++++++++
13 files changed, 783 insertions(+), 2 deletions(-)
diff --git
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/DatanodeStartupPhase.java
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/DatanodeStartupPhase.java
new file mode 100644
index 00000000000..a25b0c68ef8
--- /dev/null
+++
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/DatanodeStartupPhase.java
@@ -0,0 +1,41 @@
+/*
+ * 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.ozone;
+
+/**
+ * Phases of datanode startup, in the order they are executed.
+ */
+public enum DatanodeStartupPhase {
+ INITIALIZING("Initializing"),
+ WAITING_FOR_SCM("Waiting for SCM"),
+ PREPARING_VOLUMES("Preparing volumes"),
+ LOADING_CONTAINERS("Loading containers"),
+ CHECKING_VOLUMES("Checking volumes"),
+ STARTING_SERVICES("Starting container services");
+
+ private final String description;
+
+ DatanodeStartupPhase(String description) {
+ this.description = description;
+ }
+
+ @Override
+ public String toString() {
+ return description;
+ }
+}
diff --git
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/HddsDatanodeService.java
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/HddsDatanodeService.java
index feb61f8bc0a..f0a5a2a56eb 100644
---
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/HddsDatanodeService.java
+++
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/HddsDatanodeService.java
@@ -75,6 +75,7 @@
import
org.apache.hadoop.hdds.security.x509.certificate.client.CertificateClient;
import
org.apache.hadoop.hdds.security.x509.certificate.client.DNCertificateClient;
import org.apache.hadoop.hdds.server.OzoneAdmins;
+import org.apache.hadoop.hdds.server.StartupProgress;
import org.apache.hadoop.hdds.server.http.HttpConfig;
import org.apache.hadoop.hdds.server.http.RatisDropwizardExports;
import org.apache.hadoop.hdds.tracing.TracingConfig;
@@ -142,6 +143,7 @@ public class HddsDatanodeService extends GenericCli
implements Callable<Void>, S
private List<RatisDropwizardExports.MetricReporter> ratisReporterList = null;
private DNMXBeanImpl serviceRuntimeInfo;
private ObjectName dnInfoBeanName;
+ private StartupProgress<DatanodeStartupPhase> startupProgress;
private HddsDatanodeClientProtocolServer clientProtocolServer;
private OzoneAdmins admins;
private ReconfigurationHandler reconfigurationHandler;
@@ -231,6 +233,9 @@ public void start(OzoneConfiguration configuration) {
@SuppressWarnings("methodlength")
public void start() {
+ startupProgress = new StartupProgress<>(DatanodeStartupPhase.class);
+ startupProgress.beginPhase(DatanodeStartupPhase.INITIALIZING);
+ startupProgress.registerMXBean("HddsDatanode");
serviceRuntimeInfo = new DNMXBeanImpl(HddsVersionInfo.HDDS_VERSION_INFO) {
@Override
public String getNamespace() {
@@ -375,6 +380,7 @@ public String getNamespace() {
clientProtocolServer.start();
startPlugins();
+ startupProgress.beginPhase(DatanodeStartupPhase.WAITING_FOR_SCM);
// Starting HDDS Daemons
datanodeStateMachine.startDaemon();
@@ -546,6 +552,10 @@ public DatanodeStateMachine getDatanodeStateMachine() {
return datanodeStateMachine;
}
+ public StartupProgress<DatanodeStartupPhase> getStartupProgress() {
+ return startupProgress;
+ }
+
public HddsDatanodeClientProtocolServer getClientProtocolServer() {
return clientProtocolServer;
}
@@ -602,6 +612,9 @@ public void stop() {
getClientProtocolServer().stop();
}
unregisterMXBean();
+ if (startupProgress != null) {
+ startupProgress.unregisterMXBean();
+ }
RatisDropwizardExports.clear(ratisMetricsMap, ratisReporterList);
if (secretKeyClient != null) {
diff --git
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/states/endpoint/VersionEndpointTask.java
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/states/endpoint/VersionEndpointTask.java
index a1e9cbc3765..fa5871111bf 100644
---
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/states/endpoint/VersionEndpointTask.java
+++
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/states/endpoint/VersionEndpointTask.java
@@ -22,6 +22,7 @@
import java.util.concurrent.Callable;
import org.apache.hadoop.hdds.conf.ConfigurationSource;
import
org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.SCMVersionResponseProto;
+import org.apache.hadoop.ozone.DatanodeStartupPhase;
import org.apache.hadoop.ozone.OzoneConsts;
import
org.apache.hadoop.ozone.container.common.statemachine.EndpointStateMachine;
import org.apache.hadoop.ozone.container.common.utils.StorageVolumeUtil;
@@ -78,6 +79,7 @@ public EndpointStateMachine.EndPointStates call() throws
Exception {
Objects.requireNonNull(scmId, "scmId == null");
Objects.requireNonNull(clusterId, "clusterId == null");
+
ozoneContainer.getStartupProgress().beginPhase(DatanodeStartupPhase.PREPARING_VOLUMES);
// Check DbVolumes, format DbVolume at first register time.
checkVolumeSet(ozoneContainer.getDbVolumeSet(), scmId, clusterId);
@@ -87,6 +89,7 @@ public EndpointStateMachine.EndPointStates call() throws
Exception {
// Start the container services after getting the version
information
ozoneContainer.start(clusterId);
} catch (Exception | Error ex) {
+ ozoneContainer.getStartupProgress().fail();
// Handle this in the task: its caller may already have timed out
waiting for startup.
LOG.error("Failed to start required container services for SCM {}.
Shutting down datanode.",
rpcEndPoint.getAddress(), ex);
diff --git
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/ozoneimpl/ContainerReader.java
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/ozoneimpl/ContainerReader.java
index 88a9cc50a40..edf1f0bd5ed 100644
---
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/ozoneimpl/ContainerReader.java
+++
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/ozoneimpl/ContainerReader.java
@@ -28,6 +28,7 @@
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
import org.apache.hadoop.hdds.scm.container.ContainerID;
import
org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
+import org.apache.hadoop.hdds.server.StartupProgress;
import org.apache.hadoop.ozone.common.InconsistentStorageStateException;
import org.apache.hadoop.ozone.container.common.helpers.ContainerUtils;
import org.apache.hadoop.ozone.container.common.impl.ContainerData;
@@ -79,10 +80,19 @@ public class ContainerReader implements Runnable {
private final File hddsVolumeDir;
private final MutableVolumeSet volumeSet;
private final boolean shouldDelete;
+ private final StartupProgress.Step progress;
public ContainerReader(
MutableVolumeSet volSet, HddsVolume volume, ContainerSet cset,
ConfigurationSource conf, boolean shouldDelete) {
+ this(volSet, volume, cset, conf, shouldDelete, null);
+ }
+
+ /**
+ * @param progress if not null, tracks the number of containers read from
the volume
+ */
+ public ContainerReader(MutableVolumeSet volSet, HddsVolume volume,
ContainerSet cset, ConfigurationSource conf,
+ boolean shouldDelete, StartupProgress.Step progress) {
Objects.requireNonNull(volume, "volume == null");
this.hddsVolume = volume;
this.hddsVolumeDir = hddsVolume.getHddsRootDir();
@@ -90,6 +100,7 @@ public ContainerReader(
this.config = conf;
this.volumeSet = volSet;
this.shouldDelete = shouldDelete;
+ this.progress = progress;
}
@Override
@@ -100,6 +111,14 @@ public void run() {
LOG.error("Could not read container files from the volume {}. " +
"Marking the volume as failed", hddsVolumeDir, t);
volumeSet.failVolume(hddsVolumeDir.getPath());
+ } finally {
+ if (progress != null) {
+ if (hddsVolume.isFailed()) {
+ progress.fail();
+ } else {
+ progress.end();
+ }
+ }
}
}
@@ -135,6 +154,9 @@ public void readVolume(File hddsVolumeRootDir) {
LOG.info("Start to verify containers on volume {}", hddsVolumeRootDir);
File[] containerTopDirs = currentDir.listFiles();
if (containerTopDirs != null && containerTopDirs.length > 0) {
+ if (progress != null) {
+ progress.setTotal(countContainerDirs(containerTopDirs));
+ }
for (File containerTopDir : containerTopDirs) {
if (containerTopDir.isDirectory()) {
File[] containerDirs = containerTopDir.listFiles();
@@ -155,6 +177,9 @@ public void readVolume(File hddsVolumeRootDir) {
LOG.error("Failed to load container from {}",
containerDir.getAbsolutePath(), e);
}
+ if (progress != null) {
+ progress.increment();
+ }
}
}
}
@@ -164,6 +189,18 @@ public void readVolume(File hddsVolumeRootDir) {
LOG.info("Finish verifying containers on volume {}", hddsVolumeRootDir);
}
+ private static long countContainerDirs(File[] containerTopDirs) {
+ long count = 0;
+ for (File containerTopDir : containerTopDirs) {
+ // null if not a directory
+ String[] containerDirs = containerTopDir.list();
+ if (containerDirs != null) {
+ count += containerDirs.length;
+ }
+ }
+ return count;
+ }
+
private void verifyContainerFile(long containerID,
File containerFile) {
try {
diff --git
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/ozoneimpl/OzoneContainer.java
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/ozoneimpl/OzoneContainer.java
index 67b7d0b6213..31e4be43056 100644
---
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/ozoneimpl/OzoneContainer.java
+++
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/ozoneimpl/OzoneContainer.java
@@ -68,9 +68,11 @@
import org.apache.hadoop.hdds.security.symmetric.SecretKeyVerifierClient;
import org.apache.hadoop.hdds.security.token.TokenVerifier;
import
org.apache.hadoop.hdds.security.x509.certificate.client.CertificateClient;
+import org.apache.hadoop.hdds.server.StartupProgress;
import org.apache.hadoop.hdds.utils.HddsServerUtil;
import org.apache.hadoop.hdds.utils.IOUtils;
import org.apache.hadoop.hdds.utils.db.TableIterator;
+import org.apache.hadoop.ozone.DatanodeStartupPhase;
import org.apache.hadoop.ozone.HddsDatanodeService;
import org.apache.hadoop.ozone.container.checksum.ContainerChecksumTreeManager;
import org.apache.hadoop.ozone.container.common.DatanodeStorage;
@@ -162,6 +164,7 @@ public class OzoneContainer {
private final ContainerMetrics metrics;
private WitnessedContainerMetadataStore witnessedContainerMetadataStore;
private final DatanodeStorageMetrics datanodeStorageMetrics;
+ private final StartupProgress<DatanodeStartupPhase> startupProgress;
enum InitializingStatus {
UNINITIALIZED, INITIALIZING, INITIALIZED, FAILED
@@ -185,6 +188,8 @@ public OzoneContainer(HddsDatanodeService
hddsDatanodeService,
config = conf;
this.datanodeDetails = datanodeDetails;
this.context = context;
+ this.startupProgress = hddsDatanodeService != null &&
hddsDatanodeService.getStartupProgress() != null
+ ? hddsDatanodeService.getStartupProgress() : new
StartupProgress<>(DatanodeStartupPhase.class);
this.volumeChecker = new StorageVolumeChecker(conf, new Timer(),
datanodeDetails.threadNamePrefix());
volumeSet = new MutableVolumeSet(datanodeDetails.getUuidString(), conf,
@@ -352,6 +357,10 @@ public OzoneContainer(
this(null, datanodeDetails, conf, context, null, null,
volumeChoosingPolicy);
}
+ public StartupProgress<DatanodeStartupPhase> getStartupProgress() {
+ return startupProgress;
+ }
+
public GrpcTlsConfig getTlsClientConfig() {
return tlsClientConfig;
}
@@ -377,8 +386,10 @@ public void buildContainerSet() throws IOException {
.build();
while (volumeSetIterator.hasNext()) {
StorageVolume volume = volumeSetIterator.next();
- ContainerReader containerReader = new ContainerReader(volumeSet,
- (HddsVolume) volume, containerSet, config, true);
+ HddsVolume hddsVolume = (HddsVolume) volume;
+ StartupProgress.Step step =
startupProgress.addStep(DatanodeStartupPhase.LOADING_CONTAINERS,
+ hddsVolume.getHddsRootDir().getPath());
+ ContainerReader containerReader = new ContainerReader(volumeSet,
hddsVolume, containerSet, config, true, step);
Thread thread = threadFactory.newThread(containerReader);
thread.start();
volumeThreads.add(thread);
@@ -642,12 +653,14 @@ private void terminateOnInitializationTimeout(Duration
initTimeout) {
}
private void initializeContainerServices(String clusterId) throws
IOException {
+ startupProgress.beginPhase(DatanodeStartupPhase.LOADING_CONTAINERS);
DatanodeStorage layoutStorage
= new DatanodeStorage(config);
layoutStorage.setClusterId(clusterId);
layoutStorage.persistCurrentState();
buildContainerSet();
+ startupProgress.beginPhase(DatanodeStartupPhase.CHECKING_VOLUMES);
// Start background volume checks, which will begin after the configured
// delay.
@@ -663,6 +676,7 @@ private void initializeContainerServices(String clusterId)
throws IOException {
dbVolumeSet.checkAllVolumes();
dbVolumeSet.startAllVolume();
}
+ startupProgress.beginPhase(DatanodeStartupPhase.STARTING_SERVICES);
LOG.info("Attempting to start container services.");
startContainerScrub();
@@ -684,6 +698,7 @@ private void initializeContainerServices(String clusterId)
throws IOException {
recoveringContainerScrubbingService.start();
initHddsVolumeContainer();
+ startupProgress.endPhase(DatanodeStartupPhase.STARTING_SERVICES);
}
/**
diff --git
a/hadoop-hdds/container-service/src/main/resources/webapps/hddsDatanode/dn-startup.html
b/hadoop-hdds/container-service/src/main/resources/webapps/hddsDatanode/dn-startup.html
new file mode 100644
index 00000000000..5358c7b825a
--- /dev/null
+++
b/hadoop-hdds/container-service/src/main/resources/webapps/hddsDatanode/dn-startup.html
@@ -0,0 +1,66 @@
+<!--
+ 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.
+-->
+<html>
+<head>
+ <meta charset="UTF-8">
+ <title>DataNode Startup Progress</title>
+</head>
+<body>
+ <h2>Startup Progress</h2>
+ <p ng-show="startupCtrl.startup">
+ Elapsed time: {{startupCtrl.startup.ElapsedTime |
millisecondsToMinutes}}
+ <span ng-show="startupCtrl.startup.Complete">(complete)</span>
+ <span ng-show="startupCtrl.startup.Failed">(failed)</span>
+ <span ng-hide="startupCtrl.startup.Complete ||
startupCtrl.startup.Failed">(in progress, refreshing)</span>
+ </p>
+ <table class="table">
+ <thead>
+ <tr>
+ <th>Phase</th>
+ <th>Status</th>
+ <th>Elapsed Time</th>
+ <th>Progress</th>
+ <th>Estimated Remaining Time</th>
+ </tr>
+ </thead>
+ <tbody ng-repeat="phase in startupCtrl.startup.Phases">
+ <tr ng-class="{info: phase.status == 'RUNNING', danger: phase.status
== 'FAILED'}">
+ <td><strong>{{phase.name}}</strong></td>
+ <td>{{phase.status}}</td>
+ <td><span ng-show="phase.status != 'PENDING'">{{phase.elapsedTime
| millisecondsToMinutes}}</span></td>
+ <td><span ng-show="phase.total > 0">{{phase.done}} /
{{phase.total}}
+ ({{phase.done * 100 / phase.total | number:1}}%)</span></td>
+ <td>
+ <span ng-show="phase.status == 'RUNNING' &&
phase.remainingTime >= 0">{{phase.remainingTime | millisecondsToMinutes}}</span>
+ <span ng-show="phase.status == 'RUNNING' &&
phase.remainingTime < 0">unknown</span>
+ </td>
+ </tr>
+ <tr ng-repeat="step in phase.steps" ng-class="{danger: step.status ==
'FAILED'}">
+ <td style="padding-left: 2em">{{step.name}}</td>
+ <td>{{step.status}}</td>
+ <td>{{step.elapsedTime | millisecondsToMinutes}}</td>
+ <td><span ng-show="step.total > 0">{{step.done}} / {{step.total}}
+ ({{step.done * 100 / step.total | number:1}}%)</span></td>
+ <td>
+ <span ng-show="step.status == 'RUNNING' && step.remainingTime
>= 0">{{step.remainingTime | millisecondsToMinutes}}</span>
+ <span ng-show="step.status == 'RUNNING' && step.remainingTime
< 0">unknown</span>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+</body>
+</html>
diff --git
a/hadoop-hdds/container-service/src/main/resources/webapps/hddsDatanode/dn.js
b/hadoop-hdds/container-service/src/main/resources/webapps/hddsDatanode/dn.js
index 1f5ae99f15e..98928de5316 100644
---
a/hadoop-hdds/container-service/src/main/resources/webapps/hddsDatanode/dn.js
+++
b/hadoop-hdds/container-service/src/main/resources/webapps/hddsDatanode/dn.js
@@ -90,6 +90,33 @@
});
});
+ // Register Startup Progress Controller
+ angular.module('ozone').config(function ($routeProvider) {
+ $routeProvider.when('/startup', {
+ templateUrl: 'dn-startup.html',
+ controller: 'DNStartupController as startupCtrl',
+ });
+ });
+
+ angular.module('ozone')
+ .controller('DNStartupController', function ($http, $interval, $scope)
{
+ var ctrl = this;
+ var refresh = function () {
+
$http.get("jmx?qry=Hadoop:service=HddsDatanode,name=StartupProgress")
+ .then(function (result) {
+ ctrl.startup = result.data.beans[0];
+ if (ctrl.startup && (ctrl.startup.Complete ||
ctrl.startup.Failed)) {
+ $interval.cancel(timer);
+ }
+ });
+ };
+ var timer = $interval(refresh, 2000);
+ $scope.$on('$destroy', function () {
+ $interval.cancel(timer);
+ });
+ refresh();
+ });
+
angular.module('ozone')
.filter('millisecondsToMinutes', function() {
return function(milliseconds) {
diff --git
a/hadoop-hdds/container-service/src/main/resources/webapps/hddsDatanode/index.html
b/hadoop-hdds/container-service/src/main/resources/webapps/hddsDatanode/index.html
index 0e1cbf21a00..c105821e86c 100644
---
a/hadoop-hdds/container-service/src/main/resources/webapps/hddsDatanode/index.html
+++
b/hadoop-hdds/container-service/src/main/resources/webapps/hddsDatanode/index.html
@@ -50,6 +50,7 @@
</div>
<navmenu metrics="{ 'Rpc metrics' : '#!/metrics/rpc'}"
+ extra-nav-links="[{label: 'Startup Progress', href:
'#!/startup'}]"
iostatus="true" io-link-href="#!/iostatus"
scanner="true" scanner-link-href="#!/dn-scanner"
/>
diff --git
a/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/common/states/datanode/TestRunningDatanodeState.java
b/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/common/states/datanode/TestRunningDatanodeState.java
index 459dc663c27..6a6e175c666 100644
---
a/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/common/states/datanode/TestRunningDatanodeState.java
+++
b/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/common/states/datanode/TestRunningDatanodeState.java
@@ -38,6 +38,8 @@
import java.util.concurrent.TimeUnit;
import org.apache.hadoop.hdds.conf.OzoneConfiguration;
import org.apache.hadoop.hdds.scm.net.HostAndPort;
+import org.apache.hadoop.hdds.server.StartupProgress;
+import org.apache.hadoop.ozone.DatanodeStartupPhase;
import org.apache.hadoop.ozone.OzoneConsts;
import
org.apache.hadoop.ozone.container.common.statemachine.DatanodeStateMachine;
import
org.apache.hadoop.ozone.container.common.statemachine.DatanodeStateMachine.DatanodeStates;
@@ -111,6 +113,8 @@ public void testAwait() throws InterruptedException {
void testStartupCompletesAfterHeartbeatTimeout(int failureType) throws
Exception {
OzoneConfiguration conf = new OzoneConfiguration();
OzoneContainer container = mock(OzoneContainer.class);
+ StartupProgress<DatanodeStartupPhase> startupProgress = new
StartupProgress<>(DatanodeStartupPhase.class);
+ when(container.getStartupProgress()).thenReturn(startupProgress);
DatanodeStateMachine datanode = mock(DatanodeStateMachine.class);
SCMConnectionManager connections = mock(SCMConnectionManager.class);
when(datanode.getConnectionManager()).thenReturn(connections);
@@ -147,8 +151,10 @@ void testStartupCompletesAfterHeartbeatTimeout(int
failureType) throws Exception
if (failureType == 0) {
assertThat(endpoint.getState()).isEqualTo(EndPointStates.REGISTER);
assertThat(context.getShutdownOnError()).isFalse();
+ assertThat(startupProgress.isFailed()).isFalse();
} else {
assertThat(endpoint.getState()).isEqualTo(SHUTDOWN);
+ assertThat(startupProgress.isFailed()).isTrue();
assertThat(logs.getOutput()).contains("Failed to start required
container services", "scm:9861",
failure.getClass().getName(), "Corrupt Raft log");
context.execute(executor, 5, TimeUnit.SECONDS);
@@ -166,6 +172,7 @@ void testStartupCompletesAfterHeartbeatTimeout(int
failureType) throws Exception
void testUnavailableScmDoesNotPreventStartup() throws Exception {
OzoneConfiguration conf = new OzoneConfiguration();
OzoneContainer container = mock(OzoneContainer.class);
+ when(container.getStartupProgress()).thenReturn(new
StartupProgress<>(DatanodeStartupPhase.class));
DatanodeStateMachine datanode = mock(DatanodeStateMachine.class);
SCMConnectionManager connections = mock(SCMConnectionManager.class);
when(datanode.getConnectionManager()).thenReturn(connections);
diff --git
a/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/ozoneimpl/TestContainerReader.java
b/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/ozoneimpl/TestContainerReader.java
index 234fda2cd00..5cd05c80db4 100644
---
a/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/ozoneimpl/TestContainerReader.java
+++
b/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/ozoneimpl/TestContainerReader.java
@@ -51,8 +51,11 @@
import
org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos;
import org.apache.hadoop.hdds.scm.ScmConfigKeys;
import org.apache.hadoop.hdds.scm.container.ContainerID;
+import org.apache.hadoop.hdds.server.StartupProgress;
+import org.apache.hadoop.hdds.server.StartupProgressMXBean;
import org.apache.hadoop.hdds.utils.db.InMemoryTestTable;
import org.apache.hadoop.hdds.utils.db.Table;
+import org.apache.hadoop.ozone.DatanodeStartupPhase;
import org.apache.hadoop.ozone.OzoneConfigKeys;
import org.apache.hadoop.ozone.OzoneConsts;
import org.apache.hadoop.ozone.container.checksum.ContainerChecksumTreeManager;
@@ -274,6 +277,21 @@ private List<Long> addBlocks(KeyValueContainer
keyValueContainer,
return blkNames;
}
+ @ContainerTestVersionInfo.ContainerTest
+ public void testContainerReaderProgress(ContainerTestVersionInfo
versionInfo) throws Exception {
+ setup(versionInfo);
+ StartupProgress.Step step = new
StartupProgress<>(DatanodeStartupPhase.class)
+ .addStep(DatanodeStartupPhase.LOADING_CONTAINERS,
hddsVolume.getHddsRootDir().getPath());
+
+ new ContainerReader(volumeSet, hddsVolume, containerSet, conf, true,
step).run();
+
+ assertEquals(2, containerSet.containerCount());
+ assertEquals(StartupProgressMXBean.Status.COMPLETE, step.getStatus());
+ assertEquals(2, step.getTotal());
+ assertEquals(2, step.getDone());
+ assertEquals(0, step.getRemainingTime());
+ }
+
@ContainerTestVersionInfo.ContainerTest
public void testContainerReader(ContainerTestVersionInfo versionInfo)
throws Exception {
diff --git
a/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/server/StartupProgress.java
b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/server/StartupProgress.java
new file mode 100644
index 00000000000..2f5df58c243
--- /dev/null
+++
b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/server/StartupProgress.java
@@ -0,0 +1,300 @@
+/*
+ * 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.hdds.server;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
+import javax.management.ObjectName;
+import org.apache.hadoop.metrics2.util.MBeans;
+import org.apache.hadoop.util.Time;
+
+/**
+ * Tracks the phases of a service's startup, so that its progress can be
observed while it is starting.
+ * <p>
+ * Phases are the constants of an enum, in the order they are executed. {@link
Enum#toString()} is used as the
+ * name of the phase. A phase may be divided into steps that run concurrently,
e.g. one per volume. Each step
+ * counts the work items done out of a known total, which is used to estimate
the remaining time.
+ *
+ * @param <P> the enum defining the phases
+ */
+public class StartupProgress<P extends Enum<P>> implements
StartupProgressMXBean {
+
+ private final Map<P, Phase> phases;
+ private final LongSupplier clock;
+ private ObjectName jmxBean;
+
+ public StartupProgress(Class<P> phaseType) {
+ this(phaseType, Time::monotonicNow);
+ }
+
+ @VisibleForTesting
+ StartupProgress(Class<P> phaseType, LongSupplier clock) {
+ this.clock = clock;
+ phases = new EnumMap<>(phaseType);
+ for (P phase : phaseType.getEnumConstants()) {
+ phases.put(phase, new Phase(phase.toString(), clock));
+ }
+ }
+
+ /**
+ * Begins the phase, ending all earlier phases. Has no effect if the phase
has already begun or ended,
+ * e.g. when the datanode gets the version from each SCM.
+ */
+ public void beginPhase(P phase) {
+ for (Map.Entry<P, Phase> entry : phases.entrySet()) {
+ if (entry.getKey() == phase) {
+ entry.getValue().begin();
+ return;
+ }
+ entry.getValue().end();
+ }
+ }
+
+ /**
+ * Ends the phase and all earlier phases. A phase that has not begun is
ended with zero elapsed time.
+ */
+ public void endPhase(P phase) {
+ beginPhase(phase);
+ phases.get(phase).end();
+ }
+
+ /**
+ * Marks the running phases as failed.
+ */
+ public void fail() {
+ for (Phase phase : phases.values()) {
+ if (phase.getStatus() == Status.RUNNING) {
+ phase.fail();
+ }
+ }
+ }
+
+ /**
+ * @return a new running step of the phase.
+ */
+ public Step addStep(P phase, String name) {
+ return phases.get(phase).addStep(name);
+ }
+
+ public void registerMXBean(String serviceName) {
+ jmxBean = MBeans.register(serviceName, "StartupProgress", this);
+ }
+
+ public void unregisterMXBean() {
+ if (jmxBean != null) {
+ MBeans.unregister(jmxBean);
+ jmxBean = null;
+ }
+ }
+
+ @Override
+ public boolean isComplete() {
+ return phases.values().stream().allMatch(phase -> phase.getStatus() ==
Status.COMPLETE);
+ }
+
+ @Override
+ public boolean isFailed() {
+ return phases.values().stream().anyMatch(phase -> phase.getStatus() ==
Status.FAILED);
+ }
+
+ @Override
+ public long getElapsedTime() {
+ long start = -1;
+ long end = -1;
+ for (Tracked phase : phases.values()) {
+ if (phase.startTime >= 0 && (start < 0 || phase.startTime < start)) {
+ start = phase.startTime;
+ }
+ end = Math.max(end, phase.endTime);
+ }
+ if (start < 0) {
+ return 0;
+ }
+ return (isComplete() || isFailed() ? end : clock.getAsLong()) - start;
+ }
+
+ @Override
+ public List<PhaseInfo> getPhases() {
+ return new ArrayList<>(phases.values());
+ }
+
+ /**
+ * Start and end time of a phase or step.
+ */
+ private abstract static class Tracked {
+ private final String name;
+ private final LongSupplier clock;
+ private volatile long startTime = -1;
+ private volatile long endTime = -1;
+ private volatile boolean failed;
+
+ Tracked(String name, LongSupplier clock) {
+ this.name = name;
+ this.clock = clock;
+ }
+
+ synchronized void begin() {
+ if (startTime < 0) {
+ startTime = clock.getAsLong();
+ }
+ }
+
+ public synchronized void end() {
+ begin();
+ if (endTime < 0) {
+ endTime = clock.getAsLong();
+ }
+ }
+
+ public synchronized void fail() {
+ if (endTime < 0) {
+ failed = true;
+ end();
+ }
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Status getStatus() {
+ if (endTime >= 0) {
+ return failed ? Status.FAILED : Status.COMPLETE;
+ }
+ return startTime >= 0 ? Status.RUNNING : Status.PENDING;
+ }
+
+ public long getElapsedTime() {
+ long start = startTime;
+ if (start < 0) {
+ return 0;
+ }
+ long end = endTime;
+ return (end >= 0 ? end : clock.getAsLong()) - start;
+ }
+ }
+
+ private static final class Phase extends Tracked implements PhaseInfo {
+ private final List<Step> steps = new CopyOnWriteArrayList<>();
+
+ Phase(String name, LongSupplier clock) {
+ super(name, clock);
+ }
+
+ Step addStep(String name) {
+ Step step = new Step(name, ((Tracked) this).clock);
+ step.begin();
+ steps.add(step);
+ return step;
+ }
+
+ /**
+ * Steps run concurrently, so the phase completes with its slowest step.
Unknown if no step is running,
+ * since the phase may still have work to do outside of its steps.
+ */
+ @Override
+ public long getRemainingTime() {
+ Status status = getStatus();
+ if (status == Status.COMPLETE) {
+ return 0;
+ }
+ long remaining = -1;
+ if (status == Status.RUNNING) {
+ for (Step step : steps) {
+ if (step.getStatus() == Status.RUNNING) {
+ long stepRemaining = step.getRemainingTime();
+ if (stepRemaining < 0) {
+ return -1;
+ }
+ remaining = Math.max(remaining, stepRemaining);
+ }
+ }
+ }
+ return remaining;
+ }
+
+ @Override
+ public long getDone() {
+ return steps.stream().mapToLong(Step::getDone).sum();
+ }
+
+ @Override
+ public long getTotal() {
+ return steps.stream().mapToLong(Step::getTotal).sum();
+ }
+
+ @Override
+ public List<ProgressInfo> getSteps() {
+ return new ArrayList<>(steps);
+ }
+ }
+
+ /**
+ * A part of a phase which processes a known number of work items.
+ */
+ public static final class Step extends Tracked implements ProgressInfo {
+ private final AtomicLong done = new AtomicLong();
+ private volatile long total;
+
+ private Step(String name, LongSupplier clock) {
+ super(name, clock);
+ }
+
+ public void setTotal(long total) {
+ this.total = total;
+ }
+
+ public void increment() {
+ done.incrementAndGet();
+ }
+
+ /**
+ * Estimates the remaining time assuming that the remaining work items are
processed at the same rate.
+ */
+ @Override
+ public long getRemainingTime() {
+ Status status = getStatus();
+ if (status == Status.COMPLETE) {
+ return 0;
+ }
+ long doneCount = done.get();
+ long totalCount = total;
+ if (status != Status.RUNNING || doneCount <= 0 || totalCount <= 0) {
+ return -1;
+ }
+ // average time per work item * remaining work items
+ return Math.max(0, (long) ((double) getElapsedTime() / doneCount *
(totalCount - doneCount)));
+ }
+
+ @Override
+ public long getDone() {
+ return done.get();
+ }
+
+ @Override
+ public long getTotal() {
+ return total;
+ }
+ }
+}
diff --git
a/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/server/StartupProgressMXBean.java
b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/server/StartupProgressMXBean.java
new file mode 100644
index 00000000000..1d4b652d0e7
--- /dev/null
+++
b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/server/StartupProgressMXBean.java
@@ -0,0 +1,85 @@
+/*
+ * 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.hdds.server;
+
+import java.util.List;
+
+/**
+ * JMX view of {@link StartupProgress}.
+ * <p>
+ * Times are in milliseconds. A remaining time of -1 means it cannot be
estimated (yet).
+ */
+public interface StartupProgressMXBean {
+
+ /**
+ * Status of a startup phase or step.
+ */
+ enum Status {
+ PENDING,
+ RUNNING,
+ COMPLETE,
+ FAILED
+ }
+
+ /**
+ * @return true if all phases are complete.
+ */
+ boolean isComplete();
+
+ /**
+ * @return true if any phase has failed.
+ */
+ boolean isFailed();
+
+ /**
+ * @return time from the beginning of the first phase until the end of the
last phase, or until now if
+ * startup is still in progress.
+ */
+ long getElapsedTime();
+
+ /**
+ * @return all phases in the order they are executed.
+ */
+ List<PhaseInfo> getPhases();
+
+ /**
+ * JMX view of a startup phase or of a step within a phase.
+ */
+ interface ProgressInfo {
+ String getName();
+
+ Status getStatus();
+
+ long getElapsedTime();
+
+ long getRemainingTime();
+
+ /** @return number of completed work items, summed over all steps for a
phase. */
+ long getDone();
+
+ /** @return total number of work items, summed over all steps for a phase.
*/
+ long getTotal();
+ }
+
+ /**
+ * JMX view of a startup phase.
+ */
+ interface PhaseInfo extends ProgressInfo {
+ List<ProgressInfo> getSteps();
+ }
+}
diff --git
a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/server/TestStartupProgress.java
b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/server/TestStartupProgress.java
new file mode 100644
index 00000000000..dfb6a555ace
--- /dev/null
+++
b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/server/TestStartupProgress.java
@@ -0,0 +1,168 @@
+/*
+ * 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.hdds.server;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.management.ManagementFactory;
+import java.util.concurrent.atomic.AtomicLong;
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
+import javax.management.openmbean.CompositeData;
+import org.apache.hadoop.hdds.server.StartupProgressMXBean.PhaseInfo;
+import org.apache.hadoop.hdds.server.StartupProgressMXBean.Status;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests for {@link StartupProgress}.
+ */
+public class TestStartupProgress {
+
+ private final AtomicLong now = new AtomicLong(1000);
+ private final StartupProgress<TestPhase> progress = new
StartupProgress<>(TestPhase.class, now::get);
+
+ private enum TestPhase {
+ FIRST,
+ SECOND,
+ THIRD
+ }
+
+ @Test
+ void phases() {
+ assertEquals(Status.PENDING, phase(TestPhase.FIRST).getStatus());
+ assertEquals(-1, phase(TestPhase.FIRST).getRemainingTime());
+ assertEquals(0, progress.getElapsedTime());
+
+ progress.beginPhase(TestPhase.FIRST);
+ now.addAndGet(100);
+ assertEquals(Status.RUNNING, phase(TestPhase.FIRST).getStatus());
+ assertEquals(100, phase(TestPhase.FIRST).getElapsedTime());
+ assertEquals(-1, phase(TestPhase.FIRST).getRemainingTime());
+
+ // beginning a phase ends the earlier ones
+ progress.beginPhase(TestPhase.SECOND);
+ now.addAndGet(50);
+ assertEquals(Status.COMPLETE, phase(TestPhase.FIRST).getStatus());
+ assertEquals(100, phase(TestPhase.FIRST).getElapsedTime());
+ assertEquals(0, phase(TestPhase.FIRST).getRemainingTime());
+ assertEquals(50, phase(TestPhase.SECOND).getElapsedTime());
+ assertFalse(progress.isComplete());
+ assertEquals(150, progress.getElapsedTime());
+
+ progress.endPhase(TestPhase.THIRD);
+ now.addAndGet(1000);
+ assertEquals(Status.COMPLETE, phase(TestPhase.SECOND).getStatus());
+ assertEquals(0, phase(TestPhase.THIRD).getElapsedTime());
+ assertTrue(progress.isComplete());
+ assertFalse(progress.isFailed());
+ assertEquals(150, progress.getElapsedTime());
+
+ // beginning a phase that has already ended has no effect
+ progress.beginPhase(TestPhase.SECOND);
+ assertEquals(Status.COMPLETE, phase(TestPhase.SECOND).getStatus());
+ assertEquals(50, phase(TestPhase.SECOND).getElapsedTime());
+ assertTrue(progress.isComplete());
+ assertEquals(150, progress.getElapsedTime());
+ }
+
+ @Test
+ void fail() {
+ progress.beginPhase(TestPhase.SECOND);
+ StartupProgress.Step step = progress.addStep(TestPhase.SECOND, "volume");
+ step.fail();
+ assertEquals(Status.FAILED, step.getStatus());
+ assertEquals(Status.RUNNING, phase(TestPhase.SECOND).getStatus());
+
+ now.addAndGet(100);
+ progress.fail();
+ now.addAndGet(100);
+ assertEquals(Status.COMPLETE, phase(TestPhase.FIRST).getStatus());
+ assertEquals(Status.FAILED, phase(TestPhase.SECOND).getStatus());
+ assertEquals(Status.PENDING, phase(TestPhase.THIRD).getStatus());
+ assertTrue(progress.isFailed());
+ assertFalse(progress.isComplete());
+ assertEquals(100, progress.getElapsedTime());
+ }
+
+ @Test
+ void remainingTimeOfConcurrentSteps() {
+ progress.beginPhase(TestPhase.FIRST);
+ StartupProgress.Step fast = progress.addStep(TestPhase.FIRST, "fast");
+ StartupProgress.Step slow = progress.addStep(TestPhase.FIRST, "slow");
+ assertEquals(-1, fast.getRemainingTime());
+
+ fast.setTotal(10);
+ slow.setTotal(30);
+ now.addAndGet(100);
+ for (int i = 0; i < 5; i++) {
+ fast.increment();
+ slow.increment();
+ }
+
+ assertEquals(100, fast.getRemainingTime());
+ assertEquals(500, slow.getRemainingTime());
+ assertEquals(500, phase(TestPhase.FIRST).getRemainingTime());
+ assertEquals(10, phase(TestPhase.FIRST).getDone());
+ assertEquals(40, phase(TestPhase.FIRST).getTotal());
+
+ fast.end();
+ assertEquals(Status.COMPLETE, fast.getStatus());
+ assertEquals(0, fast.getRemainingTime());
+ assertEquals(500, phase(TestPhase.FIRST).getRemainingTime());
+
+ // the phase may still have work to do after all steps are complete
+ slow.end();
+ assertEquals(Status.RUNNING, phase(TestPhase.FIRST).getStatus());
+ assertEquals(-1, phase(TestPhase.FIRST).getRemainingTime());
+ }
+
+ @Test
+ void jmx() throws Exception {
+ progress.beginPhase(TestPhase.FIRST);
+ StartupProgress.Step step = progress.addStep(TestPhase.FIRST, "volume");
+ step.setTotal(4);
+ step.increment();
+ progress.registerMXBean("TestStartupProgress");
+ try {
+ MBeanServer server = ManagementFactory.getPlatformMBeanServer();
+ ObjectName name = new
ObjectName("Hadoop:service=TestStartupProgress,name=StartupProgress");
+ assertEquals(false, server.getAttribute(name, "Complete"));
+ assertEquals(false, server.getAttribute(name, "Failed"));
+
+ CompositeData[] phases = (CompositeData[]) server.getAttribute(name,
"Phases");
+ assertEquals(3, phases.length);
+ assertEquals("FIRST", phases[0].get("name"));
+ assertEquals("RUNNING", phases[0].get("status"));
+ assertEquals("PENDING", phases[1].get("status"));
+
+ CompositeData[] steps = (CompositeData[]) phases[0].get("steps");
+ assertEquals(1, steps.length);
+ assertEquals("volume", steps[0].get("name"));
+ assertEquals(1L, steps[0].get("done"));
+ assertEquals(4L, steps[0].get("total"));
+ } finally {
+ progress.unregisterMXBean();
+ }
+ }
+
+ private PhaseInfo phase(TestPhase phase) {
+ return progress.getPhases().get(phase.ordinal());
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]