szetszwo commented on code in PR #10813: URL: https://github.com/apache/ozone/pull/10813#discussion_r3780635388
########## hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ContainerExportManager.java: ########## @@ -0,0 +1,363 @@ +/* + * 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.scm.container.export; + +import static org.apache.hadoop.hdds.scm.container.export.ExportLimits.DEFAULT_PAGE_SIZE; +import static org.apache.hadoop.hdds.scm.container.export.ExportLimits.DEFAULT_SHARD_SIZE; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayDeque; +import java.util.Comparator; +import java.util.Deque; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; +import java.util.stream.Collectors; +import org.apache.hadoop.hdds.conf.OzoneConfiguration; +import org.apache.hadoop.hdds.protocol.proto.HddsProtos.LifeCycleState; +import org.apache.hadoop.hdds.scm.container.ContainerHealthState; +import org.apache.hadoop.hdds.scm.container.ContainerID; +import org.apache.hadoop.hdds.scm.container.ContainerManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Manages asynchronous container ID export jobs on the SCM leader. + * + * <p>Health filters read {@link org.apache.hadoop.hdds.scm.container.ContainerInfo#getHealthState()} + * as last written by Replication Manager; they are not recomputed during export and may be stale + * if RM has not yet evaluated a container. + * + * <p>Job status is kept in memory only. On SCM restart or leader failover, in-flight jobs are lost + * and the operator must re-submit on the new leader. {@link ExportFileManager} owns on-disk layout, + * locking, shard files, and completed archives; this class tracks {@link ExportJob} state, + * schedules work, and applies {@code maxTerminalJobs} eviction. + */ +public class ContainerExportManager { + + private static final Logger LOG = LoggerFactory.getLogger(ContainerExportManager.class); + + //TODO: make ozone.scm.container.export.max.terminal.jobs configurable. + private static final int DEFAULT_MAX_TERMINAL_JOBS = 10; + private static final long SHUTDOWN_TIMEOUT_MS = 5_000; + + private final Map<ExportJob.Id, ExportJob> jobMap = new ConcurrentHashMap<>(); + private final Deque<String> completedArchivePaths = new ArrayDeque<>(); + private final AtomicReference<ExportJob.Id> runningJobId = new AtomicReference<>(); + private final ExecutorService workerPool; + private final ContainerManager containerManager; + private final ExportFileManager fileManager; + private final ExportMetrics metrics; + private final BooleanSupplier isLeaderReady; + private final int defaultShardSize; + private final int defaultPageSize; + private final int maxTerminalJobs; + /** SCM node id, used in the export worker thread name. */ + private final String scmId; + + public ContainerExportManager(ContainerManager containerManager, BooleanSupplier isLeaderReady, + OzoneConfiguration conf, String scmId) { + this.containerManager = Objects.requireNonNull(containerManager, "containerManager == null"); + this.isLeaderReady = Objects.requireNonNull(isLeaderReady, "isLeaderReady == null"); + this.fileManager = new ExportFileManager( + Objects.requireNonNull(ExportFileManager.resolveExportDirectory(conf), "exportDirectory == null")); Review Comment: Code like this is ugly. Think about how to make it better. ########## hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ContainerExportManager.java: ########## @@ -0,0 +1,363 @@ +/* + * 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.scm.container.export; + +import static org.apache.hadoop.hdds.scm.container.export.ExportLimits.DEFAULT_PAGE_SIZE; +import static org.apache.hadoop.hdds.scm.container.export.ExportLimits.DEFAULT_SHARD_SIZE; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayDeque; +import java.util.Comparator; +import java.util.Deque; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; +import java.util.stream.Collectors; +import org.apache.hadoop.hdds.conf.OzoneConfiguration; +import org.apache.hadoop.hdds.protocol.proto.HddsProtos.LifeCycleState; +import org.apache.hadoop.hdds.scm.container.ContainerHealthState; +import org.apache.hadoop.hdds.scm.container.ContainerID; +import org.apache.hadoop.hdds.scm.container.ContainerManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Manages asynchronous container ID export jobs on the SCM leader. + * + * <p>Health filters read {@link org.apache.hadoop.hdds.scm.container.ContainerInfo#getHealthState()} + * as last written by Replication Manager; they are not recomputed during export and may be stale + * if RM has not yet evaluated a container. + * + * <p>Job status is kept in memory only. On SCM restart or leader failover, in-flight jobs are lost + * and the operator must re-submit on the new leader. {@link ExportFileManager} owns on-disk layout, + * locking, shard files, and completed archives; this class tracks {@link ExportJob} state, + * schedules work, and applies {@code maxTerminalJobs} eviction. + */ +public class ContainerExportManager { + + private static final Logger LOG = LoggerFactory.getLogger(ContainerExportManager.class); + + //TODO: make ozone.scm.container.export.max.terminal.jobs configurable. + private static final int DEFAULT_MAX_TERMINAL_JOBS = 10; + private static final long SHUTDOWN_TIMEOUT_MS = 5_000; + + private final Map<ExportJob.Id, ExportJob> jobMap = new ConcurrentHashMap<>(); + private final Deque<String> completedArchivePaths = new ArrayDeque<>(); + private final AtomicReference<ExportJob.Id> runningJobId = new AtomicReference<>(); + private final ExecutorService workerPool; + private final ContainerManager containerManager; + private final ExportFileManager fileManager; + private final ExportMetrics metrics; + private final BooleanSupplier isLeaderReady; + private final int defaultShardSize; + private final int defaultPageSize; + private final int maxTerminalJobs; + /** SCM node id, used in the export worker thread name. */ + private final String scmId; + + public ContainerExportManager(ContainerManager containerManager, BooleanSupplier isLeaderReady, + OzoneConfiguration conf, String scmId) { + this.containerManager = Objects.requireNonNull(containerManager, "containerManager == null"); + this.isLeaderReady = Objects.requireNonNull(isLeaderReady, "isLeaderReady == null"); + this.fileManager = new ExportFileManager( + Objects.requireNonNull(ExportFileManager.resolveExportDirectory(conf), "exportDirectory == null")); + this.scmId = Objects.requireNonNull(scmId, "scmId == null"); + this.defaultShardSize = DEFAULT_SHARD_SIZE; + this.defaultPageSize = DEFAULT_PAGE_SIZE; + this.maxTerminalJobs = DEFAULT_MAX_TERMINAL_JOBS; + this.metrics = ExportMetrics.create(); + this.workerPool = newWorkerPool(this.scmId); + } + + ContainerExportManager(ContainerManager containerManager, BooleanSupplier isLeaderReady, + String exportDirectory, int defaultShardSize, int defaultPageSize, int maxTerminalJobs, + String scmId) { + this.containerManager = Objects.requireNonNull(containerManager, "containerManager == null"); + this.isLeaderReady = Objects.requireNonNull(isLeaderReady, "isLeaderReady == null"); + this.fileManager = new ExportFileManager(Objects.requireNonNull(exportDirectory, "exportDirectory == null")); + this.scmId = Objects.requireNonNull(scmId, "scmId == null"); + this.defaultShardSize = defaultShardSize; + this.defaultPageSize = defaultPageSize; + this.maxTerminalJobs = maxTerminalJobs; + this.metrics = null; + this.workerPool = newWorkerPool(this.scmId); + } + + private static ExecutorService newWorkerPool(String scmId) { + return Executors.newSingleThreadExecutor(r -> { + Thread t = new Thread(r, scmId + "-ContainerExportWorker"); + t.setDaemon(true); + return t; + }); + } + + /** + * Initializes the export directory. Must be called once before submitting jobs. + */ + public void start() throws IOException { + fileManager.start(); + reloadCompletedArchives(); + LOG.info("ContainerExportManager started (dir={}, defaultShardSize={}, defaultPageSize={}, maxTerminalJobs={})", + fileManager.getExportDirectory(), defaultShardSize, defaultPageSize, maxTerminalJobs); + } + + /** + * Submit a container ID export job on the SCM leader. + * Batch sizing is described by {@link ExportSizing}. + * + * @return job id, or {@code null} if not leader or another export is already running + */ + public ExportJob.Id submitJob(ContainerID start, LifeCycleState lifeCycleState, + ContainerHealthState healthState, long maxRows, int pageSize, int shardSize) { + if (!isLeaderReady.getAsBoolean()) { + return null; + } + if (lifeCycleState == null && healthState == null) { + throw new IllegalArgumentException("At least one of healthState or lifecycleState filter is required."); + } + validateRequest(start); + ExportSizing.validate(maxRows, pageSize, shardSize); + ExportSizing sizing = ExportSizing.resolve(maxRows, pageSize, shardSize, defaultPageSize, defaultShardSize); + + ExportJob.Id jobId = ExportJob.Id.newId(); + if (!runningJobId.compareAndSet(null, jobId)) { + return null; + } + + ExportScope scope = ExportScope.of(lifeCycleState, healthState); + Instant now = Instant.now(); + String metadataTimestamp = ExportFileManager.formatMetadataTimestamp(now); + String tarPath = fileManager.resolveArchivePath(scope, now, jobId); + + ExportJob job = new ExportJob(jobId, scope, metadataTimestamp, tarPath, start, sizing); + + evictOldTerminalJobs(); + jobMap.put(jobId, job); + + if (metrics != null) { + metrics.incrExportJobsSubmitted(); + } + + workerPool.submit(() -> executeExport(job)); + LOG.info("Submitted container ID export job {} (scope={}, start={}, maxRows={}, pageSize={}, shardSize={})", + jobId, scope, start, sizing.getMaxRows(), sizing.getPageSize(), sizing.getShardSize()); + return jobId; + } + + private static void validateRequest(ContainerID start) { + if (start != null && start.getProtobuf().getId() < 0) { Review Comment: Is it possible to create a ContainerID with id < 0 ? ########## hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ContainerExportManager.java: ########## @@ -0,0 +1,363 @@ +/* + * 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.scm.container.export; + +import static org.apache.hadoop.hdds.scm.container.export.ExportLimits.DEFAULT_PAGE_SIZE; +import static org.apache.hadoop.hdds.scm.container.export.ExportLimits.DEFAULT_SHARD_SIZE; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayDeque; +import java.util.Comparator; +import java.util.Deque; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; +import java.util.stream.Collectors; +import org.apache.hadoop.hdds.conf.OzoneConfiguration; +import org.apache.hadoop.hdds.protocol.proto.HddsProtos.LifeCycleState; +import org.apache.hadoop.hdds.scm.container.ContainerHealthState; +import org.apache.hadoop.hdds.scm.container.ContainerID; +import org.apache.hadoop.hdds.scm.container.ContainerManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Manages asynchronous container ID export jobs on the SCM leader. + * + * <p>Health filters read {@link org.apache.hadoop.hdds.scm.container.ContainerInfo#getHealthState()} + * as last written by Replication Manager; they are not recomputed during export and may be stale + * if RM has not yet evaluated a container. + * + * <p>Job status is kept in memory only. On SCM restart or leader failover, in-flight jobs are lost + * and the operator must re-submit on the new leader. {@link ExportFileManager} owns on-disk layout, + * locking, shard files, and completed archives; this class tracks {@link ExportJob} state, + * schedules work, and applies {@code maxTerminalJobs} eviction. + */ +public class ContainerExportManager { + + private static final Logger LOG = LoggerFactory.getLogger(ContainerExportManager.class); + + //TODO: make ozone.scm.container.export.max.terminal.jobs configurable. + private static final int DEFAULT_MAX_TERMINAL_JOBS = 10; + private static final long SHUTDOWN_TIMEOUT_MS = 5_000; + + private final Map<ExportJob.Id, ExportJob> jobMap = new ConcurrentHashMap<>(); + private final Deque<String> completedArchivePaths = new ArrayDeque<>(); + private final AtomicReference<ExportJob.Id> runningJobId = new AtomicReference<>(); + private final ExecutorService workerPool; + private final ContainerManager containerManager; + private final ExportFileManager fileManager; + private final ExportMetrics metrics; Review Comment: Since the change is still quite big, let's add metrics later. We can add it with the conf. ########## hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ContainerExportManager.java: ########## @@ -0,0 +1,363 @@ +/* + * 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.scm.container.export; + +import static org.apache.hadoop.hdds.scm.container.export.ExportLimits.DEFAULT_PAGE_SIZE; +import static org.apache.hadoop.hdds.scm.container.export.ExportLimits.DEFAULT_SHARD_SIZE; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayDeque; +import java.util.Comparator; +import java.util.Deque; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; +import java.util.stream.Collectors; +import org.apache.hadoop.hdds.conf.OzoneConfiguration; +import org.apache.hadoop.hdds.protocol.proto.HddsProtos.LifeCycleState; +import org.apache.hadoop.hdds.scm.container.ContainerHealthState; +import org.apache.hadoop.hdds.scm.container.ContainerID; +import org.apache.hadoop.hdds.scm.container.ContainerManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Manages asynchronous container ID export jobs on the SCM leader. + * + * <p>Health filters read {@link org.apache.hadoop.hdds.scm.container.ContainerInfo#getHealthState()} + * as last written by Replication Manager; they are not recomputed during export and may be stale + * if RM has not yet evaluated a container. + * + * <p>Job status is kept in memory only. On SCM restart or leader failover, in-flight jobs are lost + * and the operator must re-submit on the new leader. {@link ExportFileManager} owns on-disk layout, + * locking, shard files, and completed archives; this class tracks {@link ExportJob} state, + * schedules work, and applies {@code maxTerminalJobs} eviction. + */ +public class ContainerExportManager { + + private static final Logger LOG = LoggerFactory.getLogger(ContainerExportManager.class); + + //TODO: make ozone.scm.container.export.max.terminal.jobs configurable. + private static final int DEFAULT_MAX_TERMINAL_JOBS = 10; + private static final long SHUTDOWN_TIMEOUT_MS = 5_000; + + private final Map<ExportJob.Id, ExportJob> jobMap = new ConcurrentHashMap<>(); + private final Deque<String> completedArchivePaths = new ArrayDeque<>(); + private final AtomicReference<ExportJob.Id> runningJobId = new AtomicReference<>(); + private final ExecutorService workerPool; + private final ContainerManager containerManager; + private final ExportFileManager fileManager; + private final ExportMetrics metrics; + private final BooleanSupplier isLeaderReady; + private final int defaultShardSize; + private final int defaultPageSize; + private final int maxTerminalJobs; + /** SCM node id, used in the export worker thread name. */ + private final String scmId; + + public ContainerExportManager(ContainerManager containerManager, BooleanSupplier isLeaderReady, + OzoneConfiguration conf, String scmId) { + this.containerManager = Objects.requireNonNull(containerManager, "containerManager == null"); + this.isLeaderReady = Objects.requireNonNull(isLeaderReady, "isLeaderReady == null"); + this.fileManager = new ExportFileManager( + Objects.requireNonNull(ExportFileManager.resolveExportDirectory(conf), "exportDirectory == null")); + this.scmId = Objects.requireNonNull(scmId, "scmId == null"); + this.defaultShardSize = DEFAULT_SHARD_SIZE; + this.defaultPageSize = DEFAULT_PAGE_SIZE; + this.maxTerminalJobs = DEFAULT_MAX_TERMINAL_JOBS; + this.metrics = ExportMetrics.create(); + this.workerPool = newWorkerPool(this.scmId); + } + + ContainerExportManager(ContainerManager containerManager, BooleanSupplier isLeaderReady, + String exportDirectory, int defaultShardSize, int defaultPageSize, int maxTerminalJobs, + String scmId) { + this.containerManager = Objects.requireNonNull(containerManager, "containerManager == null"); + this.isLeaderReady = Objects.requireNonNull(isLeaderReady, "isLeaderReady == null"); + this.fileManager = new ExportFileManager(Objects.requireNonNull(exportDirectory, "exportDirectory == null")); + this.scmId = Objects.requireNonNull(scmId, "scmId == null"); + this.defaultShardSize = defaultShardSize; + this.defaultPageSize = defaultPageSize; + this.maxTerminalJobs = maxTerminalJobs; + this.metrics = null; + this.workerPool = newWorkerPool(this.scmId); + } + + private static ExecutorService newWorkerPool(String scmId) { + return Executors.newSingleThreadExecutor(r -> { + Thread t = new Thread(r, scmId + "-ContainerExportWorker"); + t.setDaemon(true); + return t; + }); + } + + /** + * Initializes the export directory. Must be called once before submitting jobs. + */ + public void start() throws IOException { + fileManager.start(); + reloadCompletedArchives(); + LOG.info("ContainerExportManager started (dir={}, defaultShardSize={}, defaultPageSize={}, maxTerminalJobs={})", + fileManager.getExportDirectory(), defaultShardSize, defaultPageSize, maxTerminalJobs); + } + + /** + * Submit a container ID export job on the SCM leader. + * Batch sizing is described by {@link ExportSizing}. + * + * @return job id, or {@code null} if not leader or another export is already running + */ + public ExportJob.Id submitJob(ContainerID start, LifeCycleState lifeCycleState, + ContainerHealthState healthState, long maxRows, int pageSize, int shardSize) { + if (!isLeaderReady.getAsBoolean()) { + return null; + } + if (lifeCycleState == null && healthState == null) { + throw new IllegalArgumentException("At least one of healthState or lifecycleState filter is required."); + } + validateRequest(start); Review Comment: Move lifeCycleState == null && healthState inside validateRequest(..). ########## hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ContainerExportManager.java: ########## @@ -0,0 +1,363 @@ +/* + * 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.scm.container.export; + +import static org.apache.hadoop.hdds.scm.container.export.ExportLimits.DEFAULT_PAGE_SIZE; +import static org.apache.hadoop.hdds.scm.container.export.ExportLimits.DEFAULT_SHARD_SIZE; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayDeque; +import java.util.Comparator; +import java.util.Deque; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; +import java.util.stream.Collectors; +import org.apache.hadoop.hdds.conf.OzoneConfiguration; +import org.apache.hadoop.hdds.protocol.proto.HddsProtos.LifeCycleState; +import org.apache.hadoop.hdds.scm.container.ContainerHealthState; +import org.apache.hadoop.hdds.scm.container.ContainerID; +import org.apache.hadoop.hdds.scm.container.ContainerManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Manages asynchronous container ID export jobs on the SCM leader. + * + * <p>Health filters read {@link org.apache.hadoop.hdds.scm.container.ContainerInfo#getHealthState()} + * as last written by Replication Manager; they are not recomputed during export and may be stale + * if RM has not yet evaluated a container. + * + * <p>Job status is kept in memory only. On SCM restart or leader failover, in-flight jobs are lost + * and the operator must re-submit on the new leader. {@link ExportFileManager} owns on-disk layout, + * locking, shard files, and completed archives; this class tracks {@link ExportJob} state, + * schedules work, and applies {@code maxTerminalJobs} eviction. + */ +public class ContainerExportManager { + + private static final Logger LOG = LoggerFactory.getLogger(ContainerExportManager.class); + + //TODO: make ozone.scm.container.export.max.terminal.jobs configurable. + private static final int DEFAULT_MAX_TERMINAL_JOBS = 10; + private static final long SHUTDOWN_TIMEOUT_MS = 5_000; + + private final Map<ExportJob.Id, ExportJob> jobMap = new ConcurrentHashMap<>(); + private final Deque<String> completedArchivePaths = new ArrayDeque<>(); + private final AtomicReference<ExportJob.Id> runningJobId = new AtomicReference<>(); + private final ExecutorService workerPool; + private final ContainerManager containerManager; + private final ExportFileManager fileManager; + private final ExportMetrics metrics; + private final BooleanSupplier isLeaderReady; + private final int defaultShardSize; + private final int defaultPageSize; Review Comment: Remove "default". ########## hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ContainerExportManager.java: ########## @@ -0,0 +1,363 @@ +/* + * 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.scm.container.export; + +import static org.apache.hadoop.hdds.scm.container.export.ExportLimits.DEFAULT_PAGE_SIZE; +import static org.apache.hadoop.hdds.scm.container.export.ExportLimits.DEFAULT_SHARD_SIZE; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayDeque; +import java.util.Comparator; +import java.util.Deque; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; +import java.util.stream.Collectors; +import org.apache.hadoop.hdds.conf.OzoneConfiguration; +import org.apache.hadoop.hdds.protocol.proto.HddsProtos.LifeCycleState; +import org.apache.hadoop.hdds.scm.container.ContainerHealthState; +import org.apache.hadoop.hdds.scm.container.ContainerID; +import org.apache.hadoop.hdds.scm.container.ContainerManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Manages asynchronous container ID export jobs on the SCM leader. + * + * <p>Health filters read {@link org.apache.hadoop.hdds.scm.container.ContainerInfo#getHealthState()} + * as last written by Replication Manager; they are not recomputed during export and may be stale + * if RM has not yet evaluated a container. + * + * <p>Job status is kept in memory only. On SCM restart or leader failover, in-flight jobs are lost + * and the operator must re-submit on the new leader. {@link ExportFileManager} owns on-disk layout, + * locking, shard files, and completed archives; this class tracks {@link ExportJob} state, + * schedules work, and applies {@code maxTerminalJobs} eviction. + */ +public class ContainerExportManager { + + private static final Logger LOG = LoggerFactory.getLogger(ContainerExportManager.class); + + //TODO: make ozone.scm.container.export.max.terminal.jobs configurable. + private static final int DEFAULT_MAX_TERMINAL_JOBS = 10; + private static final long SHUTDOWN_TIMEOUT_MS = 5_000; + + private final Map<ExportJob.Id, ExportJob> jobMap = new ConcurrentHashMap<>(); + private final Deque<String> completedArchivePaths = new ArrayDeque<>(); + private final AtomicReference<ExportJob.Id> runningJobId = new AtomicReference<>(); + private final ExecutorService workerPool; + private final ContainerManager containerManager; + private final ExportFileManager fileManager; + private final ExportMetrics metrics; + private final BooleanSupplier isLeaderReady; + private final int defaultShardSize; + private final int defaultPageSize; + private final int maxTerminalJobs; + /** SCM node id, used in the export worker thread name. */ + private final String scmId; + + public ContainerExportManager(ContainerManager containerManager, BooleanSupplier isLeaderReady, + OzoneConfiguration conf, String scmId) { + this.containerManager = Objects.requireNonNull(containerManager, "containerManager == null"); + this.isLeaderReady = Objects.requireNonNull(isLeaderReady, "isLeaderReady == null"); + this.fileManager = new ExportFileManager( + Objects.requireNonNull(ExportFileManager.resolveExportDirectory(conf), "exportDirectory == null")); + this.scmId = Objects.requireNonNull(scmId, "scmId == null"); + this.defaultShardSize = DEFAULT_SHARD_SIZE; + this.defaultPageSize = DEFAULT_PAGE_SIZE; + this.maxTerminalJobs = DEFAULT_MAX_TERMINAL_JOBS; + this.metrics = ExportMetrics.create(); + this.workerPool = newWorkerPool(this.scmId); + } + + ContainerExportManager(ContainerManager containerManager, BooleanSupplier isLeaderReady, + String exportDirectory, int defaultShardSize, int defaultPageSize, int maxTerminalJobs, + String scmId) { + this.containerManager = Objects.requireNonNull(containerManager, "containerManager == null"); + this.isLeaderReady = Objects.requireNonNull(isLeaderReady, "isLeaderReady == null"); + this.fileManager = new ExportFileManager(Objects.requireNonNull(exportDirectory, "exportDirectory == null")); + this.scmId = Objects.requireNonNull(scmId, "scmId == null"); + this.defaultShardSize = defaultShardSize; + this.defaultPageSize = defaultPageSize; + this.maxTerminalJobs = maxTerminalJobs; + this.metrics = null; + this.workerPool = newWorkerPool(this.scmId); + } Review Comment: Always try to minimize code duplication -- Combine these two constructors: ```java public ContainerExportManager(String scmId, ContainerManager containerManager, BooleanSupplier isLeaderReady, OzoneConfiguration conf) { this(scmId, containerManager, isLeaderReady, ExportFileManager.resolveExportDirectory(conf), DEFAULT_SHARD_SIZE, DEFAULT_PAGE_SIZE, DEFAULT_MAX_TERMINAL_JOBS); } ContainerExportManager(String scmId, ContainerManager containerManager, BooleanSupplier isLeaderReady, String exportDirectory, int defaultShardSize, int defaultPageSize, int maxTerminalJobs) { this.containerManager = Objects.requireNonNull(containerManager, "containerManager == null"); this.isLeaderReady = Objects.requireNonNull(isLeaderReady, "isLeaderReady == null"); this.fileManager = new ExportFileManager(exportDirectory); this.defaultShardSize = defaultShardSize; this.defaultPageSize = defaultPageSize; this.maxTerminalJobs = maxTerminalJobs; this.metrics = null; this.workerPool = newWorkerPool(scmId); } ``` ########## hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ContainerExportManager.java: ########## @@ -0,0 +1,363 @@ +/* + * 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.scm.container.export; + +import static org.apache.hadoop.hdds.scm.container.export.ExportLimits.DEFAULT_PAGE_SIZE; +import static org.apache.hadoop.hdds.scm.container.export.ExportLimits.DEFAULT_SHARD_SIZE; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayDeque; +import java.util.Comparator; +import java.util.Deque; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; +import java.util.stream.Collectors; +import org.apache.hadoop.hdds.conf.OzoneConfiguration; +import org.apache.hadoop.hdds.protocol.proto.HddsProtos.LifeCycleState; +import org.apache.hadoop.hdds.scm.container.ContainerHealthState; +import org.apache.hadoop.hdds.scm.container.ContainerID; +import org.apache.hadoop.hdds.scm.container.ContainerManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Manages asynchronous container ID export jobs on the SCM leader. + * + * <p>Health filters read {@link org.apache.hadoop.hdds.scm.container.ContainerInfo#getHealthState()} + * as last written by Replication Manager; they are not recomputed during export and may be stale + * if RM has not yet evaluated a container. + * + * <p>Job status is kept in memory only. On SCM restart or leader failover, in-flight jobs are lost + * and the operator must re-submit on the new leader. {@link ExportFileManager} owns on-disk layout, + * locking, shard files, and completed archives; this class tracks {@link ExportJob} state, + * schedules work, and applies {@code maxTerminalJobs} eviction. + */ +public class ContainerExportManager { + + private static final Logger LOG = LoggerFactory.getLogger(ContainerExportManager.class); + + //TODO: make ozone.scm.container.export.max.terminal.jobs configurable. + private static final int DEFAULT_MAX_TERMINAL_JOBS = 10; + private static final long SHUTDOWN_TIMEOUT_MS = 5_000; + + private final Map<ExportJob.Id, ExportJob> jobMap = new ConcurrentHashMap<>(); + private final Deque<String> completedArchivePaths = new ArrayDeque<>(); + private final AtomicReference<ExportJob.Id> runningJobId = new AtomicReference<>(); + private final ExecutorService workerPool; + private final ContainerManager containerManager; + private final ExportFileManager fileManager; + private final ExportMetrics metrics; + private final BooleanSupplier isLeaderReady; + private final int defaultShardSize; + private final int defaultPageSize; + private final int maxTerminalJobs; + /** SCM node id, used in the export worker thread name. */ + private final String scmId; + + public ContainerExportManager(ContainerManager containerManager, BooleanSupplier isLeaderReady, + OzoneConfiguration conf, String scmId) { + this.containerManager = Objects.requireNonNull(containerManager, "containerManager == null"); + this.isLeaderReady = Objects.requireNonNull(isLeaderReady, "isLeaderReady == null"); + this.fileManager = new ExportFileManager( + Objects.requireNonNull(ExportFileManager.resolveExportDirectory(conf), "exportDirectory == null")); + this.scmId = Objects.requireNonNull(scmId, "scmId == null"); + this.defaultShardSize = DEFAULT_SHARD_SIZE; + this.defaultPageSize = DEFAULT_PAGE_SIZE; + this.maxTerminalJobs = DEFAULT_MAX_TERMINAL_JOBS; + this.metrics = ExportMetrics.create(); + this.workerPool = newWorkerPool(this.scmId); + } + + ContainerExportManager(ContainerManager containerManager, BooleanSupplier isLeaderReady, + String exportDirectory, int defaultShardSize, int defaultPageSize, int maxTerminalJobs, + String scmId) { + this.containerManager = Objects.requireNonNull(containerManager, "containerManager == null"); + this.isLeaderReady = Objects.requireNonNull(isLeaderReady, "isLeaderReady == null"); + this.fileManager = new ExportFileManager(Objects.requireNonNull(exportDirectory, "exportDirectory == null")); + this.scmId = Objects.requireNonNull(scmId, "scmId == null"); + this.defaultShardSize = defaultShardSize; + this.defaultPageSize = defaultPageSize; + this.maxTerminalJobs = maxTerminalJobs; + this.metrics = null; + this.workerPool = newWorkerPool(this.scmId); + } + + private static ExecutorService newWorkerPool(String scmId) { + return Executors.newSingleThreadExecutor(r -> { + Thread t = new Thread(r, scmId + "-ContainerExportWorker"); + t.setDaemon(true); + return t; + }); + } + + /** + * Initializes the export directory. Must be called once before submitting jobs. + */ + public void start() throws IOException { + fileManager.start(); + reloadCompletedArchives(); + LOG.info("ContainerExportManager started (dir={}, defaultShardSize={}, defaultPageSize={}, maxTerminalJobs={})", + fileManager.getExportDirectory(), defaultShardSize, defaultPageSize, maxTerminalJobs); + } + + /** + * Submit a container ID export job on the SCM leader. + * Batch sizing is described by {@link ExportSizing}. + * + * @return job id, or {@code null} if not leader or another export is already running + */ + public ExportJob.Id submitJob(ContainerID start, LifeCycleState lifeCycleState, + ContainerHealthState healthState, long maxRows, int pageSize, int shardSize) { + if (!isLeaderReady.getAsBoolean()) { + return null; + } + if (lifeCycleState == null && healthState == null) { + throw new IllegalArgumentException("At least one of healthState or lifecycleState filter is required."); + } + validateRequest(start); + ExportSizing.validate(maxRows, pageSize, shardSize); + ExportSizing sizing = ExportSizing.resolve(maxRows, pageSize, shardSize, defaultPageSize, defaultShardSize); Review Comment: - Remove ExportSizing.validate(..) and ExportSizing.resolve(..). - Move all the logic to ExportSizing(..) constructor. Such a simple logic should not be split into three methods. ########## hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/container/export/ExportLimits.java: ########## @@ -0,0 +1,34 @@ +/* + * 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.scm.container.export; + +/** + * Shared limits and defaults for container ID export. + */ +public final class ExportLimits { + + public static final String EXPORT_SUBDIR = "exports"; + + public static final int DEFAULT_PAGE_SIZE = 100_000; + public static final int DEFAULT_SHARD_SIZE = 500_000; + public static final int MAX_PAGE_SIZE = 1_000_000; + public static final int MAX_SHARD_SIZE = 5_000_000; Review Comment: Add javadoc to explain: - What are "page" and "shard". - What are default and max? ########## hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ExportJob.java: ########## @@ -69,6 +87,190 @@ public int hashCode() { } } - private ExportJob() { + /** + * Snapshot of export progress returned to callers. Reads live fields from the enclosing job. + */ + public final class Status { + private Status() { + } + + public Id getId() { + return id; + } + + public ExecutionState getExecutionState() { + return ExportJob.this.getExecutionState(); + } + + public long getTotalRows() { + return ExportJob.this.getTotalRows(); + } + + public long getElapsedMs() { + return ExportJob.this.getElapsedMs(); + } + + public String getTarPath() { + return ExportJob.this.getTarPath(); + } + + public String getErrorMessage() { + return ExportJob.this.getErrorMessage(); + } + } + + /** + * Job execution state. + */ + public enum ExecutionState { + RUNNING(false), + SUCCEEDED(true), + FAILED(true); + + private final boolean terminal; + + ExecutionState(boolean terminal) { + this.terminal = terminal; + } + + public boolean isTerminal() { + return terminal; + } + } + + ExportJob(Id id, ExportScope scope, String timestamp, String tarPath, ContainerID startContainerId, + ExportSizing sizing) { + this.id = id; + this.scope = scope; + this.timestamp = timestamp; + this.tarPath = tarPath; + this.startContainerId = startContainerId != null ? startContainerId : ContainerID.valueOf(0); + this.sizing = sizing; + } + + Id getId() { + return id; + } + + String getTimestamp() { + return timestamp; + } + + ContainerID getStartContainerId() { + return startContainerId; + } + + LifeCycleState getLifeCycleState() { + return scope.getLifeCycleState(); + } + + ContainerHealthState getHealthState() { + return scope.getHealthState(); + } + + long getMaxRows() { + return sizing.getMaxRows(); + } + + int getPageSize() { + return sizing.getPageSize(); + } + + int getShardSize() { + return sizing.getShardSize(); + } + + synchronized String getTarPath() { + return tarPath; + } + + synchronized ExecutionState getExecutionState() { + return executionState; + } + + synchronized long getEndTimeNs() { + return endTimeNs; + } + + synchronized long getTotalRows() { + return totalRows; + } + + synchronized long getElapsedMs() { + if (startTimeNs <= 0) { + return 0; + } + long endNs = endTimeNs > 0 ? endTimeNs : System.nanoTime(); + return TimeUnit.NANOSECONDS.toMillis(endNs - startTimeNs); + } + + synchronized String getErrorMessage() { + return errorMessage; + } + + synchronized void startExecution() { + if (executionState.isTerminal()) { + throw new IllegalStateException("Export job " + id + " is already terminal: " + executionState); + } + startTimeNs = System.nanoTime(); + } + + synchronized void updateTotalRows(long rows) { + totalRows = rows; + } + + synchronized void completeWithNoMatches() { + tarPath = null; + transitionToTerminal(ExecutionState.SUCCEEDED); + } + + synchronized void completeWithArchive(String archivePath) { + tarPath = archivePath; + transitionToTerminal(ExecutionState.SUCCEEDED); + } + + synchronized void fail(String message) { + errorMessage = message; + transitionToTerminal(ExecutionState.FAILED); + } + + private synchronized void transitionToTerminal(ExecutionState terminalState) { + if (executionState.isTerminal()) { + throw new IllegalStateException("Export job " + id + " is already terminal: " + executionState); + } + executionState = terminalState; + endTimeNs = System.nanoTime(); + } + + Status toStatus() { + return new Status(); + } + + String shardFileName(int partIndex) { + return String.format("container-ids_%s_%s_part%03d.txt", + scope.getValue(), timestamp, partIndex); Review Comment: timestamp has METADATA_TIMESTAMP_FORMAT which has ":". We should never use ":" in a file name. ########## hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ExportFileManager.java: ########## @@ -82,6 +94,10 @@ final class ExportFileManager { static final String EXPORT_ARCHIVE_TMP_SUFFIX = EXPORT_ARCHIVE_SUFFIX + AtomicFileOutputStream.TMP_EXTENSION; static final String EXPORT_LOCK_NAME = "in_use.lock"; private static final int ARCHIVE_TIMESTAMP_LENGTH = 16; + private static final DateTimeFormatter ARCHIVE_TIMESTAMP_FORMAT = + DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC); + private static final DateTimeFormatter METADATA_TIMESTAMP_FORMAT = + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").withZone(ZoneOffset.UTC); Review Comment: Let's use only one format. ```java DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss").withZone(ZoneOffset.UTC); ``` -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
