This is an automated email from the ASF dual-hosted git repository. smengcl pushed a commit to branch ozone-2.1 in repository https://gitbox.apache.org/repos/asf/ozone.git
commit 6ec59a7e3cfe8f1c4356d986c9b572d431dc7771 Author: Siyao Meng <[email protected]> AuthorDate: Fri Nov 6 05:13:06 2026 -0800 HDDS-17721. Recon should download SCM DB over HTTP(S) when gRPC TLS is enabled (#11954) Co-authored-by: Claude Opus 5.5 <[email protected]> (cherry picked from commit 889767e078fbc1382db42bbebba1edca9b92c87f) --- .../common/src/main/resources/ozone-default.xml | 19 ++ .../apache/hadoop/hdds/utils/HddsServerUtil.java | 2 +- .../hdds/scm/server/SCMDBCheckpointServlet.java | 32 ++- .../hdds/scm/TestSCMDbCheckpointServlet.java | 8 + .../hadoop/ozone/recon/ReconServerConfigKeys.java | 7 + .../impl/StorageContainerServiceProviderImpl.java | 172 ++++++++++-- .../TestStorageContainerServiceProviderImpl.java | 294 ++++++++++++++++++++- 7 files changed, 512 insertions(+), 22 deletions(-) diff --git a/hadoop-hdds/common/src/main/resources/ozone-default.xml b/hadoop-hdds/common/src/main/resources/ozone-default.xml index cae8d2cdd0b..49168192faa 100644 --- a/hadoop-hdds/common/src/main/resources/ozone-default.xml +++ b/hadoop-hdds/common/src/main/resources/ozone-default.xml @@ -3489,6 +3489,25 @@ If enabled, SCM DB Snapshot is taken by Recon. </description> </property> + <property> + <name>ozone.recon.scm.snapshot.connection.timeout</name> + <value>60s</value> + <tag>OZONE, RECON, SCM</tag> + <description> + Connection timeout for the HTTP(S) call made by Recon to download the SCM DB checkpoint, + used when hdds.grpc.tls.enabled is true. + </description> + </property> + <property> + <name>ozone.recon.scm.snapshot.read.timeout</name> + <value>10m</value> + <tag>OZONE, RECON, SCM</tag> + <description> + Read timeout for the HTTP(S) call made by Recon to download the SCM DB checkpoint, + used when hdds.grpc.tls.enabled is true. SCM creates the checkpoint before it sends + any data, so this should cover the checkpoint creation time. + </description> + </property> <property> <name>hdds.tracing.enabled</name> <value>false</value> diff --git a/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/utils/HddsServerUtil.java b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/utils/HddsServerUtil.java index 2da0e3b0cdf..6b7a7bcc6ba 100644 --- a/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/utils/HddsServerUtil.java +++ b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/utils/HddsServerUtil.java @@ -654,7 +654,7 @@ public static void includeRatisSnapshotCompleteFlag( includeFile(file, OZONE_RATIS_SNAPSHOT_COMPLETE_FLAG_NAME, archiveOutput); } - static boolean ratisSnapshotComplete(Path dir) { + public static boolean ratisSnapshotComplete(Path dir) { return new File(dir.toString(), OZONE_RATIS_SNAPSHOT_COMPLETE_FLAG_NAME).exists(); } diff --git a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/SCMDBCheckpointServlet.java b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/SCMDBCheckpointServlet.java index 275228a5fe5..f6ea39cccc1 100644 --- a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/SCMDBCheckpointServlet.java +++ b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/SCMDBCheckpointServlet.java @@ -19,9 +19,16 @@ import static org.apache.hadoop.hdds.scm.server.SCMHTTPServerConfig.ConfigStrings.HDDS_SCM_HTTP_AUTH_TYPE; +import java.io.IOException; +import java.nio.file.Path; +import java.util.Collection; +import java.util.LinkedHashSet; import javax.servlet.ServletException; +import org.apache.hadoop.hdds.recon.ReconConfig; import org.apache.hadoop.hdds.utils.DBCheckpointServlet; +import org.apache.hadoop.hdds.utils.db.DBCheckpoint; import org.apache.hadoop.ozone.OzoneConsts; +import org.apache.hadoop.security.UserGroupInformation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -37,17 +44,20 @@ * `ozone.administrator`, e.g. `scm/[email protected]` * If Kerberos is not enabled, simply append the login user name to * `ozone.administrator`, e.g. `scm` + * + * Recon (`ozone.recon.kerberos.principal`) is also allowed, to download the SCM DB. */ public class SCMDBCheckpointServlet extends DBCheckpointServlet { private static final Logger LOG = LoggerFactory.getLogger(SCMDBCheckpointServlet.class); private static final long serialVersionUID = 1L; + private transient StorageContainerManager scm; @Override public void init() throws ServletException { - StorageContainerManager scm = (StorageContainerManager) getServletContext() + scm = (StorageContainerManager) getServletContext() .getAttribute(OzoneConsts.SCM_CONTEXT_ATTRIBUTE); if (scm == null) { @@ -57,11 +67,29 @@ public void init() throws ServletException { // SCM admin checks are not configurable on this branch, so SPNEGO alone enables the check. final boolean spnegoEnabled = "kerberos".equals(scm.getConfiguration().get(HDDS_SCM_HTTP_AUTH_TYPE, "simple")); + + // Only SCM admins and Recon are allowed + Collection<String> allowedUsers = new LinkedHashSet<>(scm.getScmAdminUsernames()); + String reconPrincipal = scm.getConfiguration().getObject(ReconConfig.class).getKerberosPrincipal(); + if (!reconPrincipal.isEmpty()) { + allowedUsers.add(UserGroupInformation.createRemoteUser(reconPrincipal).getShortUserName()); + } + initialize(scm.getScmMetadataStore().getStore(), scm.getMetrics().getDBCheckpointMetrics(), spnegoEnabled, - scm.getScmAdminUsernames(), + allowedUsers, scm.getScmAdminGroups(), spnegoEnabled); } + + /** + * Like the inter-SCM gRPC download, flushes the SCM transaction buffer and looks up the store per request, + * because installing a checkpoint replaces it. + */ + @Override + public DBCheckpoint getCheckpoint(Path ignoredTmpdir, boolean flush) throws IOException { + scm.getScmHAManager().asSCMHADBTransactionBuffer().flush(); + return scm.getScmMetadataStore().getStore().getCheckpoint(flush); + } } diff --git a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/TestSCMDbCheckpointServlet.java b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/TestSCMDbCheckpointServlet.java index 31d91be145f..108ef30e1df 100644 --- a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/TestSCMDbCheckpointServlet.java +++ b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/TestSCMDbCheckpointServlet.java @@ -17,6 +17,7 @@ package org.apache.hadoop.hdds.scm; +import static org.apache.hadoop.hdds.recon.ReconConfig.ConfigStrings.OZONE_RECON_KERBEROS_PRINCIPAL_KEY; import static org.apache.hadoop.hdds.scm.server.SCMHTTPServerConfig.ConfigStrings.HDDS_SCM_HTTP_AUTH_TYPE; import static org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_ACL_ENABLED; import static org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_ADMINISTRATORS; @@ -216,6 +217,7 @@ void testSpnegoEnabled(String httpMethod) throws Exception { OzoneConfiguration conf = cluster.getConf(); conf.set(OZONE_ADMINISTRATORS, "scmadmin"); conf.set(HDDS_SCM_HTTP_AUTH_TYPE, "kerberos"); + conf.set(OZONE_RECON_KERBEROS_PRINCIPAL_KEY, "recon/localhost@REALM"); cluster.restartStorageContainerManager(true); ServletContext servletContextMock = mock(ServletContext.class); @@ -243,6 +245,12 @@ void testSpnegoEnabled(String httpMethod) throws Exception { doEndpoint(); verify(responseMock, times(2)).setStatus(HttpServletResponse.SC_FORBIDDEN); verify(scmDbCheckpointServletMock).getCheckpoint(any(), anyBoolean()); + + // Recon gets past the permission check, to download the SCM DB. + when(userPrincipalMock.getName()).thenReturn("recon/localhost@REALM"); + doEndpoint(); + verify(responseMock, times(2)).setStatus(HttpServletResponse.SC_FORBIDDEN); + verify(scmDbCheckpointServletMock, times(2)).getCheckpoint(any(), anyBoolean()); } /** diff --git a/hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/ReconServerConfigKeys.java b/hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/ReconServerConfigKeys.java index d3f68423871..7519fb1f063 100644 --- a/hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/ReconServerConfigKeys.java +++ b/hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/ReconServerConfigKeys.java @@ -149,6 +149,13 @@ public final class ReconServerConfigKeys { public static final String OZONE_RECON_SCM_CONNECTION_REQUEST_TIMEOUT_DEFAULT = "5s"; + public static final String OZONE_RECON_SCM_SNAPSHOT_CONNECTION_TIMEOUT = + "ozone.recon.scm.snapshot.connection.timeout"; + public static final String OZONE_RECON_SCM_SNAPSHOT_CONNECTION_TIMEOUT_DEFAULT = "60s"; + + public static final String OZONE_RECON_SCM_SNAPSHOT_READ_TIMEOUT = "ozone.recon.scm.snapshot.read.timeout"; + public static final String OZONE_RECON_SCM_SNAPSHOT_READ_TIMEOUT_DEFAULT = "10m"; + public static final String OZONE_RECON_NSSUMMARY_FLUSH_TO_DB_MAX_THRESHOLD = "ozone.recon.nssummary.flush.db.max.threshold"; diff --git a/hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/spi/impl/StorageContainerServiceProviderImpl.java b/hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/spi/impl/StorageContainerServiceProviderImpl.java index 3b6164447b3..070bb53da4b 100644 --- a/hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/spi/impl/StorageContainerServiceProviderImpl.java +++ b/hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/spi/impl/StorageContainerServiceProviderImpl.java @@ -17,20 +17,52 @@ package org.apache.hadoop.ozone.recon.spi.impl; +import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_GRPC_TLS_ENABLED; +import static org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_ADDRESS_KEY; +import static org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_HTTPS_ADDRESS_KEY; +import static org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_HTTPS_BIND_PORT_DEFAULT; +import static org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_HTTP_ADDRESS_KEY; +import static org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_HTTP_BIND_PORT_DEFAULT; +import static org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_RATIS_PORT_DEFAULT; +import static org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_RATIS_PORT_KEY; +import static org.apache.hadoop.hdds.scm.server.SCMHTTPServerConfig.ConfigStrings.HDDS_SCM_HTTP_AUTH_TYPE; +import static org.apache.hadoop.hdds.utils.HddsServerUtil.OZONE_RATIS_SNAPSHOT_COMPLETE_FLAG_NAME; import static org.apache.hadoop.hdds.utils.HddsServerUtil.getScmSecurityClientWithMaxRetry; +import static org.apache.hadoop.hdds.utils.HddsServerUtil.ratisSnapshotComplete; +import static org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_HTTP_POLICY_KEY; +import static org.apache.hadoop.ozone.OzoneConsts.OZONE_DB_CHECKPOINT_HTTP_ENDPOINT; +import static org.apache.hadoop.ozone.OzoneConsts.OZONE_DB_CHECKPOINT_REQUEST_FLUSH; import static org.apache.hadoop.ozone.recon.ReconConstants.RECON_SCM_SNAPSHOT_DB; +import static org.apache.hadoop.ozone.recon.ReconServerConfigKeys.OZONE_RECON_SCM_SNAPSHOT_CONNECTION_TIMEOUT; +import static org.apache.hadoop.ozone.recon.ReconServerConfigKeys.OZONE_RECON_SCM_SNAPSHOT_CONNECTION_TIMEOUT_DEFAULT; +import static org.apache.hadoop.ozone.recon.ReconServerConfigKeys.OZONE_RECON_SCM_SNAPSHOT_READ_TIMEOUT; +import static org.apache.hadoop.ozone.recon.ReconServerConfigKeys.OZONE_RECON_SCM_SNAPSHOT_READ_TIMEOUT_DEFAULT; import static org.apache.hadoop.security.UserGroupInformation.getCurrentUser; +import com.google.common.net.HostAndPort; +import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.io.File; import java.io.IOException; +import java.io.InputStream; +import java.io.InterruptedIOException; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import javax.inject.Inject; import javax.validation.constraints.NotNull; import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.apache.hadoop.hdds.HddsUtils; import org.apache.hadoop.hdds.conf.OzoneConfiguration; import org.apache.hadoop.hdds.protocol.proto.HddsProtos; import org.apache.hadoop.hdds.protocolPB.SCMSecurityProtocolClientSideTranslatorPB; @@ -42,14 +74,18 @@ import org.apache.hadoop.hdds.scm.pipeline.Pipeline; import org.apache.hadoop.hdds.scm.protocol.StorageContainerLocationProtocol; import org.apache.hadoop.hdds.security.SecurityConfig; +import org.apache.hadoop.hdds.server.http.HttpConfig; import org.apache.hadoop.hdds.utils.db.DBCheckpoint; import org.apache.hadoop.hdds.utils.db.RocksDBCheckpoint; +import org.apache.hadoop.hdfs.web.URLConnectionFactory; import org.apache.hadoop.ozone.ClientVersion; +import org.apache.hadoop.ozone.ha.ConfUtils; import org.apache.hadoop.ozone.recon.ReconContext; import org.apache.hadoop.ozone.recon.ReconUtils; import org.apache.hadoop.ozone.recon.scm.ReconStorageConfig; import org.apache.hadoop.ozone.recon.security.ReconCertificateClient; import org.apache.hadoop.ozone.recon.spi.StorageContainerServiceProvider; +import org.apache.hadoop.security.SecurityUtil; import org.apache.ratis.proto.RaftProtos; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -139,24 +175,11 @@ public DBCheckpoint getSCMDBSnapshot() { for (String ratisRole : ratisRoles) { String[] role = ratisRole.split(":"); if (role[2].equals(RaftProtos.RaftPeerRole.LEADER.toString())) { - String hostAddress = role[4].trim(); - int grpcPort = configuration.getInt( - ScmConfigKeys.OZONE_SCM_GRPC_PORT_KEY, - ScmConfigKeys.OZONE_SCM_GRPC_PORT_DEFAULT); - SecurityConfig secConf = new SecurityConfig(configuration); - SCMSecurityProtocolClientSideTranslatorPB scmSecurityClient = - getScmSecurityClientWithMaxRetry( - configuration, getCurrentUser()); - try (ReconCertificateClient certClient = - new ReconCertificateClient( - secConf, scmSecurityClient, reconStorage, null, null); - SCMSnapshotDownloader downloadClient = new InterSCMGrpcClient( - hostAddress, grpcPort, configuration, certClient)) { - downloadClient.download(targetFile.toPath()).get(); - } catch (ExecutionException | InterruptedException e) { - LOG.error("Rocks DB checkpoint downloading failed: {}", e); - throw new IOException(e); + if (secConf.isSecurityEnabled() && secConf.isGrpcTlsEnabled()) { + downloadSCMDBCheckpoint(getSCMDBCheckpointUrl(role[0], Integer.parseInt(role[1])), targetFile); + } else { + downloadSCMDBCheckpointOverGrpc(role[4].trim(), targetFile, secConf); } LOG.info("Downloaded SCM Snapshot from Leader SCM"); break; @@ -181,9 +204,124 @@ private RocksDBCheckpoint getRocksDBCheckpoint(String snapshotFileName, File tar snapshotFileName); reconUtils.untarCheckpointFile(targetFile, untarredDbDir); FileUtils.deleteQuietly(targetFile); + // SCM writes this flag last, so a checkpoint without it was cut short. + if (!ratisSnapshotComplete(untarredDbDir)) { + FileUtils.deleteQuietly(untarredDbDir.toFile()); + throw new IOException("Incomplete SCM DB checkpoint: " + OZONE_RATIS_SNAPSHOT_COMPLETE_FLAG_NAME + " not found"); + } return new RocksDBCheckpoint(untarredDbDir); } + private void downloadSCMDBCheckpointOverGrpc(String hostAddress, File targetFile, SecurityConfig secConf) + throws IOException { + int grpcPort = + configuration.getInt(ScmConfigKeys.OZONE_SCM_GRPC_PORT_KEY, ScmConfigKeys.OZONE_SCM_GRPC_PORT_DEFAULT); + SCMSecurityProtocolClientSideTranslatorPB scmSecurityClient = + getScmSecurityClientWithMaxRetry(configuration, getCurrentUser()); + try (ReconCertificateClient certClient = + new ReconCertificateClient(secConf, scmSecurityClient, reconStorage, null, null); + SCMSnapshotDownloader downloadClient = + new InterSCMGrpcClient(hostAddress, grpcPort, configuration, certClient)) { + downloadClient.download(targetFile.toPath()).get(); + } catch (ExecutionException | InterruptedException e) { + LOG.error("Rocks DB checkpoint downloading failed: {}", e); + throw new IOException(e); + } + } + + /** + * Downloads the SCM DB checkpoint over HTTP(S), authenticated with SPNEGO when SCM requires it. + * Used when gRPC TLS is enabled, because the inter-SCM gRPC server then accepts SCM certificates only. + */ + private void downloadSCMDBCheckpoint(String url, File targetFile) throws IOException { + LOG.info("Downloading SCM DB checkpoint from {}", url); + int connectTimeout = (int) configuration.getTimeDuration(OZONE_RECON_SCM_SNAPSHOT_CONNECTION_TIMEOUT, + OZONE_RECON_SCM_SNAPSHOT_CONNECTION_TIMEOUT_DEFAULT, TimeUnit.MILLISECONDS); + int readTimeout = (int) configuration.getTimeDuration(OZONE_RECON_SCM_SNAPSHOT_READ_TIMEOUT, + OZONE_RECON_SCM_SNAPSHOT_READ_TIMEOUT_DEFAULT, TimeUnit.MILLISECONDS); + URLConnectionFactory connectionFactory = + URLConnectionFactory.newDefaultURLConnectionFactory(connectTimeout, readTimeout, configuration); + boolean spnegoEnabled = "kerberos".equals(configuration.get(HDDS_SCM_HTTP_AUTH_TYPE, "simple")); + AtomicBoolean cancelled = new AtomicBoolean(); + // Download in another thread, so that the sync can return as soon as it is cancelled (interrupted). + ExecutorService executor = Executors.newSingleThreadExecutor( + new ThreadFactoryBuilder().setNameFormat("ReconSCMDBDownload-%d").setDaemon(true).build()); + Future<?> download = executor.submit(() -> SecurityUtil.doAsLoginUser(() -> { + HttpURLConnection connection = null; + try { + connection = reconUtils.makeHttpCall(connectionFactory, url, spnegoEnabled); + try (InputStream in = connection.getInputStream(); + OutputStream out = Files.newOutputStream(targetFile.toPath())) { + byte[] buffer = new byte[IOUtils.DEFAULT_BUFFER_SIZE]; + for (int n; (n = in.read(buffer)) != -1;) { + if (cancelled.get()) { + throw new InterruptedIOException("SCM DB checkpoint download cancelled"); + } + out.write(buffer, 0, n); + } + } + } catch (Exception e) { + FileUtils.deleteQuietly(targetFile); + throw e; + } finally { + if (connection != null) { + connection.disconnect(); + } + connectionFactory.destroy(); + if (cancelled.get()) { + FileUtils.deleteQuietly(targetFile); + } + } + return null; + })); + executor.shutdown(); + try { + download.get(); + } catch (InterruptedException e) { + // A blocked HttpURLConnection read cannot be aborted from another thread: closing its stream or disconnecting + // waits for the reader. So do not wait for it. The download stops at its next read or its read timeout. + cancelled.set(true); + FileUtils.deleteQuietly(targetFile); + Thread.currentThread().interrupt(); + throw new InterruptedIOException("SCM DB checkpoint download cancelled"); + } catch (ExecutionException e) { + throw e.getCause() instanceof IOException ? (IOException) e.getCause() : new IOException(e.getCause()); + } + } + + /** + * Returns the DB checkpoint URL of the SCM with Ratis address {@code host:ratisPort}. The HTTP(S) port is taken from + * the address configured for that SCM node, else from the common SCM HTTP(S) address. + */ + private String getSCMDBCheckpointUrl(String host, int ratisPort) { + boolean httpsEnabled = HttpConfig.getHttpPolicy(configuration).isHttpsEnabled(); + if (!httpsEnabled) { + LOG.warn("Downloading the SCM DB unencrypted over HTTP although {} is true. Set {} to HTTPS_ONLY or " + + "HTTP_AND_HTTPS to encrypt it.", HDDS_GRPC_TLS_ENABLED, OZONE_HTTP_POLICY_KEY); + } + String addressKey = httpsEnabled ? OZONE_SCM_HTTPS_ADDRESS_KEY : OZONE_SCM_HTTP_ADDRESS_KEY; + List<String> addressKeys = new ArrayList<>(); + String serviceId = HddsUtils.getScmServiceId(configuration); + if (serviceId != null) { + for (String nodeId : HddsUtils.getSCMNodeIds(configuration, serviceId)) { + // Match the node's Ratis address the way SCMHANodeDetails builds it, since SCMs may share a host. + String scmAddress = + configuration.getTrimmed(ConfUtils.addKeySuffixes(OZONE_SCM_ADDRESS_KEY, serviceId, nodeId)); + int nodeRatisPort = HddsUtils.getHostPort(scmAddress).orElse(configuration.getInt( + ConfUtils.addKeySuffixes(OZONE_SCM_RATIS_PORT_KEY, serviceId, nodeId), + configuration.getInt(OZONE_SCM_RATIS_PORT_KEY, OZONE_SCM_RATIS_PORT_DEFAULT))); + if (HddsUtils.getHostName(scmAddress).filter(host::equals).isPresent() && nodeRatisPort == ratisPort) { + addressKeys.add(ConfUtils.addKeySuffixes(addressKey, serviceId, nodeId)); + } + } + } + addressKeys.add(addressKey); + int port = HddsUtils.getPortNumberFromConfigKeys(configuration, addressKeys.toArray(new String[0])) + .orElse(httpsEnabled ? OZONE_SCM_HTTPS_BIND_PORT_DEFAULT : OZONE_SCM_HTTP_BIND_PORT_DEFAULT); + return (httpsEnabled ? "https://" : "http://") + HostAndPort.fromParts(host, port) + + OZONE_DB_CHECKPOINT_HTTP_ENDPOINT + "?" + OZONE_DB_CHECKPOINT_REQUEST_FLUSH + "=true"; + } + @Override public List<ContainerInfo> getListOfContainers( long startContainerID, int count, HddsProtos.LifeCycleState state) diff --git a/hadoop-ozone/recon/src/test/java/org/apache/hadoop/ozone/recon/spi/impl/TestStorageContainerServiceProviderImpl.java b/hadoop-ozone/recon/src/test/java/org/apache/hadoop/ozone/recon/spi/impl/TestStorageContainerServiceProviderImpl.java index 6bf88bc216c..34037aa8f8b 100644 --- a/hadoop-ozone/recon/src/test/java/org/apache/hadoop/ozone/recon/spi/impl/TestStorageContainerServiceProviderImpl.java +++ b/hadoop-ozone/recon/src/test/java/org/apache/hadoop/ozone/recon/spi/impl/TestStorageContainerServiceProviderImpl.java @@ -17,47 +17,107 @@ package org.apache.hadoop.ozone.recon.spi.impl; +import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_GRPC_TLS_ENABLED; +import static org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_ADDRESS_KEY; +import static org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_HTTP_ADDRESS_KEY; +import static org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_NODES_KEY; +import static org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_SERVICE_IDS_KEY; +import static org.apache.hadoop.hdds.scm.server.SCMHTTPServerConfig.ConfigStrings.HDDS_SCM_HTTP_AUTH_TYPE; +import static org.apache.hadoop.hdds.utils.HddsServerUtil.OZONE_RATIS_SNAPSHOT_COMPLETE_FLAG_NAME; +import static org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_HTTP_POLICY_KEY; +import static org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_SECURITY_ENABLED_KEY; +import static org.apache.hadoop.ozone.OzoneConsts.OZONE_DB_CHECKPOINT_HTTP_ENDPOINT; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import com.google.common.util.concurrent.Uninterruptibles; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; +import com.sun.net.httpserver.HttpServer; +import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Collection; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import org.apache.commons.io.FileUtils; import org.apache.hadoop.hdds.HddsConfigKeys; import org.apache.hadoop.hdds.conf.OzoneConfiguration; import org.apache.hadoop.hdds.protocol.proto.HddsProtos; +import org.apache.hadoop.hdds.scm.ScmInfo; +import org.apache.hadoop.hdds.scm.ha.InterSCMGrpcClient; import org.apache.hadoop.hdds.scm.pipeline.Pipeline; import org.apache.hadoop.hdds.scm.pipeline.PipelineID; import org.apache.hadoop.hdds.scm.protocol.StorageContainerLocationProtocol; +import org.apache.hadoop.hdds.server.http.HttpConfig; +import org.apache.hadoop.hdds.utils.HddsServerUtil; +import org.apache.hadoop.hdds.utils.db.DBCheckpoint; +import org.apache.hadoop.ozone.recon.ReconContext; import org.apache.hadoop.ozone.recon.ReconUtils; +import org.apache.hadoop.ozone.recon.security.ReconCertificateClient; import org.apache.hadoop.ozone.recon.spi.StorageContainerServiceProvider; +import org.apache.ozone.test.GenericTestUtils; +import org.apache.ozone.test.GenericTestUtils.LogCapturer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; /** * Class to test StorageContainerServiceProviderImpl APIs. */ public class TestStorageContainerServiceProviderImpl { + private static final String LEADER = "scm1.example.com:9894:LEADER:e428ca07-b2a3-4756-bf9b-a4abb033c7d1:10.0.0.1"; + private Injector injector; private HddsProtos.PipelineID pipelineID; + private File testDir; @BeforeEach - void setup(@TempDir File testDir) { + void setup(@TempDir File tempDir) { + testDir = tempDir; injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { try { StorageContainerLocationProtocol mockScmClient = mock( StorageContainerLocationProtocol.class); - ReconUtils reconUtils = new ReconUtils(); + ReconUtils reconUtils = spy(new ReconUtils()); OzoneConfiguration conf = new OzoneConfiguration(); conf.set(HddsConfigKeys.OZONE_METADATA_DIRS, testDir.getPath()); pipelineID = PipelineID.randomId().getProtobuf(); @@ -98,4 +158,234 @@ public void testGetPipeline() throws IOException { verify(scmClient, times(1)) .getPipeline(pipelineID); } + + /** + * Recon downloads the SCM snapshot from whichever peer reports itself as + * LEADER, using the resolved address carried in the encoded role string. + */ + @Test + public void testGetSCMDBSnapshotConnectsToLeader() throws Exception { + StorageContainerServiceProvider scmProvider = + injector.getInstance(StorageContainerServiceProvider.class); + StorageContainerLocationProtocol scmClient = + injector.getInstance(StorageContainerLocationProtocol.class); + + setPeerRoles(scmClient, + "scm2.example.com:9894:FOLLOWER:61b1c8e5-da40-4567-8a17-96a0234ba14e:10.0.0.2", + "scm1.example.com:9894:LEADER:e428ca07-b2a3-4756-bf9b-a4abb033c7d1:10.0.0.1"); + + AtomicReference<String> downloadHost = new AtomicReference<>(); + try (MockedStatic<HddsServerUtil> stubbedServerUtil = mockStatic(HddsServerUtil.class); + MockedConstruction<ReconCertificateClient> stubbedCertClient = + mockConstruction(ReconCertificateClient.class); + MockedConstruction<InterSCMGrpcClient> downloaders = + mockConstruction(InterSCMGrpcClient.class, (downloader, context) -> { + downloadHost.set((String) context.arguments().get(0)); + when(downloader.download(any())) + .thenReturn(CompletableFuture.completedFuture(null)); + })) { + scmProvider.getSCMDBSnapshot(); + + assertEquals(1, downloaders.constructed().size()); + } + + // The follower is listed first, so this also pins that the LEADER entry is + // the one selected. + assertEquals("10.0.0.1", downloadHost.get()); + // Without gRPC TLS, the inter-SCM gRPC server accepts Recon, so HTTP is not used. + verify(injector.getInstance(ReconUtils.class), never()).makeHttpCall(any(), anyString(), anyBoolean()); + } + + /** + * With gRPC TLS, Recon downloads the SCM snapshot from the leader over HTTP from the SCM DB checkpoint endpoint. + */ + @Test + public void testGetSCMDBSnapshotOverHttpConnectsToLeader() throws Exception { + String url = getSCMDBSnapshot(false, + "scm2.example.com:9894:FOLLOWER:61b1c8e5-da40-4567-8a17-96a0234ba14e:10.0.0.2", + "scm1.example.com:9894:LEADER:e428ca07-b2a3-4756-bf9b-a4abb033c7d1:10.0.0.1"); + + // The follower is listed first, so this also pins that the LEADER entry is + // the one selected. + assertEquals("http://scm1.example.com:9876/dbCheckpoint?flushBeforeCheckpoint=true", url); + } + + /** + * With SCM HA, Recon uses the HTTP address of the leader SCM node, and SPNEGO when SCM requires Kerberos. + * The leader node is matched by host and Ratis port, since SCMs may share a host. + */ + @Test + public void testGetSCMDBSnapshotUsesLeaderHttpAddress() throws Exception { + OzoneConfiguration conf = injector.getInstance(OzoneConfiguration.class); + conf.set(OZONE_SCM_SERVICE_IDS_KEY, "scmservice"); + conf.set(OZONE_SCM_NODES_KEY + ".scmservice", "scm1,scm2"); + conf.set(OZONE_SCM_ADDRESS_KEY + ".scmservice.scm1", "scm.example.com"); + conf.set(OZONE_SCM_ADDRESS_KEY + ".scmservice.scm2", "scm.example.com:9895"); + conf.set(OZONE_SCM_HTTP_ADDRESS_KEY + ".scmservice.scm1", "scm.example.com:9998"); + conf.set(OZONE_SCM_HTTP_ADDRESS_KEY + ".scmservice.scm2", "scm.example.com:9999"); + conf.set(HDDS_SCM_HTTP_AUTH_TYPE, "kerberos"); + + String url = getSCMDBSnapshot(true, + "scm.example.com:9894:FOLLOWER:61b1c8e5-da40-4567-8a17-96a0234ba14e:10.0.0.1", + "scm.example.com:9895:LEADER:e428ca07-b2a3-4756-bf9b-a4abb033c7d1:10.0.0.1"); + + assertEquals("http://scm.example.com:9999/dbCheckpoint?flushBeforeCheckpoint=true", url); + } + + /** + * In secure mode with gRPC TLS enabled, Recon still downloads the SCM DB over plain HTTP, but warns that it is + * not encrypted. + */ + @Test + public void testGetSCMDBSnapshotWarnsOverHttpWithGrpcTls() throws Exception { + LogCapturer logs = LogCapturer.captureLogs(StorageContainerServiceProviderImpl.class); + try { + assertEquals("http://scm1.example.com:9876/dbCheckpoint?flushBeforeCheckpoint=true", + getSCMDBSnapshot(false, LEADER)); + assertThat(logs.getOutput()).contains("Downloading the SCM DB unencrypted over HTTP"); + } finally { + logs.stopCapturing(); + } + } + + /** + * Recon downloads the SCM DB from the HTTPS address when HTTPS is enabled. + */ + @Test + public void testGetSCMDBSnapshotOverHttps() throws Exception { + OzoneConfiguration conf = injector.getInstance(OzoneConfiguration.class); + conf.set(OZONE_HTTP_POLICY_KEY, HttpConfig.Policy.HTTPS_ONLY.name()); + LogCapturer logs = LogCapturer.captureLogs(StorageContainerServiceProviderImpl.class); + try { + assertEquals("https://scm1.example.com:9877/dbCheckpoint?flushBeforeCheckpoint=true", + getSCMDBSnapshot(false, LEADER)); + assertThat(logs.getOutput()).doesNotContain("unencrypted"); + } finally { + logs.stopCapturing(); + } + } + + /** + * A checkpoint without the completion flag, e.g. cut short by an error on SCM, is rejected. + */ + @Test + public void testGetSCMDBSnapshotRejectsIncompleteCheckpoint() throws Exception { + enableGrpcTls(); + ReconUtils reconUtils = injector.getInstance(ReconUtils.class); + setPeerRoles(injector.getInstance(StorageContainerLocationProtocol.class), LEADER); + HttpURLConnection connection = mock(HttpURLConnection.class); + when(connection.getInputStream()).thenReturn(new ByteArrayInputStream(new byte[0])); + doReturn(connection).when(reconUtils).makeHttpCall(any(), anyString(), anyBoolean()); + doNothing().when(reconUtils).untarCheckpointFile(any(), any()); + + assertNull(injector.getInstance(StorageContainerServiceProvider.class).getSCMDBSnapshot()); + assertThat(injector.getInstance(ReconContext.class).getErrors()) + .contains(ReconContext.ErrorCode.GET_SCM_DB_SNAPSHOT_FAILED); + } + + /** + * Cancelling the SCM DB sync returns without waiting for a download that SCM stalls, either after sending part of + * the checkpoint or before responding, and the partial checkpoint is removed. + */ + @ParameterizedTest + @ValueSource(booleans = {true, false}) + public void testGetSCMDBSnapshotCancelDoesNotWaitForStalledDownload(boolean stallMidBody) throws Exception { + enableGrpcTls(); + CountDownLatch responding = new CountDownLatch(1); + CountDownLatch stall = new CountDownLatch(1); + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext(OZONE_DB_CHECKPOINT_HTTP_ENDPOINT, exchange -> { + if (stallMidBody) { + exchange.sendResponseHeaders(200, 1 << 20); + exchange.getResponseBody().write(new byte[1024]); + exchange.getResponseBody().flush(); + } + responding.countDown(); + Uninterruptibles.awaitUninterruptibly(stall); + if (!stallMidBody) { + exchange.sendResponseHeaders(200, -1); + } + exchange.close(); + }); + server.start(); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + injector.getInstance(OzoneConfiguration.class) + .set(OZONE_SCM_HTTP_ADDRESS_KEY, "127.0.0.1:" + server.getAddress().getPort()); + setPeerRoles(injector.getInstance(StorageContainerLocationProtocol.class), + "127.0.0.1:9894:LEADER:e428ca07-b2a3-4756-bf9b-a4abb033c7d1:127.0.0.1"); + Future<DBCheckpoint> sync = + executor.submit(() -> injector.getInstance(StorageContainerServiceProvider.class).getSCMDBSnapshot()); + assertTrue(responding.await(10, TimeUnit.SECONDS)); + if (stallMidBody) { + GenericTestUtils.waitFor(() -> listTarFiles().stream().anyMatch(f -> f.length() > 0), 100, 10000); + } + + // Like ReconStorageContainerManagerFacade#cancelScmDbSnapshotSync + sync.cancel(true); + executor.shutdown(); + assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS)); + } finally { + executor.shutdownNow(); + stall.countDown(); + } + try { + // The download thread cleans up when it stops. + GenericTestUtils.waitFor(() -> Thread.getAllStackTraces().keySet().stream() + .noneMatch(thread -> thread.getName().startsWith("ReconSCMDBDownload")), 100, 10000); + assertThat(listTarFiles()).isEmpty(); + } finally { + server.stop(0); + } + } + + private Collection<File> listTarFiles() { + return FileUtils.listFiles(testDir, new String[] {"tar"}, true); + } + + /** + * Gets the SCM DB snapshot from SCM peers with {@code peerRoles}, in secure mode with gRPC TLS enabled. + * + * @return the URL the snapshot was downloaded from + */ + private String getSCMDBSnapshot(boolean spnegoEnabled, String... peerRoles) throws Exception { + StorageContainerServiceProvider scmProvider = + injector.getInstance(StorageContainerServiceProvider.class); + StorageContainerLocationProtocol scmClient = + injector.getInstance(StorageContainerLocationProtocol.class); + ReconUtils reconUtils = injector.getInstance(ReconUtils.class); + + enableGrpcTls(); + setPeerRoles(scmClient, peerRoles); + HttpURLConnection connection = mock(HttpURLConnection.class); + when(connection.getInputStream()).thenReturn(new ByteArrayInputStream(new byte[0])); + doReturn(connection).when(reconUtils).makeHttpCall(any(), anyString(), anyBoolean()); + doAnswer(invocation -> { + Path untarredDbDir = invocation.getArgument(1); + Files.createDirectories(untarredDbDir); + Files.createFile(untarredDbDir.resolve(OZONE_RATIS_SNAPSHOT_COMPLETE_FLAG_NAME)); + return null; + }).when(reconUtils).untarCheckpointFile(any(), any()); + + assertNotNull(scmProvider.getSCMDBSnapshot()); + + ArgumentCaptor<String> url = ArgumentCaptor.forClass(String.class); + verify(reconUtils).makeHttpCall(any(), url.capture(), eq(spnegoEnabled)); + return url.getValue(); + } + + private void enableGrpcTls() { + OzoneConfiguration conf = injector.getInstance(OzoneConfiguration.class); + conf.setBoolean(OZONE_SECURITY_ENABLED_KEY, true); + conf.setBoolean(HDDS_GRPC_TLS_ENABLED, true); + } + + private static void setPeerRoles(StorageContainerLocationProtocol scmClient, String... peerRoles) + throws IOException { + when(scmClient.getScmInfo()).thenReturn(new ScmInfo.Builder() + .setClusterId("CID-6a1b5b1e-3f5a-4b5c-8f6d-2a1c3e4f5a6b") + .setScmId("scm1") + .setPeerRoles(Arrays.asList(peerRoles)) + .build()); + } } --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
