You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cassandra.apache.org by yc...@apache.org on 2025/06/06 18:47:07 UTC
(cassandra-sidecar) branch trunk updated: CASSSIDECAR-222: Adding Live Migration list files handler. (#212)
This is an automated email from the ASF dual-hosted git repository.
ycai pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/cassandra-sidecar.git
The following commit(s) were added to refs/heads/trunk by this push:
new a09ae704 CASSSIDECAR-222: Adding Live Migration list files handler. (#212)
a09ae704 is described below
commit a09ae704f472ccfb9ef8bdf239028c2f6d724188
Author: N V Harikrishna <n....@gmail.com>
AuthorDate: Sat Jun 7 00:17:02 2025 +0530
CASSSIDECAR-222: Adding Live Migration list files handler. (#212)
Patch by n.v.harikrishna ; reviewed by Francisco Guerrero, Yifan Cai for CASSSIDECAR-222
---
CHANGES.txt | 1 +
.../cassandra/sidecar/common/ApiEndpointsV1.java | 15 +
.../sidecar/common/response/InstanceFileInfo.java | 79 +++++
.../common/response/InstanceFilesListResponse.java | 107 ++++++
conf/sidecar.yaml | 30 +-
.../acl/authorization/BasicPermissions.java | 3 +
.../sidecar/config/LiveMigrationConfiguration.java | 48 +++
.../sidecar/config/SidecarConfiguration.java | 5 +
.../yaml/LiveMigrationConfigurationImpl.java | 74 ++++
.../config/yaml/SidecarConfigurationImpl.java | 23 ++
.../LiveMigrationApiEnableDisableHandler.java | 107 ++++++
.../LiveMigrationListInstanceFilesHandler.java | 100 ++++++
.../handlers/livemigration/LiveMigrationMap.java | 72 ++++
.../LiveMigrationMapSidecarConfigImpl.java | 61 ++++
.../livemigration/CassandraInstanceFiles.java | 41 +++
.../livemigration/CassandraInstanceFilesImpl.java | 146 ++++++++
.../sidecar/livemigration/DirVisitor.java | 104 ++++++
.../LiveMigrationInstanceMetadataUtil.java | 202 +++++++++++
.../LiveMigrationPlaceholderUtil.java | 106 ++++++
.../livemigration/MigrationFileVisitor.java | 122 +++++++
.../sidecar/modules/LiveMigrationModule.java | 56 +++
.../cassandra/sidecar/modules/SidecarModules.java | 3 +-
.../modules/multibindings/VertxRouteMapKeys.java | 5 +
.../cassandra/sidecar/HelperTestModules.java | 102 ++++++
.../sidecar/config/SidecarConfigurationTest.java | 21 ++
.../LiveMigrationApiEnableDisableHandlerTest.java | 159 +++++++++
.../LiveMigrationListInstanceFilesHandlerTest.java | 393 +++++++++++++++++++++
.../LiveMigrationMapSidecarConfigImplTest.java | 81 +++++
.../CassandraInstanceFilesImplTest.java | 236 +++++++++++++
.../sidecar/livemigration/DirVisitorTest.java | 79 +++++
.../livemigration/InstanceFileInfoTestUtil.java | 41 +++
.../LiveMigrationInstanceMetadataUtilTest.java | 322 +++++++++++++++++
.../LiveMigrationPlaceholderUtilTest.java | 73 ++++
.../livemigration/MigrationFileVisitorTest.java | 83 +++++
.../cassandra/sidecar/utils/TestFileUtils.java | 37 ++
.../resources/config/sidecar_live_migration.yaml | 213 +++++++++++
36 files changed, 3348 insertions(+), 2 deletions(-)
diff --git a/CHANGES.txt b/CHANGES.txt
index 81900f23..68144490 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,5 +1,6 @@
0.2.0
-----
+ * Added endpoint for listing files for Live Migration (CASSSIDECAR-222)
* Use List roles statement to check for super user status (CASSSIDECAR-252)
* remove file:// from sidecar.logdir property (CASSSIDECAR-251)
* Add APP_HOME prefix for log config and log dir in cassandra-sidecar startup script (CASSSIDECAR-247)
diff --git a/client-common/src/main/java/org/apache/cassandra/sidecar/common/ApiEndpointsV1.java b/client-common/src/main/java/org/apache/cassandra/sidecar/common/ApiEndpointsV1.java
index 4be4c4a8..cd1c62ab 100644
--- a/client-common/src/main/java/org/apache/cassandra/sidecar/common/ApiEndpointsV1.java
+++ b/client-common/src/main/java/org/apache/cassandra/sidecar/common/ApiEndpointsV1.java
@@ -141,6 +141,21 @@ public final class ApiEndpointsV1
public static final String STREAM_STATS_ROUTE = API_V1 + CASSANDRA + "/stats/streams";
public static final String TABLE_STATS_ROUTE = API_V1 + CASSANDRA + PER_KEYSPACE + PER_TABLE + "/stats";
+
+ // Live Migration APIs
+ public static final String LIVE_MIGRATION_API_PREFIX = API_V1 + "/live-migration";
+
+ public static final String LIVE_MIGRATION_FILES_API = LIVE_MIGRATION_API_PREFIX + "/files";
+
+ public static final String LIVE_MIGRATION_CDC_RAW_DIR_PATH = LIVE_MIGRATION_FILES_API + "/cdc_raw";
+ public static final String LIVE_MIGRATION_COMMITLOG_DIR_PATH = LIVE_MIGRATION_FILES_API + "/commitlog";
+ public static final String LIVE_MIGRATION_DATA_FILE_DIR_PATH = LIVE_MIGRATION_FILES_API + "/data";
+ public static final String LIVE_MIGRATION_HINTS_DIR_PATH = LIVE_MIGRATION_FILES_API + "/hints";
+ public static final String LIVE_MIGRATION_LOCAL_SYSTEM_DATA_FILE_DIR_PATH = LIVE_MIGRATION_FILES_API
+ + "/local_system_data";
+ public static final String LIVE_MIGRATION_SAVED_CACHES_DIR_PATH = LIVE_MIGRATION_FILES_API + "/saved_caches";
+
+
private ApiEndpointsV1()
{
throw new IllegalStateException(getClass() + " is a constants container and shall not be instantiated");
diff --git a/client-common/src/main/java/org/apache/cassandra/sidecar/common/response/InstanceFileInfo.java b/client-common/src/main/java/org/apache/cassandra/sidecar/common/response/InstanceFileInfo.java
new file mode 100644
index 00000000..5dc3d9c6
--- /dev/null
+++ b/client-common/src/main/java/org/apache/cassandra/sidecar/common/response/InstanceFileInfo.java
@@ -0,0 +1,79 @@
+/*
+ * 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.cassandra.sidecar.common.response;
+
+import java.util.Objects;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+/**
+ * Class for holding information of a downloadable file during Live Migration.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class InstanceFileInfo
+{
+ public final String fileUrl;
+ // size is only relevant when the fileType is 'FILE'.
+ // It is set to -1 for directories.
+ public final long size;
+ public final FileType fileType;
+
+ // The latest timestamp at which the file/dir was modified represented in milliseconds.
+ public final long lastModifiedTime;
+
+ public InstanceFileInfo(@JsonProperty("fileUrl") String fileUrl,
+ @JsonProperty("size") long size,
+ @JsonProperty("fileType") FileType fileType,
+ @JsonProperty("lastModifiedTime") long lastModifiedTime)
+ {
+ this.fileUrl = fileUrl;
+ this.size = size;
+ this.fileType = fileType;
+ this.lastModifiedTime = lastModifiedTime;
+ }
+
+ /**
+ * Enum for file type
+ */
+ public enum FileType
+ {
+ FILE,
+ DIRECTORY
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (o == null || getClass() != o.getClass()) return false;
+ InstanceFileInfo that = (InstanceFileInfo) o;
+ return size == that.size
+ && lastModifiedTime == that.lastModifiedTime
+ && Objects.equals(fileUrl, that.fileUrl)
+ && fileType == that.fileType;
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return Objects.hash(fileUrl, size, fileType, lastModifiedTime);
+ }
+}
diff --git a/client-common/src/main/java/org/apache/cassandra/sidecar/common/response/InstanceFilesListResponse.java b/client-common/src/main/java/org/apache/cassandra/sidecar/common/response/InstanceFilesListResponse.java
new file mode 100644
index 00000000..f5be5a50
--- /dev/null
+++ b/client-common/src/main/java/org/apache/cassandra/sidecar/common/response/InstanceFilesListResponse.java
@@ -0,0 +1,107 @@
+/*
+ * 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.cassandra.sidecar.common.response;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.apache.cassandra.sidecar.common.ApiEndpointsV1;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Class representing response for {@link ApiEndpointsV1#LIVE_MIGRATION_FILES_API}.
+ * Holds list of file urls (with their individual sizes) + total size of files
+ * <p>
+ * Sample format:
+ * <pre>
+ * {
+ * "totalSize": 123456789,
+ * "files" : [
+ * {
+ * "fileUrl": "/api/v1/live-migration/files/{type_of_directory}/{directory_index}/{relative_file_path}",
+ * "size": 123456789,
+ * "fileType": "FILE",
+ * "lastModifiedTime": 1707193655406
+ * },
+ *
+ * {
+ * "fileUrl": "/api/v1/live-migration/files/{type_of_directory}/{directory_index}/{relative_file_path}",
+ * "size": -1,
+ * "fileType": "DIRECTORY",
+ * "lastModifiedTime": 1707798915999
+ * }
+ * ]
+ * }
+ * </pre>
+ */
+public class InstanceFilesListResponse
+{
+ private final List<InstanceFileInfo> files;
+ private final long totalSize;
+
+ public InstanceFilesListResponse(@NotNull List<InstanceFileInfo> files)
+ {
+ this.files = Collections.unmodifiableList(files);
+ long sum = 0L;
+ for (InstanceFileInfo file : files)
+ {
+ if (file.fileType.equals(InstanceFileInfo.FileType.FILE))
+ {
+ long size = file.size;
+ sum += size;
+ }
+ }
+ totalSize = sum;
+ }
+
+ @JsonCreator
+ public InstanceFilesListResponse(@JsonProperty("files") List<InstanceFileInfo> files,
+ @JsonProperty("totalSize") long totalSize)
+ {
+ this.files = Collections.unmodifiableList(files);
+ this.totalSize = totalSize;
+ }
+
+ public List<InstanceFileInfo> getFiles()
+ {
+ return files;
+ }
+
+ public long getTotalSize()
+ {
+ return totalSize;
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (o == null || getClass() != o.getClass()) return false;
+ InstanceFilesListResponse that = (InstanceFilesListResponse) o;
+ return totalSize == that.totalSize && Objects.equals(files, that.files);
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return Objects.hash(files, totalSize);
+ }
+}
diff --git a/conf/sidecar.yaml b/conf/sidecar.yaml
index c3aca75f..32c627c5 100644
--- a/conf/sidecar.yaml
+++ b/conf/sidecar.yaml
@@ -59,7 +59,7 @@ cassandra_instances:
# Directory where Cassandra stores the data of the local system keyspaces.
# By default, Cassandra stores the data of the local system keyspaces in the
# first of the data directories specified by data_file_directories.
- # local_system_data_file_directory:
+ # local_system_data_file_dir:
jmx_host: 127.0.0.1
jmx_port: 7199
@@ -366,3 +366,31 @@ s3_client:
# uri:
# username:
# password:
+
+live_migration:
+ # By default, the directories handled by Cassandra like data_dir, commitlog_dir, hints_dir, saved_caches_dir,
+ # cdc_dir, and local_system_data_file_dir are included as part of migration. Admin/operator can exclude files
+ # and directories from migration by specifying them in the `files_to_exclude` list and the `dirs_to_exclude`
+ # list configurations mentioned below.
+ #
+ # 'glob' and 'regex' patterns can be used to specify exclusions. Internally, Java's java.nio.file.PathMatcher
+ # is used to evaluate these exclusions. Exclusions should be specified in the format "syntax:pattern" expected
+ # by PathMatcher. There is no need to specify the absolute path of directories handled by Cassandra.
+ # They can be specified using the supported placeholders listed below.
+ #
+ # COMMITLOG_DIR - commit log directory
+ # HINTS_DIR - hints directory
+ # SAVED_CACHES_DIR - saved caches directory
+ # CDC_RAW_DIR - cdc raw directory
+ # LOCAL_SYSTEM_DATA_FILE_DIR - local system data file data directory
+ # DATA_FILE_DIR - all data directories
+ # DATA_FILE_DIR_0 - first data directory
+ # DATA_FILE_DIR_1 - second data directory
+ #
+ # A sample glob pattern to exclude all snapshot folders from Live Migration looks like this:
+ # glob:${DATA_FILE_DIR}/*/*/snapshots
+ files_to_exclude: [ ] # List of files to exclude from Live Migration.
+ dirs_to_exclude:
+ - glob:${DATA_FILE_DIR}/*/*/snapshots # Excludes snapshot directories in data folder to copy to destination
+ migration_map: # Map of source and destination Cassandra instances
+# localhost1: localhost4 # This entry says that localhost1 will be migrated to localhost4
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/BasicPermissions.java b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/BasicPermissions.java
index 76fb723b..5b57fd7b 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/BasicPermissions.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/BasicPermissions.java
@@ -76,4 +76,7 @@ public class BasicPermissions
// cassandra stats permissions
public static final Permission STATS = new StandardPermission("STATS", CLUSTER_SCOPE);
+
+ // Live Migration permissions
+ public static final Permission LIST_FILES = new DomainAwarePermission("LIVE_MIGRATION:LIST_FILES", CLUSTER_SCOPE);
}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/config/LiveMigrationConfiguration.java b/server/src/main/java/org/apache/cassandra/sidecar/config/LiveMigrationConfiguration.java
new file mode 100644
index 00000000..8cae359c
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/config/LiveMigrationConfiguration.java
@@ -0,0 +1,48 @@
+/*
+ * 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.cassandra.sidecar.config;
+
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Configuration for Live Migration feature.
+ */
+public interface LiveMigrationConfiguration
+{
+
+ /**
+ * Files to be excluded from Live Migration.
+ * @return set of file exclusion patterns.
+ */
+ Set<String> filesToExclude();
+
+ /**
+ * Directories to be excluded from Live Migration.
+ * @return set of directory exclusion patterns.
+ */
+ Set<String> directoriesToExclude();
+
+ /**
+ * Map of source and destination Cassandra instances to migrate.
+ *
+ * @return Map of strings where key is the source instance hostname and value is the destination instance hostname.
+ */
+ Map<String, String> migrationMap();
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/config/SidecarConfiguration.java b/server/src/main/java/org/apache/cassandra/sidecar/config/SidecarConfiguration.java
index b72fed92..011b9f7c 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/config/SidecarConfiguration.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/config/SidecarConfiguration.java
@@ -104,4 +104,9 @@ public interface SidecarConfiguration
*/
@NotNull
SchemaReportingConfiguration schemaReportingConfiguration();
+
+ /**
+ * @return the configuration for live migration
+ */
+ LiveMigrationConfiguration liveMigrationConfiguration();
}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/config/yaml/LiveMigrationConfigurationImpl.java b/server/src/main/java/org/apache/cassandra/sidecar/config/yaml/LiveMigrationConfigurationImpl.java
new file mode 100644
index 00000000..41d46dd8
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/config/yaml/LiveMigrationConfigurationImpl.java
@@ -0,0 +1,74 @@
+/*
+ * 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.cassandra.sidecar.config.yaml;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.apache.cassandra.sidecar.config.LiveMigrationConfiguration;
+
+/**
+ * Configuration required for live migrating the Cassandra instances.
+ */
+public class LiveMigrationConfigurationImpl implements LiveMigrationConfiguration
+{
+
+ private final Set<String> filesToExclude;
+ private final Set<String> directoriesToExclude;
+ private final Map<String, String> migrationMap;
+
+ public LiveMigrationConfigurationImpl()
+ {
+ this(Collections.emptySet(), Collections.emptySet(), Collections.emptyMap());
+ }
+
+ @JsonCreator
+ public LiveMigrationConfigurationImpl(@JsonProperty("files_to_exclude") Set<String> filesToExclude,
+ @JsonProperty("dirs_to_exclude") Set<String> directoriesToExclude,
+ @JsonProperty("migration_map") Map<String, String> migrationMap)
+ {
+ this.filesToExclude = filesToExclude;
+ this.directoriesToExclude = directoriesToExclude;
+ this.migrationMap = migrationMap == null ? Collections.emptyMap() : Collections.unmodifiableMap(migrationMap);
+ }
+
+ @Override
+ @JsonProperty("files_to_exclude")
+ public Set<String> filesToExclude()
+ {
+ return filesToExclude;
+ }
+
+ @Override
+ @JsonProperty("dirs_to_exclude")
+ public Set<String> directoriesToExclude()
+ {
+ return directoriesToExclude;
+ }
+
+ @Override
+ @JsonProperty("migration_map")
+ public Map<String, String> migrationMap()
+ {
+ return migrationMap;
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/config/yaml/SidecarConfigurationImpl.java b/server/src/main/java/org/apache/cassandra/sidecar/config/yaml/SidecarConfigurationImpl.java
index d4c1fde7..fcc36778 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/config/yaml/SidecarConfigurationImpl.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/config/yaml/SidecarConfigurationImpl.java
@@ -43,6 +43,7 @@ import org.apache.cassandra.sidecar.config.AccessControlConfiguration;
import org.apache.cassandra.sidecar.config.CassandraInputValidationConfiguration;
import org.apache.cassandra.sidecar.config.DriverConfiguration;
import org.apache.cassandra.sidecar.config.InstanceConfiguration;
+import org.apache.cassandra.sidecar.config.LiveMigrationConfiguration;
import org.apache.cassandra.sidecar.config.MetricsConfiguration;
import org.apache.cassandra.sidecar.config.PeriodicTaskConfiguration;
import org.apache.cassandra.sidecar.config.RestoreJobConfiguration;
@@ -112,6 +113,9 @@ public class SidecarConfigurationImpl implements SidecarConfiguration
@NotNull
protected final SchemaReportingConfiguration schemaReportingConfiguration;
+ @JsonProperty("live_migration")
+ private LiveMigrationConfiguration liveMigrationConfiguration;
+
public SidecarConfigurationImpl()
{
this(builder());
@@ -134,6 +138,7 @@ public class SidecarConfigurationImpl implements SidecarConfiguration
s3ClientConfiguration = builder.s3ClientConfiguration;
vertxConfiguration = builder.vertxConfiguration;
schemaReportingConfiguration = builder.schemaReportingConfiguration;
+ liveMigrationConfiguration = builder.liveMigrationConfiguration;
}
/**
@@ -291,6 +296,11 @@ public class SidecarConfigurationImpl implements SidecarConfiguration
return schemaReportingConfiguration;
}
+ public LiveMigrationConfiguration liveMigrationConfiguration()
+ {
+ return liveMigrationConfiguration;
+ }
+
public static SidecarConfigurationImpl readYamlConfiguration(String yamlConfigurationPath) throws IOException
{
try
@@ -410,6 +420,7 @@ public class SidecarConfigurationImpl implements SidecarConfiguration
private S3ClientConfiguration s3ClientConfiguration = new S3ClientConfigurationImpl();
private VertxConfiguration vertxConfiguration = new VertxConfigurationImpl();
private SchemaReportingConfiguration schemaReportingConfiguration = new SchemaReportingConfigurationImpl();
+ private LiveMigrationConfiguration liveMigrationConfiguration = new LiveMigrationConfigurationImpl();
protected Builder()
{
@@ -591,6 +602,18 @@ public class SidecarConfigurationImpl implements SidecarConfiguration
return update(builder -> builder.schemaReportingConfiguration = configuration);
}
+ /**
+ * Sets the {@code liveMigrationConfiguration} and returns a reference to this Builder enabling method
+ * chaining
+ *
+ * @param liveMigrationConfiguration the {@code liveMigrationConfiguration} to set
+ * @return a reference to this Builder
+ */
+ public Builder liveMigrationConfiguration(LiveMigrationConfiguration liveMigrationConfiguration)
+ {
+ return update(b -> b.liveMigrationConfiguration = liveMigrationConfiguration);
+ }
+
/**
* Returns a {@code SidecarConfigurationImpl} built from the parameters previously set.
*
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/handlers/livemigration/LiveMigrationApiEnableDisableHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/handlers/livemigration/LiveMigrationApiEnableDisableHandler.java
new file mode 100644
index 00000000..327ca56a
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/handlers/livemigration/LiveMigrationApiEnableDisableHandler.java
@@ -0,0 +1,107 @@
+/*
+ * 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.cassandra.sidecar.handlers.livemigration;
+
+import com.google.inject.Inject;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.cluster.InstancesMetadata;
+import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadata;
+import org.apache.cassandra.sidecar.config.LiveMigrationConfiguration;
+
+import static org.apache.cassandra.sidecar.handlers.AbstractHandler.extractHostAddressWithoutPort;
+
+
+/**
+ * Handler for enabling or disabling live-migration APIs. It helps to enable Live Migration APIs for
+ * either source/destination specified in {@link LiveMigrationConfiguration#migrationMap()}.
+ */
+public class LiveMigrationApiEnableDisableHandler
+{
+ final LiveMigrationMap liveMigrationMap;
+ final InstancesMetadata instancesMetadata;
+
+ @Inject
+ public LiveMigrationApiEnableDisableHandler(LiveMigrationMap liveMigrationMap,
+ InstancesMetadata instancesMetadata)
+ {
+ this.liveMigrationMap = liveMigrationMap;
+ this.instancesMetadata = instancesMetadata;
+ }
+
+ /**
+ * Enables route if local instance is getting live migrated (source).
+ *
+ * @param rc - routing context
+ */
+ public void isSource(RoutingContext rc)
+ {
+ InstanceMetadata instanceMeta = getLocalInstanceMeta(rc);
+ if (liveMigrationMap.isSource(instanceMeta))
+ {
+ rc.next();
+ }
+ else
+ {
+ rc.fail(HttpResponseStatus.NOT_FOUND.code());
+ }
+ }
+
+ /**
+ * Enables route if local instance is the destination.
+ *
+ * @param rc - routing context
+ */
+ public void isDestination(RoutingContext rc)
+ {
+ InstanceMetadata instanceMeta = getLocalInstanceMeta(rc);
+ if (liveMigrationMap.isDestination(instanceMeta))
+ {
+ rc.next();
+ }
+ else
+ {
+ rc.fail(HttpResponseStatus.NOT_FOUND.code());
+ }
+ }
+
+ /**
+ * Enables route if local instance is either source or destination in live migration map.
+ *
+ * @param rc - routing context
+ */
+ public void isSourceOrDestination(RoutingContext rc)
+ {
+ InstanceMetadata instanceMeta = getLocalInstanceMeta(rc);
+ if (liveMigrationMap.isAny(instanceMeta))
+ {
+ rc.next();
+ }
+ else
+ {
+ rc.fail(HttpResponseStatus.NOT_FOUND.code());
+ }
+ }
+
+ private InstanceMetadata getLocalInstanceMeta(RoutingContext rc)
+ {
+ String host = extractHostAddressWithoutPort(rc.request());
+ return instancesMetadata.instanceFromHost(host);
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/handlers/livemigration/LiveMigrationListInstanceFilesHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/handlers/livemigration/LiveMigrationListInstanceFilesHandler.java
new file mode 100644
index 00000000..24f8f5e2
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/handlers/livemigration/LiveMigrationListInstanceFilesHandler.java
@@ -0,0 +1,100 @@
+/*
+ * 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.cassandra.sidecar.handlers.livemigration;
+
+import java.io.IOException;
+import java.util.Set;
+import javax.inject.Inject;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.vertx.core.http.HttpServerRequest;
+import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
+import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadata;
+import org.apache.cassandra.sidecar.common.response.InstanceFilesListResponse;
+import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
+import org.apache.cassandra.sidecar.config.SidecarConfiguration;
+import org.apache.cassandra.sidecar.handlers.AbstractHandler;
+import org.apache.cassandra.sidecar.handlers.AccessProtected;
+import org.apache.cassandra.sidecar.livemigration.CassandraInstanceFiles;
+import org.apache.cassandra.sidecar.livemigration.CassandraInstanceFilesImpl;
+import org.apache.cassandra.sidecar.utils.CassandraInputValidator;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.jetbrains.annotations.NotNull;
+
+import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpException;
+
+/**
+ * Endpoint for returning list of files that a destination instance can copy.
+ */
+public class LiveMigrationListInstanceFilesHandler extends AbstractHandler<Void> implements AccessProtected
+{
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(LiveMigrationListInstanceFilesHandler.class);
+ private final SidecarConfiguration sidecarConfiguration;
+
+ @Inject
+ public LiveMigrationListInstanceFilesHandler(InstanceMetadataFetcher metadataFetcher,
+ ExecutorPools executorPools,
+ CassandraInputValidator validator,
+ SidecarConfiguration sidecarConfiguration)
+ {
+ super(metadataFetcher, executorPools, validator);
+ this.sidecarConfiguration = sidecarConfiguration;
+ }
+
+ @Override
+ protected Void extractParamsOrThrow(RoutingContext context)
+ {
+ return null;
+ }
+
+ @Override
+ protected void handleInternal(RoutingContext context, HttpServerRequest httpRequest, @NotNull String host,
+ SocketAddress remoteAddress, Void request)
+ {
+ InstanceMetadata instanceMetadata = metadataFetcher.instance(host);
+
+ CassandraInstanceFiles filesList = new CassandraInstanceFilesImpl(instanceMetadata,
+ sidecarConfiguration.liveMigrationConfiguration());
+ executorPools.service().runBlocking(() -> {
+ try
+ {
+
+ context.json(new InstanceFilesListResponse(filesList.files()));
+ }
+ catch (IOException e)
+ {
+ LOGGER.error("Could not fetch instance files information.", e);
+ context.fail(wrapHttpException(HttpResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage(), e));
+ }
+ });
+ }
+
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ return Set.of(BasicPermissions.LIST_FILES.toAuthorization());
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/handlers/livemigration/LiveMigrationMap.java b/server/src/main/java/org/apache/cassandra/sidecar/handlers/livemigration/LiveMigrationMap.java
new file mode 100644
index 00000000..46b7e8d5
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/handlers/livemigration/LiveMigrationMap.java
@@ -0,0 +1,72 @@
+/*
+ * 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.cassandra.sidecar.handlers.livemigration;
+
+import java.util.Map;
+
+import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadata;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Map of source to destination C* instances to do the Live Migration.
+ */
+public interface LiveMigrationMap
+{
+ /**
+ * Tells whether given instance is configured as source or not.
+ *
+ * @param instanceMeta Cassandra instance metadata
+ * @return true if given instance is configured as source for live migration.
+ */
+ default boolean isSource(@NotNull InstanceMetadata instanceMeta)
+ {
+ Map<String, String> map = getMigrationMap();
+ return map != null && map.containsKey(String.valueOf(instanceMeta.host()));
+ }
+
+ /**
+ * Tells whether given instance is configured as destination or not.
+ *
+ * @param instanceMeta Cassandra instance metadata
+ * @return true if given instance is configured as destination for live migration.
+ */
+ default boolean isDestination(@NotNull InstanceMetadata instanceMeta)
+ {
+ Map<String, String> map = getMigrationMap();
+ return map != null && map.containsValue(String.valueOf(instanceMeta.host()));
+ }
+
+ /**
+ * Tells whether given instance is configured as either source or destination.
+ *
+ * @param instanceMeta Cassandra instance metadata
+ * @return true if given instance is either source or destination
+ */
+ default boolean isAny(@NotNull InstanceMetadata instanceMeta)
+ {
+ return isSource(instanceMeta) || isDestination(instanceMeta);
+ }
+
+ /**
+ * Returns map of source and destination
+ *
+ * @return map of source and destination
+ */
+ Map<String, String> getMigrationMap();
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/handlers/livemigration/LiveMigrationMapSidecarConfigImpl.java b/server/src/main/java/org/apache/cassandra/sidecar/handlers/livemigration/LiveMigrationMapSidecarConfigImpl.java
new file mode 100644
index 00000000..61368015
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/handlers/livemigration/LiveMigrationMapSidecarConfigImpl.java
@@ -0,0 +1,61 @@
+/*
+ * 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.cassandra.sidecar.handlers.livemigration;
+
+import java.util.Map;
+
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadata;
+import org.apache.cassandra.sidecar.config.LiveMigrationConfiguration;
+import org.apache.cassandra.sidecar.config.SidecarConfiguration;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Implementation for {@link LiveMigrationMap} using Sidecar configuration.
+ */
+@Singleton
+public class LiveMigrationMapSidecarConfigImpl implements LiveMigrationMap
+{
+ private final LiveMigrationConfiguration liveMigrationConfiguration;
+
+ @Inject
+ public LiveMigrationMapSidecarConfigImpl(SidecarConfiguration sidecarConfiguration)
+ {
+ this.liveMigrationConfiguration = sidecarConfiguration.liveMigrationConfiguration();
+ }
+
+ @Override
+ public boolean isSource(@NotNull InstanceMetadata instanceMeta)
+ {
+ return liveMigrationConfiguration.migrationMap().containsKey(instanceMeta.host());
+ }
+
+ @Override
+ public boolean isDestination(@NotNull InstanceMetadata instanceMeta)
+ {
+ return liveMigrationConfiguration.migrationMap().containsValue(instanceMeta.host());
+ }
+
+ @Override
+ public Map<String, String> getMigrationMap()
+ {
+ return liveMigrationConfiguration.migrationMap();
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/livemigration/CassandraInstanceFiles.java b/server/src/main/java/org/apache/cassandra/sidecar/livemigration/CassandraInstanceFiles.java
new file mode 100644
index 00000000..1fdd567a
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/livemigration/CassandraInstanceFiles.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.cassandra.sidecar.livemigration;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.apache.cassandra.sidecar.common.response.InstanceFileInfo;
+import org.apache.cassandra.sidecar.config.LiveMigrationConfiguration;
+
+/**
+ * Lists files that a Cassandra instance has.
+ */
+public interface CassandraInstanceFiles
+{
+ /**
+ * Lists files belong to a Cassandra instance after excluding default set files to exclude
+ * {@link LiveMigrationConfiguration#filesToExclude()} and default set of directories to exclude
+ * {@link LiveMigrationConfiguration#directoriesToExclude()}.
+ *
+ * @return list of files a Cassandra instance has after excluding default files and folders.
+ * @throws IOException when failed to read any file or folder.
+ */
+ List<InstanceFileInfo> files() throws IOException;
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/livemigration/CassandraInstanceFilesImpl.java b/server/src/main/java/org/apache/cassandra/sidecar/livemigration/CassandraInstanceFilesImpl.java
new file mode 100644
index 00000000..a6639651
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/livemigration/CassandraInstanceFilesImpl.java
@@ -0,0 +1,146 @@
+/*
+ * 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.cassandra.sidecar.livemigration;
+
+import java.io.IOException;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadata;
+import org.apache.cassandra.sidecar.common.response.InstanceFileInfo;
+import org.apache.cassandra.sidecar.config.LiveMigrationConfiguration;
+
+import static org.apache.cassandra.sidecar.livemigration.LiveMigrationPlaceholderUtil.hasAnyPlaceholder;
+import static org.apache.cassandra.sidecar.livemigration.LiveMigrationPlaceholderUtil.replacePlaceholder;
+
+/**
+ * Helper class to get the list of files to use during Live Migration.
+ */
+public class CassandraInstanceFilesImpl implements CassandraInstanceFiles
+{
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(CassandraInstanceFilesImpl.class);
+
+ private final InstanceMetadata instanceMetadata;
+
+ private final LiveMigrationConfiguration configuration;
+
+ public CassandraInstanceFilesImpl(InstanceMetadata instanceMetadata,
+ LiveMigrationConfiguration configuration)
+ {
+ this.instanceMetadata = instanceMetadata;
+ this.configuration = configuration;
+ }
+
+ @Override
+ public List<InstanceFileInfo> files() throws IOException
+ {
+ return files(configuration.filesToExclude(), configuration.directoriesToExclude());
+ }
+
+ private List<InstanceFileInfo> files(Set<String> filesToExclude,
+ Set<String> dirsToExclude) throws IOException
+ {
+ List<DirVisitor> dirVisitors = dirVisitorList(filesToExclude, dirsToExclude);
+ List<InstanceFileInfo> instanceFileInfos = new ArrayList<>();
+
+ for (DirVisitor dirVisitor : dirVisitors)
+ {
+ instanceFileInfos.addAll(dirVisitor.files());
+ }
+
+ LOGGER.info("{} number of files are getting listed", instanceFileInfos.size());
+ return instanceFileInfos;
+ }
+
+ private List<DirVisitor> dirVisitorList(Set<String> filesToExclude,
+ Set<String> dirsToExclude)
+ {
+ List<DirVisitor> dataFilesToVisit = new ArrayList<>();
+ List<String> dirsToCopy = LiveMigrationInstanceMetadataUtil.dirsToCopy(instanceMetadata);
+ Map<String, String> dirPathPrefix = LiveMigrationInstanceMetadataUtil.dirPathPrefixMap(instanceMetadata);
+ Map<String, Set<String>> dirPlaceholderMap = LiveMigrationInstanceMetadataUtil.dirPlaceHoldersMap(instanceMetadata);
+
+ for (String dir : dirsToCopy)
+ {
+ dirToVisit(dir,
+ dirPlaceholderMap.get(dir),
+ dirPathPrefix.get(dir),
+ filesToExclude,
+ dirsToExclude)
+ .ifPresent(dataFilesToVisit::add);
+ }
+
+ return dataFilesToVisit;
+ }
+
+ private Optional<DirVisitor> dirToVisit(String homeDir, Set<String> placeholders, String pathPrefix,
+ Set<String> filesToExclude, Set<String> dirsToExclude)
+ {
+ if (null == homeDir)
+ {
+ return Optional.empty();
+ }
+
+ Objects.requireNonNull(placeholders, "placeholders are required");
+ Objects.requireNonNull(pathPrefix, "pathPrefix is required");
+
+ Path homeDirPath = Paths.get(homeDir);
+ if (!Files.exists(homeDirPath))
+ {
+ LOGGER.info("Directory {} does not exist.", homeDir);
+ return Optional.empty();
+ }
+
+ List<PathMatcher> fileExclusionMatchers = toPathMatchers(filesToExclude, placeholders, homeDir);
+ List<PathMatcher> dirExclusionMatchers = toPathMatchers(dirsToExclude, placeholders, homeDir);
+
+ return Optional.of(new DirVisitor(homeDir, pathPrefix, fileExclusionMatchers, dirExclusionMatchers));
+ }
+
+ List<PathMatcher> toPathMatchers(Set<String> exclusions, Set<String> homeDirPlaceholders, String homeDir)
+ {
+ if (null == exclusions || exclusions.isEmpty())
+ {
+ return Collections.emptyList();
+ }
+
+ return exclusions.stream()
+ .filter(exclusion -> !hasAnyPlaceholder(exclusion)
+ || hasAnyPlaceholder(exclusion, homeDirPlaceholders))
+ .map(file -> replacePlaceholder(file, homeDirPlaceholders, homeDir))
+ .filter(Objects::nonNull)
+ .map(file -> FileSystems.getDefault().getPathMatcher(file))
+ .collect(Collectors.toList());
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/livemigration/DirVisitor.java b/server/src/main/java/org/apache/cassandra/sidecar/livemigration/DirVisitor.java
new file mode 100644
index 00000000..7149a685
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/livemigration/DirVisitor.java
@@ -0,0 +1,104 @@
+/*
+ * 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.cassandra.sidecar.livemigration;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.Paths;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.cassandra.sidecar.common.response.InstanceFileInfo;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Explores single directory of a Cassandra Instance.
+ */
+public class DirVisitor
+{
+ private static final Logger LOGGER = LoggerFactory.getLogger(DirVisitor.class);
+ private final String homeDir;
+ private final Path homeDirPath;
+ private final String pathPrefix;
+ private final MigrationFileVisitor fileVisitor;
+
+ public DirVisitor(String homeDir,
+ String pathPrefix,
+ List<PathMatcher> fileExclusionMatchers,
+ List<PathMatcher> dirExclusionMatchers)
+ {
+ this.homeDir = homeDir;
+ this.homeDirPath = Paths.get(homeDir);
+ this.pathPrefix = pathPrefix;
+ this.fileVisitor = new MigrationFileVisitor(homeDir, fileExclusionMatchers, dirExclusionMatchers);
+ }
+
+ /**
+ * Returns list of files and directories (urls) that can be downloaded by destination which is trying
+ * to clone current instance.
+ *
+ * @return List of {@link InstanceFileInfo} for each file and directory considered for Live Migration.
+ * @throws IOException - when cannot access files of a data home directory
+ */
+ public List<InstanceFileInfo> files() throws IOException
+ {
+ Files.walkFileTree(homeDirPath, fileVisitor);
+ List<Path> validFiles = fileVisitor.validFilePaths();
+ final List<InstanceFileInfo> infos = new ArrayList<>();
+ for (final Path path : validFiles)
+ {
+ infos.add(toInstanceFileInfo(path));
+ }
+ LOGGER.debug("Found {} instance files for homeDir {}", infos.size(), homeDir);
+ return infos;
+ }
+
+ private InstanceFileInfo toInstanceFileInfo(@NotNull Path path) throws IOException
+ {
+ BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
+ long lastModifiedTime = attrs.lastModifiedTime().toMillis();
+ String fileUrl = buildInstanceFileUrl(path);
+ boolean isDirectory = attrs.isDirectory();
+ InstanceFileInfo.FileType fileType = isDirectory
+ ? InstanceFileInfo.FileType.DIRECTORY
+ : InstanceFileInfo.FileType.FILE;
+ // 'size' doesn't have any significance for directories. Hence, setting it to -1 explicitly.
+ long size = isDirectory ? -1 : attrs.size();
+
+ return new InstanceFileInfo(fileUrl, size, fileType, lastModifiedTime);
+ }
+
+ /**
+ * Constructs live migration URL path for given file.
+ *
+ * @param path file for which URL needs to be constructed.
+ * @return URL path for given file
+ */
+ private String buildInstanceFileUrl(@NotNull Path path)
+ {
+ String relativePath = homeDirPath.relativize(path).toString();
+ return pathPrefix + "/" + relativePath;
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/livemigration/LiveMigrationInstanceMetadataUtil.java b/server/src/main/java/org/apache/cassandra/sidecar/livemigration/LiveMigrationInstanceMetadataUtil.java
new file mode 100644
index 00000000..ae2d814f
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/livemigration/LiveMigrationInstanceMetadataUtil.java
@@ -0,0 +1,202 @@
+/*
+ * 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.cassandra.sidecar.livemigration;
+
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadata;
+import org.jetbrains.annotations.NotNull;
+
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_CDC_RAW_DIR_PATH;
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_COMMITLOG_DIR_PATH;
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_DATA_FILE_DIR_PATH;
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_HINTS_DIR_PATH;
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_LOCAL_SYSTEM_DATA_FILE_DIR_PATH;
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_SAVED_CACHES_DIR_PATH;
+import static org.apache.cassandra.sidecar.livemigration.LiveMigrationPlaceholderUtil.CDC_RAW_DIR_PLACEHOLDER;
+import static org.apache.cassandra.sidecar.livemigration.LiveMigrationPlaceholderUtil.COMMITLOG_DIR_PLACEHOLDER;
+import static org.apache.cassandra.sidecar.livemigration.LiveMigrationPlaceholderUtil.DATA_FILE_DIR_PLACEHOLDER;
+import static org.apache.cassandra.sidecar.livemigration.LiveMigrationPlaceholderUtil.HINTS_DIR_PLACEHOLDER;
+import static org.apache.cassandra.sidecar.livemigration.LiveMigrationPlaceholderUtil.LOCAL_SYSTEM_DATA_FILE_DIR_PLACEHOLDER;
+import static org.apache.cassandra.sidecar.livemigration.LiveMigrationPlaceholderUtil.SAVED_CACHES_DIR_PLACEHOLDER;
+
+/**
+ * Utility class for having all {@link InstanceMetadata} related helper functions related to
+ * Live Migration in one place.
+ */
+@SuppressWarnings("ConstantValue")
+public class LiveMigrationInstanceMetadataUtil
+{
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(LiveMigrationInstanceMetadataUtil.class);
+
+ /**
+ * List of directories Live Migration considers to transfer between source and destination.
+ */
+ public static List<String> dirsToCopy(InstanceMetadata instanceMetadata)
+ {
+ List<String> dirsToCopy = new ArrayList<>();
+ dirsToCopy.add(instanceMetadata.hintsDir());
+ dirsToCopy.add(instanceMetadata.commitlogDir());
+ if (instanceMetadata.savedCachesDir() != null)
+ {
+ dirsToCopy.add(instanceMetadata.savedCachesDir());
+ }
+ if (instanceMetadata.cdcDir() != null)
+ {
+ dirsToCopy.add(instanceMetadata.cdcDir());
+ }
+ if (instanceMetadata.localSystemDataFileDir() != null)
+ {
+ dirsToCopy.add(instanceMetadata.localSystemDataFileDir());
+ }
+ dirsToCopy.addAll(instanceMetadata.dataDirs());
+ return Collections.unmodifiableList(dirsToCopy);
+ }
+
+ /**
+ * Returns map of directory that can be copied and the index to use while constructing
+ * url for file transfer.
+ */
+ public static Map<String, String> dirPathPrefixMap(InstanceMetadata instanceMetadata)
+ {
+ Map<String, String> dirIndexMap = new HashMap<>();
+ dirIndexMap.put(instanceMetadata.hintsDir(), LIVE_MIGRATION_HINTS_DIR_PATH + "/0");
+ dirIndexMap.put(instanceMetadata.commitlogDir(), LIVE_MIGRATION_COMMITLOG_DIR_PATH + "/0");
+ if (instanceMetadata.savedCachesDir() != null)
+ {
+ dirIndexMap.put(instanceMetadata.savedCachesDir(), LIVE_MIGRATION_SAVED_CACHES_DIR_PATH + "/0");
+ }
+ if (instanceMetadata.cdcDir() != null)
+ {
+ dirIndexMap.put(instanceMetadata.cdcDir(), LIVE_MIGRATION_CDC_RAW_DIR_PATH + "/0");
+ }
+ if (instanceMetadata.localSystemDataFileDir() != null)
+ {
+ dirIndexMap.put(instanceMetadata.localSystemDataFileDir(), LIVE_MIGRATION_LOCAL_SYSTEM_DATA_FILE_DIR_PATH + "/0");
+ }
+ for (int i = 0; i < instanceMetadata.dataDirs().size(); i++)
+ {
+ dirIndexMap.put(instanceMetadata.dataDirs().get(i), LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/" + i);
+ }
+ return Collections.unmodifiableMap(dirIndexMap);
+ }
+
+ /**
+ * Returns map of directory and set of placeholders that represent the directory.
+ */
+ public static Map<String, Set<String>> dirPlaceHoldersMap(InstanceMetadata instanceMetadata)
+ {
+ Map<String, Set<String>> placeholderMap = new HashMap<>();
+
+ placeholderMap.put(instanceMetadata.hintsDir(), Collections.singleton(HINTS_DIR_PLACEHOLDER));
+ placeholderMap.put(instanceMetadata.commitlogDir(), Collections.singleton(COMMITLOG_DIR_PLACEHOLDER));
+ if (instanceMetadata.savedCachesDir() != null)
+ {
+ placeholderMap.put(instanceMetadata.savedCachesDir(), Collections.singleton(SAVED_CACHES_DIR_PLACEHOLDER));
+ }
+
+ if (instanceMetadata.cdcDir() != null)
+ {
+ placeholderMap.put(instanceMetadata.cdcDir(), Collections.singleton(CDC_RAW_DIR_PLACEHOLDER));
+ }
+
+ if (instanceMetadata.localSystemDataFileDir() != null)
+ {
+ placeholderMap.put(instanceMetadata.localSystemDataFileDir(),
+ Collections.singleton(LOCAL_SYSTEM_DATA_FILE_DIR_PLACEHOLDER));
+ }
+
+ List<String> dataDirs = instanceMetadata.dataDirs();
+ for (int i = 0; i < dataDirs.size(); i++)
+ {
+ String dir = dataDirs.get(i);
+ Set<String> placeholders = Set.of(DATA_FILE_DIR_PLACEHOLDER, DATA_FILE_DIR_PLACEHOLDER + "_" + i);
+ placeholderMap.put(dir, placeholders);
+ }
+
+ return Collections.unmodifiableMap(placeholderMap);
+ }
+
+ /**
+ * Converts given live migration file download URL to local path.
+ *
+ * @param fileUrl Live migration file download URL
+ * @param metadata Cassandra instance metadata
+ * @return local path for given live migration file download URL
+ */
+ public static String localPath(@NotNull String fileUrl,
+ @NotNull InstanceMetadata metadata)
+ {
+
+ if (fileUrl.contains("/../") || fileUrl.endsWith("/.."))
+ {
+ String errorMessage = "Tried to access file using relative path " + fileUrl + ".";
+ LOGGER.error(errorMessage);
+ throw new IllegalArgumentException(errorMessage);
+ }
+
+ Map<String, String> urlToLocalDirMap = migrationUrlLocalDirMap(metadata);
+ for (Map.Entry<String, String> entry : urlToLocalDirMap.entrySet())
+ {
+ if (fileUrl.startsWith(entry.getKey()))
+ {
+ Objects.requireNonNull(entry.getValue(), () -> "No local path found for url " + fileUrl);
+ String relativePath = fileUrl.substring(entry.getKey().length());
+ return Paths.get(entry.getValue(), relativePath).toAbsolutePath().toString();
+ }
+ }
+
+ throw new IllegalArgumentException("File url " + fileUrl + " is unknown.");
+ }
+
+ private static Map<String, String> migrationUrlLocalDirMap(InstanceMetadata instanceMetadata)
+ {
+ Map<String, String> urlToLocalDirMap = new HashMap<>();
+ urlToLocalDirMap.put(LIVE_MIGRATION_COMMITLOG_DIR_PATH + "/0/", instanceMetadata.commitlogDir());
+ urlToLocalDirMap.put(LIVE_MIGRATION_HINTS_DIR_PATH + "/0/", instanceMetadata.hintsDir());
+ urlToLocalDirMap.put(LIVE_MIGRATION_SAVED_CACHES_DIR_PATH + "/0/", instanceMetadata.savedCachesDir());
+
+ if (instanceMetadata.cdcDir() != null)
+ {
+ urlToLocalDirMap.put(LIVE_MIGRATION_CDC_RAW_DIR_PATH + "/0/", instanceMetadata.cdcDir());
+ }
+ if (instanceMetadata.localSystemDataFileDir() != null)
+ {
+ urlToLocalDirMap.put(LIVE_MIGRATION_LOCAL_SYSTEM_DATA_FILE_DIR_PATH + "/0/", instanceMetadata.localSystemDataFileDir());
+ }
+
+ for (int i = 0; i < instanceMetadata.dataDirs().size(); i++)
+ {
+ urlToLocalDirMap.put(LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/" + i + "/", instanceMetadata.dataDirs().get(0));
+ }
+
+ return urlToLocalDirMap;
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/livemigration/LiveMigrationPlaceholderUtil.java b/server/src/main/java/org/apache/cassandra/sidecar/livemigration/LiveMigrationPlaceholderUtil.java
new file mode 100644
index 00000000..a421f7d4
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/livemigration/LiveMigrationPlaceholderUtil.java
@@ -0,0 +1,106 @@
+/*
+ * 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.cassandra.sidecar.livemigration;
+
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * Utility class for replacing placeholder in Live Migration exclusion paths.
+ * <p>
+ * A placeholder looks like this: "${PLACEHOLDER}/*\/*\/*-Data.db".
+ */
+public class LiveMigrationPlaceholderUtil
+{
+
+ public static final String DATA_FILE_DIR_PLACEHOLDER = "DATA_FILE_DIR";
+ public static final String COMMITLOG_DIR_PLACEHOLDER = "COMMITLOG_DIR";
+ public static final String HINTS_DIR_PLACEHOLDER = "HINTS_DIR";
+ public static final String SAVED_CACHES_DIR_PLACEHOLDER = "SAVED_CACHES_DIR";
+ public static final String CDC_RAW_DIR_PLACEHOLDER = "CDC_RAW_DIR";
+ public static final String LOCAL_SYSTEM_DATA_FILE_DIR_PLACEHOLDER = "LOCAL_SYSTEM_DATA_FILE_DIR";
+ private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\$\\{(\\w+)}.*");
+
+ /**
+ * Replaces a placeholder with a value specified in given input. There can be more than one placeholder
+ * pointing to singe value.
+ *
+ * @param input input string having placeholder to replace
+ * @param placeholders set of placeholders to search for
+ * @param value value with which placeholder will be replaced
+ * @return input unchanged if no placeholder is found and input with placeholder replaced if placeholder is in given
+ * placeholders, otherwise null.
+ */
+ @Nullable
+ public static String replacePlaceholder(String input, Set<String> placeholders, String value)
+ {
+ String placeholder = getPlaceholder(input);
+
+ if (placeholder == null)
+ {
+ return input;
+ }
+ if (placeholders.contains(placeholder))
+ {
+ return input.replace("${" + placeholder + "}", value);
+ }
+
+ return null;
+ }
+
+ /**
+ * Checks whether given input has any placeholder init.
+ * Placeholders can be specified using {@link #PLACEHOLDER_PATTERN} pattern.
+ *
+ * @param input input string to test
+ * @return true if the given input contains a placeholder, otherwise false
+ */
+ public static boolean hasAnyPlaceholder(String input)
+ {
+ String placeholder = getPlaceholder(input);
+ return placeholder != null;
+ }
+
+ /**
+ * Checks whether given input has any of the placeholders specified in {@code knownPlaceHolders}.
+ * Placeholders can be specified using {@link #PLACEHOLDER_PATTERN} pattern.
+ *
+ * @param input input string to test
+ * @param knownPlaceHolders set of placeholders {@code input} is expected to have.
+ * @return true if given input contains any one of the knownPlaceHolders, otherwise false
+ */
+ public static boolean hasAnyPlaceholder(String input, Set<String> knownPlaceHolders)
+ {
+ String placeholder = getPlaceholder(input);
+ return placeholder != null && knownPlaceHolders.contains(placeholder);
+ }
+
+ private static @Nullable String getPlaceholder(String input)
+ {
+ Matcher matcher = PLACEHOLDER_PATTERN.matcher(input);
+ if (matcher.find())
+ {
+ return matcher.group(1);
+ }
+ return null;
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/livemigration/MigrationFileVisitor.java b/server/src/main/java/org/apache/cassandra/sidecar/livemigration/MigrationFileVisitor.java
new file mode 100644
index 00000000..5e57a5c0
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/livemigration/MigrationFileVisitor.java
@@ -0,0 +1,122 @@
+/*
+ * 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.cassandra.sidecar.livemigration;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * File visitor to walk through given directory.
+ */
+public class MigrationFileVisitor extends SimpleFileVisitor<Path>
+{
+ private static final Logger LOGGER = LoggerFactory.getLogger(MigrationFileVisitor.class);
+ private final String homeDir;
+ private final List<Path> validFiles;
+ private final List<PathMatcher> filesToExclude;
+ private final List<PathMatcher> directoriesToExclude;
+
+ public MigrationFileVisitor(@NotNull String homeDir,
+ @NotNull List<PathMatcher> filesToExcludeMatchers,
+ @NotNull List<PathMatcher> directoriesToExcludeMatchers)
+ {
+ this.homeDir = homeDir;
+ this.validFiles = new ArrayList<>();
+ this.filesToExclude = filesToExcludeMatchers;
+ this.directoriesToExclude = directoriesToExcludeMatchers;
+ }
+
+ private boolean shouldExcludeDir(Path dir)
+ {
+ Objects.requireNonNull(dir);
+ return directoriesToExclude.stream().anyMatch(matcher -> matcher.matches(dir));
+ }
+
+ private boolean shouldExcludeFile(Path file)
+ {
+ Objects.requireNonNull(file);
+ return filesToExclude.stream().anyMatch(matcher -> matcher.matches(file));
+ }
+
+ @Override
+ public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
+ {
+ if (shouldExcludeDir(dir))
+ {
+ return FileVisitResult.SKIP_SUBTREE;
+ }
+
+ if (!dir.toAbsolutePath().toString().equals(homeDir))
+ {
+ validFiles.add(dir);
+ }
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
+ {
+ Objects.requireNonNull(file);
+ Objects.requireNonNull(attrs);
+
+ if (!shouldExcludeFile(file))
+ {
+ validFiles.add(file);
+ }
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException
+ {
+ // SimpleFileVisitor is checking if the file is null. Hence, checking the same condition here.
+ Objects.requireNonNull(file);
+ boolean isDirectory = Files.isDirectory(file);
+ final String absolutePath = file.toFile().getAbsolutePath();
+ if ((isDirectory && shouldExcludeDir(file)) || (!isDirectory && shouldExcludeFile(file)))
+ {
+ LOGGER.info("Got the exception wile trying to visit: {}. However, it's a part of the exclude list. " +
+ "Hence ignoring the exception.", absolutePath, exc);
+ return FileVisitResult.CONTINUE;
+ }
+ else
+ {
+ LOGGER.error("File/Directory visit failed for: {}", absolutePath, exc);
+ throw exc;
+ }
+ }
+
+ public List<Path> validFilePaths()
+ {
+ return validFiles;
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/modules/LiveMigrationModule.java b/server/src/main/java/org/apache/cassandra/sidecar/modules/LiveMigrationModule.java
new file mode 100644
index 00000000..3e4f86f3
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/modules/LiveMigrationModule.java
@@ -0,0 +1,56 @@
+/*
+ * 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.cassandra.sidecar.modules;
+
+import com.google.inject.AbstractModule;
+import com.google.inject.multibindings.ProvidesIntoMap;
+import org.apache.cassandra.sidecar.handlers.livemigration.LiveMigrationApiEnableDisableHandler;
+import org.apache.cassandra.sidecar.handlers.livemigration.LiveMigrationListInstanceFilesHandler;
+import org.apache.cassandra.sidecar.handlers.livemigration.LiveMigrationMap;
+import org.apache.cassandra.sidecar.handlers.livemigration.LiveMigrationMapSidecarConfigImpl;
+import org.apache.cassandra.sidecar.modules.multibindings.KeyClassMapKey;
+import org.apache.cassandra.sidecar.modules.multibindings.VertxRouteMapKeys;
+import org.apache.cassandra.sidecar.routes.RouteBuilder;
+import org.apache.cassandra.sidecar.routes.VertxRoute;
+
+/**
+ * Module for supporting LiveMigration feature.
+ */
+public class LiveMigrationModule extends AbstractModule
+{
+
+ @Override
+ protected void configure()
+ {
+ bind(LiveMigrationMap.class).to(LiveMigrationMapSidecarConfigImpl.class);
+ }
+
+
+ @ProvidesIntoMap
+ @KeyClassMapKey(VertxRouteMapKeys.LiveMigrationListInstanceFilesRouteKey.class)
+ VertxRoute listInstanceFiles(RouteBuilder.Factory factory,
+ LiveMigrationApiEnableDisableHandler liveMigrationApiEnableDisableHandler,
+ LiveMigrationListInstanceFilesHandler liveMigrationListInstanceFilesHandler)
+ {
+ return factory.builderForRoute()
+ .handler(liveMigrationApiEnableDisableHandler::isSourceOrDestination)
+ .handler(liveMigrationListInstanceFilesHandler)
+ .build();
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/modules/SidecarModules.java b/server/src/main/java/org/apache/cassandra/sidecar/modules/SidecarModules.java
index 3c1f22d4..db727f41 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/modules/SidecarModules.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/modules/SidecarModules.java
@@ -59,7 +59,8 @@ public class SidecarModules
new SSTablesAccessModule(),
new TelemetryModule(),
new UtilitiesModule(),
- new MultiBindingTypeResolverModule());
+ new MultiBindingTypeResolverModule(),
+ new LiveMigrationModule());
}
/**
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/modules/multibindings/VertxRouteMapKeys.java b/server/src/main/java/org/apache/cassandra/sidecar/modules/multibindings/VertxRouteMapKeys.java
index 43430113..3a4e7431 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/modules/multibindings/VertxRouteMapKeys.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/modules/multibindings/VertxRouteMapKeys.java
@@ -193,6 +193,11 @@ public interface VertxRouteMapKeys
HttpMethod HTTP_METHOD = HttpMethod.GET;
String ROUTE_URI = ApiEndpointsV1.SNAPSHOTS_ROUTE;
}
+ interface LiveMigrationListInstanceFilesRouteKey extends RouteClassKey
+ {
+ HttpMethod HTTP_METHOD = HttpMethod.GET;
+ String ROUTE_URI = ApiEndpointsV1.LIVE_MIGRATION_FILES_API;
+ }
interface SSTableCleanupRouteKey extends RouteClassKey
{
HttpMethod HTTP_METHOD = HttpMethod.DELETE;
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/HelperTestModules.java b/server/src/test/java/org/apache/cassandra/sidecar/HelperTestModules.java
new file mode 100644
index 00000000..e25510ef
--- /dev/null
+++ b/server/src/test/java/org/apache/cassandra/sidecar/HelperTestModules.java
@@ -0,0 +1,102 @@
+/*
+ * 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.cassandra.sidecar;
+
+import java.util.List;
+import java.util.Objects;
+
+import com.google.inject.AbstractModule;
+import io.vertx.core.http.HttpServerRequest;
+import io.vertx.core.http.HttpServerResponse;
+import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.cluster.InstancesMetadata;
+import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadata;
+import org.apache.cassandra.sidecar.exceptions.NoSuchCassandraInstanceException;
+
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Collection of Guice modules helpful for unit testing.
+ */
+public class HelperTestModules
+{
+ /**
+ * Test module for mocking Vertx routing context.
+ */
+ public static class RoutingContextTestModule extends AbstractModule
+ {
+ RoutingContext mockRoutingContext = mock(RoutingContext.class);
+ HttpServerRequest httpServerRequest = mock(HttpServerRequest.class);
+ HttpServerResponse httpServerResponse = mock(HttpServerResponse.class);
+ SocketAddress socketAddress = mock(SocketAddress.class);
+
+ @Override
+ protected void configure()
+ {
+ bind(SocketAddress.class).toInstance(socketAddress);
+ bind(HttpServerRequest.class).toInstance(httpServerRequest);
+ bind(RoutingContext.class).toInstance(mockRoutingContext);
+ bind(HttpServerResponse.class).toInstance(httpServerResponse);
+
+ when(httpServerResponse.setStatusCode(anyInt())).thenReturn(httpServerResponse);
+ when(httpServerResponse.putHeader(anyString(), anyString())).thenReturn(httpServerResponse);
+ when(httpServerRequest.localAddress()).thenReturn(socketAddress);
+
+ when(mockRoutingContext.request()).thenReturn(httpServerRequest);
+ when(mockRoutingContext.response()).thenReturn(httpServerResponse);
+ }
+ }
+
+ /**
+ * Helper module for mocking {@link InstanceMetadata} for unit tests.
+ */
+ public static class InstanceMetadataTestModule extends AbstractModule
+ {
+
+ private final List<InstanceMetadata> instanceMetadataList;
+
+ public InstanceMetadataTestModule(List<InstanceMetadata> instanceMetadataList)
+ {
+ this.instanceMetadataList = instanceMetadataList;
+ }
+
+ protected void configure()
+ {
+ InstancesMetadata mockInstancesMetadata = mock(InstancesMetadata.class);
+ when(mockInstancesMetadata.instances()).thenReturn(instanceMetadataList);
+ when(mockInstancesMetadata.instanceFromHost(anyString()))
+ .thenAnswer(invocation -> instanceMetadataList.stream()
+ .filter(instanceMetadata -> Objects.equals(instanceMetadata.host(),
+ invocation.getArgument(0)))
+ .findFirst()
+ .orElseThrow(() -> new NoSuchCassandraInstanceException("Instance does not exist")));
+ when(mockInstancesMetadata.instanceFromId(anyInt()))
+ .thenAnswer(invocation -> instanceMetadataList.stream()
+ .filter(instanceMetadata -> invocation.getArgument(0).equals(instanceMetadata.id()))
+ .findFirst()
+ .orElseThrow(() -> new NoSuchCassandraInstanceException("No Cassandra instance exists with given ID")));
+
+ bind(InstancesMetadata.class).toInstance(mockInstancesMetadata);
+ }
+ }
+}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/config/SidecarConfigurationTest.java b/server/src/test/java/org/apache/cassandra/sidecar/config/SidecarConfigurationTest.java
index cf75bb7d..294ac1bd 100644
--- a/server/src/test/java/org/apache/cassandra/sidecar/config/SidecarConfigurationTest.java
+++ b/server/src/test/java/org/apache/cassandra/sidecar/config/SidecarConfigurationTest.java
@@ -472,6 +472,27 @@ class SidecarConfigurationTest
assertThat(clusterLeaseConfig.electorateMembershipStrategy()).isEqualTo("MostReplicatedKeyspaceTokenZeroElectorateMembership");
}
+ @Test
+ void testSidecarLiveMigrationConfiguration() throws IOException
+ {
+ Path yamlPath = yaml("config/sidecar_live_migration.yaml");
+ SidecarConfiguration config = SidecarConfigurationImpl.readYamlConfiguration(yamlPath);
+ LiveMigrationConfiguration liveMigrationConfiguration = config.liveMigrationConfiguration();
+ assertThat(liveMigrationConfiguration).isNotNull();
+
+ assertThat(liveMigrationConfiguration.filesToExclude()).isNotNull()
+ .hasSize(1)
+ .contains("${DATA_FILE_DIR}/test.log");
+
+ assertThat(liveMigrationConfiguration.directoriesToExclude()).isNotNull()
+ .hasSize(1)
+ .contains("${DATA_FILE_DIR}/*/*/snapshots");
+
+ assertThat(liveMigrationConfiguration.migrationMap()).isNotNull()
+ .hasSize(1)
+ .containsEntry("localhost1", "localhost4");
+ }
+
void validateSingleInstanceSidecarConfiguration(SidecarConfiguration config)
{
assertThat(config.cassandraInstances()).isNotNull().hasSize(1);
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/handlers/livemigration/LiveMigrationApiEnableDisableHandlerTest.java b/server/src/test/java/org/apache/cassandra/sidecar/handlers/livemigration/LiveMigrationApiEnableDisableHandlerTest.java
new file mode 100644
index 00000000..952213af
--- /dev/null
+++ b/server/src/test/java/org/apache/cassandra/sidecar/handlers/livemigration/LiveMigrationApiEnableDisableHandlerTest.java
@@ -0,0 +1,159 @@
+/*
+ * 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.cassandra.sidecar.handlers.livemigration;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.jupiter.api.Test;
+
+import com.codahale.metrics.MetricRegistry;
+import com.google.inject.AbstractModule;
+import com.google.inject.Guice;
+import com.google.inject.Injector;
+import io.vertx.core.Vertx;
+import io.vertx.core.http.HttpServerRequest;
+import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.HelperTestModules.InstanceMetadataTestModule;
+import org.apache.cassandra.sidecar.HelperTestModules.RoutingContextTestModule;
+import org.apache.cassandra.sidecar.cluster.CassandraAdapterDelegate;
+import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadata;
+import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadataImpl;
+
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+class LiveMigrationApiEnableDisableHandlerTest
+{
+ private static final InstanceMetadata SOURCE_META = createMockInstanceMeta(100001, "localhost", "/tmp/dummy");
+ private static final InstanceMetadata DEST_META = createMockInstanceMeta(100002, "localhost2", "/tmp/dummy2");
+ private static final InstanceMetadata NON_MIGRATION_INSTANCE_META = createMockInstanceMeta(100003, "localhost3", "/tmp/dummy3");
+ private static final List<InstanceMetadata> INSTANCE_METADATA_LIST = new ArrayList<>(2)
+ {{
+ add(SOURCE_META);
+ add(DEST_META);
+ add(NON_MIGRATION_INSTANCE_META);
+ }};
+ private static final Map<String, String> MIGRATION_MAP = new HashMap<>()
+ {{
+ put(SOURCE_META.host(), DEST_META.host());
+ }};
+
+ private static InstanceMetadata createMockInstanceMeta(int id, String host, String rootDir)
+ {
+
+ return InstanceMetadataImpl.builder()
+ .id(id)
+ .host(host)
+ .port(9042)
+ .dataDirs(List.of(rootDir + "/data0", rootDir + "/data1"))
+ .hintsDir(rootDir + "/hints")
+ .commitlogDir(rootDir + "/commitlog")
+ .savedCachesDir(rootDir + "/saved_caches")
+ .stagingDir(rootDir + "/staging")
+ .delegate(mock(CassandraAdapterDelegate.class))
+ .metricRegistry(mock(MetricRegistry.class))
+ .build();
+ }
+
+ Injector getInjector()
+ {
+ return Guice.createInjector(new TestModule(INSTANCE_METADATA_LIST));
+ }
+
+ @Test
+ public void testIsSource()
+ {
+ final Injector injector = getInjector();
+ configureReqLocalHost(injector, SOURCE_META);
+
+ final LiveMigrationApiEnableDisableHandler enableDisableHandler = injector.getInstance(LiveMigrationApiEnableDisableHandler.class);
+ final RoutingContext routingContext = injector.getInstance(RoutingContext.class);
+ enableDisableHandler.isSource(routingContext);
+ verify(routingContext, times(1)).next();
+ verify(routingContext, times(0)).response();
+
+ configureReqLocalHost(injector, DEST_META);
+ enableDisableHandler.isSource(routingContext);
+ verify(routingContext, times(1)).fail(eq(404));
+ }
+
+ @Test
+ public void testIsDestination()
+ {
+ final Injector injector = getInjector();
+ configureReqLocalHost(injector, DEST_META);
+
+ final LiveMigrationApiEnableDisableHandler enableDisableHandler = injector.getInstance(LiveMigrationApiEnableDisableHandler.class);
+ final RoutingContext routingContext = injector.getInstance(RoutingContext.class);
+ enableDisableHandler.isDestination(routingContext);
+ verify(routingContext, times(1)).next();
+ verify(routingContext, times(0)).response();
+
+ configureReqLocalHost(injector, SOURCE_META);
+ enableDisableHandler.isDestination(routingContext);
+ verify(routingContext, times(1)).fail(eq(404));
+ }
+
+ @Test
+ public void testNonMigrationHost()
+ {
+ final Injector injector = getInjector();
+ final LiveMigrationApiEnableDisableHandler enableDisableHandler = injector.getInstance(LiveMigrationApiEnableDisableHandler.class);
+ final RoutingContext routingContext = injector.getInstance(RoutingContext.class);
+
+ configureReqLocalHost(injector, NON_MIGRATION_INSTANCE_META);
+ enableDisableHandler.isSource(routingContext);
+ verify(routingContext, times(1)).fail(eq(404));
+ }
+
+ private void configureReqLocalHost(final Injector injector, final InstanceMetadata source)
+ {
+ final SocketAddress socketAddress = injector.getInstance(SocketAddress.class);
+ final HttpServerRequest serverRequest = injector.getInstance(HttpServerRequest.class);
+ when(socketAddress.host()).thenReturn(source.host());
+ when(serverRequest.host()).thenReturn(source.host());
+ }
+
+ private static class TestModule extends AbstractModule
+ {
+ private final List<InstanceMetadata> instanceMetadataList;
+
+ public TestModule(List<InstanceMetadata> instanceMetadataList)
+ {
+ this.instanceMetadataList = instanceMetadataList;
+ }
+
+ @Override
+ protected void configure()
+ {
+ bind(Vertx.class).toInstance(Vertx.vertx());
+ LiveMigrationMap mockLiveMigrationMap = () -> MIGRATION_MAP;
+ bind(LiveMigrationMap.class).toInstance(mockLiveMigrationMap);
+ install(new RoutingContextTestModule());
+ install(new InstanceMetadataTestModule(instanceMetadataList));
+ }
+ }
+}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/handlers/livemigration/LiveMigrationListInstanceFilesHandlerTest.java b/server/src/test/java/org/apache/cassandra/sidecar/handlers/livemigration/LiveMigrationListInstanceFilesHandlerTest.java
new file mode 100644
index 00000000..98fa8168
--- /dev/null
+++ b/server/src/test/java/org/apache/cassandra/sidecar/handlers/livemigration/LiveMigrationListInstanceFilesHandlerTest.java
@@ -0,0 +1,393 @@
+/*
+ * 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.cassandra.sidecar.handlers.livemigration;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.codahale.metrics.MetricRegistry;
+import com.google.inject.AbstractModule;
+import com.google.inject.Guice;
+import com.google.inject.Injector;
+import com.google.inject.util.Modules;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.vertx.core.Vertx;
+import io.vertx.ext.web.client.WebClient;
+import io.vertx.ext.web.codec.BodyCodec;
+import io.vertx.junit5.VertxExtension;
+import io.vertx.junit5.VertxTestContext;
+import org.apache.cassandra.sidecar.HelperTestModules.InstanceMetadataTestModule;
+import org.apache.cassandra.sidecar.TestModule;
+import org.apache.cassandra.sidecar.cluster.InstancesMetadata;
+import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadata;
+import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadataImpl;
+import org.apache.cassandra.sidecar.common.response.InstanceFileInfo;
+import org.apache.cassandra.sidecar.common.response.InstanceFileInfo.FileType;
+import org.apache.cassandra.sidecar.common.response.InstanceFilesListResponse;
+import org.apache.cassandra.sidecar.config.LiveMigrationConfiguration;
+import org.apache.cassandra.sidecar.config.SidecarConfiguration;
+import org.apache.cassandra.sidecar.config.yaml.SidecarConfigurationImpl;
+import org.apache.cassandra.sidecar.metrics.MetricRegistryFactory;
+import org.apache.cassandra.sidecar.modules.SidecarModules;
+import org.apache.cassandra.sidecar.server.Server;
+
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_COMMITLOG_DIR_PATH;
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_DATA_FILE_DIR_PATH;
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_FILES_API;
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_HINTS_DIR_PATH;
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_SAVED_CACHES_DIR_PATH;
+import static org.apache.cassandra.sidecar.livemigration.InstanceFileInfoTestUtil.findInstanceFileInfo;
+import static org.apache.cassandra.sidecar.utils.TestFileUtils.createFile;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(VertxExtension.class)
+class LiveMigrationListInstanceFilesHandlerTest
+{
+ private static final int FIRST_ID = 1000110;
+ private static final String FIRST_INSTANCE_IP = "127.0.0.1";
+ private static final int SECOND_ID = 1000111;
+ private static final String SECOND_INSTANCE_IP = "127.0.0.2";
+ private static final int THIRD_ID = 1000112;
+ private static final String THIRD_INSTANCE_IP = "127.0.0.3";
+ private static final MetricRegistryFactory REGISTRY_FACTORY =
+ new MetricRegistryFactory("cassandra_sidecar_" + UUID.randomUUID(), Collections.emptyList(), Collections.emptyList());
+ private static final Logger LOGGER = LoggerFactory.getLogger(LiveMigrationListInstanceFilesHandlerTest.class);
+
+ private final Vertx vertx = Vertx.vertx();
+
+ @TempDir
+ Path tempDir;
+
+ Injector injector;
+ Server server;
+ private List<String> dataDirs;
+ private String commitlogDir;
+ private String hintsDir;
+ private String savedCachesDir;
+
+ @BeforeEach
+ public void setup() throws InterruptedException
+ {
+ InstanceMetadata sourceInstanceMeta = getInstanceMetadata(FIRST_INSTANCE_IP, FIRST_ID);
+ InstanceMetadata destinationInstanceMeta = getInstanceMetadata(SECOND_INSTANCE_IP, SECOND_ID);
+ InstanceMetadata nonSourceOrDestinationInstanceMeta = getInstanceMetadata(THIRD_INSTANCE_IP, THIRD_ID);
+ ListInstanceFilesHandlerTestModule handlerTestModule = new ListInstanceFilesHandlerTestModule(
+ Arrays.asList(sourceInstanceMeta, destinationInstanceMeta, nonSourceOrDestinationInstanceMeta));
+ injector = Guice.createInjector(Modules.override(SidecarModules.all())
+ .with(Modules.override(new TestModule())
+ .with(handlerTestModule)));
+ InstancesMetadata instancesMetadata = injector.getInstance(InstancesMetadata.class);
+ InstanceMetadata firstInstanceMetadata = instancesMetadata.instanceFromId(FIRST_ID);
+ dataDirs = firstInstanceMetadata.dataDirs();
+ commitlogDir = firstInstanceMetadata.commitlogDir();
+ hintsDir = firstInstanceMetadata.hintsDir();
+ savedCachesDir = firstInstanceMetadata.savedCachesDir();
+
+ server = injector.getInstance(Server.class);
+ VertxTestContext context = new VertxTestContext();
+ server.start()
+ .onSuccess(s -> context.completeNow())
+ .onFailure(context::failNow);
+ context.awaitCompletion(15, TimeUnit.SECONDS);
+ }
+
+
+ @AfterEach
+ void after() throws InterruptedException
+ {
+ CountDownLatch closeLatch = new CountDownLatch(1);
+ server.close().onSuccess(res -> closeLatch.countDown());
+ if (closeLatch.await(60, TimeUnit.SECONDS))
+ LOGGER.info("Close event received before timeout.");
+ else
+ LOGGER.error("Close event timed out.");
+ }
+
+ private InstanceMetadata getInstanceMetadata(String instanceIp,
+ int instanceId)
+ {
+ String root = tempDir.toString();
+ dataDirs = Arrays.asList(root + "/d1/data", root + "/d2/data");
+ MetricRegistry instanceSpecificRegistry = REGISTRY_FACTORY.getOrCreate(instanceId);
+
+ return InstanceMetadataImpl.builder()
+ .id(instanceId)
+ .host(instanceIp)
+ .port(9042)
+ .dataDirs(dataDirs)
+ .hintsDir(root + "/hints")
+ .commitlogDir(root + "/commitlog")
+ .savedCachesDir(root + "/saved_caches")
+ .stagingDir(root + "/staging")
+ .metricRegistry(instanceSpecificRegistry)
+ .build();
+ }
+
+ @Test
+ public void testApiOnSource(VertxTestContext context) throws IOException
+ {
+ String dummyContent = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
+ int fileSize = dummyContent.length();
+
+ // First data directory files
+ createFile(dummyContent, dataDirs.get(0), "ks1/table1/snapshots/snapshot1.db"); // This file doesn't qualify to be returned as it is a snapshot file
+
+ // Second data directory files
+ createFile(dummyContent, dataDirs.get(1), "ks1/table1/mf-kb-data.db");
+ createFile(dummyContent, dataDirs.get(1), "ks2/table2/mf-kc-data.db");
+ createFile(dummyContent, dataDirs.get(1), "ks2/table2/snapshots-magic.txt");
+ createFile(dummyContent, dataDirs.get(1), "snapshots/table3/mf-kc-data.db");
+ createFile(dummyContent, dataDirs.get(1), "heapdumps/table1/heapdumps-magic.txt");
+
+ // Commitlog directory files
+ createFile(dummyContent, commitlogDir, "Commitlog-7-1.log");
+ createFile(dummyContent, commitlogDir, "Commitlog-7-2.log");
+
+ // Hints directory files
+ createFile(dummyContent, hintsDir, "abcd-1.hints");
+ createFile(dummyContent, hintsDir, "def1-2.hints");
+
+ // Saved caches directory files
+ createFile(dummyContent, savedCachesDir, "cache1.db");
+ createFile(dummyContent, savedCachesDir, "cache2.db");
+
+ List<String> expectedFilesUrls = Arrays.asList(LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/1" + "/ks1/table1/mf-kb-data.db",
+ LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/1" + "/ks2/table2/mf-kc-data.db",
+ LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/1" + "/ks2/table2/snapshots-magic.txt",
+ LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/1" + "/snapshots/table3/mf-kc-data.db",
+ LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/1" + "/heapdumps/table1/heapdumps-magic.txt",
+
+ LIVE_MIGRATION_COMMITLOG_DIR_PATH + "/0" + "/Commitlog-7-1.log",
+ LIVE_MIGRATION_COMMITLOG_DIR_PATH + "/0" + "/Commitlog-7-2.log",
+
+ LIVE_MIGRATION_HINTS_DIR_PATH + "/0" + "/abcd-1.hints",
+ LIVE_MIGRATION_HINTS_DIR_PATH + "/0" + "/def1-2.hints",
+
+ LIVE_MIGRATION_SAVED_CACHES_DIR_PATH + "/0" + "/cache1.db",
+ LIVE_MIGRATION_SAVED_CACHES_DIR_PATH + "/0" + "/cache2.db");
+
+ LiveMigrationConfiguration liveMigrationConfig = injector.getInstance(SidecarConfiguration.class)
+ .liveMigrationConfiguration();
+ when(liveMigrationConfig.migrationMap()).thenReturn(Map.of(FIRST_INSTANCE_IP, SECOND_INSTANCE_IP));
+
+ List<String> unexpectedFilesUrls = new ArrayList<>();
+ unexpectedFilesUrls.add(LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0" + "ks1/table1/snapshots/snapshot1.db");
+
+ Set<String> unexpectedDirUrls = new HashSet<>();
+ // Snapshots are excluded by default
+ unexpectedDirUrls.add(LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0" + "/ks1/table1/snapshots");
+ unexpectedDirUrls.add(LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/1" + "/ks1/table1/snapshots");
+
+ WebClient client = WebClient.create(vertx);
+ client.get(server.actualPort(), "127.0.0.1", LIVE_MIGRATION_FILES_API)
+ .as(BodyCodec.buffer())
+ .send(resp -> context.verify(() -> {
+
+ assertThat(resp.result().statusCode()).isEqualTo(HttpResponseStatus.OK.code());
+
+ InstanceFilesListResponse instanceFilesList = resp.result().bodyAsJson(InstanceFilesListResponse.class);
+ assertThat(instanceFilesList).isNotNull();
+ assertThat(instanceFilesList.getTotalSize()).isEqualTo((long) expectedFilesUrls.size() * fileSize);
+
+ for (String expectedFileUrl : expectedFilesUrls)
+ {
+ InstanceFileInfo fileInfo = findInstanceFileInfo(instanceFilesList.getFiles(), expectedFileUrl);
+ assertThat(fileInfo).isNotNull();
+ assertThat(fileInfo.fileType).isEqualTo(FileType.FILE);
+ assertThat(fileInfo.size).isEqualTo(fileSize);
+ }
+
+ for (String unexpectedFileUrl : unexpectedFilesUrls)
+ {
+ InstanceFileInfo fileInfo = findInstanceFileInfo(instanceFilesList.getFiles(), unexpectedFileUrl);
+ assertThat(fileInfo).isNull();
+ }
+
+ for (String unexpectedDirUrl : unexpectedDirUrls)
+ {
+ InstanceFileInfo dirInfo = findInstanceFileInfo(instanceFilesList.getFiles(), unexpectedDirUrl);
+ assertThat(dirInfo).isNull();
+ }
+
+
+ List<InstanceFileInfo> fileInfos = instanceFilesList.getFiles()
+ .stream()
+ .filter(file -> file.fileType.equals(FileType.FILE))
+ .collect(Collectors.toList());
+
+ assertThat(fileInfos).hasSize(expectedFilesUrls.size());
+
+ client.close();
+ context.completeNow();
+ }));
+ }
+
+ @Test
+ public void testApiOnDestination(VertxTestContext context) throws IOException
+ {
+ String dummyContent = "01234567890123456789012345678901";
+ int filesSize = dummyContent.length();
+ // First data directory files
+ createFile(dummyContent, dataDirs.get(0), "ks1/table1/snapshots/snapshot1.db"); // This file doesn't qualify to be returned as it is a snapshot file
+
+ createFile(dummyContent, dataDirs.get(1), "/ks1/table1/mf-kb-data.db");
+ createFile(dummyContent, dataDirs.get(1), "/ks2/table2/mf-kc-data.db");
+ createFile(dummyContent, dataDirs.get(1), "/ks2/table2/snapshots-magic.txt");
+
+ List<String> expectedFileUrls = Arrays.asList(LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/1" + "/ks1/table1/mf-kb-data.db",
+ LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/1" + "/ks2/table2/mf-kc-data.db",
+ LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/1" + "/ks2/table2/snapshots-magic.txt");
+
+ List<String> unexpectedFileUrls = new ArrayList<>();
+ unexpectedFileUrls.add(LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0" + "/ks1/table1/snapshots/snapshot1.db"); // index of first data home directory
+
+ Set<String> unexpectedDirUrls = new HashSet<>();
+ unexpectedDirUrls.add(LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0" + "/ks1/table1/snapshots");
+ unexpectedDirUrls.add(LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/1" + "/ks1/table1/snapshots");
+
+ final Map<String, String> migrationMap = new HashMap<>()
+ {{
+ put(SECOND_INSTANCE_IP, FIRST_INSTANCE_IP);
+ }};
+
+ LiveMigrationConfiguration mockLiveMigrationConfig = injector.getInstance(SidecarConfiguration.class)
+ .liveMigrationConfiguration();
+ when(mockLiveMigrationConfig.migrationMap()).thenReturn(migrationMap);
+
+
+ WebClient client = WebClient.create(vertx);
+ client.get(server.actualPort(), "127.0.0.1", LIVE_MIGRATION_FILES_API)
+ .as(BodyCodec.buffer())
+ .send(resp -> context.verify(() -> {
+ assertThat(resp.result().statusCode()).isEqualTo(HttpResponseStatus.OK.code());
+
+ InstanceFilesListResponse instanceFilesList = resp.result().bodyAsJson(InstanceFilesListResponse.class);
+ assertThat(instanceFilesList).isNotNull();
+ assertThat(instanceFilesList.getTotalSize()).isEqualTo((long) expectedFileUrls.size() * filesSize);
+
+ for (String expectedFileUrl : expectedFileUrls)
+ {
+ InstanceFileInfo fileInfo = findInstanceFileInfo(instanceFilesList.getFiles(), expectedFileUrl);
+ assertThat(fileInfo).isNotNull();
+ assertThat(fileInfo.fileType).isEqualTo(FileType.FILE);
+ assertThat(fileInfo.size).isEqualTo(filesSize);
+ }
+
+ for (String unexpectedFileUrl : unexpectedFileUrls)
+ {
+ InstanceFileInfo fileInfo = findInstanceFileInfo(instanceFilesList.getFiles(), unexpectedFileUrl);
+ assertThat(fileInfo).isNull();
+ }
+
+ for (String unexpectedDirUrl : unexpectedDirUrls)
+ {
+ InstanceFileInfo dirInfo = findInstanceFileInfo(instanceFilesList.getFiles(), unexpectedDirUrl);
+ assertThat(dirInfo).isNull();
+ }
+
+ List<InstanceFileInfo> fileInfos = instanceFilesList.getFiles()
+ .stream()
+ .filter(file -> file.fileType.equals(FileType.FILE))
+ .collect(Collectors.toList());
+
+ assertThat(fileInfos).hasSize(expectedFileUrls.size());
+
+ client.close();
+ context.completeNow();
+ }));
+ }
+
+ @Test
+ public void testApiOnNonSourceOrDestination(VertxTestContext context)
+ {
+ final Map<String, String> migrationMap = new HashMap<>()
+ {{
+ put(SECOND_INSTANCE_IP, THIRD_INSTANCE_IP);
+ }};
+
+ LiveMigrationConfiguration mockLiveMigrationConfiguration = injector.getInstance(SidecarConfiguration.class)
+ .liveMigrationConfiguration();
+ when(mockLiveMigrationConfiguration.migrationMap()).thenReturn(migrationMap);
+
+ WebClient client = WebClient.create(vertx);
+
+ client.get(server.actualPort(), "127.0.0.1", LIVE_MIGRATION_FILES_API)
+ .as(BodyCodec.buffer())
+ .send(resp -> {
+ assertThat(resp.result().statusCode()).isEqualTo(HttpResponseStatus.NOT_FOUND.code());
+ assertThat(resp.result().statusMessage()).isEqualTo("Not Found");
+
+ client.close();
+ context.completeNow();
+ });
+ }
+
+ private static class ListInstanceFilesHandlerTestModule extends AbstractModule
+ {
+
+ private final List<InstanceMetadata> instanceMetaList;
+
+ public ListInstanceFilesHandlerTestModule(List<InstanceMetadata> instanceMetaList)
+ {
+ this.instanceMetaList = instanceMetaList;
+ }
+
+ @Override
+ protected void configure()
+ {
+
+ LiveMigrationConfiguration mockLiveMigrationConfiguration = mock(LiveMigrationConfiguration.class);
+ when(mockLiveMigrationConfiguration.filesToExclude())
+ .thenReturn(Collections.emptySet());
+ when(mockLiveMigrationConfiguration.directoriesToExclude())
+ .thenReturn(Collections.singleton("glob:${DATA_FILE_DIR}/*/*/snapshots"));
+ when(mockLiveMigrationConfiguration.migrationMap())
+ .thenReturn(Collections.emptyMap());
+
+ SidecarConfiguration sidecarConfiguration = SidecarConfigurationImpl.builder()
+ .liveMigrationConfiguration(mockLiveMigrationConfiguration)
+ .build();
+
+ bind(SidecarConfiguration.class).toInstance(sidecarConfiguration);
+ install(new InstanceMetadataTestModule(instanceMetaList));
+ }
+ }
+}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/handlers/livemigration/LiveMigrationMapSidecarConfigImplTest.java b/server/src/test/java/org/apache/cassandra/sidecar/handlers/livemigration/LiveMigrationMapSidecarConfigImplTest.java
new file mode 100644
index 00000000..c2811810
--- /dev/null
+++ b/server/src/test/java/org/apache/cassandra/sidecar/handlers/livemigration/LiveMigrationMapSidecarConfigImplTest.java
@@ -0,0 +1,81 @@
+/*
+ * 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.cassandra.sidecar.handlers.livemigration;
+
+import java.nio.file.Path;
+import java.util.Collections;
+import java.util.Map;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import com.codahale.metrics.MetricRegistry;
+import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadata;
+import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadataImpl;
+import org.apache.cassandra.sidecar.config.LiveMigrationConfiguration;
+import org.apache.cassandra.sidecar.config.yaml.LiveMigrationConfigurationImpl;
+import org.apache.cassandra.sidecar.config.yaml.SidecarConfigurationImpl;
+
+import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
+
+class LiveMigrationMapSidecarConfigImplTest
+{
+
+ @TempDir
+ private Path tempDirPath;
+
+ @Test
+ void testMigrationMap()
+ {
+ LiveMigrationConfiguration liveMigrationConfiguration =
+ new LiveMigrationConfigurationImpl(Collections.emptySet(),
+ Collections.emptySet(),
+ Map.of("localhost1", "localhost4"));
+
+ SidecarConfigurationImpl sidecarConfig =
+ SidecarConfigurationImpl.builder()
+ .liveMigrationConfiguration(liveMigrationConfiguration).build();
+
+ LiveMigrationMapSidecarConfigImpl migrationMapSidecarConfig =
+ new LiveMigrationMapSidecarConfigImpl(sidecarConfig);
+
+ InstanceMetadata localhost1Metadata = instanceMetadata("localhost1", 1);
+ InstanceMetadata localhost2Metadata = instanceMetadata("localhost2", 2);
+ InstanceMetadata localhost4Metadata = instanceMetadata("localhost4", 4);
+
+ assertThat(migrationMapSidecarConfig.getMigrationMap()).isNotNull();
+ assertThat(migrationMapSidecarConfig.getMigrationMap().size()).isEqualTo(1);
+
+ assertThat(migrationMapSidecarConfig.isSource(localhost1Metadata)).isTrue();
+ assertThat(migrationMapSidecarConfig.isDestination(localhost1Metadata)).isFalse();
+
+ assertThat(migrationMapSidecarConfig.isSource(localhost2Metadata)).isFalse();
+ assertThat(migrationMapSidecarConfig.isDestination(localhost2Metadata)).isFalse();
+
+ assertThat(migrationMapSidecarConfig.isSource(localhost4Metadata)).isFalse();
+ assertThat(migrationMapSidecarConfig.isDestination(localhost4Metadata)).isTrue();
+ }
+
+ InstanceMetadata instanceMetadata(String host, int id)
+ {
+ return InstanceMetadataImpl.builder().host(host).id(id).port(9042)
+ .storageDir(tempDirPath.toAbsolutePath() + "/" + host)
+ .metricRegistry(new MetricRegistry()).build();
+ }
+}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/livemigration/CassandraInstanceFilesImplTest.java b/server/src/test/java/org/apache/cassandra/sidecar/livemigration/CassandraInstanceFilesImplTest.java
new file mode 100644
index 00000000..b77043c4
--- /dev/null
+++ b/server/src/test/java/org/apache/cassandra/sidecar/livemigration/CassandraInstanceFilesImplTest.java
@@ -0,0 +1,236 @@
+/*
+ * 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.cassandra.sidecar.livemigration;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadata;
+import org.apache.cassandra.sidecar.common.response.InstanceFileInfo;
+import org.apache.cassandra.sidecar.config.LiveMigrationConfiguration;
+
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_CDC_RAW_DIR_PATH;
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_COMMITLOG_DIR_PATH;
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_DATA_FILE_DIR_PATH;
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_HINTS_DIR_PATH;
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_LOCAL_SYSTEM_DATA_FILE_DIR_PATH;
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_SAVED_CACHES_DIR_PATH;
+import static org.apache.cassandra.sidecar.common.response.InstanceFileInfo.FileType.DIRECTORY;
+import static org.apache.cassandra.sidecar.livemigration.InstanceFileInfoTestUtil.findInstanceFileInfo;
+import static org.apache.cassandra.sidecar.utils.TestFileUtils.createFile;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+class CassandraInstanceFilesImplTest
+{
+ private static final String DATA_DIR_1 = "data1";
+ private static final String CDC_DIR = "cdc_raw";
+ private static final String COMMITLOG_DIR = "commitlog";
+ private static final String HINTS_DIR = "hints";
+ private static final String SAVED_CACHES_DIR = "saved_caches";
+ private static final String LOCAL_SYSTEM_DATA_FILES_DIR = "local_system";
+ private static final String STAGING_DIR = "sstable-staging";
+
+ @TempDir
+ Path tempDir;
+
+ @Test
+ public void testFiles() throws IOException
+ {
+ String cassandraHomeDir = tempDir.resolve("testGetFiles").toString();
+ InstanceMetadata instanceMetadata = getInstanceMetadata(cassandraHomeDir);
+ LiveMigrationConfiguration liveMigrationConfig = mock(LiveMigrationConfiguration.class);
+ when(liveMigrationConfig.filesToExclude()).thenReturn(Collections.emptySet());
+ when(liveMigrationConfig.directoriesToExclude()).thenReturn(Collections.emptySet());
+
+ String content = "abcdefg";
+ createFile(content, instanceMetadata.dataDirs().get(0), "ks1", "t1", "file1.db");
+ createFile(content, instanceMetadata.cdcDir(), "cdc_raw1.log");
+ createFile(content, instanceMetadata.commitlogDir(), "commitlog0");
+ createFile(content, instanceMetadata.hintsDir(), "hints1");
+ createFile(content, instanceMetadata.savedCachesDir(), "cache1.db");
+ createFile(content, instanceMetadata.localSystemDataFileDir(), "system", "local", "data1.db");
+ createFile(content, instanceMetadata.stagingDir(), "stage-data.db");
+
+ CassandraInstanceFilesImpl instanceFiles = new CassandraInstanceFilesImpl(instanceMetadata, liveMigrationConfig);
+ List<InstanceFileInfo> instanceFileInfoList = instanceFiles.files();
+
+ assertThat(instanceFileInfoList).isNotEmpty();
+ InstanceFileInfo ks1FileInfo = findInstanceFileInfo(instanceFileInfoList,
+ LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0/ks1");
+ assertThat(ks1FileInfo).isNotNull();
+ assertThat(ks1FileInfo.fileType).isEqualTo(DIRECTORY);
+
+ InstanceFileInfo ks1T1FileInfo = findInstanceFileInfo(instanceFileInfoList,
+ LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0/ks1/t1");
+ assertThat(ks1T1FileInfo).isNotNull();
+ assertThat(ks1T1FileInfo.fileType).isEqualTo(DIRECTORY);
+
+ assertThat(findInstanceFileInfo(instanceFileInfoList, LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0/ks1/t1/file1.db")).isNotNull();
+ assertThat(findInstanceFileInfo(instanceFileInfoList, LIVE_MIGRATION_CDC_RAW_DIR_PATH + "/0/cdc_raw1.log")).isNotNull();
+ assertThat(findInstanceFileInfo(instanceFileInfoList, LIVE_MIGRATION_COMMITLOG_DIR_PATH + "/0/commitlog0")).isNotNull();
+ assertThat(findInstanceFileInfo(instanceFileInfoList, LIVE_MIGRATION_HINTS_DIR_PATH + "/0/hints1")).isNotNull();
+ assertThat(findInstanceFileInfo(instanceFileInfoList, LIVE_MIGRATION_SAVED_CACHES_DIR_PATH + "/0/cache1.db")).isNotNull();
+ assertThat(findInstanceFileInfo(instanceFileInfoList, LIVE_MIGRATION_LOCAL_SYSTEM_DATA_FILE_DIR_PATH
+ + "/0/system/local/data1.db")).isNotNull();
+ }
+
+ @Test
+ public void testFilesNoExclusionsSpecified() throws IOException
+ {
+ String cassandraHomeDir = tempDir.resolve("testGetFilesNoExclusionsSpecified").toString();
+ InstanceMetadata instanceMetadata = getInstanceMetadata(cassandraHomeDir);
+ LiveMigrationConfiguration liveMigrationConfig = mock(LiveMigrationConfiguration.class);
+ when(liveMigrationConfig.filesToExclude()).thenReturn(null);
+ when(liveMigrationConfig.directoriesToExclude()).thenReturn(null);
+
+ String content = "abcdefg";
+ createFile(content, instanceMetadata.dataDirs().get(0), "ks1", "t1", "file1.db");
+
+ CassandraInstanceFilesImpl instanceFiles = new CassandraInstanceFilesImpl(instanceMetadata, liveMigrationConfig);
+ List<InstanceFileInfo> instanceFileInfoList = instanceFiles.files();
+
+ assertThat(instanceFileInfoList).isNotEmpty();
+ InstanceFileInfo ks1FileInfo = findInstanceFileInfo(instanceFileInfoList,
+ LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0/ks1");
+ assertThat(ks1FileInfo).isNotNull();
+ assertThat(ks1FileInfo.fileType).isEqualTo(DIRECTORY);
+
+ InstanceFileInfo ks1T1FileInfo = findInstanceFileInfo(instanceFileInfoList,
+ LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0/ks1/t1");
+ assertThat(ks1T1FileInfo).isNotNull();
+ assertThat(ks1T1FileInfo.fileType).isEqualTo(DIRECTORY);
+
+ assertThat(findInstanceFileInfo(instanceFileInfoList, LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0/ks1/t1/file1.db")).isNotNull();
+ }
+
+ @Test
+ public void testFilesAndDirsExcluded() throws IOException
+ {
+ String cassandraHomeDir = tempDir.resolve("testGetFilesWithFilesAndDirsExcluded").toString();
+ InstanceMetadata instanceMetadata = getInstanceMetadata(cassandraHomeDir);
+
+ Set<String> dirsToExclude = new HashSet<>();
+ Set<String> filesToExclude = new HashSet<>();
+
+ LiveMigrationConfiguration liveMigrationConfig = mock(LiveMigrationConfiguration.class);
+ when(liveMigrationConfig.filesToExclude()).thenReturn(filesToExclude);
+ when(liveMigrationConfig.directoriesToExclude()).thenReturn(dirsToExclude);
+
+ String content = "abcdefg";
+ createFile(content, instanceMetadata.dataDirs().get(0), "ks1", "t1", "file1.db");
+ createFile(content, instanceMetadata.cdcDir(), "cdc_raw1.log");
+ createFile(content, instanceMetadata.commitlogDir(), "commitlog0");
+ createFile(content, instanceMetadata.hintsDir(), "hints1");
+ createFile(content, instanceMetadata.savedCachesDir(), "cache1.db");
+ createFile(content, instanceMetadata.localSystemDataFileDir(), "system", "local", "data1.db");
+ createFile(content, instanceMetadata.stagingDir(), "stage-data.db");
+
+ dirsToExclude.add("glob:" + instanceMetadata.hintsDir()); // dir excluded without placeholder
+ dirsToExclude.add("glob:${COMMITLOG_DIR}"); // dir excluded using placeholder
+
+ filesToExclude.add("glob:" + instanceMetadata.dataDirs().get(0) + "/ks1/t1/file1.db");
+ filesToExclude.add("glob:${CDC_RAW_DIR}" + "/*.log");
+
+
+ CassandraInstanceFilesImpl instanceFiles = new CassandraInstanceFilesImpl(instanceMetadata, liveMigrationConfig);
+ List<InstanceFileInfo> instanceFileInfoList = instanceFiles.files();
+
+ assertThat(instanceFileInfoList).isNotEmpty();
+ InstanceFileInfo ks1FileInfo = findInstanceFileInfo(instanceFileInfoList,
+ LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0/ks1");
+ assertThat(ks1FileInfo).isNotNull();
+ assertThat(ks1FileInfo.fileType).isEqualTo(DIRECTORY);
+
+ InstanceFileInfo ks1T1FileInfo = findInstanceFileInfo(instanceFileInfoList,
+ LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0/ks1/t1");
+ assertThat(ks1T1FileInfo).isNotNull();
+ assertThat(ks1T1FileInfo.fileType).isEqualTo(DIRECTORY);
+
+ assertThat(findInstanceFileInfo(instanceFileInfoList, LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0/ks1/t1/file1.db")).isNull();
+ assertThat(findInstanceFileInfo(instanceFileInfoList, LIVE_MIGRATION_CDC_RAW_DIR_PATH + "/0/cdc_raw1.log")).isNull();
+ assertThat(findInstanceFileInfo(instanceFileInfoList, LIVE_MIGRATION_COMMITLOG_DIR_PATH)).isNull();
+ assertThat(findInstanceFileInfo(instanceFileInfoList, LIVE_MIGRATION_COMMITLOG_DIR_PATH + "/0")).isNull();
+ assertThat(findInstanceFileInfo(instanceFileInfoList, LIVE_MIGRATION_HINTS_DIR_PATH)).isNull();
+ assertThat(findInstanceFileInfo(instanceFileInfoList, LIVE_MIGRATION_HINTS_DIR_PATH + "/0")).isNull();
+ assertThat(findInstanceFileInfo(instanceFileInfoList, LIVE_MIGRATION_SAVED_CACHES_DIR_PATH + "/0/cache1.db")).isNotNull();
+ assertThat(findInstanceFileInfo(instanceFileInfoList, LIVE_MIGRATION_LOCAL_SYSTEM_DATA_FILE_DIR_PATH
+ + "/0/system/local/data1.db")).isNotNull();
+ }
+
+ @Test
+ public void testFilesWhenFewDirectoriesDoesNotExist() throws IOException
+ {
+ //cdc_dir, saved_caches_dir & local_system_data_files_dir not present
+ String cassandraHomeDir = tempDir.resolve("testGetFiles").toString();
+ InstanceMetadata instanceMetadata = getInstanceMetadata(cassandraHomeDir);
+ when(instanceMetadata.cdcDir()).thenReturn(null); // cdc dir is null
+ when(instanceMetadata.savedCachesDir()).thenReturn(null); // saved caches dir is null
+ when(instanceMetadata.localSystemDataFileDir()).thenReturn(null);
+ LiveMigrationConfiguration liveMigrationConfig = mock(LiveMigrationConfiguration.class);
+ when(liveMigrationConfig.filesToExclude()).thenReturn(Collections.emptySet());
+ when(liveMigrationConfig.directoriesToExclude()).thenReturn(Collections.emptySet());
+
+ String content = "abcdefg";
+ createFile(content, instanceMetadata.dataDirs().get(0), "ks1", "t1", "file1.db");
+
+ CassandraInstanceFilesImpl instanceFiles = new CassandraInstanceFilesImpl(instanceMetadata, liveMigrationConfig);
+ List<InstanceFileInfo> instanceFileInfoList = instanceFiles.files();
+ assertThat(instanceFileInfoList).isNotEmpty();
+
+ InstanceFileInfo ks1FileInfo = findInstanceFileInfo(instanceFileInfoList,
+ LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0/ks1");
+ assertThat(ks1FileInfo).isNotNull();
+ assertThat(ks1FileInfo.fileType).isEqualTo(DIRECTORY);
+
+ InstanceFileInfo ks1T1FileInfo = findInstanceFileInfo(instanceFileInfoList,
+ LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0/ks1/t1");
+ assertThat(ks1T1FileInfo).isNotNull();
+ assertThat(ks1T1FileInfo.fileType).isEqualTo(DIRECTORY);
+
+ assertThat(findInstanceFileInfo(instanceFileInfoList, LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0/ks1/t1/file1.db")).isNotNull();
+ }
+
+
+ InstanceMetadata getInstanceMetadata(String cassandraHomeDir)
+ {
+ InstanceMetadata instanceMetadata = mock(InstanceMetadata.class);
+ List<String> dataDirs = new ArrayList<>(1);
+ dataDirs.add(cassandraHomeDir + "/" + DATA_DIR_1);
+ when(instanceMetadata.dataDirs()).thenReturn(dataDirs);
+ when(instanceMetadata.cdcDir()).thenReturn(cassandraHomeDir + "/" + CDC_DIR);
+ when(instanceMetadata.commitlogDir()).thenReturn(cassandraHomeDir + "/" + COMMITLOG_DIR);
+ when(instanceMetadata.hintsDir()).thenReturn(cassandraHomeDir + "/" + HINTS_DIR);
+ when(instanceMetadata.savedCachesDir()).thenReturn(cassandraHomeDir + "/" + SAVED_CACHES_DIR);
+ when(instanceMetadata.localSystemDataFileDir())
+ .thenReturn(cassandraHomeDir + "/" + LOCAL_SYSTEM_DATA_FILES_DIR);
+ when(instanceMetadata.stagingDir()).thenReturn(cassandraHomeDir + "/" + STAGING_DIR);
+
+ return instanceMetadata;
+ }
+}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/livemigration/DirVisitorTest.java b/server/src/test/java/org/apache/cassandra/sidecar/livemigration/DirVisitorTest.java
new file mode 100644
index 00000000..f8cd5b2d
--- /dev/null
+++ b/server/src/test/java/org/apache/cassandra/sidecar/livemigration/DirVisitorTest.java
@@ -0,0 +1,79 @@
+/*
+ * 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.cassandra.sidecar.livemigration;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Collections;
+import java.util.List;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import org.apache.cassandra.sidecar.common.response.InstanceFileInfo;
+
+import static org.apache.cassandra.sidecar.livemigration.InstanceFileInfoTestUtil.findInstanceFileInfo;
+import static org.apache.cassandra.sidecar.utils.TestFileUtils.createDirectory;
+import static org.apache.cassandra.sidecar.utils.TestFileUtils.createFile;
+import static org.assertj.core.api.Assertions.assertThat;
+
+class DirVisitorTest
+{
+ @TempDir
+ Path tempDir;
+
+ @SuppressWarnings("DataFlowIssue")
+ @Test
+ void testFiles() throws IOException
+ {
+ Path dataDir = Paths.get(tempDir.toString(), "data");
+ Files.createDirectories(dataDir);
+
+ String homeDir = dataDir.toString();
+ createDirectory(homeDir, "ks1", "t1");
+ // creating a test file with length 4
+ createFile("abcd", homeDir, "ks1", "t1", "data1.db");
+ // creating a test file with length 5
+ createFile("efghi", homeDir, "ks1", "t1", "data2.db");
+ int homeDirIndex = 3;
+ String pathPrefix = "/DUMMY_PREFIX/" + homeDirIndex;
+
+ DirVisitor dirVisitor = new DirVisitor(homeDir, pathPrefix, Collections.emptyList(), Collections.emptyList());
+ List<InstanceFileInfo> files = dirVisitor.files();
+ assertThat(files.size()).isEqualTo(4); // Two directories and two files
+
+ assertThat(findInstanceFileInfo(files, pathPrefix + "/ks1")).isNotNull();
+ assertThat(findInstanceFileInfo(files, pathPrefix + "/ks1").size)
+ .isEqualTo(-1);
+
+ assertThat(findInstanceFileInfo(files, pathPrefix + "/ks1/t1")).isNotNull();
+ assertThat(findInstanceFileInfo(files, pathPrefix + "/ks1/t1").size)
+ .isEqualTo(-1);
+
+ assertThat(findInstanceFileInfo(files, pathPrefix + "/ks1/t1/data1.db")).isNotNull();
+ assertThat(findInstanceFileInfo(files, pathPrefix + "/ks1/t1/data1.db").size)
+ .isEqualTo(4);
+
+ assertThat(findInstanceFileInfo(files, pathPrefix + "/ks1/t1/data2.db")).isNotNull();
+ assertThat(findInstanceFileInfo(files, pathPrefix + "/ks1/t1/data2.db").size)
+ .isEqualTo(5);
+ }
+}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/livemigration/InstanceFileInfoTestUtil.java b/server/src/test/java/org/apache/cassandra/sidecar/livemigration/InstanceFileInfoTestUtil.java
new file mode 100644
index 00000000..769c5930
--- /dev/null
+++ b/server/src/test/java/org/apache/cassandra/sidecar/livemigration/InstanceFileInfoTestUtil.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.cassandra.sidecar.livemigration;
+
+import java.util.List;
+
+import org.apache.cassandra.sidecar.common.response.InstanceFileInfo;
+
+/**
+ * Utility class to work with {@link InstanceFileInfo} instances easily for unit testing.
+ */
+public class InstanceFileInfoTestUtil
+{
+ public static InstanceFileInfo findInstanceFileInfo(List<InstanceFileInfo> fileInfoList, String fileUrl)
+ {
+ for (InstanceFileInfo fileInfo : fileInfoList)
+ {
+ if (fileInfo.fileUrl.equals(fileUrl))
+ {
+ return fileInfo;
+ }
+ }
+ return null;
+ }
+}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/livemigration/LiveMigrationInstanceMetadataUtilTest.java b/server/src/test/java/org/apache/cassandra/sidecar/livemigration/LiveMigrationInstanceMetadataUtilTest.java
new file mode 100644
index 00000000..6f8fb050
--- /dev/null
+++ b/server/src/test/java/org/apache/cassandra/sidecar/livemigration/LiveMigrationInstanceMetadataUtilTest.java
@@ -0,0 +1,322 @@
+/*
+ * 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.cassandra.sidecar.livemigration;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Function;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadata;
+import org.mockito.Mockito;
+
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_CDC_RAW_DIR_PATH;
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_COMMITLOG_DIR_PATH;
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_DATA_FILE_DIR_PATH;
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_HINTS_DIR_PATH;
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_LOCAL_SYSTEM_DATA_FILE_DIR_PATH;
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.LIVE_MIGRATION_SAVED_CACHES_DIR_PATH;
+import static org.apache.cassandra.sidecar.livemigration.LiveMigrationInstanceMetadataUtil.localPath;
+import static org.apache.cassandra.sidecar.livemigration.LiveMigrationPlaceholderUtil.CDC_RAW_DIR_PLACEHOLDER;
+import static org.apache.cassandra.sidecar.livemigration.LiveMigrationPlaceholderUtil.COMMITLOG_DIR_PLACEHOLDER;
+import static org.apache.cassandra.sidecar.livemigration.LiveMigrationPlaceholderUtil.DATA_FILE_DIR_PLACEHOLDER;
+import static org.apache.cassandra.sidecar.livemigration.LiveMigrationPlaceholderUtil.HINTS_DIR_PLACEHOLDER;
+import static org.apache.cassandra.sidecar.livemigration.LiveMigrationPlaceholderUtil.LOCAL_SYSTEM_DATA_FILE_DIR_PLACEHOLDER;
+import static org.apache.cassandra.sidecar.livemigration.LiveMigrationPlaceholderUtil.SAVED_CACHES_DIR_PLACEHOLDER;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
+import static org.assertj.core.api.Assertions.entry;
+import static org.mockito.Mockito.when;
+
+class LiveMigrationInstanceMetadataUtilTest
+{
+ private static final String DATA_DIR = "data";
+ private static final String HINTS_DIR = "hints";
+ private static final String COMMITLOG_DIR = "commitlog";
+ private static final String SAVED_CACHES_DIR = "saved_caches";
+ private static final String CDC_RAW_DIR = "cdc_raw";
+ private static final String LOCAL_SYSTEM_DIR = "local_system_data";
+ private static final String STAGING_DIR = "sstable-staging";
+
+ private static final String FILE_NAME = "file1.db";
+
+ @TempDir
+ Path tempDir;
+
+ @Test
+ public void testDirsToCopy()
+ {
+ String cassandraHomeDir = tempDir.resolve("testDirsToCopy").toString();
+ InstanceMetadata instanceMetadata = getInstanceMetadata(cassandraHomeDir);
+ List<String> dataDirs = new ArrayList<>(2);
+ String dataDir2 = DATA_DIR + "2";
+ dataDirs.add(cassandraHomeDir + "/" + DATA_DIR);
+ dataDirs.add(cassandraHomeDir + "/" + dataDir2);
+ when(instanceMetadata.dataDirs()).thenReturn(dataDirs);
+
+ List<String> dirsToCopy = LiveMigrationInstanceMetadataUtil.dirsToCopy(instanceMetadata);
+
+ assertThat(dirsToCopy.size()).isEqualTo(7);
+ assertThat(dirsToCopy).contains(cassandraHomeDir + "/" + DATA_DIR)
+ .contains(cassandraHomeDir + "/" + dataDir2)
+ .contains(cassandraHomeDir + "/" + HINTS_DIR)
+ .contains(cassandraHomeDir + "/" + COMMITLOG_DIR)
+ .contains(cassandraHomeDir + "/" + SAVED_CACHES_DIR)
+ .contains(cassandraHomeDir + "/" + CDC_RAW_DIR)
+ .contains(cassandraHomeDir + "/" + LOCAL_SYSTEM_DIR);
+ }
+
+ @Test
+ public void testDirsToCopyFewDirsNotConfigured()
+ {
+ String cassandraHomeDir = tempDir.resolve("testDirsToCopyFewDirsNotConfigured").toString();
+ InstanceMetadata instanceMetadata = getInstanceMetadata(cassandraHomeDir);
+ when(instanceMetadata.cdcDir()).thenReturn(null);
+ when(instanceMetadata.localSystemDataFileDir()).thenReturn(null);
+
+ List<String> dirsToCopy = LiveMigrationInstanceMetadataUtil.dirsToCopy(instanceMetadata);
+
+ assertThat(dirsToCopy).hasSize(4);
+
+ assertThat(dirsToCopy).doesNotContain(cassandraHomeDir + "/" + CDC_RAW_DIR)
+ .doesNotContain(cassandraHomeDir + "/" + LOCAL_SYSTEM_DIR);
+ }
+
+ @Test
+ public void testDirPathPrefixMap()
+ {
+ String cassandraHomeDir = tempDir.resolve("testDirPathPrefixMap").toString();
+ InstanceMetadata instanceMetadata = getInstanceMetadata(cassandraHomeDir);
+ List<String> dataDirs = new ArrayList<>(2);
+ String dataDir2 = DATA_DIR + "2";
+ dataDirs.add(cassandraHomeDir + "/" + DATA_DIR);
+ dataDirs.add(cassandraHomeDir + "/" + dataDir2);
+ when(instanceMetadata.dataDirs()).thenReturn(dataDirs);
+
+ Map<String, String> dirPathPrefixMap = LiveMigrationInstanceMetadataUtil.dirPathPrefixMap(instanceMetadata);
+
+ List<String> dirsToCopy = LiveMigrationInstanceMetadataUtil.dirsToCopy(instanceMetadata);
+ assertThat(dirPathPrefixMap).hasSize(dirsToCopy.size());
+ assertThat(dirPathPrefixMap.keySet()).containsAll(dirsToCopy);
+ assertThat(dirPathPrefixMap).contains(
+ entry(cassandraHomeDir + "/" + DATA_DIR, LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0"),
+ entry(cassandraHomeDir + "/" + dataDir2, LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/1"),
+ entry(cassandraHomeDir + "/" + HINTS_DIR, LIVE_MIGRATION_HINTS_DIR_PATH + "/0"),
+ entry(cassandraHomeDir + "/" + COMMITLOG_DIR, LIVE_MIGRATION_COMMITLOG_DIR_PATH + "/0"),
+ entry(cassandraHomeDir + "/" + SAVED_CACHES_DIR, LIVE_MIGRATION_SAVED_CACHES_DIR_PATH + "/0"),
+ entry(cassandraHomeDir + "/" + CDC_RAW_DIR, LIVE_MIGRATION_CDC_RAW_DIR_PATH + "/0"),
+ entry(cassandraHomeDir + "/" + LOCAL_SYSTEM_DIR, LIVE_MIGRATION_LOCAL_SYSTEM_DATA_FILE_DIR_PATH + "/0")
+ );
+ }
+
+ @Test
+ public void testDirPathPrefixMapFewDirsNotConfigured()
+ {
+ String cassandraHomeDir = tempDir.resolve("testDirsToCopyFewDirsNotConfigured").toString();
+ InstanceMetadata instanceMetadata = getInstanceMetadata(cassandraHomeDir);
+ when(instanceMetadata.cdcDir()).thenReturn(null);
+ when(instanceMetadata.localSystemDataFileDir()).thenReturn(null);
+
+ Map<String, String> dirPathPrefixMap = LiveMigrationInstanceMetadataUtil.dirPathPrefixMap(instanceMetadata);
+
+ List<String> dirsToCopy = LiveMigrationInstanceMetadataUtil.dirsToCopy(instanceMetadata);
+ assertThat(dirPathPrefixMap).hasSize(dirsToCopy.size());
+ assertThat(dirPathPrefixMap.keySet()).containsAll(dirsToCopy);
+ assertThat(dirPathPrefixMap).doesNotContainKey(cassandraHomeDir + "/" + CDC_RAW_DIR)
+ .doesNotContainKey(cassandraHomeDir + "/" + LOCAL_SYSTEM_DIR);
+ }
+
+ @Test
+ public void testDirPlaceholderMap()
+ {
+ String cassandraHomeDir = tempDir.resolve("testDirPlaceholderMap").toString();
+ InstanceMetadata instanceMetadata = getInstanceMetadata(cassandraHomeDir);
+ List<String> dataDirs = new ArrayList<>(2);
+ String dataDir2 = DATA_DIR + "2";
+ dataDirs.add(cassandraHomeDir + "/" + DATA_DIR);
+ dataDirs.add(cassandraHomeDir + "/" + dataDir2);
+ when(instanceMetadata.dataDirs()).thenReturn(dataDirs);
+
+ Map<String, Set<String>> dirPathPrefixMap = LiveMigrationInstanceMetadataUtil.dirPlaceHoldersMap(instanceMetadata);
+
+ List<String> dirsToCopy = LiveMigrationInstanceMetadataUtil.dirsToCopy(instanceMetadata);
+ assertThat(dirPathPrefixMap).hasSize(dirsToCopy.size());
+ assertThat(dirPathPrefixMap.keySet()).containsAll(dirsToCopy);
+ assertThat(dirPathPrefixMap).contains(
+
+ entry(cassandraHomeDir + "/" + DATA_DIR, new HashSet<>()
+ {{
+ add(DATA_FILE_DIR_PLACEHOLDER);
+ add(DATA_FILE_DIR_PLACEHOLDER + "_" + 0);
+ }}),
+ entry(cassandraHomeDir + "/" + dataDir2, new HashSet<>()
+ {{
+ add(DATA_FILE_DIR_PLACEHOLDER);
+ add(DATA_FILE_DIR_PLACEHOLDER + "_" + 1);
+ }}),
+ entry(cassandraHomeDir + "/" + HINTS_DIR, Collections.singleton(HINTS_DIR_PLACEHOLDER)),
+ entry(cassandraHomeDir + "/" + COMMITLOG_DIR, Collections.singleton(COMMITLOG_DIR_PLACEHOLDER)),
+ entry(cassandraHomeDir + "/" + SAVED_CACHES_DIR, Collections.singleton(SAVED_CACHES_DIR_PLACEHOLDER)),
+ entry(cassandraHomeDir + "/" + CDC_RAW_DIR, Collections.singleton(CDC_RAW_DIR_PLACEHOLDER)),
+ entry(cassandraHomeDir + "/" + LOCAL_SYSTEM_DIR, Collections.singleton(LOCAL_SYSTEM_DATA_FILE_DIR_PLACEHOLDER))
+
+ );
+ }
+
+ @Test
+ public void testDirPlaceholderMapFewDirsNotConfigured()
+ {
+ String cassandraHomeDir = tempDir.resolve("testDirPlaceholderMapFewDirsNotConfigured").toString();
+ InstanceMetadata instanceMetadata = getInstanceMetadata(cassandraHomeDir);
+ when(instanceMetadata.cdcDir()).thenReturn(null);
+ when(instanceMetadata.localSystemDataFileDir()).thenReturn(null);
+
+ Map<String, Set<String>> dirPathPrefixMap = LiveMigrationInstanceMetadataUtil.dirPlaceHoldersMap(instanceMetadata);
+
+ List<String> dirsToCopy = LiveMigrationInstanceMetadataUtil.dirsToCopy(instanceMetadata);
+ assertThat(dirPathPrefixMap).hasSize(dirsToCopy.size());
+ assertThat(dirPathPrefixMap.keySet()).containsAll(dirsToCopy);
+
+ assertThat(dirPathPrefixMap).doesNotContainKey(cassandraHomeDir + "/" + CDC_RAW_DIR)
+ .doesNotContainKey(cassandraHomeDir + "/" + LOCAL_SYSTEM_DIR);
+ }
+
+
+ @Test
+ public void testLocalPath()
+ {
+ String cassandraHomeDir = tempDir.resolve("testLocalPath").toString();
+ InstanceMetadata instanceMetadata = getInstanceMetadata(cassandraHomeDir);
+
+ validateLocalPath(instanceMetadata.dataDirs().get(0) + "/" + FILE_NAME,
+ LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0/" + FILE_NAME,
+ instanceMetadata);
+ validateLocalPath(instanceMetadata.cdcDir() + "/" + FILE_NAME,
+ LIVE_MIGRATION_CDC_RAW_DIR_PATH + "/0/" + FILE_NAME,
+ instanceMetadata);
+ validateLocalPath(instanceMetadata.commitlogDir() + "/" + FILE_NAME,
+ LIVE_MIGRATION_COMMITLOG_DIR_PATH + "/0/" + FILE_NAME,
+ instanceMetadata);
+ validateLocalPath(instanceMetadata.hintsDir() + "/" + FILE_NAME,
+ LIVE_MIGRATION_HINTS_DIR_PATH + "/0/" + FILE_NAME,
+ instanceMetadata);
+ validateLocalPath(instanceMetadata.savedCachesDir() + "/" + FILE_NAME,
+ LIVE_MIGRATION_SAVED_CACHES_DIR_PATH + "/0/" + FILE_NAME,
+ instanceMetadata);
+ validateLocalPath(instanceMetadata.localSystemDataFileDir() + "/" + FILE_NAME,
+ LIVE_MIGRATION_LOCAL_SYSTEM_DATA_FILE_DIR_PATH + "/0/" + FILE_NAME,
+ instanceMetadata);
+ }
+
+ @Test
+ public void testRelativeLocalPaths()
+ {
+ String cassandraHomeDir = tempDir.resolve("testLocalPath").toString();
+ InstanceMetadata instanceMetadata = getInstanceMetadata(cassandraHomeDir);
+
+ validateIllegalLocalPath(LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0/../" + FILE_NAME,
+ instanceMetadata);
+ validateIllegalLocalPath(LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0/../../" + FILE_NAME,
+ instanceMetadata);
+ validateIllegalLocalPath(LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0/" + FILE_NAME + "/..",
+ instanceMetadata);
+ validateIllegalLocalPath(LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0/../../../../etc/passwd",
+ instanceMetadata);
+ validateIllegalLocalPath(LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/../../../../etc/passwd",
+ instanceMetadata);
+ validateIllegalLocalPath(LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/0/" + FILE_NAME + "/../../../../etc/passwd",
+ instanceMetadata);
+ }
+
+ @Test
+ public void testLocalPathNonExistingDirs()
+ {
+ String cassandraHomeDir = tempDir.resolve("testGetLocalPathNonExistingDirs").toString();
+ InstanceMetadata instanceMetadata = getInstanceMetadata(cassandraHomeDir);
+ when(instanceMetadata.cdcDir()).thenReturn(null);
+ when(instanceMetadata.localSystemDataFileDir()).thenReturn(null);
+
+ assertThatIllegalArgumentException()
+ .isThrownBy(() -> localPath(LIVE_MIGRATION_CDC_RAW_DIR_PATH + "/0/" + FILE_NAME,
+ instanceMetadata));
+
+ assertThatIllegalArgumentException()
+ .isThrownBy(() -> localPath(LIVE_MIGRATION_LOCAL_SYSTEM_DATA_FILE_DIR_PATH + "/0/" + FILE_NAME,
+ instanceMetadata));
+ }
+
+ @Test
+ public void testLocalPathInvalidDownloadUrls()
+ {
+
+ String cassandraHomeDir = tempDir.resolve("testLocalPathInvalidDownloadUrls").toString();
+ InstanceMetadata instanceMetadata = getInstanceMetadata(cassandraHomeDir);
+
+ Function<String, String> localPath = (url) -> localPath(url, instanceMetadata);
+
+ assertThatIllegalArgumentException()
+ .isThrownBy(() -> localPath.apply(LIVE_MIGRATION_DATA_FILE_DIR_PATH + "/2/" + FILE_NAME));
+
+ assertThatIllegalArgumentException()
+ .isThrownBy(() -> localPath.apply(LIVE_MIGRATION_CDC_RAW_DIR_PATH + "/1/" + FILE_NAME));
+
+ assertThatIllegalArgumentException()
+ .isThrownBy(() -> localPath.apply(LIVE_MIGRATION_COMMITLOG_DIR_PATH + "/1/" + FILE_NAME));
+
+ assertThatIllegalArgumentException()
+ .isThrownBy(() -> localPath.apply(LIVE_MIGRATION_HINTS_DIR_PATH + "/1/" + FILE_NAME));
+
+ assertThatIllegalArgumentException()
+ .isThrownBy(() -> localPath.apply(LIVE_MIGRATION_SAVED_CACHES_DIR_PATH + "/1/" + FILE_NAME));
+ assertThatIllegalArgumentException()
+ .isThrownBy(() -> localPath.apply(LIVE_MIGRATION_LOCAL_SYSTEM_DATA_FILE_DIR_PATH + "/1/" + FILE_NAME));
+ }
+
+ void validateLocalPath(String expectedPath, String fileDownloadUrl, InstanceMetadata instanceMetadata)
+ {
+ assertThat(localPath(fileDownloadUrl, instanceMetadata)).isEqualTo(expectedPath);
+ }
+
+ void validateIllegalLocalPath(String fileDownloadUrl, InstanceMetadata instanceMetadata)
+ {
+ assertThatIllegalArgumentException()
+ .isThrownBy(() -> localPath(fileDownloadUrl, instanceMetadata));
+ }
+
+ InstanceMetadata getInstanceMetadata(String cassandraHomeDir)
+ {
+ InstanceMetadata instanceMetadata = Mockito.mock(InstanceMetadata.class);
+ when(instanceMetadata.dataDirs()).thenReturn(Collections.singletonList(cassandraHomeDir + "/" + DATA_DIR));
+ when(instanceMetadata.cdcDir()).thenReturn(cassandraHomeDir + "/" + CDC_RAW_DIR);
+ when(instanceMetadata.commitlogDir()).thenReturn(cassandraHomeDir + "/" + COMMITLOG_DIR);
+ when(instanceMetadata.hintsDir()).thenReturn(cassandraHomeDir + "/" + HINTS_DIR);
+ when(instanceMetadata.savedCachesDir()).thenReturn(cassandraHomeDir + "/" + SAVED_CACHES_DIR);
+ when(instanceMetadata.localSystemDataFileDir()).thenReturn(cassandraHomeDir + "/" + LOCAL_SYSTEM_DIR);
+ when(instanceMetadata.stagingDir()).thenReturn(cassandraHomeDir + "/" + STAGING_DIR);
+
+ return instanceMetadata;
+ }
+}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/livemigration/LiveMigrationPlaceholderUtilTest.java b/server/src/test/java/org/apache/cassandra/sidecar/livemigration/LiveMigrationPlaceholderUtilTest.java
new file mode 100644
index 00000000..e800dcf6
--- /dev/null
+++ b/server/src/test/java/org/apache/cassandra/sidecar/livemigration/LiveMigrationPlaceholderUtilTest.java
@@ -0,0 +1,73 @@
+/*
+ * 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.cassandra.sidecar.livemigration;
+
+import java.util.Collections;
+
+import org.junit.jupiter.api.Test;
+
+import static org.apache.cassandra.sidecar.livemigration.LiveMigrationPlaceholderUtil.hasAnyPlaceholder;
+import static org.apache.cassandra.sidecar.livemigration.LiveMigrationPlaceholderUtil.replacePlaceholder;
+import static org.assertj.core.api.Assertions.assertThat;
+
+class LiveMigrationPlaceholderUtilTest
+{
+ @Test
+ public void testReplacePlaceholder()
+ {
+ assertThat(replacePlaceholder("/no/placeholder/dir", Collections.singleton("DATA_DIR"), "data_dir"))
+ .isEqualTo("/no/placeholder/dir");
+
+ assertThat(replacePlaceholder("${DATA_DIR}/ks1", Collections.singleton("DATA_DIR"), "/data_dir"))
+ .isEqualTo("/data_dir/ks1");
+
+ // replacement of placeholder happens if and only if the placeholder given is found.
+ assertThat(replacePlaceholder("${HINTS_DIR}/ks1", Collections.singleton("DATA_DIR"), "/data_dir"))
+ .isNull();
+ }
+
+ @Test
+ void testHasAnyPlaceHolder()
+ {
+ assertThat(hasAnyPlaceholder("glob:/var/log/cassandra/data")).isFalse();
+ assertThat(hasAnyPlaceholder("/var/log/cassandra/data")).isFalse();
+ assertThat(hasAnyPlaceholder("glob:/var/log/cassandra/data/**")).isFalse();
+ assertThat(hasAnyPlaceholder("glob:${SOME_DIR}/cassandra/data/**")).isTrue();
+ assertThat(hasAnyPlaceholder("regex:${SOME_DIR_1}/cassandra/data/**")).isTrue();
+ assertThat(hasAnyPlaceholder("${SOME_DIR_2}/cassandra/data/**")).isTrue();
+ assertThat(hasAnyPlaceholder("{SOME_DIR_2}/cassandra/data/**")).isFalse();
+ }
+
+ @Test
+ void testHasKnownPlaceHolder()
+ {
+ assertThat(hasAnyPlaceholder("${DATA_FILE_DIR}/ks/t1", Collections.singleton("HINTS_DIR"))).isFalse();
+ assertThat(hasAnyPlaceholder("glob:${DATA_FILE_DIR}/ks/t1", Collections.singleton("HINTS_DIR"))).isFalse();
+
+
+ assertThat(hasAnyPlaceholder("${HINTS_DIR}/ks/t1", Collections.singleton("HINTS_DIR"))).isTrue();
+ assertThat(hasAnyPlaceholder("glob:${HINTS_DIR}/ks/t1", Collections.singleton("HINTS_DIR"))).isTrue();
+
+ assertThat(hasAnyPlaceholder("${DATA_FILE_DIR}/ks/t1", Collections.singleton("DATA_FILE_DIR"))).isTrue();
+ assertThat(hasAnyPlaceholder("glob:${DATA_FILE_DIR}/ks/t1", Collections.singleton("DATA_FILE_DIR"))).isTrue();
+ assertThat(hasAnyPlaceholder("regex:${DATA_FILE_DIR}/k*/t1", Collections.singleton("DATA_FILE_DIR"))).isTrue();
+
+ assertThat(hasAnyPlaceholder("glob:${DATA_FILE_DIR}/ks/t1", Collections.singleton("DATA_FILE_DIR_0"))).isFalse();
+ }
+}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/livemigration/MigrationFileVisitorTest.java b/server/src/test/java/org/apache/cassandra/sidecar/livemigration/MigrationFileVisitorTest.java
new file mode 100644
index 00000000..40d7f37b
--- /dev/null
+++ b/server/src/test/java/org/apache/cassandra/sidecar/livemigration/MigrationFileVisitorTest.java
@@ -0,0 +1,83 @@
+/*
+ * 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.cassandra.sidecar.livemigration;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.FileSystems;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.util.Collections;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.assertj.core.api.Assertions.assertThatIOException;
+import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
+
+class MigrationFileVisitorTest
+{
+ @TempDir
+ Path tempDir;
+
+ @Test
+ public void testVisitFileFailedForExcludedDir() throws IOException
+ {
+ String homeDir = tempDir.toString();
+ Path excludedDirPath = tempDir.resolve("test_dir");
+ Files.createDirectories(excludedDirPath);
+
+ Path excludedDir2Path = tempDir.resolve("test_dir2");
+ Files.createDirectories(excludedDir2Path);
+
+ PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + excludedDirPath);
+ MigrationFileVisitor fileVisitor = new MigrationFileVisitor(homeDir,
+ Collections.emptyList(),
+ Collections.singletonList(pathMatcher));
+
+ // It should continue if failed to visit an excluded directory
+ assertThat(fileVisitor.visitFileFailed(excludedDirPath, new IOException())).isEqualTo(FileVisitResult.CONTINUE);
+ assertThatIOException().isThrownBy(() -> fileVisitor.visitFileFailed(excludedDir2Path, new IOException()));
+ }
+
+
+ @Test
+ public void testVisitFileFailedForFile() throws IOException
+ {
+ String homeDir = tempDir.toString();
+ Path excludedFilePath = tempDir.resolve("test_file");
+ Files.write(excludedFilePath, "test string".getBytes(StandardCharsets.UTF_8));
+
+ Path excludedFile2Path = tempDir.resolve("test_file2");
+ Files.write(excludedFile2Path, "test string".getBytes(StandardCharsets.UTF_8));
+
+ PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + excludedFilePath);
+ MigrationFileVisitor fileVisitor = new MigrationFileVisitor(homeDir,
+ Collections.singletonList(pathMatcher),
+ Collections.emptyList());
+
+ // It should continue if failed to visit an excluded file
+ assertThat(fileVisitor.visitFileFailed(excludedFilePath, new IOException()))
+ .isEqualTo(FileVisitResult.CONTINUE);
+
+ assertThatIOException().isThrownBy(() -> fileVisitor.visitFileFailed(excludedFile2Path, new IOException()));
+ }
+}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/utils/TestFileUtils.java b/server/src/test/java/org/apache/cassandra/sidecar/utils/TestFileUtils.java
index 195ef348..764c87f6 100644
--- a/server/src/test/java/org/apache/cassandra/sidecar/utils/TestFileUtils.java
+++ b/server/src/test/java/org/apache/cassandra/sidecar/utils/TestFileUtils.java
@@ -20,8 +20,10 @@ package org.apache.cassandra.sidecar.utils;
import java.io.IOException;
import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.concurrent.ThreadLocalRandom;
/**
@@ -58,4 +60,39 @@ public class TestFileUtils
}
return filePath;
}
+
+ /**
+ * Creates a file with given {@code content}. File path can be specified as sequence of Strings just like
+ * {@link Paths#get(String, String...)}.
+ *
+ * @param content contents of file
+ * @param first the path string or initial part of the path string
+ * @param more additional strings to be joined to form the path string
+ * @throws IOException when cannot create file
+ */
+ public static void createFile(String content, String first, String... more) throws IOException
+ {
+ Path file = Paths.get(first, more);
+ Path parent = file.getParent();
+ if (null == parent)
+ {
+ throw new IOException("Parent doesn't exists for file " + file);
+ }
+ Files.createDirectories(parent);
+ Files.write(file, content.getBytes(StandardCharsets.UTF_8));
+ }
+
+ /**
+ * Creates directory. Directory path can be specified as sequence of Strings
+ * just like {@link Paths#get(String, String...)}.
+ *
+ * @param first the path string or initial part of the path string
+ * @param more additional strings to be joined to form the path string
+ * @throws IOException when cannot create directory
+ */
+ public static void createDirectory(String first, String... more) throws IOException
+ {
+ Path dir = Paths.get(first, more);
+ Files.createDirectories(dir);
+ }
}
diff --git a/server/src/test/resources/config/sidecar_live_migration.yaml b/server/src/test/resources/config/sidecar_live_migration.yaml
new file mode 100644
index 00000000..94893792
--- /dev/null
+++ b/server/src/test/resources/config/sidecar_live_migration.yaml
@@ -0,0 +1,213 @@
+#
+# 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.
+#
+
+#
+# Cassandra SideCar configuration file
+#
+cassandra_instances:
+ - id: 1
+ host: localhost1
+ port: 9042
+ storage_dir: /ccm/test/node1
+ data_dirs:
+ - /ccm/test/node1/data0
+ - /ccm/test/node1/data1
+ staging_dir: /ccm/test/node1/sstable-staging
+ commitlog_dir: /ccm/test/node1/commitlog
+ hints_dir: /ccm/test/node1/hints
+ saved_caches_dir: /ccm/test/node1/saved_caches
+ local_system_data_file_dir: /ccm/test/node1/local_system_data
+ jmx_host: 127.0.0.1
+ jmx_port: 7100
+ jmx_ssl_enabled: false
+ # jmx_role:
+ # jmx_role_password:
+ - id: 2
+ host: localhost2
+ port: 9042
+ storage_dir: /ccm/test/node2
+ data_dirs:
+ - /ccm/test/node2/data0
+ - /ccm/test/node2/data1
+ staging_dir: /ccm/test/node2/sstable-staging
+ commitlog_dir: /ccm/test/node2/commitlog
+ hints_dir: /ccm/test/node2/hints
+ saved_caches_dir: /ccm/test/node2/saved_caches
+ local_system_data_file_dir: /ccm/test/node2/local_system_data
+ jmx_host: 127.0.0.1
+ jmx_port: 7200
+ jmx_ssl_enabled: false
+ # jmx_role:
+ # jmx_role_password:
+ - id: 3
+ host: localhost3
+ port: 9042
+ storage_dir: /ccm/test/node3
+ data_dirs:
+ - /ccm/test/node3/data0
+ - /ccm/test/node3/data1
+ staging_dir: /ccm/test/node3/sstable-staging
+ commitlog_dir: /ccm/test/node3/commitlog
+ hints_dir: /ccm/test/node3/hints
+ saved_caches_dir: /ccm/test/node3/saved_caches
+ local_system_data_file_dir: /ccm/test/node3/local_system_data
+ jmx_host: 127.0.0.1
+ jmx_port: 7300
+ jmx_ssl_enabled: false
+# jmx_role:
+# jmx_role_password:
+
+sidecar:
+ host: 0.0.0.0
+ port: 9043
+ request_idle_timeout: 5m
+ request_timeout: 5m
+ tcp_keep_alive: false
+ accept_backlog: 1024
+ server_verticle_instances: 1
+ throttle:
+ stream_requests_per_sec: 5000
+ timeout: 10s
+ traffic_shaping:
+ inbound_global_bandwidth_bps: 500
+ outbound_global_bandwidth_bps: 1500
+ peak_outbound_global_bandwidth_bps: 2000
+ max_delay_to_wait: 15s
+ check_interval_for_stats: 1s
+ sstable_upload:
+ concurrent_upload_limit: 80
+ min_free_space_percent: 10
+ # file_permissions: "rw-r--r--" # when not specified, the default file permissions are owner read & write, group & others read
+ allowable_time_skew: 1h
+ sstable_import:
+ execute_interval: 100ms
+ cache:
+ expire_after_access: 2h # 2 hours
+ maximum_size: 10000
+ sstable_snapshot:
+ snapshot_list_cache:
+ expire_after_access: 350ms
+ maximum_size: 450
+ worker_pools:
+ service:
+ name: "sidecar-worker-pool"
+ size: 20
+ max_execution_time: 1m # 1 minute
+ internal:
+ name: "sidecar-internal-worker-pool"
+ size: 20
+ max_execution_time: 15m # 15 minutes
+ jmx:
+ max_retries: 1
+ retry_delay: 1234ms
+ schema:
+ is_enabled: false
+ keyspace: sidecar_internal
+ replication_strategy: SimpleStrategy
+ replication_factor: 1
+ lease_schema_ttl: 5m
+ coordination:
+ cluster_lease_claim:
+ electorate_membership_strategy: MostReplicatedKeyspaceTokenZeroElectorateMembership
+ enabled: true
+ initial_delay: 1s
+ initial_delay_random_delta: 30s
+ execute_interval: 100s
+
+vertx:
+ filesystem_options:
+ classpath_resolving_enabled: false
+ file_caching_enabled: false
+
+#
+# Enable SSL configuration (Disabled by default)
+#
+# ssl:
+# enabled: true
+# use_openssl: true
+# handshake_timeout: 10s
+# client_auth: NONE # valid options are NONE, REQUEST, REQUIRED
+# accepted_protocols:
+# - TLSv1.2
+# - TLSv1.3
+# cipher_suites: []
+# keystore:
+# type: PKCS12
+# path: "path/to/keystore.p12"
+# password: password
+# check_interval: 5m
+# truststore:
+# path: "path/to/truststore.p12"
+# password: password
+
+access_control:
+ enabled: true
+ authenticators:
+ - class_name: org.apache.cassandra.sidecar.acl.authentication.MutualTLSAuthenticationHandlerFactory
+ parameters:
+ certificate_validator: io.vertx.ext.auth.mtls.impl.AllowAllCertificateValidator
+ certificate_identity_extractor: org.apache.cassandra.sidecar.acl.authentication.CassandraIdentityExtractor
+ - class_name: org.apache.cassandra.sidecar.acl.authentication.JwtAuthenticationHandlerFactory
+ parameters:
+ site: https://authorization.com
+ client_id: recognized_client_id
+ config_discover_interval: 1m
+ authorizer:
+ - class_name: org.apache.cassandra.sidecar.acl.authorization.RoleBasedAuthorizationProvider
+ admin_identities:
+ - spiffe://authorized/admin/identity1
+ - spiffe://authorized/admin/identity2
+ permission_cache:
+ enabled: true
+ expire_after_access: 5m
+ maximum_size: 1000
+ warmup_retries: 5
+ warmup_retry_interval: 2s
+
+healthcheck:
+ initial_delay: 100ms
+ execute_interval: 30s
+
+sidecar_peer_health:
+ enabled: false
+ frequency: 30s
+ max_retries: 5
+ retry_delay: 10s
+
+cassandra_input_validation:
+ forbidden_keyspaces:
+ - system_schema
+ - system_traces
+ - system_distributed
+ - system
+ - system_auth
+ - system_views
+ - system_virtual_schema
+ - sidecar_internal
+ allowed_chars_for_directory: "[a-zA-Z][a-zA-Z0-9_]{0,47}"
+ allowed_chars_for_quoted_name: "[a-zA-Z_0-9]{1,48}"
+ allowed_chars_for_component_name: "[a-zA-Z0-9_-]+(.db|.cql|.json|.crc32|TOC.txt)"
+ allowed_chars_for_restricted_component_name: "[a-zA-Z0-9_-]+(.db|TOC.txt)"
+
+live_migration:
+ files_to_exclude:
+ - ${DATA_FILE_DIR}/test.log
+ dirs_to_exclude:
+ - ${DATA_FILE_DIR}/*/*/snapshots
+ migration_map:
+ localhost1: localhost4
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org