aboutsummaryrefslogtreecommitdiffstats
path: root/node-admin/src/main/java
diff options
context:
space:
mode:
authorValerij Fredriksen <freva@users.noreply.github.com>2021-10-15 16:57:16 +0200
committerGitHub <noreply@github.com>2021-10-15 16:57:16 +0200
commit16aaaffdccccf8440a9c0dc2e452c941943d3557 (patch)
treedcf22ac83ecde008a8a80183717a69d822752802 /node-admin/src/main/java
parenta0de877aed8c7303ebf835e889db7314dd9fbb4e (diff)
Revert "Revert "Use ContainerPath""
Diffstat (limited to 'node-admin/src/main/java')
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/container/ContainerOperations.java2
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/StorageMaintainer.java32
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoreCollector.java19
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoredumpHandler.java58
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/identity/AthenzCredentialsMaintainer.java46
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/AbstractProducer.java6
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/Artifact.java22
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/ArtifactProducer.java7
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/JvmDumper.java32
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/PerfReporter.java15
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/PmapReporter.java9
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/VespaLogDumper.java8
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/VespaServiceDumperImpl.java49
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/ContainerData.java27
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContext.java39
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextImpl.java83
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImpl.java7
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/UserNamespace.java48
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/fs/ContainerFileSystem.java10
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/fs/ContainerFileSystemProvider.java41
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/fs/ContainerUserPrincipalLookupService.java89
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/fs/package-info.java5
22 files changed, 297 insertions, 357 deletions
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/container/ContainerOperations.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/container/ContainerOperations.java
index acac2098d53..fd38d38b381 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/container/ContainerOperations.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/container/ContainerOperations.java
@@ -141,7 +141,7 @@ public class ContainerOperations {
}
private String executeNodeCtlInContainer(NodeAgentContext context, String program) {
- String[] command = new String[] {context.pathInNodeUnderVespaHome("bin/vespa-nodectl").toString(), program};
+ String[] command = new String[] {context.containerPathUnderVespaHome("bin/vespa-nodectl").pathInContainer(), program};
return executeCommandInContainerAsRoot(context, command).getOutput();
}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/StorageMaintainer.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/StorageMaintainer.java
index 340f43b4671..9328eb232a6 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/StorageMaintainer.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/StorageMaintainer.java
@@ -22,6 +22,7 @@ import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentTask;
import com.yahoo.vespa.hosted.node.admin.task.util.file.DiskSize;
import com.yahoo.vespa.hosted.node.admin.task.util.file.FileFinder;
import com.yahoo.vespa.hosted.node.admin.task.util.file.UnixPath;
+import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerPath;
import com.yahoo.vespa.hosted.node.admin.task.util.process.Terminal;
import java.net.URI;
@@ -85,7 +86,7 @@ public class StorageMaintainer {
if (archiveUri.isEmpty()) return false;
ApplicationId owner = context.node().owner().orElseThrow();
- List<SyncFileInfo> syncFileInfos = FileFinder.files(pathOnHostUnderContainerVespaHome(context, "logs/vespa"))
+ List<SyncFileInfo> syncFileInfos = FileFinder.files(context.containerPathUnderVespaHome("logs/vespa"))
.maxDepth(2)
.stream()
.sorted(Comparator.comparing(FileFinder.FileAttributes::lastModifiedTime))
@@ -100,7 +101,7 @@ public class StorageMaintainer {
DiskSize cachedDiskUsage = diskUsage.getIfPresent(context.containerName());
if (cachedDiskUsage != null) return Optional.of(cachedDiskUsage);
- DiskSize diskUsageBytes = getDiskUsed(context, context.pathOnHostFromPathInNode("/"));
+ DiskSize diskUsageBytes = getDiskUsed(context, context.containerPath("/").pathOnHost());
diskUsage.put(context.containerName(), diskUsageBytes);
return Optional.of(diskUsageBytes);
} catch (Exception e) {
@@ -109,11 +110,11 @@ public class StorageMaintainer {
}
}
- DiskSize getDiskUsed(TaskContext context, Path path) {
- if (!Files.exists(path)) return DiskSize.ZERO;
+ DiskSize getDiskUsed(TaskContext context, Path pathOnHost) {
+ if (!Files.exists(pathOnHost)) return DiskSize.ZERO;
String output = terminal.newCommandLine(context)
- .add("du", "-xsk", path.toString())
+ .add("du", "-xsk", pathOnHost.toString())
.setTimeout(Duration.ofSeconds(60))
.executeSilently()
.getOutput();
@@ -149,18 +150,18 @@ public class StorageMaintainer {
Function<Instant, Double> monthNormalizer = instant -> Duration.between(instant, start).getSeconds() / oneMonthSeconds;
List<DiskCleanupRule> rules = new ArrayList<>();
- rules.add(CoredumpCleanupRule.forContainer(pathOnHostUnderContainerVespaHome(context, "var/crash")));
+ rules.add(CoredumpCleanupRule.forContainer(context.containerPathUnderVespaHome("var/crash")));
if (context.node().membership().map(m -> m.type().hasContainer()).orElse(false))
- rules.add(new LinearCleanupRule(() -> FileFinder.files(pathOnHostUnderContainerVespaHome(context, "logs/vespa/qrs")).list(),
+ rules.add(new LinearCleanupRule(() -> FileFinder.files(context.containerPathUnderVespaHome("logs/vespa/qrs")).list(),
fa -> monthNormalizer.apply(fa.lastModifiedTime()), Priority.LOWEST, Priority.HIGHEST));
if (context.nodeType() == NodeType.tenant && context.node().membership().map(m -> m.type().isAdmin()).orElse(false))
- rules.add(new LinearCleanupRule(() -> FileFinder.files(pathOnHostUnderContainerVespaHome(context, "logs/vespa/logarchive")).list(),
+ rules.add(new LinearCleanupRule(() -> FileFinder.files(context.containerPathUnderVespaHome("logs/vespa/logarchive")).list(),
fa -> monthNormalizer.apply(fa.lastModifiedTime()), Priority.LOWEST, Priority.HIGHEST));
if (context.nodeType() == NodeType.proxy)
- rules.add(new LinearCleanupRule(() -> FileFinder.files(pathOnHostUnderContainerVespaHome(context, "logs/nginx")).list(),
+ rules.add(new LinearCleanupRule(() -> FileFinder.files(context.containerPathUnderVespaHome("logs/nginx")).list(),
fa -> monthNormalizer.apply(fa.lastModifiedTime()), Priority.LOWEST, Priority.MEDIUM));
return rules;
@@ -202,16 +203,17 @@ public class StorageMaintainer {
* Removes old files, reports coredumps and archives container data, runs when container enters state "dirty"
*/
public void archiveNodeStorage(NodeAgentContext context) {
- Path logsDirInContainer = context.pathInNodeUnderVespaHome("logs");
+ ContainerPath logsDirInContainer = context.containerPathUnderVespaHome("logs");
Path containerLogsInArchiveDir = archiveContainerStoragePath
- .resolve(context.containerName().asString() + "_" + DATE_TIME_FORMATTER.format(clock.instant()) + logsDirInContainer);
- UnixPath containerLogsOnHost = new UnixPath(context.pathOnHostFromPathInNode(logsDirInContainer));
+ .resolve(context.containerName().asString() + "_" + DATE_TIME_FORMATTER.format(clock.instant()) + logsDirInContainer.pathInContainer());
+ // Files.move() does not support moving non-empty directories across providers, move using host paths
+ UnixPath containerLogsOnHost = new UnixPath(logsDirInContainer.pathOnHost());
if (containerLogsOnHost.exists()) {
new UnixPath(containerLogsInArchiveDir).createParents();
containerLogsOnHost.moveIfExists(containerLogsInArchiveDir);
}
- new UnixPath(context.pathOnHostFromPathInNode("/")).deleteRecursively();
+ new UnixPath(context.containerPath("/")).deleteRecursively();
}
private String getMicrocodeVersion() {
@@ -235,8 +237,4 @@ public class StorageMaintainer {
.orElse("<none>")
);
}
-
- private static Path pathOnHostUnderContainerVespaHome(NodeAgentContext context, String path) {
- return context.pathOnHostFromPathInNode(context.pathInNodeUnderVespaHome(path));
- }
}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoreCollector.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoreCollector.java
index 2c0fa439000..c5c8d0e121d 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoreCollector.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoreCollector.java
@@ -4,6 +4,7 @@ package com.yahoo.vespa.hosted.node.admin.maintenance.coredump;
import com.yahoo.vespa.hosted.node.admin.container.ContainerOperations;
import com.yahoo.vespa.hosted.node.admin.nodeadmin.ConvergenceException;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContext;
+import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerPath;
import com.yahoo.vespa.hosted.node.admin.task.util.process.CommandResult;
import java.nio.file.Path;
@@ -56,8 +57,8 @@ public class CoreCollector {
return GDB_PATH_RHEL8;
}
- String readBinPathFallback(NodeAgentContext context, Path coredumpPath) {
- String command = getGdbPath(context) + " -n -batch -core " + coredumpPath + " | grep \'^Core was generated by\'";
+ String readBinPathFallback(NodeAgentContext context, ContainerPath coredumpPath) {
+ String command = getGdbPath(context) + " -n -batch -core " + coredumpPath.pathInContainer() + " | grep \'^Core was generated by\'";
String[] wrappedCommand = {"/bin/sh", "-c", command};
CommandResult result = docker.executeCommandInContainerAsRoot(context, wrappedCommand);
@@ -69,8 +70,8 @@ public class CoreCollector {
return matcher.group("path").split(" ")[0];
}
- String readBinPath(NodeAgentContext context, Path coredumpPath) {
- String[] command = {"file", coredumpPath.toString()};
+ String readBinPath(NodeAgentContext context, ContainerPath coredumpPath) {
+ String[] command = {"file", coredumpPath.pathInContainer()};
try {
CommandResult result = docker.executeCommandInContainerAsRoot(context, command);
if (result.getExitCode() != 0) {
@@ -94,9 +95,9 @@ public class CoreCollector {
return readBinPathFallback(context, coredumpPath);
}
- List<String> readBacktrace(NodeAgentContext context, Path coredumpPath, String binPath, boolean allThreads) {
+ List<String> readBacktrace(NodeAgentContext context, ContainerPath coredumpPath, String binPath, boolean allThreads) {
String threads = allThreads ? "thread apply all bt" : "bt";
- String[] command = {getGdbPath(context), "-n", "-ex", threads, "-batch", binPath, coredumpPath.toString()};
+ String[] command = {getGdbPath(context), "-n", "-ex", threads, "-batch", binPath, coredumpPath.pathInContainer()};
CommandResult result = docker.executeCommandInContainerAsRoot(context, command);
if (result.getExitCode() != 0)
@@ -105,8 +106,8 @@ public class CoreCollector {
return List.of(result.getOutput().split("\n"));
}
- List<String> readJstack(NodeAgentContext context, Path coredumpPath, String binPath) {
- String[] command = {"jhsdb", "jstack", "--exe", binPath, "--core", coredumpPath.toString()};
+ List<String> readJstack(NodeAgentContext context, ContainerPath coredumpPath, String binPath) {
+ String[] command = {"jhsdb", "jstack", "--exe", binPath, "--core", coredumpPath.pathInContainer()};
CommandResult result = docker.executeCommandInContainerAsRoot(context, command);
if (result.getExitCode() != 0)
@@ -121,7 +122,7 @@ public class CoreCollector {
* @param coredumpPath path to core dump file inside the container
* @return map of relevant metadata about the core dump
*/
- Map<String, Object> collect(NodeAgentContext context, Path coredumpPath) {
+ Map<String, Object> collect(NodeAgentContext context, ContainerPath coredumpPath) {
if (JAVA_HEAP_DUMP_PATTERN.matcher(coredumpPath.getFileName().toString()).find())
return JAVA_HEAP_DUMP_METADATA;
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoredumpHandler.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoredumpHandler.java
index 4c0ffa3dce9..0594c5ee016 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoredumpHandler.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoredumpHandler.java
@@ -9,6 +9,7 @@ import com.yahoo.vespa.hosted.node.admin.nodeadmin.ConvergenceException;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContext;
import com.yahoo.vespa.hosted.node.admin.task.util.file.FileFinder;
import com.yahoo.vespa.hosted.node.admin.task.util.file.UnixPath;
+import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerPath;
import com.yahoo.vespa.hosted.node.admin.task.util.process.Terminal;
import java.io.IOException;
@@ -86,13 +87,13 @@ public class CoredumpHandler {
public void converge(NodeAgentContext context, Supplier<Map<String, Object>> nodeAttributesSupplier, boolean throwIfCoreBeingWritten) {
- Path containerCrashPathOnHost = context.pathOnHostFromPathInNode(crashPatchInContainer);
- Path containerProcessingPathOnHost = containerCrashPathOnHost.resolve(PROCESSING_DIRECTORY_NAME);
+ ContainerPath containerCrashPath = context.containerPath(crashPatchInContainer);
+ ContainerPath containerProcessingPath = containerCrashPath.resolve(PROCESSING_DIRECTORY_NAME);
- updateMetrics(context, containerCrashPathOnHost);
+ updateMetrics(context, containerCrashPath);
if (throwIfCoreBeingWritten) {
- List<String> pendingCores = FileFinder.files(containerCrashPathOnHost)
+ List<String> pendingCores = FileFinder.files(containerCrashPath)
.match(fileAttributes -> !isReadyForProcessing(fileAttributes))
.maxDepth(1).stream()
.map(FileFinder.FileAttributes::filename)
@@ -103,16 +104,17 @@ public class CoredumpHandler {
}
// Check if we have already started to process a core dump or we can enqueue a new core one
- getCoredumpToProcess(containerCrashPathOnHost, containerProcessingPathOnHost)
+ getCoredumpToProcess(containerCrashPath, containerProcessingPath)
.ifPresent(path -> processAndReportSingleCoredump(context, path, nodeAttributesSupplier));
}
/** @return path to directory inside processing directory that contains a core dump file to process */
- Optional<Path> getCoredumpToProcess(Path containerCrashPathOnHost, Path containerProcessingPathOnHost) {
- return FileFinder.directories(containerProcessingPathOnHost).stream()
+ Optional<ContainerPath> getCoredumpToProcess(ContainerPath containerCrashPath, ContainerPath containerProcessingPath) {
+ return FileFinder.directories(containerProcessingPath).stream()
.map(FileFinder.FileAttributes::path)
.findAny()
- .or(() -> enqueueCoredump(containerCrashPathOnHost, containerProcessingPathOnHost));
+ .map(ContainerPath.class::cast)
+ .or(() -> enqueueCoredump(containerCrashPath, containerProcessingPath));
}
/**
@@ -124,8 +126,8 @@ public class CoredumpHandler {
*
* @return path to directory inside processing directory which contains the enqueued core dump file
*/
- Optional<Path> enqueueCoredump(Path containerCrashPathOnHost, Path containerProcessingPathOnHost) {
- List<Path> toProcess = FileFinder.files(containerCrashPathOnHost)
+ Optional<ContainerPath> enqueueCoredump(ContainerPath containerCrashPath, ContainerPath containerProcessingPath) {
+ List<Path> toProcess = FileFinder.files(containerCrashPath)
.match(this::isReadyForProcessing)
.maxDepth(1)
.stream()
@@ -141,7 +143,7 @@ public class CoredumpHandler {
// Either there are no files in crash directory, or all the files are hs_err files.
if (coredumpIndex == -1) return Optional.empty();
- Path enqueuedDir = uncheck(() -> Files.createDirectories(containerProcessingPathOnHost.resolve(coredumpIdSupplier.get())));
+ ContainerPath enqueuedDir = (ContainerPath) uncheck(() -> Files.createDirectories(containerProcessingPath.resolve(coredumpIdSupplier.get())));
IntStream.range(0, coredumpIndex + 1)
.forEach(i -> {
Path path = toProcess.get(i);
@@ -151,7 +153,7 @@ public class CoredumpHandler {
return Optional.of(enqueuedDir);
}
- void processAndReportSingleCoredump(NodeAgentContext context, Path coredumpDirectory, Supplier<Map<String, Object>> nodeAttributesSupplier) {
+ void processAndReportSingleCoredump(NodeAgentContext context, ContainerPath coredumpDirectory, Supplier<Map<String, Object>> nodeAttributesSupplier) {
try {
String metadata = getMetadata(context, coredumpDirectory, nodeAttributesSupplier);
String coredumpId = coredumpDirectory.getFileName().toString();
@@ -167,17 +169,16 @@ public class CoredumpHandler {
* @return coredump metadata from metadata.json if present, otherwise attempts to get metadata using
* {@link CoreCollector} and stores it to metadata.json
*/
- String getMetadata(NodeAgentContext context, Path coredumpDirectory, Supplier<Map<String, Object>> nodeAttributesSupplier) throws IOException {
+ String getMetadata(NodeAgentContext context, ContainerPath coredumpDirectory, Supplier<Map<String, Object>> nodeAttributesSupplier) throws IOException {
UnixPath metadataPath = new UnixPath(coredumpDirectory.resolve(METADATA_FILE_NAME));
if (!Files.exists(metadataPath.toPath())) {
- Path coredumpFilePathOnHost = findCoredumpFileInProcessingDirectory(coredumpDirectory);
- Path coredumpFilePathInContainer = context.pathInNodeFromPathOnHost(coredumpFilePathOnHost);
- Map<String, Object> metadata = new HashMap<>(coreCollector.collect(context, coredumpFilePathInContainer));
+ ContainerPath coredumpFile = findCoredumpFileInProcessingDirectory(coredumpDirectory);
+ Map<String, Object> metadata = new HashMap<>(coreCollector.collect(context, coredumpFile));
metadata.putAll(nodeAttributesSupplier.get());
metadata.put("coredump_path", doneCoredumpsPath
.resolve(context.containerName().asString())
- .resolve(coredumpDirectory.getFileName())
- .resolve(coredumpFilePathOnHost.getFileName()).toString());
+ .resolve(coredumpDirectory.getFileName().toString())
+ .resolve(coredumpFile.getFileName().toString()).toString());
String metadataFields = objectMapper.writeValueAsString(Map.of("fields", metadata));
metadataPath.writeUtf8File(metadataFields);
@@ -191,23 +192,24 @@ public class CoredumpHandler {
* Compresses core file (and deletes the uncompressed core), then moves the entire core dump processing
* directory to {@link #doneCoredumpsPath} for archive
*/
- private void finishProcessing(NodeAgentContext context, Path coredumpDirectory) throws IOException {
- Path coreFile = findCoredumpFileInProcessingDirectory(coredumpDirectory);
- Path compressedCoreFile = coreFile.getParent().resolve(coreFile.getFileName() + ".lz4");
+ private void finishProcessing(NodeAgentContext context, ContainerPath coredumpDirectory) throws IOException {
+ ContainerPath coreFile = findCoredumpFileInProcessingDirectory(coredumpDirectory);
+ ContainerPath compressedCoreFile = coreFile.resolveSibling(coreFile.getFileName() + ".lz4");
terminal.newCommandLine(context)
- .add(LZ4_PATH, "-f", coreFile.toString(), compressedCoreFile.toString())
+ .add(LZ4_PATH, "-f", coreFile.pathOnHost().toString(), compressedCoreFile.pathOnHost().toString())
.setTimeout(Duration.ofMinutes(30))
.execute();
- new UnixPath(compressedCoreFile).setGroupId(operatorGroupId).setPermissions("rw-r-----");
+ new UnixPath(compressedCoreFile.pathOnHost()).setGroupId(operatorGroupId).setPermissions("rw-r-----");
Files.delete(coreFile);
Path newCoredumpDirectory = doneCoredumpsPath.resolve(context.containerName().asString());
uncheck(() -> Files.createDirectories(newCoredumpDirectory));
- Files.move(coredumpDirectory, newCoredumpDirectory.resolve(coredumpDirectory.getFileName()));
+ // Files.move() does not support moving non-empty directories across providers, move using host paths
+ Files.move(coredumpDirectory.pathOnHost(), newCoredumpDirectory.resolve(coredumpDirectory.getFileName().toString()));
}
- Path findCoredumpFileInProcessingDirectory(Path coredumpProccessingDirectory) {
- return FileFinder.files(coredumpProccessingDirectory)
+ ContainerPath findCoredumpFileInProcessingDirectory(ContainerPath coredumpProccessingDirectory) {
+ return (ContainerPath) FileFinder.files(coredumpProccessingDirectory)
.match(nameStartsWith(COREDUMP_FILENAME_PREFIX).and(nameEndsWith(".lz4").negate()))
.maxDepth(1)
.stream()
@@ -217,11 +219,11 @@ public class CoredumpHandler {
"No coredump file found in processing directory " + coredumpProccessingDirectory));
}
- void updateMetrics(NodeAgentContext context, Path containerCrashPathOnHost) {
+ void updateMetrics(NodeAgentContext context, ContainerPath containerCrashPath) {
Dimensions dimensions = generateDimensions(context);
// Unprocessed coredumps
- int numberOfUnprocessedCoredumps = FileFinder.files(containerCrashPathOnHost)
+ int numberOfUnprocessedCoredumps = FileFinder.files(containerCrashPath)
.match(nameStartsWith(".").negate())
.match(nameMatches(HS_ERR_PATTERN).negate())
.match(nameEndsWith(".lz4").negate())
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/identity/AthenzCredentialsMaintainer.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/identity/AthenzCredentialsMaintainer.java
index 280ebd86d13..280e58c91f1 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/identity/AthenzCredentialsMaintainer.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/identity/AthenzCredentialsMaintainer.java
@@ -26,17 +26,15 @@ import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContext;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentTask;
import com.yahoo.vespa.hosted.node.admin.task.util.file.FileFinder;
import com.yahoo.vespa.hosted.node.admin.task.util.file.UnixPath;
+import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerPath;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
-import java.nio.file.FileSystem;
-import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
@@ -110,10 +108,10 @@ public class AthenzCredentialsMaintainer implements CredentialsMaintainer {
try {
context.log(logger, Level.FINE, "Checking certificate");
- Path containerSiaDirectory = context.pathOnHostFromPathInNode(CONTAINER_SIA_DIRECTORY);
- Path privateKeyFile = SiaUtils.getPrivateKeyFile(containerSiaDirectory, context.identity());
- Path certificateFile = SiaUtils.getCertificateFile(containerSiaDirectory, context.identity());
- Path identityDocumentFile = containerSiaDirectory.resolve("vespa-node-identity-document.json");
+ ContainerPath containerSiaDirectory = context.containerPath(CONTAINER_SIA_DIRECTORY);
+ ContainerPath privateKeyFile = (ContainerPath) SiaUtils.getPrivateKeyFile(containerSiaDirectory, context.identity());
+ ContainerPath certificateFile = (ContainerPath) SiaUtils.getCertificateFile(containerSiaDirectory, context.identity());
+ ContainerPath identityDocumentFile = containerSiaDirectory.resolve("vespa-node-identity-document.json");
if (!Files.exists(privateKeyFile) || !Files.exists(certificateFile) || !Files.exists(identityDocumentFile)) {
context.log(logger, "Certificate/private key/identity document file does not exist");
Files.createDirectories(privateKeyFile.getParent());
@@ -154,15 +152,15 @@ public class AthenzCredentialsMaintainer implements CredentialsMaintainer {
}
public void clearCredentials(NodeAgentContext context) {
- FileFinder.files(context.pathOnHostFromPathInNode(CONTAINER_SIA_DIRECTORY))
+ FileFinder.files(context.containerPath(CONTAINER_SIA_DIRECTORY))
.deleteRecursively(context);
lastRefreshAttempt.remove(context.containerName());
}
@Override
public Duration certificateLifetime(NodeAgentContext context) {
- Path containerSiaDirectory = context.pathOnHostFromPathInNode(CONTAINER_SIA_DIRECTORY);
- Path certificateFile = SiaUtils.getCertificateFile(containerSiaDirectory, context.identity());
+ ContainerPath containerSiaDirectory = context.containerPath(CONTAINER_SIA_DIRECTORY);
+ ContainerPath certificateFile = (ContainerPath) SiaUtils.getCertificateFile(containerSiaDirectory, context.identity());
try {
X509Certificate certificate = readCertificateFromFile(certificateFile);
Instant now = clock.instant();
@@ -190,7 +188,7 @@ public class AthenzCredentialsMaintainer implements CredentialsMaintainer {
now)) > 0;
}
- private void registerIdentity(NodeAgentContext context, Path privateKeyFile, Path certificateFile, Path identityDocumentFile) {
+ private void registerIdentity(NodeAgentContext context, ContainerPath privateKeyFile, ContainerPath certificateFile, ContainerPath identityDocumentFile) {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA);
SignedIdentityDocument signedIdentityDocument = identityDocumentClient.getNodeIdentityDocument(context.hostname().value());
Pkcs10Csr csr = csrGenerator.generateInstanceCsr(
@@ -208,13 +206,13 @@ public class AthenzCredentialsMaintainer implements CredentialsMaintainer {
EntityBindingsMapper.toAttestationData(signedIdentityDocument),
csr);
EntityBindingsMapper.writeSignedIdentityDocumentToFile(identityDocumentFile, signedIdentityDocument);
- writePrivateKeyAndCertificate(context.userNamespace().vespaUserIdOnHost(), privateKeyFile, keyPair.getPrivate(),
- certificateFile, instanceIdentity.certificate());
+ writePrivateKeyAndCertificate(context.userNamespace().vespaUserId(),
+ privateKeyFile, keyPair.getPrivate(), certificateFile, instanceIdentity.certificate());
context.log(logger, "Instance successfully registered and credentials written to file");
}
}
- private void refreshIdentity(NodeAgentContext context, Path privateKeyFile, Path certificateFile, Path identityDocumentFile) {
+ private void refreshIdentity(NodeAgentContext context, ContainerPath privateKeyFile, ContainerPath certificateFile, ContainerPath identityDocumentFile) {
SignedIdentityDocument identityDocument = EntityBindingsMapper.readSignedIdentityDocumentFromFile(identityDocumentFile);
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA);
Pkcs10Csr csr = csrGenerator.generateInstanceCsr(
@@ -236,8 +234,8 @@ public class AthenzCredentialsMaintainer implements CredentialsMaintainer {
context.identity(),
identityDocument.providerUniqueId().asDottedString(),
csr);
- writePrivateKeyAndCertificate(context.userNamespace().vespaUserIdOnHost(), privateKeyFile, keyPair.getPrivate(),
- certificateFile, instanceIdentity.certificate());
+ writePrivateKeyAndCertificate(context.userNamespace().vespaUserId(),
+ privateKeyFile, keyPair.getPrivate(), certificateFile, instanceIdentity.certificate());
context.log(logger, "Instance successfully refreshed and credentials written to file");
} catch (ZtsClientException e) {
if (e.getErrorCode() == 403 && e.getDescription().startsWith("Certificate revoked")) {
@@ -253,23 +251,23 @@ public class AthenzCredentialsMaintainer implements CredentialsMaintainer {
}
- private static void writePrivateKeyAndCertificate(int vespaUidOnHost,
- Path privateKeyFile,
+ private static void writePrivateKeyAndCertificate(int vespaUid,
+ ContainerPath privateKeyFile,
PrivateKey privateKey,
- Path certificateFile,
+ ContainerPath certificateFile,
X509Certificate certificate) {
- writeFile(privateKeyFile, vespaUidOnHost, KeyUtils.toPem(privateKey));
- writeFile(certificateFile, vespaUidOnHost, X509CertificateUtils.toPem(certificate));
+ writeFile(privateKeyFile, vespaUid, KeyUtils.toPem(privateKey));
+ writeFile(certificateFile, vespaUid, X509CertificateUtils.toPem(certificate));
}
- private static void writeFile(Path path, int vespaUidOnHost, String utf8Content) {
+ private static void writeFile(ContainerPath path, int vespaUid, String utf8Content) {
new UnixPath(path.resolveSibling(path.getFileName() + ".tmp"))
.writeUtf8File(utf8Content, "r--------")
- .setOwnerId(vespaUidOnHost)
+ .setOwnerId(vespaUid)
.atomicMove(path);
}
- private static X509Certificate readCertificateFromFile(Path certificateFile) throws IOException {
+ private static X509Certificate readCertificateFromFile(ContainerPath certificateFile) throws IOException {
String pemEncodedCertificate = new String(Files.readAllBytes(certificateFile));
return X509CertificateUtils.fromPem(pemEncodedCertificate);
}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/AbstractProducer.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/AbstractProducer.java
index 6bcf41b89c2..1756b81f795 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/AbstractProducer.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/AbstractProducer.java
@@ -3,10 +3,10 @@ package com.yahoo.vespa.hosted.node.admin.maintenance.servicedump;
import com.yahoo.vespa.hosted.node.admin.container.ContainerOperations;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContext;
+import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerPath;
import com.yahoo.vespa.hosted.node.admin.task.util.process.CommandResult;
import java.io.IOException;
-import java.nio.file.Path;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -48,8 +48,8 @@ abstract class AbstractProducer implements ArtifactProducer {
}
protected int findVespaServicePid(NodeAgentContext ctx, String configId) throws IOException {
- Path findPidBinary = ctx.pathInNodeUnderVespaHome("libexec/vespa/find-pid");
- CommandResult findPidResult = executeCommand(ctx, List.of(findPidBinary.toString(), configId), true);
+ ContainerPath findPidBinary = ctx.containerPathUnderVespaHome("libexec/vespa/find-pid");
+ CommandResult findPidResult = executeCommand(ctx, List.of(findPidBinary.pathInContainer(), configId), true);
return Integer.parseInt(findPidResult.getOutput());
}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/Artifact.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/Artifact.java
index edab90afea7..6f29a9c2558 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/Artifact.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/Artifact.java
@@ -1,7 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.maintenance.servicedump;
-import java.nio.file.Path;
+import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerPath;
+
import java.util.Optional;
/**
@@ -21,18 +22,14 @@ class Artifact {
}
private final Classification classification;
- private final Path fileInNode;
- private final Path fileOnHost;
+ private final ContainerPath file;
private final boolean compressOnUpload;
private Artifact(Builder builder) {
- if (builder.fileOnHost == null && builder.fileInNode == null) {
+ if (builder.file == null) {
throw new IllegalArgumentException("No file specified");
- } else if (builder.fileOnHost != null && builder.fileInNode != null) {
- throw new IllegalArgumentException("Only a single file can be specified");
}
- this.fileInNode = builder.fileInNode;
- this.fileOnHost = builder.fileOnHost;
+ this.file = builder.file;
this.classification = builder.classification;
this.compressOnUpload = Boolean.TRUE.equals(builder.compressOnUpload);
}
@@ -40,21 +37,18 @@ class Artifact {
static Builder newBuilder() { return new Builder(); }
Optional<Classification> classification() { return Optional.ofNullable(classification); }
- Optional<Path> fileInNode() { return Optional.ofNullable(fileInNode); }
- Optional<Path> fileOnHost() { return Optional.ofNullable(fileOnHost); }
+ ContainerPath file() { return file; }
boolean compressOnUpload() { return compressOnUpload; }
static class Builder {
private Classification classification;
- private Path fileInNode;
- private Path fileOnHost;
+ private ContainerPath file;
private Boolean compressOnUpload;
private Builder() {}
Builder classification(Classification c) { this.classification = c; return this; }
- Builder fileInNode(Path f) { this.fileInNode = f; return this; }
- Builder fileOnHost(Path f) { this.fileOnHost = f; return this; }
+ Builder file(ContainerPath f) { this.file = f; return this; }
Builder compressOnUpload() { this.compressOnUpload = true; return this; }
Artifact build() { return new Artifact(this); }
}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/ArtifactProducer.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/ArtifactProducer.java
index e4a9e6aeea5..0394756cc77 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/ArtifactProducer.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/ArtifactProducer.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.maintenance.servicedump;
+import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerPath;
import com.yahoo.vespa.hosted.node.admin.task.util.process.CommandResult;
-import java.nio.file.Path;
import java.util.List;
import java.util.OptionalDouble;
@@ -22,9 +22,8 @@ interface ArtifactProducer {
String serviceId();
int servicePid();
CommandResult executeCommandInNode(List<String> command, boolean logOutput);
- Path outputDirectoryInNode();
- Path pathInNodeUnderVespaHome(String relativePath);
- Path pathOnHostFromPathInNode(Path pathInNode);
+ ContainerPath outputContainerPath();
+ ContainerPath containerPathUnderVespaHome(String relativePath);
Options options();
interface Options {
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/JvmDumper.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/JvmDumper.java
index cf206918568..8b6ca1384e9 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/JvmDumper.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/JvmDumper.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.maintenance.servicedump;
+import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerPath;
import com.yahoo.yolean.concurrent.Sleeper;
-import java.nio.file.Path;
import java.time.Duration;
import java.util.List;
@@ -22,12 +22,12 @@ class JvmDumper {
@Override
public List<Artifact> produceArtifacts(Context ctx) {
- Path heapDumpFile = ctx.outputDirectoryInNode().resolve("jvm-heap-dump.bin");
+ ContainerPath heapDumpFile = ctx.outputContainerPath().resolve("jvm-heap-dump.bin");
List<String> cmd = List.of(
- "jmap", "-dump:live,format=b,file=" + heapDumpFile, Integer.toString(ctx.servicePid()));
+ "jmap", "-dump:live,format=b,file=" + heapDumpFile.pathInContainer(), Integer.toString(ctx.servicePid()));
ctx.executeCommandInNode(cmd, true);
return List.of(
- Artifact.newBuilder().classification(CONFIDENTIAL).fileInNode(heapDumpFile).compressOnUpload().build());
+ Artifact.newBuilder().classification(CONFIDENTIAL).file(heapDumpFile).compressOnUpload().build());
}
}
@@ -37,10 +37,10 @@ class JvmDumper {
@Override
public List<Artifact> produceArtifacts(Context ctx) {
- Path jmapReport = ctx.outputDirectoryInNode().resolve("jvm-jmap.txt");
- List<String> cmd = List.of("bash", "-c", "jhsdb jmap --heap --pid " + ctx.servicePid() + " > " + jmapReport);
+ ContainerPath jmapReport = ctx.outputContainerPath().resolve("jvm-jmap.txt");
+ List<String> cmd = List.of("bash", "-c", "jhsdb jmap --heap --pid " + ctx.servicePid() + " > " + jmapReport.pathInContainer());
ctx.executeCommandInNode(cmd, true);
- return List.of(Artifact.newBuilder().classification(INTERNAL).fileInNode(jmapReport).build());
+ return List.of(Artifact.newBuilder().classification(INTERNAL).file(jmapReport).build());
}
}
@@ -50,10 +50,10 @@ class JvmDumper {
@Override
public List<Artifact> produceArtifacts(Context ctx) {
- Path jstatReport = ctx.outputDirectoryInNode().resolve("jvm-jstat.txt");
- List<String> cmd = List.of("bash", "-c", "jstat -gcutil " + ctx.servicePid() + " > " + jstatReport);
+ ContainerPath jstatReport = ctx.outputContainerPath().resolve("jvm-jstat.txt");
+ List<String> cmd = List.of("bash", "-c", "jstat -gcutil " + ctx.servicePid() + " > " + jstatReport.pathInContainer());
ctx.executeCommandInNode(cmd, true);
- return List.of(Artifact.newBuilder().classification(INTERNAL).fileInNode(jstatReport).build());
+ return List.of(Artifact.newBuilder().classification(INTERNAL).file(jstatReport).build());
}
}
@@ -63,9 +63,9 @@ class JvmDumper {
@Override
public List<Artifact> produceArtifacts(Context ctx) {
- Path jstackReport = ctx.outputDirectoryInNode().resolve("jvm-jstack.txt");
- ctx.executeCommandInNode(List.of("bash", "-c", "jstack " + ctx.servicePid() + " > " + jstackReport), true);
- return List.of(Artifact.newBuilder().classification(INTERNAL).fileInNode(jstackReport).build());
+ ContainerPath jstackReport = ctx.outputContainerPath().resolve("jvm-jstack.txt");
+ ctx.executeCommandInNode(List.of("bash", "-c", "jstack " + ctx.servicePid() + " > " + jstackReport.pathInContainer()), true);
+ return List.of(Artifact.newBuilder().classification(INTERNAL).file(jstackReport).build());
}
}
@@ -80,9 +80,9 @@ class JvmDumper {
@Override
public List<Artifact> produceArtifacts(ArtifactProducer.Context ctx) {
int seconds = (int) (ctx.options().duration().orElse(30.0));
- Path outputFile = ctx.outputDirectoryInNode().resolve("recording.jfr");
+ ContainerPath outputFile = ctx.outputContainerPath().resolve("recording.jfr");
List<String> startCommand = List.of("jcmd", Integer.toString(ctx.servicePid()), "JFR.start", "name=host-admin",
- "path-to-gc-roots=true", "settings=profile", "filename=" + outputFile, "duration=" + seconds + "s");
+ "path-to-gc-roots=true", "settings=profile", "filename=" + outputFile.pathInContainer(), "duration=" + seconds + "s");
ctx.executeCommandInNode(startCommand, true);
sleeper.sleep(Duration.ofSeconds(seconds).plusSeconds(1));
int maxRetries = 10;
@@ -92,7 +92,7 @@ class JvmDumper {
.anyMatch(l -> l.contains("name=host-admin") && l.contains("running"));
if (!stillRunning) {
Artifact a = Artifact.newBuilder()
- .classification(CONFIDENTIAL).fileInNode(outputFile).compressOnUpload().build();
+ .classification(CONFIDENTIAL).file(outputFile).compressOnUpload().build();
return List.of(a);
}
sleeper.sleep(Duration.ofSeconds(1));
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/PerfReporter.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/PerfReporter.java
index 07c8b709e04..3dae6544304 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/PerfReporter.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/PerfReporter.java
@@ -1,7 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.maintenance.servicedump;
-import java.nio.file.Path;
+import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerPath;
+
import java.util.ArrayList;
import java.util.List;
@@ -25,15 +26,15 @@ class PerfReporter implements ArtifactProducer {
if (ctx.options().callGraphRecording()) {
perfRecordCommand.add("-g");
}
- Path recordFile = ctx.outputDirectoryInNode().resolve("perf-record.bin");
+ ContainerPath recordFile = ctx.outputContainerPath().resolve("perf-record.bin");
perfRecordCommand.addAll(
- List.of("--output=" + recordFile,
+ List.of("--output=" + recordFile.pathInContainer(),
"--pid=" + ctx.servicePid(), "sleep", Integer.toString(duration)));
ctx.executeCommandInNode(perfRecordCommand, true);
- Path reportFile = ctx.outputDirectoryInNode().resolve("perf-report.txt");
- ctx.executeCommandInNode(List.of("bash", "-c", "perf report --input=" + recordFile + " > " + reportFile), true);
+ ContainerPath reportFile = ctx.outputContainerPath().resolve("perf-report.txt");
+ ctx.executeCommandInNode(List.of("bash", "-c", "perf report --input=" + recordFile.pathInContainer() + " > " + reportFile.pathInContainer()), true);
return List.of(
- Artifact.newBuilder().classification(CONFIDENTIAL).fileInNode(recordFile).compressOnUpload().build(),
- Artifact.newBuilder().classification(INTERNAL).fileInNode(reportFile).build());
+ Artifact.newBuilder().classification(CONFIDENTIAL).file(recordFile).compressOnUpload().build(),
+ Artifact.newBuilder().classification(INTERNAL).file(reportFile).build());
}
}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/PmapReporter.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/PmapReporter.java
index 659628d03a0..8087ea7eec0 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/PmapReporter.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/PmapReporter.java
@@ -1,7 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.maintenance.servicedump;
-import java.nio.file.Path;
+import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerPath;
+
import java.util.List;
import static com.yahoo.vespa.hosted.node.admin.maintenance.servicedump.Artifact.Classification.INTERNAL;
@@ -15,9 +16,9 @@ class PmapReporter implements ArtifactProducer {
@Override
public List<Artifact> produceArtifacts(Context ctx) {
- Path pmapReport = ctx.outputDirectoryInNode().resolve("pmap.txt");
- List<String> cmd = List.of("bash", "-c", "pmap -x " + ctx.servicePid() + " > " + pmapReport);
+ ContainerPath pmapReport = ctx.outputContainerPath().resolve("pmap.txt");
+ List<String> cmd = List.of("bash", "-c", "pmap -x " + ctx.servicePid() + " > " + pmapReport.pathInContainer());
ctx.executeCommandInNode(cmd, true);
- return List.of(Artifact.newBuilder().classification(INTERNAL).fileInNode(pmapReport).build());
+ return List.of(Artifact.newBuilder().classification(INTERNAL).file(pmapReport).build());
}
}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/VespaLogDumper.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/VespaLogDumper.java
index 24224789877..e6e8df7585e 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/VespaLogDumper.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/VespaLogDumper.java
@@ -1,10 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.maintenance.servicedump;
+import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerPath;
import com.yahoo.yolean.concurrent.Sleeper;
import java.nio.file.Files;
-import java.nio.file.Path;
import java.time.Duration;
import java.util.List;
import java.util.logging.Logger;
@@ -33,12 +33,12 @@ class VespaLogDumper implements ArtifactProducer {
ctx.executeCommandInNode(List.of("kill", "-SIGPROF", Integer.toString(ctx.servicePid())), true);
sleeper.sleep(Duration.ofSeconds(3));
}
- Path vespaLogFile = ctx.pathOnHostFromPathInNode(ctx.pathInNodeUnderVespaHome("logs/vespa/vespa.log"));
- Path destination = ctx.pathOnHostFromPathInNode(ctx.outputDirectoryInNode()).resolve("vespa.log");
+ ContainerPath vespaLogFile = ctx.containerPathUnderVespaHome("logs/vespa/vespa.log");
+ ContainerPath destination = ctx.outputContainerPath().resolve("vespa.log");
if (Files.exists(vespaLogFile)) {
uncheck(() -> Files.copy(vespaLogFile, destination));
return List.of(
- Artifact.newBuilder().classification(CONFIDENTIAL).fileOnHost(destination).compressOnUpload().build());
+ Artifact.newBuilder().classification(CONFIDENTIAL).file(destination).compressOnUpload().build());
} else {
log.info("Log file '" + vespaLogFile + "' does not exist");
return List.of();
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/VespaServiceDumperImpl.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/VespaServiceDumperImpl.java
index 27b3467163c..59f5e0f3f40 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/VespaServiceDumperImpl.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/VespaServiceDumperImpl.java
@@ -12,11 +12,11 @@ import com.yahoo.vespa.hosted.node.admin.maintenance.sync.SyncFileInfo;
import com.yahoo.vespa.hosted.node.admin.maintenance.sync.SyncFileInfo.Compression;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContext;
import com.yahoo.vespa.hosted.node.admin.task.util.file.UnixPath;
+import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerPath;
import com.yahoo.vespa.hosted.node.admin.task.util.process.CommandResult;
import com.yahoo.yolean.concurrent.Sleeper;
import java.net.URI;
-import java.nio.file.Path;
import java.time.Clock;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
@@ -88,21 +88,21 @@ public class VespaServiceDumperImpl implements VespaServiceDumper {
handleFailure(context, request, startedAt, "No artifacts requested");
return;
}
- UnixPath directoryInNode = new UnixPath(context.pathInNodeUnderVespaHome("tmp/vespa-service-dump"));
- UnixPath directoryOnHost = new UnixPath(context.pathOnHostFromPathInNode(directoryInNode.toPath()));
+ ContainerPath directory = context.containerPathUnderVespaHome("tmp/vespa-service-dump");
+ UnixPath unixPathDirectory = new UnixPath(directory);
try {
context.log(log, Level.INFO,
"Creating service dump for " + configId + " requested at "
+ Instant.ofEpochMilli(request.getCreatedMillisOrNull()));
storeReport(context, ServiceDumpReport.createStartedReport(request, startedAt));
- if (directoryOnHost.exists()) {
- context.log(log, Level.INFO, "Removing existing directory '" + directoryOnHost +"'.");
- directoryOnHost.deleteRecursively();
+ if (unixPathDirectory.exists()) {
+ context.log(log, Level.INFO, "Removing existing directory '" + unixPathDirectory +"'.");
+ unixPathDirectory.deleteRecursively();
}
- context.log(log, Level.INFO, "Creating '" + directoryOnHost +"'.");
- directoryOnHost.createDirectory("rwxrwxrwx");
+ context.log(log, Level.INFO, "Creating '" + unixPathDirectory +"'.");
+ unixPathDirectory.createDirectory("rwxrwxrwx");
URI destination = serviceDumpDestination(nodeSpec, createDumpId(request));
- ProducerContext producerCtx = new ProducerContext(context, directoryInNode.toPath(), request);
+ ProducerContext producerCtx = new ProducerContext(context, directory, request);
List<Artifact> producedArtifacts = new ArrayList<>();
for (ArtifactProducer producer : artifactProducers.resolve(requestedArtifacts)) {
context.log(log, "Producing artifact of type '" + producer.artifactName() + "'");
@@ -113,9 +113,9 @@ public class VespaServiceDumperImpl implements VespaServiceDumper {
} catch (Exception e) {
handleFailure(context, request, startedAt, e);
} finally {
- if (directoryOnHost.exists()) {
- context.log(log, Level.INFO, "Deleting directory '" + directoryOnHost +"'.");
- directoryOnHost.deleteRecursively();
+ if (unixPathDirectory.exists()) {
+ context.log(log, Level.INFO, "Deleting directory '" + unixPathDirectory +"'.");
+ unixPathDirectory.deleteRecursively();
}
}
}
@@ -126,10 +126,8 @@ public class VespaServiceDumperImpl implements VespaServiceDumper {
List<SyncFileInfo> filesToUpload = producedArtifacts.stream()
.map(a -> {
Compression compression = a.compressOnUpload() ? Compression.ZSTD : Compression.NONE;
- Path fileInNode = a.fileInNode().orElse(null);
- Path fileOnHost = fileInNode != null ? ctx.pathOnHostFromPathInNode(fileInNode) : a.fileOnHost().orElseThrow();
String classification = a.classification().map(Artifact.Classification::value).orElse(null);
- return SyncFileInfo.forServiceDump(destination, fileOnHost, expiry, compression, owner, classification);
+ return SyncFileInfo.forServiceDump(destination, a.file(), expiry, compression, owner, classification);
})
.collect(Collectors.toList());
ctx.log(log, Level.INFO,
@@ -179,13 +177,13 @@ public class VespaServiceDumperImpl implements VespaServiceDumper {
private class ProducerContext implements ArtifactProducer.Context, ArtifactProducer.Context.Options {
final NodeAgentContext nodeAgentCtx;
- final Path outputDirectoryInNode;
+ final ContainerPath path;
final ServiceDumpReport request;
volatile int pid = -1;
- ProducerContext(NodeAgentContext nodeAgentCtx, Path outputDirectoryInNode, ServiceDumpReport request) {
+ ProducerContext(NodeAgentContext nodeAgentCtx, ContainerPath path, ServiceDumpReport request) {
this.nodeAgentCtx = nodeAgentCtx;
- this.outputDirectoryInNode = outputDirectoryInNode;
+ this.path = path;
this.request = request;
}
@@ -194,8 +192,8 @@ public class VespaServiceDumperImpl implements VespaServiceDumper {
@Override
public int servicePid() {
if (pid == -1) {
- Path findPidBinary = nodeAgentCtx.pathInNodeUnderVespaHome("libexec/vespa/find-pid");
- CommandResult findPidResult = executeCommandInNode(List.of(findPidBinary.toString(), serviceId()), true);
+ ContainerPath findPidBinary = nodeAgentCtx.containerPathUnderVespaHome("libexec/vespa/find-pid");
+ CommandResult findPidResult = executeCommandInNode(List.of(findPidBinary.pathInContainer(), serviceId()), true);
this.pid = Integer.parseInt(findPidResult.getOutput());
}
return pid;
@@ -224,16 +222,11 @@ public class VespaServiceDumperImpl implements VespaServiceDumper {
return result;
}
- @Override public Path outputDirectoryInNode() { return outputDirectoryInNode; }
+ @Override public ContainerPath outputContainerPath() { return path; }
@Override
- public Path pathInNodeUnderVespaHome(String relativePath) {
- return nodeAgentCtx.pathInNodeUnderVespaHome(relativePath);
- }
-
- @Override
- public Path pathOnHostFromPathInNode(Path pathInNode) {
- return nodeAgentCtx.pathOnHostFromPathInNode(pathInNode);
+ public ContainerPath containerPathUnderVespaHome(String relativePath) {
+ return nodeAgentCtx.containerPathUnderVespaHome(relativePath);
}
@Override public Options options() { return this; }
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/ContainerData.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/ContainerData.java
index e32641c0276..07e3268b9e4 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/ContainerData.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/ContainerData.java
@@ -1,6 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.nodeagent;
+import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerPath;
+
import java.nio.file.Path;
/**
@@ -9,27 +11,18 @@ import java.nio.file.Path;
* @author hakon
*/
public interface ContainerData {
- /**
- * Add or overwrite file in container at path.
- *
- * @param pathInContainer The path to the file inside the container, absolute or relative root /.
- * @param data The content of the file.
- */
- void addFile(Path pathInContainer, String data);
- /**
- * Add directory in container at path.
- *
- * @param pathInContainer The path to the directory inside the container, absolute or relative root /.
- */
- void addDirectory(Path pathInContainer);
+ /** Add or overwrite file in container at path. */
+ void addFile(ContainerPath path, String data);
+
+ /** Add directory in container at path. */
+ void addDirectory(ContainerPath path);
/**
* Symlink to a file in container at path.
- *
- * @param symlink The path to the symlink inside the container, absolute or relative root /.
- * @param target The path to the target file for the symbolic link inside the container, absolute or relative root /.
+ * @param symlink The path to the symlink inside the container
+ * @param target The path to the target file for the symbolic link inside the container
*/
- void createSymlink(Path symlink, Path target);
+ void createSymlink(ContainerPath symlink, Path target);
}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContext.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContext.java
index c585bd14e94..8cf8553bc34 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContext.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContext.java
@@ -11,8 +11,8 @@ import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.Acl;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.NodeSpec;
import com.yahoo.vespa.hosted.node.admin.container.ContainerNetworkMode;
+import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerPath;
-import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.util.Optional;
@@ -58,42 +58,11 @@ public interface NodeAgentContext extends TaskContext {
*/
double vcpuOnThisHost();
- /** The file system used by the NodeAgentContext. All paths must have the same provider. */
- FileSystem fileSystem();
+ ContainerPath containerPath(String pathInNode);
- /**
- * This method is the inverse of {@link #pathInNodeFromPathOnHost(Path)}}
- *
- * @param pathInNode absolute path in the container
- * @return the absolute path on host pointing at the same inode
- */
- Path pathOnHostFromPathInNode(Path pathInNode);
-
- default Path pathOnHostFromPathInNode(String pathInNode) {
- return pathOnHostFromPathInNode(fileSystem().getPath(pathInNode));
- }
+ ContainerPath containerPathUnderVespaHome(String relativePath);
- /**
- * This method is the inverse of {@link #pathOnHostFromPathInNode(Path)}
- *
- * @param pathOnHost absolute path on host
- * @return the absolute path in the container pointing at the same inode
- */
- Path pathInNodeFromPathOnHost(Path pathOnHost);
-
- default Path pathInNodeFromPathOnHost(String pathOnHost) {
- return pathInNodeFromPathOnHost(fileSystem().getPath(pathOnHost));
- }
-
- /**
- * @param relativePath relative path under Vespa home in container
- * @return the absolute path under Vespa home in the container
- */
- Path pathInNodeUnderVespaHome(Path relativePath);
-
- default Path pathInNodeUnderVespaHome(String relativePath) {
- return pathInNodeUnderVespaHome(fileSystem().getPath(relativePath));
- }
+ ContainerPath containerPathFromPathOnHost(Path pathOnHost);
Optional<ApplicationId> hostExclusiveTo();
}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextImpl.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextImpl.java
index 6925c1e9600..9bcf5d58d6e 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextImpl.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextImpl.java
@@ -16,11 +16,11 @@ import com.yahoo.vespa.hosted.node.admin.container.ContainerName;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.Acl;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.NodeSpec;
import com.yahoo.vespa.hosted.node.admin.container.ContainerNetworkMode;
+import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerFileSystem;
+import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerPath;
import java.nio.file.FileSystem;
-import java.nio.file.FileSystems;
import java.nio.file.Path;
-import java.nio.file.ProviderMismatchException;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
@@ -40,9 +40,8 @@ public class NodeAgentContextImpl implements NodeAgentContext {
private final AthenzIdentity identity;
private final ContainerNetworkMode containerNetworkMode;
private final ZoneApi zone;
- private final FileSystem fileSystem;
- private final Path pathToNodeRootOnHost;
- private final Path pathToVespaHome;
+ private final ContainerFileSystem containerFs;
+ private final ContainerPath pathToVespaHome;
private final UserNamespace userNamespace;
private final double cpuSpeedup;
private final Set<NodeAgentTask> disabledNodeAgentTasks;
@@ -50,8 +49,7 @@ public class NodeAgentContextImpl implements NodeAgentContext {
public NodeAgentContextImpl(NodeSpec node, Acl acl, AthenzIdentity identity,
ContainerNetworkMode containerNetworkMode, ZoneApi zone,
- FileSystem fileSystem, FlagSource flagSource,
- Path pathToContainerStorage, Path pathToVespaHome,
+ FlagSource flagSource, Path pathToContainerStorage, String pathToVespaHome,
UserNamespace userNamespace, double cpuSpeedup,
Optional<ApplicationId> hostExclusiveTo) {
if (cpuSpeedup <= 0)
@@ -63,9 +61,8 @@ public class NodeAgentContextImpl implements NodeAgentContext {
this.identity = Objects.requireNonNull(identity);
this.containerNetworkMode = Objects.requireNonNull(containerNetworkMode);
this.zone = Objects.requireNonNull(zone);
- this.fileSystem = Objects.requireNonNull(fileSystem);
- this.pathToNodeRootOnHost = requireValidPath(pathToContainerStorage).resolve(containerName.asString());
- this.pathToVespaHome = requireValidPath(pathToVespaHome);
+ this.containerFs = ContainerFileSystem.create(pathToContainerStorage.resolve(containerName.asString()), userNamespace);
+ this.pathToVespaHome = containerFs.getPath(pathToVespaHome);
this.logPrefix = containerName.asString() + ": ";
this.userNamespace = Objects.requireNonNull(userNamespace);
this.cpuSpeedup = cpuSpeedup;
@@ -120,41 +117,21 @@ public class NodeAgentContextImpl implements NodeAgentContext {
}
@Override
- public FileSystem fileSystem() {
- return fileSystem;
+ public ContainerPath containerPath(String pathInNode) {
+ return containerFs.getPath(pathInNode);
}
@Override
- public Path pathOnHostFromPathInNode(Path pathInNode) {
- requireValidPath(pathInNode);
-
- if (! pathInNode.isAbsolute())
- throw new IllegalArgumentException("Expected an absolute path in the container, got: " + pathInNode);
+ public ContainerPath containerPathUnderVespaHome(String relativePath) {
+ if (relativePath.startsWith("/"))
+ throw new IllegalArgumentException("Expected a relative path to the Vespa home, got: " + relativePath);
- return pathToNodeRootOnHost.resolve(pathInNode.getRoot().relativize(pathInNode));
+ return pathToVespaHome.resolve(relativePath);
}
@Override
- public Path pathInNodeFromPathOnHost(Path pathOnHost) {
- requireValidPath(pathOnHost);
-
- if (! pathOnHost.isAbsolute())
- throw new IllegalArgumentException("Expected an absolute path on the host, got: " + pathOnHost);
-
- if (!pathOnHost.startsWith(pathToNodeRootOnHost))
- throw new IllegalArgumentException("Path " + pathOnHost + " does not exist in the container");
-
- return pathOnHost.getRoot().resolve(pathToNodeRootOnHost.relativize(pathOnHost));
- }
-
- @Override
- public Path pathInNodeUnderVespaHome(Path relativePath) {
- requireValidPath(relativePath);
-
- if (relativePath.isAbsolute())
- throw new IllegalArgumentException("Expected a relative path to the Vespa home, got: " + relativePath);
-
- return pathToVespaHome.resolve(relativePath);
+ public ContainerPath containerPathFromPathOnHost(Path pathOnHost) {
+ return ContainerPath.fromPathOnHost(containerFs, pathOnHost);
}
@Override
@@ -186,24 +163,11 @@ public class NodeAgentContextImpl implements NodeAgentContext {
", identity=" + identity +
", dockerNetworking=" + containerNetworkMode +
", zone=" + zone +
- ", pathToNodeRootOnHost=" + pathToNodeRootOnHost +
", pathToVespaHome=" + pathToVespaHome +
", hostExclusiveTo='" + hostExclusiveTo + '\'' +
'}';
}
- private Path requireValidPath(Path path) {
- Objects.requireNonNull(path);
-
- Objects.requireNonNull(fileSystem); // to allow this method to be used in constructor.
- if (!path.getFileSystem().provider().equals(fileSystem.provider())) {
- throw new ProviderMismatchException("Expected file system provider " + fileSystem.provider() +
- " but " + path + " had " + path.getFileSystem().provider());
- }
-
- return path;
- }
-
public static NodeAgentContextImpl.Builder builder(NodeSpec node) {
return new Builder(new NodeSpec.Builder(node));
}
@@ -219,16 +183,17 @@ public class NodeAgentContextImpl implements NodeAgentContext {
/** For testing only! */
public static class Builder {
+ private static final Path DEFAULT_CONTAINER_STORAGE = Path.of("/data/vespa/storage");
+
private NodeSpec.Builder nodeSpecBuilder;
private Acl acl;
private AthenzIdentity identity;
private ContainerNetworkMode containerNetworkMode;
private ZoneApi zone;
private UserNamespace userNamespace;
- private FileSystem fileSystem = FileSystems.getDefault();
+ private Path containerStorage;
private FlagSource flagSource;
private double cpuSpeedUp = 1;
- private Path containerStorage;
private Optional<ApplicationId> hostExclusiveTo = Optional.empty();
private Builder(NodeSpec.Builder nodeSpecBuilder) {
@@ -267,8 +232,7 @@ public class NodeAgentContextImpl implements NodeAgentContext {
/** Sets the file system to use for paths. */
public Builder fileSystem(FileSystem fileSystem) {
- this.fileSystem = fileSystem;
- return this;
+ return containerStorage(fileSystem.getPath(DEFAULT_CONTAINER_STORAGE.toString()));
}
public Builder flagSource(FlagSource flagSource) {
@@ -292,6 +256,8 @@ public class NodeAgentContextImpl implements NodeAgentContext {
}
public NodeAgentContextImpl build() {
+ Objects.requireNonNull(containerStorage, "Must set one of containerStorage or fileSystem");
+
return new NodeAgentContextImpl(
nodeSpecBuilder.build(),
Optional.ofNullable(acl).orElse(Acl.EMPTY),
@@ -318,11 +284,10 @@ public class NodeAgentContextImpl implements NodeAgentContext {
return getId().region().value();
}
}),
- fileSystem,
Optional.ofNullable(flagSource).orElseGet(InMemoryFlagSource::new),
- Optional.ofNullable(containerStorage).orElseGet(() -> fileSystem.getPath("/data/vespa/storage")),
- fileSystem.getPath("/opt/vespa"),
- Optional.ofNullable(userNamespace).orElseGet(() -> new UserNamespace(10000, 10000, "vespa", "users", 1000, 100)),
+ containerStorage,
+ "/opt/vespa",
+ Optional.ofNullable(userNamespace).orElseGet(() -> new UserNamespace(100000, 100000, "vespa", "vespa", 1000, 100)),
cpuSpeedUp, hostExclusiveTo);
}
}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImpl.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImpl.java
index 391aa46716a..3ab196a052e 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImpl.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImpl.java
@@ -27,6 +27,7 @@ import com.yahoo.vespa.hosted.node.admin.maintenance.acl.AclMaintainer;
import com.yahoo.vespa.hosted.node.admin.maintenance.identity.CredentialsMaintainer;
import com.yahoo.vespa.hosted.node.admin.maintenance.servicedump.VespaServiceDumper;
import com.yahoo.vespa.hosted.node.admin.nodeadmin.ConvergenceException;
+import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerPath;
import java.nio.file.Path;
import java.time.Clock;
@@ -597,17 +598,17 @@ public class NodeAgentImpl implements NodeAgent {
protected ContainerData createContainerData(NodeAgentContext context) {
return new ContainerData() {
@Override
- public void addFile(Path pathInContainer, String data) {
+ public void addFile(ContainerPath path, String data) {
throw new UnsupportedOperationException("addFile not implemented");
}
@Override
- public void addDirectory(Path pathInContainer) {
+ public void addDirectory(ContainerPath path) {
throw new UnsupportedOperationException("addDirectory not implemented");
}
@Override
- public void createSymlink(Path symlink, Path target) {
+ public void createSymlink(ContainerPath symlink, Path target) {
throw new UnsupportedOperationException("createSymlink not implemented");
}
};
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/UserNamespace.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/UserNamespace.java
index 5b53879ceec..1a25b5c3c5e 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/UserNamespace.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/UserNamespace.java
@@ -1,13 +1,20 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.nodeagent;
+import java.util.Objects;
+
/**
* @author valerijf
*/
public class UserNamespace {
/** Total number of UID/GID that are mapped for each container */
- private static final int ID_RANGE = 1 << 16;
+ private static final int ID_RANGE = 65_536; // 2^16
+
+ /**
+ * IDs outside the ID range are translated to the overflow ID before being written to disk:
+ * https://github.com/torvalds/linux/blob/5bfc75d92efd494db37f5c4c173d3639d4772966/Documentation/admin-guide/sysctl/fs.rst#overflowgid--overflowuid */
+ private static final int OVERFLOW_ID = 65_534;
private final int uidOffset;
private final int gidOffset;
@@ -19,36 +26,33 @@ public class UserNamespace {
public UserNamespace(int uidOffset, int gidOffset, String vespaUser, String vespaGroup, int vespaUserId, int vespaGroupId) {
this.uidOffset = uidOffset;
this.gidOffset = gidOffset;
- this.vespaUser = vespaUser;
- this.vespaGroup = vespaGroup;
+ this.vespaUser = Objects.requireNonNull(vespaUser);
+ this.vespaGroup = Objects.requireNonNull(vespaGroup);
this.vespaUserId = vespaUserId;
this.vespaGroupId = vespaGroupId;
}
- public int userIdOnHost(int userIdInContainer) {
- assertValidId("User", userIdInContainer);
- return uidOffset + userIdInContainer;
- }
-
- public int groupIdOnHost(int groupIdInContainer) {
- assertValidId("Group", groupIdInContainer);
- return gidOffset + groupIdInContainer;
- }
-
- int rootUserId() { return 0; }
- int rootGroupId() { return 0; }
- int rootUserIdOnHost() { return userIdOnHost(rootUserId()); }
- int rootGroupIdOnHost() { return groupIdOnHost(rootGroupId()); }
+ public int userIdOnHost(int containerUid) { return toHostId(containerUid, uidOffset); }
+ public int groupIdOnHost(int containerGid) { return toHostId(containerGid, gidOffset); }
+ public int userIdInContainer(int hostUid) { return toContainerId(hostUid, uidOffset); }
+ public int groupIdInContainer(int hostGid) { return toContainerId(hostGid, gidOffset); }
public String vespaUser() { return vespaUser; }
public String vespaGroup() { return vespaGroup; }
public int vespaUserId() { return vespaUserId; }
public int vespaGroupId() { return vespaGroupId; }
- public int vespaUserIdOnHost() { return userIdOnHost(vespaUserId()); }
- public int vespaGroupIdOnHost() { return groupIdOnHost(vespaGroupId()); }
- private static void assertValidId(String type, int id) {
- if (id < 0) throw new IllegalArgumentException(type + " ID cannot be negative, was " + id);
- if (id >= ID_RANGE) throw new IllegalArgumentException(type + " ID must be less than " + ID_RANGE + ", was " + id);
+ public int idRange() { return ID_RANGE; }
+ public int overflowId() { return OVERFLOW_ID; }
+
+ private static int toHostId(int containerId, int idOffset) {
+ if (containerId < 0 || containerId > ID_RANGE)
+ throw new IllegalArgumentException("Invalid container id: " + containerId);
+ return idOffset + containerId;
+ }
+
+ private static int toContainerId(int hostId, int idOffset) {
+ hostId = hostId - idOffset;
+ return hostId < 0 || hostId >= ID_RANGE ? OVERFLOW_ID : hostId;
}
}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/fs/ContainerFileSystem.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/fs/ContainerFileSystem.java
index 495b72e4554..078a60ba7a5 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/fs/ContainerFileSystem.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/fs/ContainerFileSystem.java
@@ -1,15 +1,20 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.task.util.fs;
+import com.yahoo.vespa.hosted.node.admin.nodeagent.UserNamespace;
+
import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.FileSystem;
+import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.WatchService;
import java.nio.file.attribute.UserPrincipalLookupService;
import java.util.Set;
+import static com.yahoo.yolean.Exceptions.uncheck;
+
/**
* @author valerijf
*/
@@ -81,7 +86,8 @@ public class ContainerFileSystem extends FileSystem {
throw new UnsupportedOperationException();
}
- public static ContainerFileSystem create(Path containerStorageRoot, int uidOffset, int gidOffset) {
- return new ContainerFileSystemProvider(containerStorageRoot, uidOffset, gidOffset).getFileSystem(null);
+ public static ContainerFileSystem create(Path containerStorageRoot, UserNamespace userNamespace) {
+ uncheck(() -> Files.createDirectories(containerStorageRoot));
+ return new ContainerFileSystemProvider(containerStorageRoot, userNamespace).getFileSystem(null);
}
}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/fs/ContainerFileSystemProvider.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/fs/ContainerFileSystemProvider.java
index 73cd3f8cfc5..a44f90b164b 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/fs/ContainerFileSystemProvider.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/fs/ContainerFileSystemProvider.java
@@ -1,6 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.task.util.fs;
+import com.yahoo.vespa.hosted.node.admin.nodeagent.UserNamespace;
+
import java.io.IOException;
import java.net.URI;
import java.nio.channels.SeekableByteChannel;
@@ -10,6 +12,7 @@ import java.nio.file.DirectoryStream;
import java.nio.file.FileStore;
import java.nio.file.FileSystem;
import java.nio.file.FileSystemAlreadyExistsException;
+import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.OpenOption;
import java.nio.file.Path;
@@ -42,10 +45,10 @@ class ContainerFileSystemProvider extends FileSystemProvider {
private final ContainerUserPrincipalLookupService userPrincipalLookupService;
private final Path containerRootOnHost;
- ContainerFileSystemProvider(Path containerRootOnHost, int uidOffset, int gidOffset) {
+ ContainerFileSystemProvider(Path containerRootOnHost, UserNamespace userNamespace) {
this.containerFs = new ContainerFileSystem(this);
this.userPrincipalLookupService = new ContainerUserPrincipalLookupService(
- containerRootOnHost.getFileSystem().getUserPrincipalLookupService(), uidOffset, gidOffset);
+ containerRootOnHost.getFileSystem().getUserPrincipalLookupService(), userNamespace);
this.containerRootOnHost = containerRootOnHost;
}
@@ -80,8 +83,9 @@ class ContainerFileSystemProvider extends FileSystemProvider {
@Override
public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException {
Path pathOnHost = pathOnHost(path);
+ boolean existedBefore = Files.exists(pathOnHost);
SeekableByteChannel seekableByteChannel = provider(pathOnHost).newByteChannel(pathOnHost, options, attrs);
- fixOwnerToContainerRoot(toContainerPath(path));
+ if (!existedBefore) fixOwnerToContainerRoot(toContainerPath(path));
return seekableByteChannel;
}
@@ -94,8 +98,9 @@ class ContainerFileSystemProvider extends FileSystemProvider {
@Override
public void createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException {
Path pathOnHost = pathOnHost(dir);
+ boolean existedBefore = Files.exists(pathOnHost);
provider(pathOnHost).createDirectory(pathOnHost);
- fixOwnerToContainerRoot(toContainerPath(dir));
+ if (!existedBefore) fixOwnerToContainerRoot(toContainerPath(dir));
}
@Override
@@ -121,6 +126,20 @@ class ContainerFileSystemProvider extends FileSystemProvider {
}
@Override
+ public void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs) throws IOException {
+ Path pathOnHost = pathOnHost(link);
+ if (target instanceof ContainerPath)
+ target = pathOnHost.getFileSystem().getPath(toContainerPath(target).pathInContainer());
+ provider(pathOnHost).createSymbolicLink(pathOnHost, target, attrs);
+ }
+
+ @Override
+ public Path readSymbolicLink(Path link) throws IOException {
+ Path pathOnHost = pathOnHost(link);
+ return provider(pathOnHost).readSymbolicLink(pathOnHost);
+ }
+
+ @Override
public boolean isSameFile(Path path, Path path2) throws IOException {
// 'path' FS provider should be 'this'
if (path2 instanceof ContainerPath)
@@ -180,12 +199,12 @@ class ContainerFileSystemProvider extends FileSystemProvider {
return provider(pathOnHost).readAttributes(pathOnHost, attributes, options);
Map<String, Object> attrs = new HashMap<>(provider(pathOnHost).readAttributes(pathOnHost, "unix:*", options));
- int uid = userPrincipalLookupService.hostUidToContainerUid((int) attrs.get("uid"));
- int gid = userPrincipalLookupService.hostGidToContainerGid((int) attrs.get("gid"));
+ int uid = userPrincipalLookupService.userIdInContainer((int) attrs.get("uid"));
+ int gid = userPrincipalLookupService.groupIdInContainer((int) attrs.get("gid"));
attrs.put("uid", uid);
attrs.put("gid", gid);
- attrs.put("owner", new ContainerUserPrincipal(uid, (UserPrincipal) attrs.get("owner")));
- attrs.put("group", new ContainerGroupPrincipal(gid, (GroupPrincipal) attrs.get("group")));
+ attrs.put("owner", userPrincipalLookupService.userPrincipal(uid, (UserPrincipal) attrs.get("owner")));
+ attrs.put("group", userPrincipalLookupService.groupPrincipal(gid, (GroupPrincipal) attrs.get("group")));
return attrs;
}
@@ -201,8 +220,8 @@ class ContainerFileSystemProvider extends FileSystemProvider {
switch (attribute.substring(index + 1)) {
case "owner": return cast(value, ContainerUserPrincipal.class).baseFsPrincipal();
case "group": return cast(value, ContainerGroupPrincipal.class).baseFsPrincipal();
- case "uid": return userPrincipalLookupService.containerUidToHostUid(cast(value, Integer.class));
- case "gid": return userPrincipalLookupService.containerGidToHostGid(cast(value, Integer.class));
+ case "uid": return userPrincipalLookupService.userIdOnHost(cast(value, Integer.class));
+ case "gid": return userPrincipalLookupService.groupIdOnHost(cast(value, Integer.class));
}
} // else basic file attribute
return value;
@@ -250,7 +269,7 @@ class ContainerFileSystemProvider extends FileSystemProvider {
private static <T> T cast(Object value, Class<T> type) {
if (type.isInstance(value)) return type.cast(value);
- throw new ProviderMismatchException("Expected " + type.getName() + ", was " + value.getClass().getName());
+ throw new ProviderMismatchException("Expected " + type.getSimpleName() + ", was " + value.getClass().getName());
}
private static Path pathOnHost(Path path) {
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/fs/ContainerUserPrincipalLookupService.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/fs/ContainerUserPrincipalLookupService.java
index 893e86ca239..ae65f6a7f7f 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/fs/ContainerUserPrincipalLookupService.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/fs/ContainerUserPrincipalLookupService.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.task.util.fs;
-import com.google.common.collect.ImmutableBiMap;
+import com.yahoo.vespa.hosted.node.admin.nodeagent.UserNamespace;
import java.io.IOException;
import java.nio.file.attribute.GroupPrincipal;
@@ -9,58 +9,60 @@ import java.nio.file.attribute.UserPrincipal;
import java.nio.file.attribute.UserPrincipalLookupService;
import java.nio.file.attribute.UserPrincipalNotFoundException;
import java.util.Objects;
-import java.util.Optional;
/**
* @author valerijf
*/
class ContainerUserPrincipalLookupService extends UserPrincipalLookupService {
- /** Total number of UID/GID that are mapped for each container */
- private static final int ID_RANGE = 1 << 16;
-
- /**
- * IDs outside the ID range are translated to the overflow ID before being written to disk:
- * https://github.com/torvalds/linux/blob/5bfc75d92efd494db37f5c4c173d3639d4772966/Documentation/admin-guide/sysctl/fs.rst#overflowgid--overflowuid */
- static final int OVERFLOW_ID = 65_534;
-
- private static final ImmutableBiMap<String, Integer> CONTAINER_IDS_BY_NAME = ImmutableBiMap.<String, Integer>builder()
- .put("root", 0)
- .put("vespa", 1000)
- .build();
-
private final UserPrincipalLookupService baseFsUserPrincipalLookupService;
- private final int uidOffset;
- private final int gidOffset;
+ private final UserNamespace userNamespace;
- ContainerUserPrincipalLookupService(UserPrincipalLookupService baseFsUserPrincipalLookupService, int uidOffset, int gidOffset) {
- this.baseFsUserPrincipalLookupService = baseFsUserPrincipalLookupService;
- this.uidOffset = uidOffset;
- this.gidOffset = gidOffset;
+ ContainerUserPrincipalLookupService(UserPrincipalLookupService baseFsUserPrincipalLookupService, UserNamespace userNamespace) {
+ this.baseFsUserPrincipalLookupService = Objects.requireNonNull(baseFsUserPrincipalLookupService);
+ this.userNamespace = Objects.requireNonNull(userNamespace);
}
- public int containerUidToHostUid(int containerUid) { return containerIdToHostId(containerUid, uidOffset); }
- public int containerGidToHostGid(int containerGid) { return containerIdToHostId(containerGid, gidOffset); }
- public int hostUidToContainerUid(int hostUid) { return hostIdToContainerId(hostUid, uidOffset); }
- public int hostGidToContainerGid(int hostGid) { return hostIdToContainerId(hostGid, gidOffset); }
+ public int userIdOnHost(int containerUid) { return userNamespace.userIdOnHost(containerUid); }
+ public int groupIdOnHost(int containerGid) { return userNamespace.groupIdOnHost(containerGid); }
+ public int userIdInContainer(int hostUid) { return userNamespace.userIdInContainer(hostUid); }
+ public int groupIdInContainer(int hostGid) { return userNamespace.groupIdInContainer(hostGid); }
@Override
public ContainerUserPrincipal lookupPrincipalByName(String name) throws IOException {
- int containerUid = resolve(name);
- String hostUid = String.valueOf(containerUidToHostUid(containerUid));
- return new ContainerUserPrincipal(containerUid, baseFsUserPrincipalLookupService.lookupPrincipalByName(hostUid));
+ int containerUid = resolveName(name, userNamespace.vespaUser(), userNamespace.vespaUserId());
+ String user = resolveId(containerUid, userNamespace.vespaUser(), userNamespace.vespaUserId());
+ String hostUid = String.valueOf(userIdOnHost(containerUid));
+ return new ContainerUserPrincipal(containerUid, user, baseFsUserPrincipalLookupService.lookupPrincipalByName(hostUid));
}
@Override
public ContainerGroupPrincipal lookupPrincipalByGroupName(String group) throws IOException {
- int containerGid = resolve(group);
- String hostGid = String.valueOf(containerGidToHostGid(containerGid));
- return new ContainerGroupPrincipal(containerGid, baseFsUserPrincipalLookupService.lookupPrincipalByGroupName(hostGid));
+ int containerGid = resolveName(group, userNamespace.vespaGroup(), userNamespace.vespaGroupId());
+ String name = resolveId(containerGid, userNamespace.vespaGroup(), userNamespace.vespaGroupId());
+ String hostGid = String.valueOf(groupIdOnHost(containerGid));
+ return new ContainerGroupPrincipal(containerGid, name, baseFsUserPrincipalLookupService.lookupPrincipalByGroupName(hostGid));
+ }
+
+ public ContainerUserPrincipal userPrincipal(int uid, UserPrincipal baseFsPrincipal) {
+ String name = resolveId(uid, userNamespace.vespaUser(), userNamespace.vespaUserId());
+ return new ContainerUserPrincipal(uid, name, baseFsPrincipal);
+ }
+
+ public ContainerGroupPrincipal groupPrincipal(int gid, GroupPrincipal baseFsPrincipal) {
+ String name = resolveId(gid, userNamespace.vespaGroup(), userNamespace.vespaGroupId());
+ return new ContainerGroupPrincipal(gid, name, baseFsPrincipal);
}
- private static int resolve(String name) throws UserPrincipalNotFoundException {
- Integer id = CONTAINER_IDS_BY_NAME.get(name);
- if (id != null) return id;
+ private String resolveId(int id, String vespaName, int vespaId) {
+ if (id == 0) return "root";
+ if (id == vespaId) return vespaName;
+ return String.valueOf(id);
+ }
+
+ private int resolveName(String name, String vespaName, int vespaId) throws UserPrincipalNotFoundException {
+ if (name.equals("root")) return 0;
+ if (name.equals(vespaName)) return vespaId;
try {
return Integer.parseInt(name);
@@ -74,9 +76,9 @@ class ContainerUserPrincipalLookupService extends UserPrincipalLookupService {
private final String name;
private final UserPrincipal baseFsPrincipal;
- private NamedPrincipal(int id, UserPrincipal baseFsPrincipal) {
+ private NamedPrincipal(int id, String name, UserPrincipal baseFsPrincipal) {
this.id = id;
- this.name = Optional.ofNullable(CONTAINER_IDS_BY_NAME.inverse().get(id)).orElseGet(() -> Integer.toString(id));
+ this.name = Objects.requireNonNull(name);
this.baseFsPrincipal = Objects.requireNonNull(baseFsPrincipal);
}
@@ -113,23 +115,12 @@ class ContainerUserPrincipalLookupService extends UserPrincipalLookupService {
}
static final class ContainerUserPrincipal extends NamedPrincipal {
- ContainerUserPrincipal(int id, UserPrincipal baseFsPrincipal) { super(id, baseFsPrincipal); }
+ private ContainerUserPrincipal(int id, String name, UserPrincipal baseFsPrincipal) { super(id, name, baseFsPrincipal); }
}
static final class ContainerGroupPrincipal extends NamedPrincipal implements GroupPrincipal {
- ContainerGroupPrincipal(int id, GroupPrincipal baseFsPrincipal) { super(id, baseFsPrincipal); }
+ private ContainerGroupPrincipal(int id, String name, GroupPrincipal baseFsPrincipal) { super(id, name, baseFsPrincipal); }
@Override public GroupPrincipal baseFsPrincipal() { return (GroupPrincipal) super.baseFsPrincipal(); }
}
-
- private static int containerIdToHostId(int id, int idOffset) {
- if (id < 0 || id > ID_RANGE)
- throw new IllegalArgumentException("Invalid container id: " + id);
- return idOffset + id;
- }
-
- private static int hostIdToContainerId(int id, int idOffset) {
- id = id - idOffset;
- return id < 0 || id >= ID_RANGE ? OVERFLOW_ID : id;
- }
}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/fs/package-info.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/fs/package-info.java
new file mode 100644
index 00000000000..a2a86604fdd
--- /dev/null
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/fs/package-info.java
@@ -0,0 +1,5 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+@ExportPackage
+package com.yahoo.vespa.hosted.node.admin.task.util.fs;
+
+import com.yahoo.osgi.annotation.ExportPackage;