The Unified and Autonomous Development Platform
chore: Reworked directory permission for CI/CD and workspace
Robin Shen84872540b486
diff --git a/pom.xml b/pom.xmlindex 4bd6e9e840..3c4dc5b206 100644--- a/pom.xml+++ b/pom.xml@@ -676,8 +676,8 @@</repository></repositories><properties>- <commons.version>3.2.8</commons.version>- <agent.version>2.4.12</agent.version>+ <commons.version>3.2.9</commons.version>+ <agent.version>2.5.0</agent.version><slf4j.version>2.0.9</slf4j.version><logback.version>1.4.14</logback.version><antlr.version>4.7.2</antlr.version>diff --git a/server-core/src/main/java/io/onedev/server/buildspec/BuildSpec.java b/server-core/src/main/java/io/onedev/server/buildspec/BuildSpec.javaindex 32c37332e9..a7874d225b 100644--- a/server-core/src/main/java/io/onedev/server/buildspec/BuildSpec.java+++ b/server-core/src/main/java/io/onedev/server/buildspec/BuildSpec.java@@ -2465,8 +2465,27 @@ public class BuildSpec implements Serializable, Validatable {return null;}+ private static void migrate47_setDefaultRunAs(MappingNode node) {+ for (var tuple : node.getValue()) {+ if (((ScalarNode) tuple.getKeyNode()).getValue().equals("runAs"))+ return;+ }+ node.getValue().add(new NodeTuple(+ new ScalarNode(Tag.STR, "runAs"),+ new ScalarNode(Tag.STR, "0:0")));+ }+@SuppressWarnings("unused")private void migrate47(VersionedYamlDoc doc, Stack<Integer> versions) {+ for (NodeTuple specTuple: doc.getValue()) {+ String specObjectKey = ((ScalarNode) specTuple.getKeyNode()).getValue();+ if (specObjectKey.equals("services")) {+ SequenceNode servicesNode = (SequenceNode) specTuple.getValueNode();+ for (Node servicesNodeItem: servicesNode.getValue())+ migrate47_setDefaultRunAs((MappingNode) servicesNodeItem);+ }+ }+migrateSteps(doc, versions, stepsNode -> {Map<String, String> checksumMap = new LinkedHashMap<>();for (Node stepsNodeItem : stepsNode.getValue()) {@@ -2556,6 +2575,14 @@ public class BuildSpec implements Serializable, Validatable {}}}+ migrate47_setDefaultRunAs(stepNode);+ } else if ("BuildImageWithKanikoStep".equals(stepType)+ || "SSHCommandStep".equals(stepType)+ || "SCPCommandStep".equals(stepType)+ || "PushImageStep".equals(stepType)+ || "PullImageStep".equals(stepType)+ || "RenovateStep".equals(stepType)) {+ migrate47_setDefaultRunAs(stepNode);}}});diff --git a/server-core/src/main/java/io/onedev/server/buildspec/Service.java b/server-core/src/main/java/io/onedev/server/buildspec/Service.javaindex 54a15b45b6..4886bf20fe 100644--- a/server-core/src/main/java/io/onedev/server/buildspec/Service.java+++ b/server-core/src/main/java/io/onedev/server/buildspec/Service.java@@ -38,7 +38,7 @@ public class Service implements NamedElement {private String readinessCheckCommand;- private String runAs;+ private String runAs = "0:0";private List<RegistryLogin> registryLogins = new ArrayList<>();@@ -111,10 +111,9 @@ public class Service implements NamedElement {this.readinessCheckCommand = readinessCheckCommand;}- @Editable(order=450, name="Run As", group = "More Settings", placeholder = "root", description = "Optionally specify uid:gid to run container as. " +- "<b class='text-warning'>Note:</b> This setting should be left empty if container runtime is rootless or " +- "using user namespace remapping")+ @Editable(order=450, name="Run As", group = "More Settings", description = "Specify uid:gid to run container as")@Pattern(regexp="\\d+:\\d+", message = "Should be specified in form of <uid>:<gid>")+ @NotEmptypublic String getRunAs() {return runAs;}diff --git a/server-core/src/main/java/io/onedev/server/buildspec/step/BuildImageWithKanikoStep.java b/server-core/src/main/java/io/onedev/server/buildspec/step/BuildImageWithKanikoStep.javaindex 2fa764cbdd..d2c2f99cc1 100644--- a/server-core/src/main/java/io/onedev/server/buildspec/step/BuildImageWithKanikoStep.java+++ b/server-core/src/main/java/io/onedev/server/buildspec/step/BuildImageWithKanikoStep.java@@ -1,28 +1,32 @@package io.onedev.server.buildspec.step;-import static io.onedev.agent.AgentUtils.buildDockerConfig;+import static io.onedev.agent.AgentUtils.buildAuthConfig;import static io.onedev.k8shelper.RegistryLoginFacade.merge;import static io.onedev.server.buildspec.step.StepGroup.DOCKER_IMAGE;import java.io.Serializable;import java.util.ArrayList;+import java.util.HashMap;import java.util.List;import java.util.Map;import javax.validation.constraints.NotEmpty;import javax.validation.constraints.NotNull;+import com.fasterxml.jackson.core.JsonProcessingException;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.onedev.commons.codeassist.InputSuggestion;import io.onedev.commons.utils.ExplicitException;import io.onedev.commons.utils.StringUtils;import io.onedev.k8shelper.CommandFacade;import io.onedev.k8shelper.RegistryLoginFacade;import io.onedev.k8shelper.StepFacade;-import io.onedev.server.annotation.Path;import io.onedev.server.annotation.Editable;import io.onedev.server.annotation.Interpolative;import io.onedev.server.annotation.Multiline;import io.onedev.server.annotation.NoSpace;+import io.onedev.server.annotation.Path;import io.onedev.server.annotation.ReservedOptions;import io.onedev.server.buildspec.BuildSpec;import io.onedev.server.buildspec.param.ParamCombination;@@ -65,7 +69,7 @@ public class BuildImageWithKanikoStep extends CommandStep {@Overridepublic String getRunAs() {- return null;+ return "0:0";}@Editable(order=100, description="Optionally specify build context path relative to <a href='https://docs.onedev.io/concepts#job-workdir' target='_blank'>job working directory</a>. "@@ -145,7 +149,13 @@ public class BuildImageWithKanikoStep extends CommandStep {DockerAware registryLoginAware = (DockerAware) jobExecutor;commandsBuilder.append("cat <<EOF>> /kaniko/.docker/config.json\n");var mergedRegistryLogins = merge(registryLogins, registryLoginAware.getRegistryLogins(jobToken));- commandsBuilder.append(buildDockerConfig(mergedRegistryLogins)).append("\n");+ var configMap = new HashMap<String, Object>();+ configMap.put("auths", buildAuthConfig(mergedRegistryLogins));+ try {+ commandsBuilder.append(new ObjectMapper().writeValueAsString(configMap)).append("\n");+ } catch (JsonProcessingException e) {+ throw new RuntimeException(e);+ }commandsBuilder.append("EOF\n");}if (getTrustCertificates() != null) {diff --git a/server-core/src/main/java/io/onedev/server/buildspec/step/CommandStep.java b/server-core/src/main/java/io/onedev/server/buildspec/step/CommandStep.javaindex 7c225407ed..6e8bb39262 100644--- a/server-core/src/main/java/io/onedev/server/buildspec/step/CommandStep.java+++ b/server-core/src/main/java/io/onedev/server/buildspec/step/CommandStep.java@@ -44,7 +44,7 @@ public class CommandStep extends Step {private Interpreter interpreter = new DefaultInterpreter();- private String runAs;+ private String runAs = "0:0";private List<RegistryLogin> registryLogins = new ArrayList<>();@@ -84,11 +84,10 @@ public class CommandStep extends Step {this.interpreter = interpreter;}- @Editable(order=8000, name="Run As", group = "More Settings", placeholder = "root", description = "Optionally specify uid:gid to run container as. " +- "<b class='text-warning'>Note:</b> This setting should be left empty if container runtime is rootless or " +- "using user namespace remapping")+ @Editable(order=8000, name="Run As", group = "More Settings", description = "Specify uid:gid to run container as")@DependsOn(property="runInContainer")@Pattern(regexp="\\d+:\\d+", message = "Should be specified in form of <uid>:<gid>")+ @NotEmptypublic String getRunAs() {return runAs;}diff --git a/server-core/src/main/java/io/onedev/server/buildspec/step/CraneStep.java b/server-core/src/main/java/io/onedev/server/buildspec/step/CraneStep.javaindex 0ef26c29bf..cf4ffa781c 100644--- a/server-core/src/main/java/io/onedev/server/buildspec/step/CraneStep.java+++ b/server-core/src/main/java/io/onedev/server/buildspec/step/CraneStep.java@@ -1,11 +1,15 @@package io.onedev.server.buildspec.step;-import static io.onedev.agent.AgentUtils.buildDockerConfig;+import static io.onedev.agent.AgentUtils.buildAuthConfig;import static io.onedev.k8shelper.RegistryLoginFacade.merge;+import java.util.HashMap;import java.util.List;import java.util.Map;+import com.fasterxml.jackson.core.JsonProcessingException;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.onedev.commons.codeassist.InputSuggestion;import io.onedev.k8shelper.CommandFacade;import io.onedev.k8shelper.RegistryLoginFacade;@@ -46,7 +50,7 @@ public abstract class CraneStep extends CommandStep {@Overridepublic String getRunAs() {- return null;+ return "0:0";}@Editable(order=1000, name="Certificates to Trust", group = "More Settings", placeholder = "Base64 encoded PEM format, starting with " +@@ -93,7 +97,13 @@ public abstract class CraneStep extends CommandStep {commandsBuilder.append("mkdir /root/.docker\n");commandsBuilder.append("cat <<EOF>> /root/.docker/config.json\n");var mergedRegistryLogins = merge(registryLogins, registryLoginAware.getRegistryLogins(jobToken));- commandsBuilder.append(buildDockerConfig(mergedRegistryLogins)).append("\n");+ var configMap = new HashMap<String, Object>();+ configMap.put("auths", buildAuthConfig(mergedRegistryLogins));+ try {+ commandsBuilder.append(new ObjectMapper().writeValueAsString(configMap)).append("\n");+ } catch (JsonProcessingException e) {+ throw new RuntimeException(e);+ }commandsBuilder.append("EOF\n");}if (getTrustCertificates() != null) {diff --git a/server-core/src/main/java/io/onedev/server/buildspec/step/SCPCommandStep.java b/server-core/src/main/java/io/onedev/server/buildspec/step/SCPCommandStep.javaindex 13ddf34611..1d1a66c5bf 100644--- a/server-core/src/main/java/io/onedev/server/buildspec/step/SCPCommandStep.java+++ b/server-core/src/main/java/io/onedev/server/buildspec/step/SCPCommandStep.java@@ -103,7 +103,7 @@ public class SCPCommandStep extends CommandStep {@Overridepublic String getRunAs() {- return null;+ return "0:0";}@Overridediff --git a/server-core/src/main/java/io/onedev/server/buildspec/step/SSHCommandStep.java b/server-core/src/main/java/io/onedev/server/buildspec/step/SSHCommandStep.javaindex 99e677292e..37ffcf6cfe 100644--- a/server-core/src/main/java/io/onedev/server/buildspec/step/SSHCommandStep.java+++ b/server-core/src/main/java/io/onedev/server/buildspec/step/SSHCommandStep.java@@ -123,7 +123,7 @@ public class SSHCommandStep extends CommandStep {@Overridepublic String getRunAs() {- return null;+ return "0:0";}@Overridediff --git a/server-core/src/main/java/io/onedev/server/cache/ServerCacheProvisioner.java b/server-core/src/main/java/io/onedev/server/cache/ServerCacheProvisioner.javaindex 7190649633..4d8ace9498 100644--- a/server-core/src/main/java/io/onedev/server/cache/ServerCacheProvisioner.java+++ b/server-core/src/main/java/io/onedev/server/cache/ServerCacheProvisioner.java@@ -3,7 +3,6 @@ package io.onedev.server.cache;import java.io.File;import java.io.IOException;import java.io.InputStream;-import java.util.List;import javax.ws.rs.client.Client;import javax.ws.rs.client.ClientBuilder;@@ -18,6 +17,7 @@ import org.glassfish.jersey.client.ClientProperties;import org.jspecify.annotations.Nullable;import io.onedev.commons.utils.ExplicitException;+import io.onedev.commons.utils.TarUtils;import io.onedev.commons.utils.TaskLogger;import io.onedev.k8shelper.CacheAvailability;import io.onedev.k8shelper.CacheConfigFacade;@@ -32,28 +32,23 @@ import io.onedev.server.security.SecurityUtils;import io.onedev.server.service.AccessTokenService;import io.onedev.server.service.ProjectService;import io.onedev.server.service.RunCacheService;-import io.onedev.server.service.support.CacheQueryResult;public abstract class ServerCacheProvisioner extends CacheProvisioner {-+public ServerCacheProvisioner(File baseDir, TaskLogger logger) {super(baseDir, logger);}@Overrideprotected CacheAvailability downloadCache(String key, @Nullable String checksum,- String cachePathsString, List<File> cacheDirs) {- var cacheQueryResult = getCacheService().queryCache(getProjectId(), key, checksum);- return downloadCache(cacheQueryResult, cachePathsString, cacheDirs);- }-- private CacheAvailability downloadCache(@Nullable CacheQueryResult cacheQueryResult, String cachePathsString, List<File> cacheDirs) {- if (cacheQueryResult != null) {- var projectId = cacheQueryResult.getProjectId();- var cacheId = cacheQueryResult.getCacheId();+ String path, File cacheDir) {+ var cacheFindResult = getCacheService().findCache(getProjectId(), key, checksum, path);+ if (cacheFindResult != null) {+ var projectId = cacheFindResult.getProjectId();var activeServer = getProjectService().getActiveServer(projectId, true);if (activeServer.equals(getClusterService().getLocalServerAddress())) {- return getCacheService().downloadCache(cacheQueryResult, cachePathsString, is -> untar(cacheDirs, is));+ return getCacheService().downloadCache(cacheFindResult,+ is -> TarUtils.untar(is, cacheDir, false));} else {Client client = ClientBuilder.newClient();client.property(ClientProperties.REQUEST_ENTITY_PROCESSING, "CHUNKED");@@ -62,9 +57,9 @@ public abstract class ServerCacheProvisioner extends CacheProvisioner {var target = client.target(serverUrl).path("~api/cluster/cache").queryParam("projectId", projectId)- .queryParam("cacheId", cacheId)- .queryParam("exactMatch", cacheQueryResult.isExactMatch())- .queryParam("cachePathsString", cachePathsString);+ .queryParam("dirName", cacheFindResult.getDirName())+ .queryParam("pathIndex", cacheFindResult.getPathIndex())+ .queryParam("exactMatch", cacheFindResult.isExactMatch());Invocation.Builder builder = target.request();builder.header(HttpHeaders.AUTHORIZATION,KubernetesHelper.BEARER + " " + getClusterService().getCredential());@@ -72,8 +67,8 @@ public abstract class ServerCacheProvisioner extends CacheProvisioner {KubernetesHelper.checkStatus(response);try (var is = response.readEntity(InputStream.class)) {var cacheAvailability = CacheAvailability.values()[is.read()];- if (cacheAvailability != CacheAvailability.NOT_FOUND)- untar(cacheDirs, is);+ if (cacheAvailability != CacheAvailability.NOT_FOUND)+ TarUtils.untar(is, cacheDir, false);return cacheAvailability;} catch (IOException e) {throw new RuntimeException(e);@@ -89,11 +84,10 @@ public abstract class ServerCacheProvisioner extends CacheProvisioner {}@Override- protected boolean uploadCache(CacheConfigFacade cacheConfig, List<File> cacheDirs) {+ protected boolean uploadCache(CacheConfigFacade cacheConfig, String path, File cacheDir) {var key = cacheConfig.getKey();var checksum = cacheConfig.getChecksum();- var cachePathsString = cacheConfig.getPathsAsString();-+var projectId = getSessionService().call(() -> {Project uploadProject;if (cacheConfig.getUploadProjectPath() != null) {@@ -103,7 +97,7 @@ public abstract class ServerCacheProvisioner extends CacheProvisioner {throw new ExplicitException("Upload project not found: " + uploadProjectPath);} else {uploadProject = getProjectService().load(getProjectId());- }+ }var accessTokenValue = cacheConfig.getUploadAccessToken();if (canUploadTo(uploadProject)) {@@ -112,16 +106,16 @@ public abstract class ServerCacheProvisioner extends CacheProvisioner {var accessToken = getAccessTokenService().findByValue(accessTokenValue);if (accessToken != null && SecurityUtils.canUploadCache(accessToken.asSubject(), uploadProject))return uploadProject.getId();- }+ }return null;});-+if (projectId != null) {- Long cacheId = getCacheService().createCache(projectId, key, checksum);var activeServer = getProjectService().getActiveServer(projectId, true);if (activeServer.equals(getClusterService().getLocalServerAddress())) {- getCacheService().uploadCache(projectId, cacheId, cachePathsString, os -> tar(cacheDirs, os));+ getCacheService().uploadCache(projectId, key, checksum, path,+ os -> TarUtils.tar(cacheDir, os, false));} else {Client client = ClientBuilder.newClient();client.property(ClientProperties.REQUEST_ENTITY_PROCESSING, "CHUNKED");@@ -130,12 +124,13 @@ public abstract class ServerCacheProvisioner extends CacheProvisioner {var target = client.target(serverUrl).path("~api/cluster/cache").queryParam("projectId", projectId)- .queryParam("cacheId", cacheId)- .queryParam("cachePathsString", cachePathsString);+ .queryParam("key", key)+ .queryParam("checksum", checksum)+ .queryParam("path", path);Invocation.Builder builder = target.request();builder.header(HttpHeaders.AUTHORIZATION,KubernetesHelper.BEARER + " " + getClusterService().getCredential());- StreamingOutput output = os -> tar(cacheDirs, os);+ StreamingOutput output = os -> TarUtils.tar(cacheDir, os, false);try (Response response = builder.post(Entity.entity(output, MediaType.APPLICATION_OCTET_STREAM))) {KubernetesHelper.checkStatus(response);}@@ -153,19 +148,19 @@ public abstract class ServerCacheProvisioner extends CacheProvisioner {@Sessionalprotected abstract boolean canUploadTo(Project uploadProject);-+protected ClusterService getClusterService() {return OneDev.getInstance(ClusterService.class);}-+protected ProjectService getProjectService() {return OneDev.getInstance(ProjectService.class);}-+protected RunCacheService getCacheService() {return OneDev.getInstance(RunCacheService.class);}-+protected SessionService getSessionService() {return OneDev.getInstance(SessionService.class);}diff --git a/server-core/src/main/java/io/onedev/server/cluster/ClusterResource.java b/server-core/src/main/java/io/onedev/server/cluster/ClusterResource.javaindex 32b40a931e..e39e4c0e10 100644--- a/server-core/src/main/java/io/onedev/server/cluster/ClusterResource.java+++ b/server-core/src/main/java/io/onedev/server/cluster/ClusterResource.java@@ -59,7 +59,7 @@ import io.onedev.server.service.BuildService;import io.onedev.server.service.PackBlobService;import io.onedev.server.service.ProjectService;import io.onedev.server.service.RunCacheService;-import io.onedev.server.service.support.CacheQueryResult;+import io.onedev.server.service.support.CacheFindResult;import io.onedev.server.util.IOUtils;import io.onedev.server.util.concurrent.WorkExecutionService;import io.onedev.server.util.patternset.PatternSet;@@ -232,14 +232,14 @@ public class ClusterResource {@Produces(MediaType.APPLICATION_OCTET_STREAM)@GETpublic Response downloadCache(- @QueryParam("projectId") Long projectId,- @QueryParam("cacheId") Long cacheId,- @QueryParam("exactMatch") boolean exactMatch,- @QueryParam("cachePathsString") String cachePathsString) {+ @QueryParam("projectId") Long projectId,+ @QueryParam("dirName") String dirName,+ @QueryParam("pathIndex") int pathIndex,+ @QueryParam("exactMatch") boolean exactMatch) {if (!SecurityUtils.isSystem())throw new UnauthorizedException("This api can only be accessed via cluster credential");- var cacheQueryResult = new CacheQueryResult(projectId, cacheId, exactMatch);- StreamingOutput out = os -> cacheService.downloadCache(cacheQueryResult, cachePathsString, os);+ var cacheFindResult = new CacheFindResult(projectId, dirName, pathIndex, exactMatch);+ StreamingOutput out = os -> cacheService.downloadCache(cacheFindResult, os);return ok(out).build();}@@ -461,12 +461,13 @@ public class ClusterResource {@POSTpublic Response uploadCache(@QueryParam("projectId") Long projectId,- @QueryParam("cacheId") Long cacheId,- @QueryParam("cachePathsString") String cachePathsString,+ @QueryParam("key") String key,+ @QueryParam("checksum") String checksum,+ @QueryParam("path") String path,InputStream cacheStream) {if (!SecurityUtils.isSystem())throw new UnauthorizedException("This api can only be accessed via cluster credential");- cacheService.uploadCache(projectId, cacheId, cachePathsString, cacheStream);+ cacheService.uploadCache(projectId, key, checksum, path, cacheStream);return ok().build();}diff --git a/server-core/src/main/java/io/onedev/server/data/migration/DataMigrator.java b/server-core/src/main/java/io/onedev/server/data/migration/DataMigrator.javaindex ae5776e1c3..bd3fdb6902 100644--- a/server-core/src/main/java/io/onedev/server/data/migration/DataMigrator.java+++ b/server-core/src/main/java/io/onedev/server/data/migration/DataMigrator.java@@ -8628,6 +8628,8 @@ public class DataMigrator {tokenElement.setName("token");}dom.writeToFile(file, false);+ } else if (file.getName().startsWith("RunCaches.xml")) {+ FileUtils.deleteFile(file);}}}diff --git a/server-core/src/main/java/io/onedev/server/git/CommandUtils.java b/server-core/src/main/java/io/onedev/server/git/CommandUtils.javaindex 6f6fa7aabc..3abf89daaa 100644--- a/server-core/src/main/java/io/onedev/server/git/CommandUtils.java+++ b/server-core/src/main/java/io/onedev/server/git/CommandUtils.java@@ -48,7 +48,7 @@ public class CommandUtils {SecretMasker.push(text -> StringUtils.replace(text, clusterService.getCredential(), "******"));try {Commandline git = newGit();- git.environments().put("HOME", homeDir.getAbsolutePath());+ git.envs().put("HOME", homeDir.getAbsolutePath());String extraHeader = KubernetesHelper.AUTHORIZATION + ": "+ KubernetesHelper.BEARER + " " + clusterService.getCredential();git.addArgs("config", "--global", "http.extraHeader", extraHeader);diff --git a/server-core/src/main/java/io/onedev/server/git/command/AdvertiseReceiveRefsCommand.java b/server-core/src/main/java/io/onedev/server/git/command/AdvertiseReceiveRefsCommand.javaindex 95c42a17bc..0ed5c8a4e4 100644--- a/server-core/src/main/java/io/onedev/server/git/command/AdvertiseReceiveRefsCommand.java+++ b/server-core/src/main/java/io/onedev/server/git/command/AdvertiseReceiveRefsCommand.java@@ -40,7 +40,7 @@ public class AdvertiseReceiveRefsCommand {Commandline git = newGit().workingDir(workingDir);if (protocol != null)- git.environments().put("GIT_PROTOCOL", protocol);+ git.envs().put("GIT_PROTOCOL", protocol);git.addArgs("receive-pack", "--stateless-rpc", "--advertise-refs", ".");git.execute(output, new LineConsumer() {diff --git a/server-core/src/main/java/io/onedev/server/git/command/AdvertiseUploadRefsCommand.java b/server-core/src/main/java/io/onedev/server/git/command/AdvertiseUploadRefsCommand.javaindex a1c3f4a952..b18e223eb9 100644--- a/server-core/src/main/java/io/onedev/server/git/command/AdvertiseUploadRefsCommand.java+++ b/server-core/src/main/java/io/onedev/server/git/command/AdvertiseUploadRefsCommand.java@@ -38,7 +38,7 @@ public class AdvertiseUploadRefsCommand {Commandline git = newGit().workingDir(workingDir);if (protocol != null)- git.environments().put("GIT_PROTOCOL", protocol);+ git.envs().put("GIT_PROTOCOL", protocol);git.addArgs("upload-pack", "--stateless-rpc", "--advertise-refs", ".");git.execute(output, new LineConsumer() {diff --git a/server-core/src/main/java/io/onedev/server/git/command/CloneCommand.java b/server-core/src/main/java/io/onedev/server/git/command/CloneCommand.javaindex 252256ec27..9bdf1ee6df 100644--- a/server-core/src/main/java/io/onedev/server/git/command/CloneCommand.java+++ b/server-core/src/main/java/io/onedev/server/git/command/CloneCommand.java@@ -82,7 +82,7 @@ public class CloneCommand {git.addArgs("-b", branch);if (noLfs)- git.environments().put("GIT_LFS_SKIP_SMUDGE", "1");+ git.envs().put("GIT_LFS_SKIP_SMUDGE", "1");git.addArgs(remotUrl);git.addArgs(".");diff --git a/server-core/src/main/java/io/onedev/server/git/command/GetRawCommitCommand.java b/server-core/src/main/java/io/onedev/server/git/command/GetRawCommitCommand.javaindex 60a804ed9a..c47364b49f 100644--- a/server-core/src/main/java/io/onedev/server/git/command/GetRawCommitCommand.java+++ b/server-core/src/main/java/io/onedev/server/git/command/GetRawCommitCommand.java@@ -33,7 +33,7 @@ public class GetRawCommitCommand {public byte[] run() {Commandline git = newGit().workingDir(workingDir);- git.environments().putAll(envs);+ git.envs().putAll(envs);git.addArgs("cat-file", "commit", revision);diff --git a/server-core/src/main/java/io/onedev/server/git/command/GetRawTagCommand.java b/server-core/src/main/java/io/onedev/server/git/command/GetRawTagCommand.javaindex 5f31eb88c4..ebf3ae9b57 100644--- a/server-core/src/main/java/io/onedev/server/git/command/GetRawTagCommand.java+++ b/server-core/src/main/java/io/onedev/server/git/command/GetRawTagCommand.java@@ -38,7 +38,7 @@ public class GetRawTagCommand {@Nullablepublic byte[] run() {Commandline git = newGit().workingDir(workingDir);- git.environments().putAll(envs);+ git.envs().putAll(envs);git.addArgs("cat-file", "tag", tag);diff --git a/server-core/src/main/java/io/onedev/server/git/command/IsAncestorCommand.java b/server-core/src/main/java/io/onedev/server/git/command/IsAncestorCommand.javaindex 004f0b5096..dd02b6c1bc 100644--- a/server-core/src/main/java/io/onedev/server/git/command/IsAncestorCommand.java+++ b/server-core/src/main/java/io/onedev/server/git/command/IsAncestorCommand.java@@ -37,7 +37,7 @@ public class IsAncestorCommand {public boolean run() {Commandline git = newGit().workingDir(workingDir);- git.environments().putAll(envs);+ git.envs().putAll(envs);git.addArgs("merge-base", "--is-ancestor", ancestor, descendant);diff --git a/server-core/src/main/java/io/onedev/server/git/command/ListChangedFilesCommand.java b/server-core/src/main/java/io/onedev/server/git/command/ListChangedFilesCommand.javaindex e79f7eb706..4251b46695 100644--- a/server-core/src/main/java/io/onedev/server/git/command/ListChangedFilesCommand.java+++ b/server-core/src/main/java/io/onedev/server/git/command/ListChangedFilesCommand.java@@ -42,7 +42,7 @@ public class ListChangedFilesCommand {final Set<String> changedFiles = new HashSet<String>();Commandline git = newGit().workingDir(workingDir);- git.environments().putAll(envs);+ git.envs().putAll(envs);if (fromRev.equals(ObjectId.zeroId().name()))git.addArgs("ls-tree", "--name-only", toRev);diff --git a/server-core/src/main/java/io/onedev/server/git/command/LogCommand.java b/server-core/src/main/java/io/onedev/server/git/command/LogCommand.javaindex ac9abc663b..e308392e86 100644--- a/server-core/src/main/java/io/onedev/server/git/command/LogCommand.java+++ b/server-core/src/main/java/io/onedev/server/git/command/LogCommand.java@@ -84,7 +84,7 @@ public abstract class LogCommand {public void run() {Commandline git = newGit().workingDir(workingDir);- git.environments().putAll(envs);+ git.envs().putAll(envs);String format = "hash:%H %n";diff --git a/server-core/src/main/java/io/onedev/server/git/command/ReceivePackCommand.java b/server-core/src/main/java/io/onedev/server/git/command/ReceivePackCommand.javaindex d47424199b..73ed72ee15 100644--- a/server-core/src/main/java/io/onedev/server/git/command/ReceivePackCommand.java+++ b/server-core/src/main/java/io/onedev/server/git/command/ReceivePackCommand.java@@ -52,10 +52,10 @@ public class ReceivePackCommand {public ExecutionResult run() {Commandline git = newGit().workingDir(workingDir);- git.environments().putAll(envs);+ git.envs().putAll(envs);if (protocol != null)- git.environments().put("GIT_PROTOCOL", protocol);+ git.envs().put("GIT_PROTOCOL", protocol);git.addArgs("receive-pack");if (statelessRpc)diff --git a/server-core/src/main/java/io/onedev/server/git/command/UploadPackCommand.java b/server-core/src/main/java/io/onedev/server/git/command/UploadPackCommand.javaindex 1649d325b1..a9e7f68cf2 100644--- a/server-core/src/main/java/io/onedev/server/git/command/UploadPackCommand.java+++ b/server-core/src/main/java/io/onedev/server/git/command/UploadPackCommand.java@@ -52,10 +52,10 @@ public class UploadPackCommand {public ExecutionResult run() {Commandline git = newGit().workingDir(workingDir);- git.environments().putAll(envs);+ git.envs().putAll(envs);if (protocol != null)- git.environments().put("GIT_PROTOCOL", protocol);+ git.envs().put("GIT_PROTOCOL", protocol);git.addArgs("upload-pack");if (statelessRpc)diff --git a/server-core/src/main/java/io/onedev/server/model/Project.java b/server-core/src/main/java/io/onedev/server/model/Project.javaindex c7af24776f..bfa209fdc0 100644--- a/server-core/src/main/java/io/onedev/server/model/Project.java+++ b/server-core/src/main/java/io/onedev/server/model/Project.java@@ -277,9 +277,6 @@ public class Project extends AbstractEntity implements LabelSupport<ProjectLabel@OneToMany(mappedBy="project")private Collection<Build> builds = new ArrayList<>();- @OneToMany(mappedBy="project", cascade=CascadeType.REMOVE)- private Collection<RunCache> jobCaches = new ArrayList<>();-@OneToMany(mappedBy= "project")private Collection<PackBlob> packBlobs = new ArrayList<>();@@ -1332,14 +1329,6 @@ public class Project extends AbstractEntity implements LabelSupport<ProjectLabelthis.builds = builds;}- public Collection<RunCache> getJobCaches() {- return jobCaches;- }-- public void setJobCaches(Collection<RunCache> jobCaches) {- this.jobCaches = jobCaches;- }-public Collection<PackBlob> getPackBlobs() {return packBlobs;}diff --git a/server-core/src/main/java/io/onedev/server/model/RunCache.java b/server-core/src/main/java/io/onedev/server/model/RunCache.javadeleted file mode 100644index af5d44e28a..0000000000--- a/server-core/src/main/java/io/onedev/server/model/RunCache.java+++ /dev/null@@ -1,88 +0,0 @@-package io.onedev.server.model;--import static io.onedev.server.model.RunCache.PROP_ACCESS_DATE;-import static io.onedev.server.model.RunCache.PROP_CHECKSUM;-import static io.onedev.server.model.RunCache.PROP_KEY;--import java.util.Date;--import javax.persistence.Column;-import javax.persistence.Entity;-import javax.persistence.FetchType;-import javax.persistence.Index;-import javax.persistence.JoinColumn;-import javax.persistence.ManyToOne;-import javax.persistence.Table;-import javax.persistence.UniqueConstraint;--import org.jspecify.annotations.Nullable;--/**- * @author robin- *- */-@Entity-@Table(- indexes={@Index(columnList="o_project_id"), @Index(columnList=PROP_KEY), @Index(columnList = PROP_ACCESS_DATE)},- uniqueConstraints={@UniqueConstraint(columnNames={"o_project_id", PROP_KEY, PROP_CHECKSUM})})-public class RunCache extends AbstractEntity {-- private static final long serialVersionUID = 1L;-- public static final String PROP_PROJECT = "project";-- public static final String PROP_KEY = "key";-- public static final String PROP_CHECKSUM = "checksum";-- public static final String PROP_ACCESS_DATE = "accessDate";-- @ManyToOne(fetch=FetchType.LAZY)- @JoinColumn(nullable=false)- private Project project;-- @Column(nullable=false)- private String key;-- private String checksum;-- private Date accessDate;-- public Project getProject() {- return project;- }-- public void setProject(Project project) {- this.project = project;- }-- public String getKey() {- return key;- }-- public void setKey(String key) {- this.key = key;- }-- @Nullable- public String getChecksum() {- return checksum;- }-- public void setChecksum(@Nullable String checksum) {- this.checksum = checksum;- }-- public Date getAccessDate() {- return accessDate;- }-- public void setAccessDate(Date accessDate) {- this.accessDate = accessDate;- }-- public static String getLockName(Long projectId, Long cacheId) {- return "job-cache:" + projectId + ":" + cacheId;- }--}diff --git a/server-core/src/main/java/io/onedev/server/model/User.java b/server-core/src/main/java/io/onedev/server/model/User.javaindex 4a4635c44a..9d6ef2ba44 100644--- a/server-core/src/main/java/io/onedev/server/model/User.java+++ b/server-core/src/main/java/io/onedev/server/model/User.java@@ -8,6 +8,10 @@ import static io.onedev.server.security.SecurityUtils.asPrincipals;import static io.onedev.server.security.SecurityUtils.asUserPrincipal;import static io.onedev.server.security.SecurityUtils.isAdministrator;+import java.io.UnsupportedEncodingException;+import java.net.URLDecoder;+import java.net.URLEncoder;+import java.nio.charset.StandardCharsets;import java.util.ArrayList;import java.util.Collection;import java.util.Comparator;@@ -1312,6 +1316,22 @@ public class User extends AbstractEntity implements AuthenticationInfo {return entitledAis;}+ public static String encodeWorkspaceDataKey(String dataKey) {+ try {+ return URLEncoder.encode(dataKey, StandardCharsets.UTF_8.name());+ } catch (UnsupportedEncodingException e) {+ throw new RuntimeException(e);+ }+ }++ public static String decodeWorkspaceDataKey(String encodedDataKey) {+ try {+ return URLDecoder.decode(encodedDataKey, StandardCharsets.UTF_8.name());+ } catch (UnsupportedEncodingException e) {+ throw new RuntimeException(e);+ }+ }+public static String getWorkspaceDataLockName(Long userId, String dataKey) {return "workspace-data:" + userId + ":" + dataKey;}diff --git a/server-core/src/main/java/io/onedev/server/model/support/administration/workspaceprovisioner/WorkspaceProvisioner.java b/server-core/src/main/java/io/onedev/server/model/support/administration/workspaceprovisioner/WorkspaceProvisioner.javaindex 2720806683..8470bb6fa8 100644--- a/server-core/src/main/java/io/onedev/server/model/support/administration/workspaceprovisioner/WorkspaceProvisioner.java+++ b/server-core/src/main/java/io/onedev/server/model/support/administration/workspaceprovisioner/WorkspaceProvisioner.java@@ -5,7 +5,6 @@ import static io.onedev.k8shelper.KubernetesHelper.initRepository;import static io.onedev.k8shelper.KubernetesHelper.installGitLfs;import static io.onedev.k8shelper.KubernetesHelper.setupGitCerts;import static io.onedev.k8shelper.KubernetesHelper.setupOriginUrl;-import static io.onedev.k8shelper.KubernetesHelper.setupSafeDirectory;import static java.util.stream.Collectors.toMap;import java.io.File;@@ -150,27 +149,21 @@ public abstract class WorkspaceProvisioner implements Serializable {var remoteAccessArgs = new ArrayList<String>();var trustCertsFile = new File(workspaceDir, "trust-certs.pem");remoteAccessArgs.addAll(setupGitCerts(git, Bootstrap.getTrustCertsDir(), trustCertsFile,- runtimeWorkspaceDirPath + "/" + trustCertsFile.getName(),- infoLogger, warningLogger));+ runtimeWorkspaceDirPath + "/" + trustCertsFile.getName(), infoLogger, warningLogger));remoteAccessArgs.addAll(cloneInfo.setupGitAuth(git, workspaceDir, runtimeWorkspaceDirPath,infoLogger, warningLogger));- if (!Bootstrap.isInDocker()) {- setupSafeDirectory(git, runtimeWorkspaceDirPath + "/work",- null, infoLogger, warningLogger);- }-- git.arguments("config", "user.name", context.getUserName());+ git.args("-c", "safe.directory=*", "config", "user.name", context.getUserName());git.execute(infoLogger, warningLogger).checkReturnCode();- git.arguments("config", "pull.rebase", "false");+ git.args("-c", "safe.directory=*", "config", "pull.rebase", "false");git.execute(infoLogger, warningLogger).checkReturnCode();- git.arguments("config", "user.email", context.getUserEmail());+ git.args("-c", "safe.directory=*", "config", "user.email", context.getUserEmail());git.execute(infoLogger, warningLogger).checkReturnCode();var noCommits = new AtomicBoolean(false);- git.arguments("status");+ git.args("-c", "safe.directory=*", "status");git.execute(new LineConsumer() {@Override@@ -187,7 +180,7 @@ public abstract class WorkspaceProvisioner implements Serializable {if (noCommits.get()) {if (context.getBranch() != null) {logger.log("Cloning repository...");- git.arguments(remoteAccessArgs);+ git.args(remoteAccessArgs);cloneRepository(git, context.getProjectGitDir(), cloneInfo.getCloneUrl(),GitUtils.branch2ref(context.getBranch()), null,context.getSpec().isRetrieveLfs(), false, 0,@@ -195,7 +188,7 @@ public abstract class WorkspaceProvisioner implements Serializable {} else { // no commits at server sidesetupOriginUrl(git, cloneInfo.getCloneUrl(), infoLogger, warningLogger);- git.arguments("config", "push.autoSetupRemote", "true");+ git.args("-c", "safe.directory=*", "config", "push.autoSetupRemote", "true");git.execute(infoLogger, warningLogger).checkReturnCode();if (context.getSpec().isRetrieveLfs())diff --git a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/UserData.java b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/UserData.javaindex 79bcb04a2a..5da5248b68 100644--- a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/UserData.java+++ b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/UserData.java@@ -9,10 +9,9 @@ import javax.validation.constraints.NotEmpty;import javax.validation.constraints.Size;import io.onedev.commons.codeassist.InputSuggestion;-import io.onedev.server.annotation.Path;-import io.onedev.server.annotation.PathSegment;import io.onedev.server.annotation.Editable;import io.onedev.server.annotation.Interpolative;+import io.onedev.server.annotation.Path;import io.onedev.server.web.util.SuggestionUtils;@Editable@@ -29,7 +28,6 @@ public class UserData implements Serializable {@Editable(order=100, name="Data Key", description = """Specify a key to identify the user data. Data with same key will be shared across workspaceseven if project is different""")- @PathSegment@Interpolative(variableSuggester="suggestVariables")@NotEmptypublic String getKey() {diff --git a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/WorkspaceSpec.java b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/WorkspaceSpec.javaindex 6f5d5bb0d3..e569f3090e 100644--- a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/WorkspaceSpec.java+++ b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/WorkspaceSpec.java@@ -65,7 +65,7 @@ public class WorkspaceSpec implements Serializable, Validatable {private boolean retrieveLfs;- private String runAs;+ private String runAs = "0:0";private List<Integer> containerPorts = new ArrayList<>();@@ -213,14 +213,11 @@ public class WorkspaceSpec implements Serializable, Validatable {this.retrieveLfs = retrieveLfs;}- @Editable(order = 1400, name = "Run As", group = "More Settings", placeholder = "root", description = """- Optionally specify uid:gid to run container as. \- <b class='text-warning'>Note:</b> This setting should be left empty if container runtime is rootless or \- using user namespace remapping- """)+ @Editable(order = 1400, name = "Run As", group = "More Settings", description = "Specify uid:gid to run container as")@Interpolative(variableSuggester="suggestVariables")@DependsOn(property = "runInContainer")@Pattern(regexp = "(\\d+:\\d+)?", message = "Should be specified in form of <uid>:<gid>")+ @NotEmptypublic String getRunAs() {return runAs;}diff --git a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/shell/CustomLinuxShell.java b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/shell/CustomLinuxShell.javaindex 0d13612eaf..9cf7f3de18 100644--- a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/shell/CustomLinuxShell.java+++ b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/shell/CustomLinuxShell.java@@ -26,9 +26,7 @@ public class CustomLinuxShell extends WorkspaceShell {this.shell = shell;}- @Editable(order=200, description="""- Optionally specify shell commands to run to set up the workspace. These commands will- run from working directory holding cloned repository files""")+ @Editable(order=200, descriptionProvider="getSetupCommandDescription")@Interpolative@Code(language=Code.SHELL, variableProvider="suggestVariables")@Overridediff --git a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/shell/DefaultShell.java b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/shell/DefaultShell.javaindex 4404cf27d7..b023f789b1 100644--- a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/shell/DefaultShell.java+++ b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/shell/DefaultShell.java@@ -11,10 +11,7 @@ public class DefaultShell extends WorkspaceShell {private static final long serialVersionUID = 1L;- @Editable(order=100, description="""- Optionally specify sh commands (on Linux/Unix) or batch commands (on Windows)- to run to set up the workspace. These commands will run from working directory- holding cloned repository files""")+ @Editable(order=100, descriptionProvider="getSetupCommandDescription")@Interpolative@Code(language=Code.SHELL, variableProvider="suggestVariables")@Overridediff --git a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/shell/PowerShell.java b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/shell/PowerShell.javaindex 2ea92f9534..6b8c5e69ce 100644--- a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/shell/PowerShell.java+++ b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/shell/PowerShell.java@@ -26,9 +26,7 @@ public class PowerShell extends WorkspaceShell {this.powershell = powershell;}- @Editable(order=100, description="""- Optionally specify PowerShell commands to run to set up the workspace. These commands- will run from working directory holding cloned repository files""")+ @Editable(order=100, descriptionProvider="getSetupCommandDescription")@Code(language=Code.POWER_SHELL, variableProvider="suggestVariables")@Interpolative@Overridediff --git a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/shell/WorkspaceShell.java b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/shell/WorkspaceShell.javaindex 74adff4c5a..14e46c2cc0 100644--- a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/shell/WorkspaceShell.java+++ b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/shell/WorkspaceShell.java@@ -1,5 +1,7 @@package io.onedev.server.model.support.workspace.spec.shell;+import static io.onedev.server.web.translation.Translation._T;+import java.io.Serializable;import java.util.List;@@ -29,4 +31,11 @@ public abstract class WorkspaceShell implements Serializable {return SuggestionUtils.suggestWorkspaceVariables(matchWith);}+ protected static String getSetupCommandDescription() {+ return _T("""+ Optionally specify shell commands to run to set up the workspace. These commands will+ run from working directory holding cloned repository files. It runs after cache and+ user data restored and config files generated""");+ }+}diff --git a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/OpenCodeInContainer.java b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/OpenCodeInContainer.javaindex 54768904ac..42b0fa628f 100644--- a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/OpenCodeInContainer.java+++ b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/OpenCodeInContainer.java@@ -3,9 +3,7 @@ package io.onedev.server.model.support.workspace.spec.template;import java.util.List;import io.onedev.commons.codeassist.InputSuggestion;-import io.onedev.k8shelper.UploadStrategy;import io.onedev.server.annotation.Editable;-import io.onedev.server.model.support.workspace.spec.CacheConfig;import io.onedev.server.model.support.workspace.spec.ShortcutConfig;import io.onedev.server.model.support.workspace.spec.UserData;import io.onedev.server.model.support.workspace.spec.WorkspaceSpec;@@ -35,13 +33,6 @@ public class OpenCodeInContainer extends WorkspaceSpecTemplate {shortcutConfig.setCommand("opencode");workspaceSpec.getShortcutConfigs().add(shortcutConfig);- var cacheConfig = new CacheConfig();- cacheConfig.setKey("opencode");- cacheConfig.getPaths().add("/home/opencode/.cache");- cacheConfig.getPaths().add("/home/opencode/.npm");- cacheConfig.setUploadStrategy(UploadStrategy.UPLOAD_IF_CHANGED);- workspaceSpec.getCacheConfigs().add(cacheConfig);-var userData = new UserData();userData.setKey("opencode");userData.getPaths().add("/home/opencode/.profile");diff --git a/server-core/src/main/java/io/onedev/server/service/RunCacheService.java b/server-core/src/main/java/io/onedev/server/service/RunCacheService.javaindex 53114d88b6..c79a0b98ef 100644--- a/server-core/src/main/java/io/onedev/server/service/RunCacheService.java+++ b/server-core/src/main/java/io/onedev/server/service/RunCacheService.java@@ -2,32 +2,31 @@ package io.onedev.server.service;import java.io.InputStream;import java.io.OutputStream;+import java.util.List;import java.util.function.Consumer;import org.jspecify.annotations.Nullable;import io.onedev.k8shelper.CacheAvailability;-import io.onedev.server.model.RunCache;-import io.onedev.server.service.support.CacheQueryResult;+import io.onedev.server.service.support.CacheFindResult;+import io.onedev.server.service.support.RunCacheInfo;-public interface RunCacheService extends EntityService<RunCache> {+public interface RunCacheService {@Nullable- CacheQueryResult queryCache(Long projectId, String key, @Nullable String checksum);-- @Nullable Long createCache(Long projectId, String key, @Nullable String checksum);-- CacheAvailability downloadCache(CacheQueryResult cacheQueryResult, String cachePathsString,- Consumer<InputStream> cacheStreamHandler);-- void downloadCache(CacheQueryResult cacheQueryResult, String cachePathsString, OutputStream cacheStream);-- void uploadCache(Long projectId, Long cacheId, String cachePathsString, InputStream cacheStream);-- void uploadCache(Long projectId, Long cacheId, String cachePathsString,+ CacheFindResult findCache(Long projectId, String key, @Nullable String checksum, String path);++ CacheAvailability downloadCache(CacheFindResult cacheFindResult, Consumer<InputStream> cacheStreamHandler);++ void downloadCache(CacheFindResult cacheFindResult, OutputStream cacheStream);++ void uploadCache(Long projectId, String key, @Nullable String checksum, String path, InputStream cacheStream);++ void uploadCache(Long projectId, String key, @Nullable String checksum, String path,Consumer<OutputStream> cacheStreamHandler);-- @Nullable- Long getCacheSize(Long projectId, Long cacheId);-++ List<RunCacheInfo> listCaches(Long projectId);++ void deleteCache(Long projectId, String key, @Nullable String checksum);+}diff --git a/server-core/src/main/java/io/onedev/server/service/UserService.java b/server-core/src/main/java/io/onedev/server/service/UserService.javaindex 9138c5760a..4d8e254946 100644--- a/server-core/src/main/java/io/onedev/server/service/UserService.java+++ b/server-core/src/main/java/io/onedev/server/service/UserService.java@@ -113,5 +113,5 @@ public interface UserService extends EntityService<User> {File getUserDir(Long userId);UserCache cloneCache();-+}diff --git a/server-core/src/main/java/io/onedev/server/service/impl/DefaultRunCacheService.java b/server-core/src/main/java/io/onedev/server/service/impl/DefaultRunCacheService.javaindex 9afc0d0800..640d78db99 100644--- a/server-core/src/main/java/io/onedev/server/service/impl/DefaultRunCacheService.java+++ b/server-core/src/main/java/io/onedev/server/service/impl/DefaultRunCacheService.java@@ -2,39 +2,28 @@ package io.onedev.server.service.impl;import static io.onedev.commons.utils.LockUtils.read;import static io.onedev.commons.utils.LockUtils.write;-import static io.onedev.server.model.RunCache.PROP_ACCESS_DATE;-import static io.onedev.server.model.RunCache.PROP_CHECKSUM;-import static io.onedev.server.model.RunCache.PROP_KEY;-import static io.onedev.server.model.RunCache.PROP_PROJECT;import static io.onedev.server.util.IOUtils.BUFFER_SIZE;import static java.nio.charset.StandardCharsets.UTF_8;-import static java.util.Comparator.comparing;-import java.io.BufferedOutputStream;-import java.io.ByteArrayInputStream;import java.io.File;import java.io.FileInputStream;-import java.io.FileNotFoundException;import java.io.FileOutputStream;-import java.io.FilterOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.ObjectStreamException;import java.io.OutputStream;-import java.io.SequenceInputStream;import java.io.Serializable;+import java.net.URLDecoder;+import java.net.URLEncoder;+import java.util.ArrayList;+import java.util.Comparator;import java.util.Date;import java.util.List;-import java.util.Objects;import java.util.function.Consumer;import javax.inject.Inject;import javax.inject.Singleton;-import org.apache.commons.lang3.tuple.ImmutablePair;-import org.apache.commons.lang3.tuple.Pair;-import org.hibernate.criterion.Restrictions;-import org.hibernate.exception.ConstraintViolationException;import org.joda.time.DateTime;import org.jspecify.annotations.Nullable;import org.quartz.CronScheduleBuilder;@@ -43,20 +32,17 @@ import org.slf4j.Logger;import org.slf4j.LoggerFactory;import io.onedev.commons.loader.ManagedSerializedForm;-import io.onedev.commons.utils.ExceptionUtils;import io.onedev.commons.utils.FileUtils;import io.onedev.k8shelper.CacheAvailability;-import io.onedev.k8shelper.CacheProvisioner;import io.onedev.server.event.Listen;import io.onedev.server.event.system.SystemStarted;import io.onedev.server.event.system.SystemStopping;-import io.onedev.server.model.Project;-import io.onedev.server.model.RunCache;-import io.onedev.server.persistence.TransactionService;-import io.onedev.server.persistence.annotation.Transactional;+import io.onedev.server.persistence.annotation.Sessional;import io.onedev.server.service.ProjectService;import io.onedev.server.service.RunCacheService;-import io.onedev.server.service.support.CacheQueryResult;+import io.onedev.server.service.support.CacheFindResult;+import io.onedev.server.service.support.RunCacheInfo;+import io.onedev.server.util.PathIndexUtils;import io.onedev.server.taskschedule.SchedulableTask;import io.onedev.server.taskschedule.TaskScheduler;import io.onedev.server.util.IOUtils;@@ -65,302 +51,269 @@ import io.onedev.server.util.concurrent.BatchWorker;import io.onedev.server.util.concurrent.Prioritized;@Singleton-public class DefaultRunCacheService extends BaseEntityService<RunCache>- implements RunCacheService, Serializable, SchedulableTask {-- private static final int CACHE_VERSION = 4;+public class DefaultRunCacheService implements RunCacheService, Serializable, SchedulableTask {++ private static final long serialVersionUID = 1L;private static final int HOUSE_KEEPING_PRIORITY = 50;-++ private static final String ACCESS_FILE = "access";+private static final Logger logger = LoggerFactory.getLogger(DefaultRunCacheService.class);@Injectprivate ProjectService projectService;- @Inject- private TransactionService transactionService;-@Injectprivate TaskScheduler taskScheduler;@Injectprivate BatchWorkExecutionService batchWorkExecutionService;-+private volatile String taskId;- @Nullable- private RunCache find(Project project, String key, @Nullable String checksum) {- var criteria = newCriteria();- criteria.add(Restrictions.eq(PROP_PROJECT, project));- criteria.add(Restrictions.eq(PROP_KEY, key));- if (checksum != null)- criteria.add(Restrictions.eq(PROP_CHECKSUM, checksum));- else- criteria.add(Restrictions.isNull(PROP_CHECKSUM));- return find(criteria);- }-- private String readString(File file) {+ private String encodePathSegment(String value) {try {- return FileUtils.readFileToString(file, UTF_8);- } catch (IOException e) {+ return URLEncoder.encode(value, UTF_8.name());+ } catch (java.io.UnsupportedEncodingException e) {throw new RuntimeException(e);}}-- private void writeString(File file, String content) {++ private String decodePathSegment(String value) {try {- FileUtils.writeStringToFile(file, content, UTF_8);- } catch (IOException e) {+ return URLDecoder.decode(value, UTF_8.name());+ } catch (java.io.UnsupportedEncodingException e) {throw new RuntimeException(e);}}- private void writeStream(OutputStream os, int value) {- try {- os.write(value);- } catch (IOException e) {- throw new RuntimeException(e);- }+ private String getDirName(String key, @Nullable String checksum) {+ if (checksum != null)+ return encodePathSegment(key) + ":" + encodePathSegment(checksum);+ else+ return encodePathSegment(key);}-- @Transactional- @Override- public CacheQueryResult queryCache(Long projectId, String key, @Nullable String checksum) {- var project = projectService.load(projectId);- do {- var cache = project.getJobCaches().stream()- .filter(it -> it.getKey().equals(key) && Objects.equals(it.getChecksum(), checksum))- .max(comparing(RunCache::getAccessDate));- if (cache.isPresent()) {- cache.get().setAccessDate(new Date());- return new CacheQueryResult(project.getId(), cache.get().getId(), true);- } else {- cache = project.getJobCaches().stream()- .filter(it -> it.getKey().equals(key))- .max(comparing(RunCache::getAccessDate));- if (cache.isPresent()) {- cache.get().setAccessDate(new Date());- return new CacheQueryResult(project.getId(), cache.get().getId(), false);- }- }- project = project.getParent();- } while (project != null);- return null;+ private String getKeyFromDirName(String dirName) {+ int colon = dirName.indexOf(':');+ return decodePathSegment(colon >= 0 ? dirName.substring(0, colon) : dirName);}-- @Override- public CacheAvailability downloadCache(CacheQueryResult cacheQueryResult, String cachePathsString,- Consumer<InputStream> cacheStreamHandler) {- var projectId = cacheQueryResult.getProjectId();- var cacheId = cacheQueryResult.getCacheId();- return read(RunCache.getLockName(projectId, cacheId), () -> {- var is = openCacheInputStream(projectId, cacheId, cachePathsString);- if (is != null) try (is) {- cacheStreamHandler.accept(is);- return cacheQueryResult.getCacheAvailability();- } else {- return CacheAvailability.NOT_FOUND;- }++ @Nullable+ private String getChecksumFromDirName(String dirName) {+ int colon = dirName.indexOf(':');+ return colon >= 0 ? decodePathSegment(dirName.substring(colon + 1)) : null;+ }++ private String getEncodedKeyFromDirName(String dirName) {+ int colon = dirName.indexOf(':');+ return colon >= 0 ? dirName.substring(0, colon) : dirName;+ }++ private String getLockName(Long projectId, String dirName) {+ return "run-cache:" + projectId + ":" + dirName;+ }++ private File getCacheDir(Long projectId, String dirName) {+ return new File(projectService.getCacheDir(projectId), dirName);+ }++ private boolean isCacheDirValid(File cacheDir) {+ return cacheDir.isDirectory() && PathIndexUtils.exists(cacheDir);+ }++ private String getAccessLockName(File cacheDir) {+ return "job-cache-last-access:" + cacheDir.getAbsolutePath();+ }++ private void updateLastAccessTime(File cacheDir) {+ write(getAccessLockName(cacheDir), () -> {+ FileUtils.touchFile(new File(cacheDir, ACCESS_FILE));});}- @Override- public void downloadCache(CacheQueryResult cacheQueryResult, String cachePathsString, OutputStream cacheStream) {- var projectId = cacheQueryResult.getProjectId();- var cacheId = cacheQueryResult.getCacheId();- read(RunCache.getLockName(projectId, cacheId), () -> {- var is = openCacheInputStream(projectId, cacheId, cachePathsString);- if (is != null) {- try (is) {- writeStream(cacheStream, cacheQueryResult.getCacheAvailability().ordinal());- IOUtils.copy(is, cacheStream, BUFFER_SIZE);- } catch (IOException e) {- throw new RuntimeException(e);- }- } else {- writeStream(cacheStream, CacheAvailability.NOT_FOUND.ordinal());- }+ private long readLastAccessTime(File cacheDir) {+ return read(getAccessLockName(cacheDir), () -> {+ var accessFile = new File(cacheDir, ACCESS_FILE);+ if (!accessFile.exists())+ return 0L;+ return accessFile.lastModified();});}- @SuppressWarnings("resource")@Nullable- private InputStream openCacheInputStream(Long projectId, Long cacheId, String cachePathsString) {- var cacheHome = projectService.getCacheDir(projectId);- var cacheDir = new File(cacheHome, String.valueOf(cacheId));- if (cacheDir.exists()) {- var stampFile = new File(cacheDir, "stamp");- if (stampFile.exists()) {- var stamp = readString(stampFile);- if (stamp.equals(CACHE_VERSION + ":" + cachePathsString)) {- try {- var marks = FileUtils.readFileToByteArray(new File(cacheDir, "marks"));- return new SequenceInputStream(- new ByteArrayInputStream(marks),- new FileInputStream(new File(cacheDir, "data")));- } catch (IOException e) {- throw new RuntimeException(e);+ private CacheFindResult findCache(Long projectId, File cacheDir, boolean exact, String path) {+ return read(getLockName(projectId, cacheDir.getName()), () -> {+ if (!isCacheDirValid(cacheDir))+ return null;+ var pathIndexes = PathIndexUtils.read(cacheDir);+ Integer index = pathIndexes.get(path);+ if (index == null)+ return null;+ var pathFile = new File(cacheDir, String.valueOf(index));+ if (!pathFile.exists())+ return null;+ return new CacheFindResult(projectId, cacheDir.getName(), index, exact);+ });+ }++ @Sessional+ @Override+ public CacheFindResult findCache(Long projectId, String key, @Nullable String checksum, String path) {+ var currentProject = projectService.load(projectId);+ var encodedKey = encodePathSegment(key);+ do {+ var currentProjectId = currentProject.getId();+ var findResult = projectService.runOnActiveServer(currentProjectId, () -> {+ var cachesDir = projectService.getCacheDir(currentProjectId);+ var exactName = getDirName(key, checksum);++ var exactDir = new File(cachesDir, exactName);+ var innerFindResult = findCache(currentProjectId, exactDir, true, path);+ if (innerFindResult != null)+ return innerFindResult;++ var children = cachesDir.listFiles();+ if (children != null) {+ var partialCandidates = new ArrayList<File>();+ for (var child: children) {+ if (!child.isDirectory())+ continue;+ if (child.getName().equals(exactName))+ continue;+ if (!getEncodedKeyFromDirName(child.getName()).equals(encodedKey))+ continue;+ partialCandidates.add(child);}- }- }- }+ partialCandidates.sort(Comparator.comparing((File dir) ->+ read(getLockName(currentProjectId, dir.getName()), () -> readLastAccessTime(dir))).reversed());+ for (var candidate: partialCandidates) {+ innerFindResult = findCache(currentProjectId, candidate, false, path);+ if (innerFindResult != null)+ return innerFindResult;+ }+ }+ return null;+ });+ if (findResult != null)+ return findResult;+ currentProject = currentProject.getParent();+ } while (currentProject != null);+return null;}@Override- public Long createCache(Long projectId, String key, @Nullable String checksum) {- Long cacheId;- while (true) {+ public CacheAvailability downloadCache(CacheFindResult cacheFindResult, Consumer<InputStream> cacheStreamHandler) {+ var projectId = cacheFindResult.getProjectId();+ var dirName = cacheFindResult.getDirName();+ var pathIndex = cacheFindResult.getPathIndex();+ return read(getLockName(projectId, dirName), () -> {+ var cacheDir = getCacheDir(projectId, dirName);+ var pathFile = new File(cacheDir, String.valueOf(pathIndex));+ if (!pathFile.exists())+ return CacheAvailability.NOT_FOUND;+ try (var is = new FileInputStream(pathFile)) {+ cacheStreamHandler.accept(is);+ updateLastAccessTime(cacheDir);+ return cacheFindResult.getCacheAvailability();+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ });+ }++ @Override+ public void downloadCache(CacheFindResult cacheFindResult, OutputStream cacheStream) {+ var projectId = cacheFindResult.getProjectId();+ var dirName = cacheFindResult.getDirName();+ read(getLockName(projectId, dirName), () -> {+ var cacheDir = getCacheDir(projectId, dirName);+ var pathFile = new File(cacheDir, String.valueOf(cacheFindResult.getPathIndex()));try {- cacheId = transactionService.call(() -> {- var project = projectService.load(projectId);- var cache = find(project, key, checksum);- if (cache == null) {- cache = new RunCache();- cache.setProject(project);- cache.setKey(key);- cache.setChecksum(checksum);- }- cache.setAccessDate(new Date());- dao.persist(cache);- return cache.getId();- });- break;- } catch (Exception e) {- if (ExceptionUtils.find(e, ConstraintViolationException.class) != null) {- try {- Thread.sleep(5000);- } catch (InterruptedException ex) {- throw new RuntimeException(ex);+ if (pathFile.exists()) {+ cacheStream.write(cacheFindResult.getCacheAvailability().ordinal());+ try (var is = new FileInputStream(pathFile)) {+ IOUtils.copy(is, cacheStream, BUFFER_SIZE);}+ updateLastAccessTime(cacheDir);} else {- throw e;+ cacheStream.write(CacheAvailability.NOT_FOUND.ordinal());}+ } catch (IOException e) {+ throw new RuntimeException(e);}- }- return cacheId;- }-- private void writeStamp(File cacheDir, String cachePathsString) {- writeString(new File(cacheDir, "stamp"), CACHE_VERSION + ":" + cachePathsString);+ });}-- private Pair<File, OutputStream> openCacheOutputStream(Long projectId, Long cacheId) {- var cacheHome = projectService.getCacheDir(projectId);- var cacheDir = new File(cacheHome, String.valueOf(cacheId));- FileUtils.cleanDir(cacheDir);- try {- return new ImmutablePair<>(cacheDir, new FilterOutputStream(new BufferedOutputStream(new FileOutputStream(new File(cacheDir, "data")), BUFFER_SIZE)) {-- private final byte[] buffer = new byte[CacheProvisioner.MARK_BUFFER_SIZE];-- private final byte[] singeByteArray = new byte[1];-- private int ptr;-- private void append(byte data) {- singeByteArray[0] = data;- append(singeByteArray, 0, 1);- }-- private void append(byte[] data, int offset, int length) {- if (length <= buffer.length - ptr) {- System.arraycopy(data, offset, buffer, ptr, length);- ptr += length;- } else if (length < buffer.length) {- System.arraycopy(buffer, length - buffer.length + ptr, buffer, 0, buffer.length - length);- System.arraycopy(data, offset, buffer, buffer.length - length, length);- ptr = buffer.length;- } else {- System.arraycopy(data, offset + length - buffer.length, buffer, 0, buffer.length);- ptr = buffer.length;- }- }-- @Override- public void write(int b) throws IOException {- super.write(b);- append((byte)b);- }- @Override- public void write(byte[] b, int off, int len) throws IOException {- out.write(b, off, len);- append(b, off, len);- }-- @Override- public void close() throws IOException {- super.close();- FileUtils.writeByteArrayToFile(new File(cacheDir, "marks"), buffer);- }-- });- } catch (FileNotFoundException e) {- throw new RuntimeException(e);- }- }-@Override- public void uploadCache(Long projectId, Long cacheId, String cachePathsString,+ public void uploadCache(Long projectId, String key, @Nullable String checksum, String path,Consumer<OutputStream> cacheStreamHandler) {- write(RunCache.getLockName(projectId, cacheId), () -> {- var result = openCacheOutputStream(projectId, cacheId);- try {- cacheStreamHandler.accept(result.getRight());- } finally {- IOUtils.closeQuietly(result.getRight());+ var dirName = getDirName(key, checksum);+ write(getLockName(projectId, dirName), () -> {+ var cacheDir = getCacheDir(projectId, dirName);+ FileUtils.createDir(cacheDir);+ var pathIndexes = PathIndexUtils.read(cacheDir);+ boolean wasNew = !pathIndexes.containsKey(path);+ int index = PathIndexUtils.allocate(pathIndexes, path);+ var pathFile = new File(cacheDir, String.valueOf(index));+ try (var os = new FileOutputStream(pathFile)) {+ cacheStreamHandler.accept(os);+ } catch (IOException e) {+ throw new RuntimeException(e);}- writeStamp(result.getLeft(), cachePathsString);+ if (wasNew)+ PathIndexUtils.write(cacheDir, pathIndexes);+ updateLastAccessTime(cacheDir);});}-+@Override- public void uploadCache(Long projectId, Long cacheId, String cachePathsString,+ public void uploadCache(Long projectId, String key, @Nullable String checksum, String path,InputStream cacheStream) {- write(RunCache.getLockName(projectId, cacheId), () -> {- var result = openCacheOutputStream(projectId, cacheId);+ uploadCache(projectId, key, checksum, path, os -> {try {- IOUtils.copy(cacheStream, result.getRight(), BUFFER_SIZE);+ IOUtils.copy(cacheStream, os, BUFFER_SIZE);} catch (IOException e) {throw new RuntimeException(e);- } finally {- IOUtils.closeQuietly(result.getRight());}- writeStamp(result.getLeft(), cachePathsString);});}- @Transactional@Override- public void delete(RunCache cache) {- var projectId = cache.getProject().getId();- var cacheId = cache.getId();- dao.remove(cache);- projectService.runOnActiveServer(projectId, () -> write(RunCache.getLockName(projectId, cacheId), () -> {- FileUtils.deleteDir(new File(projectService.getCacheDir(projectId), String.valueOf(cacheId)));- return null;- }));+ public List<RunCacheInfo> listCaches(Long projectId) {+ return projectService.runOnActiveServer(projectId, () -> {+ var cachesDir = projectService.getCacheDir(projectId);+ var infos = new ArrayList<RunCacheInfo>();+ var children = cachesDir.listFiles();+ if (children != null) {+ for (var child: children) {+ read(getLockName(projectId, child.getName()), () -> {+ if (isCacheDirValid(child)) {+ var dirName = child.getName();+ var indexedPaths = PathIndexUtils.listIndexedPaths(child);+ long lastAccessTime = readLastAccessTime(child);+ var key = getKeyFromDirName(dirName);+ var checksum = getChecksumFromDirName(dirName);+ infos.add(new RunCacheInfo(key, checksum,+ lastAccessTime != 0 ? new Date(lastAccessTime) : null,+ indexedPaths));+ }+ });+ }+ }+ infos.sort(Comparator.comparing((RunCacheInfo it) ->+ it.getLastAccessDate() != null ? it.getLastAccessDate().getTime() : 0L).reversed());+ return infos;+ });}- @Nullable@Override- public Long getCacheSize(Long projectId, Long cacheId) {- return projectService.runOnActiveServer(projectId, () -> read(RunCache.getLockName(projectId, cacheId), () -> {- var cacheDir = new File(projectService.getCacheDir(projectId), String.valueOf(cacheId));- if (cacheDir.exists()) {- var stampFile = new File(cacheDir, "stamp");- if (stampFile.exists()) {- var stamp = readString(stampFile);- if (stamp.startsWith(CACHE_VERSION + ":")) {- var dataFile = new File(cacheDir, "data");- if (dataFile.exists())- return dataFile.length();- }- }- }+ public void deleteCache(Long projectId, String key, @Nullable String checksum) {+ var dirName = getDirName(key, checksum);+ projectService.runOnActiveServer(projectId, () -> write(getLockName(projectId, dirName), () -> {+ FileUtils.deleteDir(getCacheDir(projectId, dirName));return null;}));}@@ -371,9 +324,9 @@ public class DefaultRunCacheService extends BaseEntityService<RunCache>@Listenpublic void on(SystemStarted event) {- taskId = taskScheduler.schedule(this);+ taskId = taskScheduler.schedule(this);}-+@Listenpublic void on(SystemStopping event) {if (taskId != null)@@ -382,35 +335,46 @@ public class DefaultRunCacheService extends BaseEntityService<RunCache>@Overridepublic void execute() {- batchWorkExecutionService.submit(new BatchWorker("job-cache-manager-house-keeping") {+ batchWorkExecutionService.submit(new BatchWorker("run-cache-house-keeping") {@Overridepublic void doWorks(List<Prioritized> works) {var now = new DateTime();for (var projectId: projectService.getActiveIds()) {- transactionService.run(() -> {- try {- var project = projectService.load(projectId);- var preserveDays = project.getHierarchyCachePreserveDays();- var threshold = now.minusDays(preserveDays);- var criteria = newCriteria();- criteria.add(Restrictions.eq(PROP_PROJECT, project));- criteria.add(Restrictions.lt(PROP_ACCESS_DATE, threshold.toDate()));- for (var cache: query(criteria))- delete(cache);- } catch (Exception e) {- logger.error("Error cleaning up job caches", e);+ try {+ var preserveDays = projectService.load(projectId).getHierarchyCachePreserveDays();+ var thresholdMillis = now.minusDays(preserveDays).getMillis();+ var cacheDirs = projectService.getCacheDir(projectId);+ var children = cacheDirs.listFiles();+ if (children == null)+ continue;+ for (var child: children) {+ if (!child.isDirectory())+ continue;+ var dirName = child.getName();+ write(getLockName(projectId, dirName), () -> {+ if (!isCacheDirValid(child)) {+ FileUtils.deleteDir(child);+ return null;+ }+ var lastAccessTime = readLastAccessTime(child);+ if (lastAccessTime < thresholdMillis)+ FileUtils.deleteDir(child);+ return null;+ });}- });+ } catch (Exception e) {+ logger.error("Error cleaning up run caches", e);+ }}}- }, new Prioritized(HOUSE_KEEPING_PRIORITY));+ }, new Prioritized(HOUSE_KEEPING_PRIORITY));}@Overridepublic ScheduleBuilder<?> getScheduleBuilder() {return CronScheduleBuilder.dailyAtHourAndMinute(0, 0);}-+}diff --git a/server-core/src/main/java/io/onedev/server/service/impl/DefaultUserService.java b/server-core/src/main/java/io/onedev/server/service/impl/DefaultUserService.javaindex d48433c463..ef16526bba 100644--- a/server-core/src/main/java/io/onedev/server/service/impl/DefaultUserService.java+++ b/server-core/src/main/java/io/onedev/server/service/impl/DefaultUserService.java@@ -85,7 +85,7 @@ public class DefaultUserService extends BaseEntityService<User> implements UserSprivate static final int TIMEOUT_SECONDS = 600;- private static final int SYNC_PRIORITY = 50;+ private static final int SYNC_PRIORITY = 50;@Injectprivate BatchWorkExecutionService batchWorkExecutionService;@@ -133,9 +133,10 @@ public class DefaultUserService extends BaseEntityService<User> implements UserSsyncDirectory(syncWithServer, "users", userId -> {syncDirectory(syncWithServer, "users/" + userId, dataType -> {if (dataType.equals("workspace-data")) {- syncDirectory(syncWithServer, "users/" + userId + "/workspace-data", dataKey -> {+ syncDirectory(syncWithServer, "users/" + userId + "/workspace-data", encodedDataKey -> {+ var dataKey = User.decodeWorkspaceDataKey(encodedDataKey);var lockName = User.getWorkspaceDataLockName(Long.valueOf(userId), dataKey);- syncDirectory(syncWithServer, "users/" + userId + "/workspace-data/" + dataKey,+ syncDirectory(syncWithServer, "users/" + userId + "/workspace-data/" + encodedDataKey,false, lockName, lockName);}, true);}@@ -749,7 +750,7 @@ public class DefaultUserService extends BaseEntityService<User> implements UserS@Overridepublic File getWorkspaceDataDir(Long userId, String dataKey, boolean createIfNotExist) {- var dataDir = new File(getWorkspaceDataBaseDir(userId), dataKey);+ var dataDir = new File(getWorkspaceDataBaseDir(userId), User.encodeWorkspaceDataKey(dataKey));if (createIfNotExist)FileUtils.createDir(dataDir);return dataDir;diff --git a/server-core/src/main/java/io/onedev/server/service/support/CacheQueryResult.java b/server-core/src/main/java/io/onedev/server/service/support/CacheFindResult.javasimilarity index 55%rename from server-core/src/main/java/io/onedev/server/service/support/CacheQueryResult.javarename to server-core/src/main/java/io/onedev/server/service/support/CacheFindResult.javaindex a108fe3727..d62dd1125b 100644--- a/server-core/src/main/java/io/onedev/server/service/support/CacheQueryResult.java+++ b/server-core/src/main/java/io/onedev/server/service/support/CacheFindResult.java@@ -4,17 +4,22 @@ import java.io.Serializable;import io.onedev.k8shelper.CacheAvailability;-public class CacheQueryResult implements Serializable {+public class CacheFindResult implements Serializable {++ private static final long serialVersionUID = 1L;private final Long projectId;- private final Long cacheId;+ private final String dirName;++ private final int pathIndex;private final boolean exactMatch;- public CacheQueryResult(Long projectId, Long cacheId, boolean exactMatch) {+ public CacheFindResult(Long projectId, String dirName, int pathIndex, boolean exactMatch) {this.projectId = projectId;- this.cacheId = cacheId;+ this.dirName = dirName;+ this.pathIndex = pathIndex;this.exactMatch = exactMatch;}@@ -22,8 +27,12 @@ public class CacheQueryResult implements Serializable {return projectId;}- public Long getCacheId() {- return cacheId;+ public String getDirName() {+ return dirName;+ }++ public int getPathIndex() {+ return pathIndex;}public boolean isExactMatch() {@@ -33,5 +42,5 @@ public class CacheQueryResult implements Serializable {public CacheAvailability getCacheAvailability() {return exactMatch ? CacheAvailability.EXACT_MATCH : CacheAvailability.PARTIAL_MATCH;}-+}diff --git a/server-core/src/main/java/io/onedev/server/service/support/PathInfo.java b/server-core/src/main/java/io/onedev/server/service/support/PathInfo.javanew file mode 100644index 0000000000..24845491ab--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/service/support/PathInfo.java@@ -0,0 +1,26 @@+package io.onedev.server.service.support;++import java.io.Serializable;++public class PathInfo implements Serializable {++ private static final long serialVersionUID = 1L;++ private final String path;++ private final long size;++ public PathInfo(String path, long size) {+ this.path = path;+ this.size = size;+ }++ public String getPath() {+ return path;+ }++ public long getSize() {+ return size;+ }++}diff --git a/server-core/src/main/java/io/onedev/server/service/support/RunCacheInfo.java b/server-core/src/main/java/io/onedev/server/service/support/RunCacheInfo.javanew file mode 100644index 0000000000..15c59d9a74--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/service/support/RunCacheInfo.java@@ -0,0 +1,49 @@+package io.onedev.server.service.support;++import java.io.Serializable;+import java.util.Date;+import java.util.List;++import org.jspecify.annotations.Nullable;++public class RunCacheInfo implements Serializable {++ private static final long serialVersionUID = 1L;++ private final String key;++ @Nullable+ private final String checksum;++ @Nullable+ private final Date lastAccessDate;++ private final List<PathInfo> indexedPaths;++ public RunCacheInfo(String key, @Nullable String checksum, @Nullable Date lastAccessDate,+ List<PathInfo> indexedPaths) {+ this.key = key;+ this.checksum = checksum;+ this.lastAccessDate = lastAccessDate;+ this.indexedPaths = indexedPaths;+ }++ public String getKey() {+ return key;+ }++ @Nullable+ public String getChecksum() {+ return checksum;+ }++ @Nullable+ public Date getLastAccessDate() {+ return lastAccessDate;+ }++ public List<PathInfo> getIndexedPaths() {+ return indexedPaths;+ }++}diff --git a/server-core/src/main/java/io/onedev/server/util/PathIndexUtils.java b/server-core/src/main/java/io/onedev/server/util/PathIndexUtils.javanew file mode 100644index 0000000000..1456ff0db6--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/util/PathIndexUtils.java@@ -0,0 +1,85 @@+package io.onedev.server.util;++import java.io.File;+import java.io.FileInputStream;+import java.io.FileOutputStream;+import java.io.IOException;+import java.io.Serializable;+import java.util.ArrayList;+import java.util.Comparator;+import java.util.HashMap;+import java.util.List;+import java.util.Map;++import org.apache.commons.lang3.SerializationUtils;++import io.onedev.server.service.support.PathInfo;++/**+ * Utility for managing a directory whose user-visible paths are stored as+ * files named by an integer index. The mapping from path to index is persisted+ * in a single index file inside the directory.+ *+ * <p>Used by both the run cache storage and the user workspace data storage to+ * avoid touching the filesystem with arbitrary user-supplied path names.+ */+public class PathIndexUtils {++ public static final String INDEX_FILE_NAME = ".path-index";++ private PathIndexUtils() {+ }++ public static File getIndexFile(File dir) {+ return new File(dir, INDEX_FILE_NAME);+ }++ public static boolean exists(File dir) {+ return getIndexFile(dir).exists();+ }++ public static Map<String, Integer> read(File dir) {+ var indexFile = getIndexFile(dir);+ if (!indexFile.exists())+ return new HashMap<>();+ try (var is = new FileInputStream(indexFile)) {+ return SerializationUtils.deserialize(is);+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }++ public static void write(File dir, Map<String, Integer> indexes) {+ var indexFile = getIndexFile(dir);+ try (var os = new FileOutputStream(indexFile)) {+ SerializationUtils.serialize((Serializable) indexes, os);+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }++ public static int allocate(Map<String, Integer> indexes, String path) {+ Integer existing = indexes.get(path);+ if (existing != null)+ return existing;+ int next = indexes.values().stream().mapToInt(Integer::intValue).max().orElse(0) + 1;+ indexes.put(path, next);+ return next;+ }++ /**+ * List the path and size of every indexed path file that exists under the+ * given directory, sorted by path.+ */+ public static List<PathInfo> listIndexedPaths(File dir) {+ var paths = new ArrayList<PathInfo>();+ for (var entry : read(dir).entrySet()) {+ var pathFile = new File(dir, String.valueOf(entry.getValue()));+ if (pathFile.isFile())+ paths.add(new PathInfo(entry.getKey(), pathFile.length()));+ }+ paths.sort(Comparator.comparing(PathInfo::getPath));+ return paths;+ }++}diff --git a/server-core/src/main/java/io/onedev/server/validation/validator/PathValidator.java b/server-core/src/main/java/io/onedev/server/validation/validator/PathValidator.javaindex b5910c4b42..3aeb4f0cdb 100644--- a/server-core/src/main/java/io/onedev/server/validation/validator/PathValidator.java+++ b/server-core/src/main/java/io/onedev/server/validation/validator/PathValidator.java@@ -39,30 +39,26 @@ public class PathValidator implements ConstraintValidator<Path, Object> {}private boolean isValidPath(String value, ConstraintValidatorContext constraintContext) {- if (value.contains("..")) {- constraintContext.disableDefaultConstraintViolation();- String message = this.message;- if (message.length() == 0)- message = "'..' is disallowed";- constraintContext.buildConstraintViolationWithTemplate(message).addConstraintViolation();- return false;- } else if (FilenameUtils.getPrefixLength(value) == 0 && type == Path.Type.ABSOLUTE) {+ String checkMessage = checkPath(type, value);+ if (checkMessage != null) {constraintContext.disableDefaultConstraintViolation();String message = this.message;if (message.length() == 0)- message = "Absolute path is required";+ message = checkMessage;constraintContext.buildConstraintViolationWithTemplate(message).addConstraintViolation();return false;- } else if (FilenameUtils.getPrefixLength(value) != 0 && type == Path.Type.RELATIVE) {- constraintContext.disableDefaultConstraintViolation();- String message = this.message;- if (message.length() == 0)- message = "Relative path is required";- constraintContext.buildConstraintViolationWithTemplate(message).addConstraintViolation();- return false;- } else {- return true;}+ return true;}+ public static String checkPath(Path.Type type, String value) {+ if (value.contains(".."))+ return "'..' is not allowed";+ else if (FilenameUtils.getPrefixLength(value) == 0 && type == Path.Type.ABSOLUTE)+ return "Absolute path is required";+ else if (FilenameUtils.getPrefixLength(value) != 0 && type == Path.Type.RELATIVE)+ return "Relative path is required";+ return null;+ }+}diff --git a/server-core/src/main/java/io/onedev/server/web/component/indexedpath/IndexedPathsPanel.html b/server-core/src/main/java/io/onedev/server/web/component/indexedpath/IndexedPathsPanel.htmlnew file mode 100644index 0000000000..baaf3010cc--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/web/component/indexedpath/IndexedPathsPanel.html@@ -0,0 +1,21 @@+<wicket:panel>+ <a wicket:id="link"><span wicket:id="label"></span> <wicket:svg href="arrow" class="icon rotate-90"></wicket:svg></a>+ <wicket:fragment wicket:id="dropdownFrag">+ <div class="p-3" style="max-height:480px;overflow:auto;">+ <table class="table table-hover mb-0">+ <thead>+ <tr>+ <th><wicket:t>Path</wicket:t></th>+ <th><wicket:t>Size</wicket:t></th>+ </tr>+ </thead>+ <tbody>+ <tr wicket:id="paths">+ <td><span wicket:id="path"></span></td>+ <td class="text-nowrap"><span wicket:id="size"></span></td>+ </tr>+ </tbody>+ </table>+ </div>+ </wicket:fragment>+</wicket:panel>diff --git a/server-core/src/main/java/io/onedev/server/web/component/indexedpath/IndexedPathsPanel.java b/server-core/src/main/java/io/onedev/server/web/component/indexedpath/IndexedPathsPanel.javanew file mode 100644index 0000000000..f67ddec48c--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/web/component/indexedpath/IndexedPathsPanel.java@@ -0,0 +1,66 @@+package io.onedev.server.web.component.indexedpath;++import java.util.List;++import org.apache.commons.io.FileUtils;+import org.apache.wicket.Component;+import org.apache.wicket.markup.html.basic.Label;+import org.apache.wicket.markup.html.list.ListItem;+import org.apache.wicket.markup.html.list.ListView;+import org.apache.wicket.markup.html.panel.Fragment;+import org.apache.wicket.markup.html.panel.GenericPanel;+import org.apache.wicket.model.IModel;+import org.apache.wicket.model.Model;++import io.onedev.server.service.support.PathInfo;+import io.onedev.server.web.component.floating.FloatingPanel;+import io.onedev.server.web.component.link.DropdownLink;++/**+ * Reusable panel showing the number of paths backed by an indexed-path+ * directory (see {@link io.onedev.server.util.PathIndexUtils}). Clicking the+ * count opens a dropdown listing each path with its on-disk size.+ */+public class IndexedPathsPanel extends GenericPanel<List<PathInfo>> {++ private static final long serialVersionUID = 1L;++ public IndexedPathsPanel(String id, IModel<List<PathInfo>> model) {+ super(id, model);+ }++ @Override+ protected void onInitialize() {+ super.onInitialize();++ var indexedPaths = getModelObject();++ var link = new DropdownLink("link") {++ private static final long serialVersionUID = 1L;++ @Override+ protected Component newContent(String id, FloatingPanel dropdown) {+ Fragment fragment = new Fragment(id, "dropdownFrag", IndexedPathsPanel.this);+ fragment.add(new ListView<>("paths", indexedPaths) {++ private static final long serialVersionUID = 1L;++ @Override+ protected void populateItem(ListItem<PathInfo> item) {+ item.add(new Label("path", item.getModelObject().getPath()));+ item.add(new Label("size",+ FileUtils.byteCountToDisplaySize(item.getModelObject().getSize())));+ }++ });+ return fragment;+ }++ };+ link.add(new Label("label", Model.of(String.valueOf(indexedPaths.size()))));+ link.setEnabled(!indexedPaths.isEmpty());+ add(link);+ }++}diff --git a/server-core/src/main/java/io/onedev/server/web/component/user/workspacedata/WorkspaceDataPanel.html b/server-core/src/main/java/io/onedev/server/web/component/user/workspacedata/WorkspaceDataPanel.htmlindex be946742e9..8a8a19b1a0 100644--- a/server-core/src/main/java/io/onedev/server/web/component/user/workspacedata/WorkspaceDataPanel.html+++ b/server-core/src/main/java/io/onedev/server/web/component/user/workspacedata/WorkspaceDataPanel.html@@ -1,26 +1,5 @@<wicket:panel><table wicket:id="keys" class="table table-hover"></table>- <wicket:fragment wicket:id="filesColumnFrag">- <a wicket:id="link"><span wicket:id="label"></span> <wicket:svg href="arrow" class="icon rotate-90"></wicket:svg></a>- </wicket:fragment>- <wicket:fragment wicket:id="filesDropdownFrag">- <div class="p-3" style="max-height:480px;overflow:auto;">- <table class="table table-hover mb-0">- <thead>- <tr>- <th><wicket:t>Path</wicket:t></th>- <th><wicket:t>Size</wicket:t></th>- </tr>- </thead>- <tbody>- <tr wicket:id="files">- <td><span wicket:id="path"></span></td>- <td class="text-nowrap"><span wicket:id="size"></span></td>- </tr>- </tbody>- </table>- </div>- </wicket:fragment><wicket:fragment wicket:id="actionFrag"><a wicket:id="delete" t:data-tippy-content="Delete this workspace data" class="btn btn-xs btn-icon btn-light btn-hover-danger"><wicket:svg href="trash" class="icon"></wicket:svg></a></wicket:fragment>diff --git a/server-core/src/main/java/io/onedev/server/web/component/user/workspacedata/WorkspaceDataPanel.java b/server-core/src/main/java/io/onedev/server/web/component/user/workspacedata/WorkspaceDataPanel.javaindex cfb0bd76cb..5a1da1eabd 100644--- a/server-core/src/main/java/io/onedev/server/web/component/user/workspacedata/WorkspaceDataPanel.java+++ b/server-core/src/main/java/io/onedev/server/web/component/user/workspacedata/WorkspaceDataPanel.java@@ -5,8 +5,6 @@ import static io.onedev.commons.utils.LockUtils.write;import static io.onedev.server.web.translation.Translation._T;import java.io.File;-import java.io.Serializable;-import java.nio.charset.StandardCharsets;import java.util.ArrayList;import java.util.Arrays;import java.util.Date;@@ -16,8 +14,6 @@ import java.util.stream.Collectors;import javax.inject.Inject;-import org.apache.commons.codec.binary.Hex;-import org.apache.wicket.Component;import org.apache.wicket.Session;import org.apache.wicket.ajax.AjaxRequestTarget;import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;@@ -28,8 +24,6 @@ import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;import org.apache.wicket.markup.html.basic.Label;-import org.apache.wicket.markup.html.list.ListItem;-import org.apache.wicket.markup.html.list.ListView;import org.apache.wicket.markup.html.panel.Fragment;import org.apache.wicket.markup.html.panel.Panel;import org.apache.wicket.markup.repeater.Item;@@ -40,11 +34,12 @@ import io.onedev.commons.utils.FileUtils;import io.onedev.server.cluster.ClusterService;import io.onedev.server.model.User;import io.onedev.server.service.UserService;+import io.onedev.server.service.support.PathInfo;+import io.onedev.server.util.PathIndexUtils;import io.onedev.server.util.DateUtils;import io.onedev.server.web.ajaxlistener.ConfirmClickListener;import io.onedev.server.web.component.datatable.DefaultDataTable;-import io.onedev.server.web.component.floating.FloatingPanel;-import io.onedev.server.web.component.link.DropdownLink;+import io.onedev.server.web.component.indexedpath.IndexedPathsPanel;import io.onedev.server.web.util.LoadableDetachableDataProvider;public class WorkspaceDataPanel extends Panel {@@ -72,6 +67,7 @@ public class WorkspaceDataPanel extends Panel {var baseDir = getWorkspaceDataBaseDir();return Arrays.stream(baseDir.listFiles(File::isDirectory)).map(File::getName)+ .map(User::decodeWorkspaceDataKey).sorted().collect(Collectors.toList());}@@ -98,50 +94,13 @@ public class WorkspaceDataPanel extends Panel {public void populateItem(Item<ICellPopulator<String>> cellItem, String componentId,IModel<String> rowModel) {var key = rowModel.getObject();- Fragment fragment = new Fragment(componentId, "filesColumnFrag", WorkspaceDataPanel.this);-- var files = read(User.getWorkspaceDataLockName(userId, key), () -> {+ List<PathInfo> indexedPaths = read(User.getWorkspaceDataLockName(userId, key), () -> {var keyDir = userService.getWorkspaceDataDir(userId, key, false);- var innerFiles = new ArrayList<FileEntry>();- if (keyDir.exists()) {- for (var file : keyDir.listFiles()) {- if (file.isFile() && !file.isHidden()) {- innerFiles.add(new FileEntry(- new String(Hex.decodeHex(file.getName()), StandardCharsets.UTF_8),- FileUtils.byteCountToDisplaySize(file.length())));- }- }- }- innerFiles.sort((a, b) -> a.path.compareTo(b.path));- return innerFiles;+ if (!keyDir.exists())+ return new ArrayList<PathInfo>();+ return PathIndexUtils.listIndexedPaths(keyDir);});-- var link = new DropdownLink("link") {-- @Override- protected Component newContent(String id, FloatingPanel dropdown) {- Fragment fragment = new Fragment(id, "filesDropdownFrag", WorkspaceDataPanel.this);-- fragment.add(new ListView<>("files", files) {-- @Override- protected void populateItem(ListItem<FileEntry> item) {- item.add(new Label("path", item.getModelObject().path));- item.add(new Label("size", item.getModelObject().size));- }-- });-- return fragment;- }-- };-- link.add(new Label("label", Model.of(String.valueOf(files.size()))));-- fragment.add(link);-- cellItem.add(fragment);+ cellItem.add(new IndexedPathsPanel(componentId, Model.ofList(indexedPaths)));}});@@ -236,17 +195,4 @@ public class WorkspaceDataPanel extends Panel {Integer.MAX_VALUE, null));}- private static class FileEntry implements Serializable {-- final String path;-- final String size;-- FileEntry(String path, String size) {- this.path = path;- this.size = size;- }-- }-}diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/setting/cache/CacheManagementPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/setting/cache/CacheManagementPage.javaindex 810eb9e887..39a0619907 100644--- a/server-core/src/main/java/io/onedev/server/web/page/project/setting/cache/CacheManagementPage.java+++ b/server-core/src/main/java/io/onedev/server/web/page/project/setting/cache/CacheManagementPage.java@@ -1,6 +1,5 @@package io.onedev.server.web.page.project.setting.cache;-import static io.onedev.server.model.RunCache.PROP_PROJECT;import static io.onedev.server.web.translation.Translation._T;import java.text.MessageFormat;@@ -8,10 +7,10 @@ import java.util.ArrayList;import java.util.Iterator;import java.util.List;-import org.apache.commons.io.FileUtils;import org.apache.wicket.Component;import org.apache.wicket.Session;import org.apache.wicket.ajax.AjaxRequestTarget;+import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;import org.apache.wicket.ajax.markup.html.AjaxLink;import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;@@ -23,21 +22,19 @@ import org.apache.wicket.markup.html.form.Form;import org.apache.wicket.markup.html.panel.Fragment;import org.apache.wicket.markup.repeater.Item;import org.apache.wicket.model.IModel;-import org.apache.wicket.model.LoadableDetachableModel;import org.apache.wicket.model.Model;import org.apache.wicket.request.mapper.parameter.PageParameters;-import org.hibernate.criterion.Order;-import org.hibernate.criterion.Restrictions;import io.onedev.server.OneDev;import io.onedev.server.data.migration.VersionedXmlDoc;-import io.onedev.server.model.RunCache;-import io.onedev.server.persistence.dao.EntityCriteria;import io.onedev.server.service.ProjectService;import io.onedev.server.service.RunCacheService;+import io.onedev.server.service.support.RunCacheInfo;import io.onedev.server.util.DateUtils;import io.onedev.server.web.WebConstants;+import io.onedev.server.web.ajaxlistener.ConfirmClickListener;import io.onedev.server.web.component.datatable.DefaultDataTable;+import io.onedev.server.web.component.indexedpath.IndexedPathsPanel;import io.onedev.server.web.editable.BeanContext;import io.onedev.server.web.page.project.setting.ProjectSettingPage;import io.onedev.server.web.page.project.setting.build.CacheSettingBean;@@ -48,7 +45,7 @@ public class CacheManagementPage extends ProjectSettingPage {private static final String PARAM_PAGE = "page";- private DataTable<RunCache, Void> cachesTable;+ private DataTable<RunCacheInfo, Void> cachesTable;public CacheManagementPage(PageParameters params) {super(params);@@ -62,6 +59,7 @@ public class CacheManagementPage extends ProjectSettingPage {bean.setPreserveDays(getProject().getBuildSetting().getCachePreserveDays());var oldAuditContent = VersionedXmlDoc.fromBean(bean).toXML();var form = new Form<Void>("cacheSetting") {+@Overrideprotected void onSubmit() {super.onSubmit();@@ -75,12 +73,12 @@ public class CacheManagementPage extends ProjectSettingPage {form.add(BeanContext.edit("editor", bean));add(form);- List<IColumn<RunCache, Void>> columns = new ArrayList<>();+ List<IColumn<RunCacheInfo, Void>> columns = new ArrayList<>();columns.add(new AbstractColumn<>(Model.of(_T("Key"))) {@Override- public void populateItem(Item<ICellPopulator<RunCache>> cellItem, String componentId, IModel<RunCache> rowModel) {+ public void populateItem(Item<ICellPopulator<RunCacheInfo>> cellItem, String componentId, IModel<RunCacheInfo> rowModel) {cellItem.add(new Label(componentId, rowModel.getObject().getKey()));}});@@ -88,7 +86,7 @@ public class CacheManagementPage extends ProjectSettingPage {columns.add(new AbstractColumn<>(Model.of(_T("Checksum"))) {@Override- public void populateItem(Item<ICellPopulator<RunCache>> cellItem, String componentId, IModel<RunCache> rowModel) {+ public void populateItem(Item<ICellPopulator<RunCacheInfo>> cellItem, String componentId, IModel<RunCacheInfo> rowModel) {var checksum = rowModel.getObject().getChecksum();if (checksum != null)cellItem.add(new Label(componentId, checksum));@@ -96,18 +94,12 @@ public class CacheManagementPage extends ProjectSettingPage {cellItem.add(new Label(componentId, "<i>N/A</i>").setEscapeModelStrings(false));}});-- columns.add(new AbstractColumn<>(Model.of(_T("Size"))) {++ columns.add(new AbstractColumn<>(Model.of(_T("#Paths"))) {@Override- public void populateItem(Item<ICellPopulator<RunCache>> cellItem, String componentId,- IModel<RunCache> rowModel) {- var cache = rowModel.getObject();- var cacheSize = getCacheService().getCacheSize(cache.getProject().getId(), cache.getId());- if (cacheSize != null)- cellItem.add(new Label(componentId, FileUtils.byteCountToDisplaySize(cacheSize)));- else- cellItem.add(new Label(componentId, "<i class='text-danger'>" + _T("File missing or obsolete") + "</i>").setEscapeModelStrings(false));+ public void populateItem(Item<ICellPopulator<RunCacheInfo>> cellItem, String componentId, IModel<RunCacheInfo> rowModel) {+ cellItem.add(new IndexedPathsPanel(componentId, Model.ofList(rowModel.getObject().getIndexedPaths())));}});@@ -115,10 +107,13 @@ public class CacheManagementPage extends ProjectSettingPage {columns.add(new AbstractColumn<>(Model.of(_T("Last Accessed"))) {@Override- public void populateItem(Item<ICellPopulator<RunCache>> cellItem, String componentId,- IModel<RunCache> rowModel) {- var cache = rowModel.getObject();- cellItem.add(new Label(componentId, DateUtils.formatDate(cache.getAccessDate())));+ public void populateItem(Item<ICellPopulator<RunCacheInfo>> cellItem, String componentId,+ IModel<RunCacheInfo> rowModel) {+ var info = rowModel.getObject();+ if (info.getLastAccessDate() != null)+ cellItem.add(new Label(componentId, DateUtils.formatDate(info.getLastAccessDate())));+ else+ cellItem.add(new Label(componentId, "<i>N/A</i>").setEscapeModelStrings(false));}});@@ -126,19 +121,34 @@ public class CacheManagementPage extends ProjectSettingPage {columns.add(new AbstractColumn<>(Model.of("")) {@Override- public void populateItem(Item<ICellPopulator<RunCache>> cellItem, String componentId, IModel<RunCache> rowModel) {+ public void populateItem(Item<ICellPopulator<RunCacheInfo>> cellItem, String componentId, IModel<RunCacheInfo> rowModel) {Fragment fragment = new Fragment(componentId, "actionFrag", CacheManagementPage.this);+ var cacheInfo = rowModel.getObject();+ String cacheName;+ var cacheChecksum = cacheInfo.getChecksum();+ if (cacheChecksum != null)+ cacheName = cacheInfo.getKey() + " (checksum: " + cacheChecksum + ")";+ else+ cacheName = cacheInfo.getKey();+fragment.add(new AjaxLink<Void>("delete") {@Overridepublic void onClick(AjaxRequestTarget target) {- var cache = rowModel.getObject();- getCacheService().delete(cache);- Session.get().success(MessageFormat.format(_T("Cache \"{0}\" deleted"), cache.getKey()));+ getCacheService().deleteCache(getProject().getId(), cacheName, cacheChecksum);+ Session.get().success(MessageFormat.format(_T("Cache \"{0}\" deleted"), cacheName));+target.add(cachesTable);}-++ @Override+ protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {+ super.updateAjaxAttributes(attributes);+ String message = MessageFormat.format(_T("Do you really want to delete cache \"{0}\"?"), cacheName);+ attributes.getAjaxCallListeners().add(new ConfirmClickListener(message));+ }+});cellItem.add(fragment);@@ -151,37 +161,28 @@ public class CacheManagementPage extends ProjectSettingPage {});- SortableDataProvider<RunCache, Void> dataProvider = new SortableDataProvider<>() {+ SortableDataProvider<RunCacheInfo, Void> dataProvider = new SortableDataProvider<>() {- private EntityCriteria<RunCache> newCriteria() {- var criteria = EntityCriteria.of(RunCache.class);- criteria.add(Restrictions.eq(PROP_PROJECT, getProject()));- return criteria;+ private List<RunCacheInfo> listCaches() {+ return getCacheService().listCaches(getProject().getId());}-+@Override- public Iterator<? extends RunCache> iterator(long first, long count) {- var criteria = newCriteria();- criteria.addOrder(Order.desc(RunCache.PROP_ACCESS_DATE));- return getCacheService().query(criteria, (int) first, (int) count).iterator();+ public Iterator<? extends RunCacheInfo> iterator(long first, long count) {+ var all = listCaches();+ int from = (int) Math.min(first, all.size());+ int to = (int) Math.min(first + count, all.size());+ return all.subList(from, to).iterator();}@Overridepublic long size() {- return getCacheService().count(newCriteria());+ return listCaches().size();}@Override- public IModel<RunCache> model(RunCache object) {- Long id = object.getId();- return new LoadableDetachableModel<>() {-- @Override- protected RunCache load() {- return getCacheService().load(id);- }-- };+ public IModel<RunCacheInfo> model(RunCacheInfo object) {+ return Model.of(object);}};diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/WorkspaceDetailPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/WorkspaceDetailPage.javaindex 96dc9ae91e..7ffd9aea62 100644--- a/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/WorkspaceDetailPage.java+++ b/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/WorkspaceDetailPage.java@@ -295,6 +295,7 @@ public abstract class WorkspaceDetailPage extends ProjectPage {@Overridepublic void onClick() {workspaceService.requestToReprovision(getWorkspace());+ setResponsePage(WorkspaceLogPage.class, getPageParameters());Session.get().success(MessageFormat.format(_T("Workspace reprovisioning requested"),getWorkspace().getReference().toString(getWorkspace().getProject())));}diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/changes/WorkspaceChangesPage.html b/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/changes/WorkspaceChangesPage.htmlindex 9c0026ee01..bc531d150a 100644--- a/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/changes/WorkspaceChangesPage.html+++ b/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/changes/WorkspaceChangesPage.html@@ -1,7 +1,7 @@<wicket:extend><div class="workspace-changes d-flex flex-grow-1 position-relative"><div wicket:id="changesSidebar" class="changes-sidebar autofit d-flex flex-column flex-grow-1 border-right">- <div wicket:id="statusError" class="alert alert-light-danger m-3"></div>+ <div wicket:id="statusError" class="alert alert-light-danger text-break m-3"></div><div class="sync-info d-flex align-items-center p-3"><div class="pull-info flex-grow-1 d-flex align-items-center"><span wicket:id="behindCount" class="mr-1"></span>diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/changes/WorkspaceChangesPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/changes/WorkspaceChangesPage.javaindex f0bd58a667..2504b01b08 100644--- a/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/changes/WorkspaceChangesPage.java+++ b/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/changes/WorkspaceChangesPage.java@@ -7,7 +7,9 @@ import java.nio.charset.StandardCharsets;import java.util.ArrayList;import java.util.List;+import io.onedev.server.web.page.project.workspaces.detail.log.WorkspaceLogPage;import org.apache.wicket.AttributeModifier;+import org.apache.wicket.RestartResponseException;import org.apache.wicket.Session;import org.apache.wicket.ajax.AjaxRequestTarget;import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;@@ -64,6 +66,9 @@ public class WorkspaceChangesPage extends WorkspaceDetailPage {public WorkspaceChangesPage(PageParameters params) {super(params);+ if (getWorkspace().getStatus() == Workspace.Status.PENDING)+ throw new RestartResponseException(WorkspaceLogPage.class, params);+selectedFile = params.get(PARAM_FILE).toString();}@@ -289,7 +294,18 @@ public class WorkspaceChangesPage extends WorkspaceDetailPage {}private void addFileSections(WebMarkupContainer container) {- GitExecutionResult statusResult = executeGit("status", "--porcelain");+ GitExecutionResult statusResult;+ if (getWorkspace().getStatus() == Workspace.Status.ACTIVE) {+ statusResult = executeGit("status", "--porcelain");+ } else {+ var errorMessage = String.format(+ "Please reprovision the workspace to show changes, " ++ "or you may login to server \"%s\" and check changes at \"%s\"",+ projectService.getActiveServer(getProject().getId(), true),+ Workspace.getWorkDir(getProject().getId(), getWorkspace().getNumber()));++ statusResult = new GitExecutionResult(new byte[0], errorMessage.getBytes(StandardCharsets.UTF_8), 1);+ }Label statusError = new Label("statusError", getErrorMessage(statusResult));statusError.setVisible(statusResult.getReturnCode() != 0);diff --git a/server-core/src/main/java/io/onedev/server/web/translation/Translation_de.java b/server-core/src/main/java/io/onedev/server/web/translation/Translation_de.javaindex db689cc835..4e92c19404 100644--- a/server-core/src/main/java/io/onedev/server/web/translation/Translation_de.java+++ b/server-core/src/main/java/io/onedev/server/web/translation/Translation_de.java@@ -575,6 +575,7 @@ public class Translation_de extends TranslationResourceBundle {m.put("CPU Intensive Task Concurrency", "CPU-intensive Aufgaben-Konkurrenz");m.put("CPU capability in millis. This is normally (CPU cores)*1000", "CPU-Kapazität in Millis. Dies ist normalerweise (CPU-Kerne)*1000");m.put("CPU cores", "CPU-Kerne");+ m.put("Cache \"{0} (checksum: {1})\" deleted", "Cache \"{0} (Prüfsumme: {1})\" gelöscht");m.put("Cache \"{0}\" deleted", "Cache \"{0}\" gelöscht");m.put("Cache Config", "Cache-Konfiguration");m.put("Cache Key", "Cache-Schlüssel");@@ -1440,7 +1441,6 @@ public class Translation_de extends TranslationResourceBundle {m.put("File is binary", "Datei ist binär");m.put("File is too large to be displayed", "Datei ist zu groß, um angezeigt zu werden");m.put("File is too large to edit here", "Datei ist zu groß, um hier bearbeitet zu werden");- m.put("File missing or obsolete", "Datei fehlt oder ist veraltet");m.put("File name", "Dateiname");m.put("File name patterns such as *.java, *.c", "Dateinamenmuster wie *.java, *.c");m.put("Files", "Dateien");@@ -2514,8 +2514,6 @@ public class Translation_de extends TranslationResourceBundle {m.put("Optionally specify Dockerfile relative to <a href='https://docs.onedev.io/concepts#job-workdir' target='_blank'>job working directory</a>. Leave empty to use file <tt>Dockerfile</tt> under build path specified above","Optional geben Sie die Dockerfile relativ zu <a href='https://docs.onedev.io/concepts#job-workdir' target='_blank'>Job-Arbeitsbereich</a> an. Lassen Sie das Feld leer, um die Datei <tt>Dockerfile</tt> unter dem oben angegebenen Build-Pfad zu verwenden");m.put("Optionally specify JavaScript config to be used by Renovate CLI", "Optional geben Sie die JavaScript-Konfiguration an, die von der Renovate-CLI verwendet werden soll");- m.put("Optionally specify PowerShell commands to run to set up the workspace. These commands\nwill run from working directory holding cloned repository files",- "Geben Sie optional PowerShell-Befehle an, die ausgeführt werden sollen, um den Arbeitsbereich einzurichten. Diese Befehle\nwerden aus dem Arbeitsverzeichnis ausgeführt, das geklonte Repository-Dateien enthält");m.put("Optionally specify SSH root URL, which will be used to construct project clone url via SSH protocol. Leave empty to derive from server url","Optional geben Sie die SSH-Root-URL an, die verwendet wird, um die Projekt-Klon-URL über das SSH-Protokoll zu erstellen. Lassen Sie das Feld leer, um es von der Server-URL abzuleiten");m.put("Optionally specify a <a href='http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html'>regular expression pattern</a> for valid values of the text input",@@ -2696,10 +2694,6 @@ public class Translation_de extends TranslationResourceBundle {"Optional geben Sie ein separates Verzeichnis an, um Paketdateien zu speichern. Nicht absolute Verzeichnisse werden als relativ zum Site-Verzeichnis betrachtet");m.put("Optionally specify services required by this job. <b class='text-warning'>NOTE:</b> Services are only supported by docker aware executors (server docker executor, remote docker executor, or kubernetes executor)","Optional geben Sie Dienste an, die für diesen Job erforderlich sind. <b class='text-warning'>HINWEIS:</b> Dienste werden nur von Docker-fähigen Executoren unterstützt (Server-Docker-Executor, Remote-Docker-Executor oder Kubernetes-Executor)");- m.put("Optionally specify sh commands (on Linux/Unix) or batch commands (on Windows)\nto run to set up the workspace. These commands will run from working directory\nholding cloned repository files",- "Geben Sie optional sh-Befehle (auf Linux/Unix) oder Batch-Befehle (auf Windows)\nan, die ausgeführt werden sollen, um den Arbeitsbereich einzurichten. Diese Befehle werden aus dem Arbeitsverzeichnis\nausgeführt, das geklonte Repository-Dateien enthält");- m.put("Optionally specify shell commands to run to set up the workspace. These commands will\nrun from working directory holding cloned repository files",- "Geben Sie optional Shell-Befehle an, die ausgeführt werden sollen, um den Arbeitsbereich einzurichten. Diese Befehle werden\naus dem Arbeitsverzeichnis ausgeführt, das geklonte Repository-Dateien enthält");m.put("Optionally specify space-separated branches applicable for this transition. Use '**', '*' or '?' for <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>path wildcard match</a>. Prefix with '-' to exclude. Leave empty to match all","Optional geben Sie durch Leerzeichen getrennte Zweige an, die für diesen Übergang anwendbar sind. Verwenden Sie '**', '*' oder '?' für <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>Pfad-Wildcard-Abgleich</a>. Präfix mit '-' zum Ausschließen. Lassen Sie das Feld leer, um alle zu entsprechen");m.put("Optionally specify space-separated branches applicable for this trigger. Use '**', '*' or '?' for <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>path wildcard match</a>. Prefix with '-' to exclude. Leave empty for default branch",@@ -2734,8 +2728,6 @@ public class Translation_de extends TranslationResourceBundle {"Optional geben Sie das Projekt an, in dem die Website-Dateien veröffentlicht werden sollen. Leer lassen, um im aktuellen Projekt zu veröffentlichen");m.put("Optionally specify uid:gid to run container as. <b class='text-warning'>Note:</b> This setting should be left empty if container runtime is rootless or using user namespace remapping","Optional geben Sie uid:gid an, um den Container auszuführen. <b class='text-warning'>Hinweis:</b> Diese Einstellung sollte leer gelassen werden, wenn die Container-Laufzeit rootless ist oder Benutzer-Namespace-Remapping verwendet");- m.put("Optionally specify uid:gid to run container as. <b class='text-warning'>Note:</b> This setting should be left empty if container runtime is rootless or using user namespace remapping\n",- "Geben Sie optional uid:gid an, um den Container als auszuführen. <b class='text-warning'>Hinweis:</b> Diese Einstellung sollte leer gelassen werden, wenn der Container-Laufzeitumgebung rootless ist oder Benutzer-Namespace-Remapping verwendet\n");m.put("Optionally specify user name to access remote repository", "Optional geben Sie den Benutzernamen für den Zugriff auf das Remote-Repository an");m.put("Optionally specify valid scopes of conventional commits (hit ENTER to add value). Leave empty to allow arbitrary scope","Optional geben Sie gültige Bereiche für konventionelle Commits an (drücken Sie ENTER, um einen Wert hinzuzufügen). Leer lassen, um beliebige Bereiche zuzulassen");@@ -3949,6 +3941,7 @@ public class Translation_de extends TranslationResourceBundle {m.put("Specify timeout in seconds when communicating with mail server", "Geben Sie das Timeout in Sekunden an, wenn mit dem Mailserver kommuniziert wird");m.put("Specify timeout in seconds. It counts from the time when job is submitted", "Geben Sie das Timeout in Sekunden an. Es zählt ab dem Zeitpunkt, an dem der Job eingereicht wird");m.put("Specify title of the issue", "Geben Sie den Titel des Problems an");+ m.put("Specify uid:gid to run container as", "Geben Sie uid:gid an, um den Container auszuführen als");m.put("Specify url of YouTrack API. For instance <tt>http://localhost:8080/api</tt>", "Geben Sie die URL der YouTrack-API an. Zum Beispiel <tt>http://localhost:8080/api</tt>");m.put("Specify user name of above machine for SSH authentication", "Geben Sie den Benutzernamen der oben genannten Maschine für die SSH-Authentifizierung an");m.put("Specify user name of specified registry", "Geben Sie den Benutzernamen des angegebenen Registrierungsdienstes an");diff --git a/server-core/src/main/java/io/onedev/server/web/translation/Translation_es.java b/server-core/src/main/java/io/onedev/server/web/translation/Translation_es.javaindex 58b42fca87..fbf1aad499 100644--- a/server-core/src/main/java/io/onedev/server/web/translation/Translation_es.java+++ b/server-core/src/main/java/io/onedev/server/web/translation/Translation_es.java@@ -575,6 +575,7 @@ public class Translation_es extends TranslationResourceBundle {m.put("CPU Intensive Task Concurrency", "Concurrencia de Tareas Intensivas de CPU");m.put("CPU capability in millis. This is normally (CPU cores)*1000", "Capacidad de CPU en milisegundos. Esto normalmente es (núcleos de CPU)*1000");m.put("CPU cores", "Núcleos de CPU");+ m.put("Cache \"{0} (checksum: {1})\" deleted", "Cache \"{0} (checksum: {1})\" eliminado");m.put("Cache \"{0}\" deleted", "Caché \"{0}\" eliminado");m.put("Cache Config", "Configuración de Caché");m.put("Cache Key", "Clave de Caché");@@ -1440,7 +1441,6 @@ public class Translation_es extends TranslationResourceBundle {m.put("File is binary", "El archivo es binario");m.put("File is too large to be displayed", "El archivo es demasiado grande para ser mostrado");m.put("File is too large to edit here", "El archivo es demasiado grande para editar aquí");- m.put("File missing or obsolete", "Archivo faltante u obsoleto");m.put("File name", "Nombre del archivo");m.put("File name patterns such as *.java, *.c", "Patrones de nombre de archivo como *.java, *.c");m.put("Files", "Archivos");@@ -2514,8 +2514,6 @@ public class Translation_es extends TranslationResourceBundle {m.put("Optionally specify Dockerfile relative to <a href='https://docs.onedev.io/concepts#job-workdir' target='_blank'>job working directory</a>. Leave empty to use file <tt>Dockerfile</tt> under build path specified above","Opcionalmente especifique el Dockerfile relativo al <a href='https://docs.onedev.io/concepts#job-workdir' target='_blank'>espacio de trabajo del trabajo</a>. Déjelo vacío para usar el archivo <tt>Dockerfile</tt> bajo la ruta de construcción especificada anteriormente.");m.put("Optionally specify JavaScript config to be used by Renovate CLI", "Opcionalmente especifique la configuración de JavaScript para usar con Renovate CLI.");- m.put("Optionally specify PowerShell commands to run to set up the workspace. These commands\nwill run from working directory holding cloned repository files",- "Opcionalmente especifique comandos de PowerShell para ejecutar para configurar el espacio de trabajo. Estos comandos\nse ejecutarán desde el directorio de trabajo que contiene los archivos del repositorio clonado");m.put("Optionally specify SSH root URL, which will be used to construct project clone url via SSH protocol. Leave empty to derive from server url","Opcionalmente especifique la URL raíz de SSH, que se utilizará para construir la URL de clonación del proyecto mediante el protocolo SSH. Déjelo vacío para derivarlo de la URL del servidor.");m.put("Optionally specify a <a href='http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html'>regular expression pattern</a> for valid values of the text input",@@ -2696,10 +2694,6 @@ public class Translation_es extends TranslationResourceBundle {"Opcionalmente especifique un directorio separado para almacenar archivos de paquetes. Un directorio no absoluto se considera relativo al directorio del sitio.");m.put("Optionally specify services required by this job. <b class='text-warning'>NOTE:</b> Services are only supported by docker aware executors (server docker executor, remote docker executor, or kubernetes executor)","Opcionalmente especifique servicios requeridos por este trabajo. <b class='text-warning'>NOTA:</b> Los servicios solo son compatibles con ejecutores conscientes de Docker (ejecutor de Docker del servidor, ejecutor de Docker remoto o ejecutor de Kubernetes).");- m.put("Optionally specify sh commands (on Linux/Unix) or batch commands (on Windows)\nto run to set up the workspace. These commands will run from working directory\nholding cloned repository files",- "Opcionalmente especifique comandos sh (en Linux/Unix) o comandos batch (en Windows)\npara ejecutar para configurar el espacio de trabajo. Estos comandos se ejecutarán desde el directorio de trabajo\nque contiene los archivos del repositorio clonado");- m.put("Optionally specify shell commands to run to set up the workspace. These commands will\nrun from working directory holding cloned repository files",- "Opcionalmente especifique comandos de shell para ejecutar para configurar el espacio de trabajo. Estos comandos se\nejecutarán desde el directorio de trabajo que contiene los archivos del repositorio clonado");m.put("Optionally specify space-separated branches applicable for this transition. Use '**', '*' or '?' for <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>path wildcard match</a>. Prefix with '-' to exclude. Leave empty to match all","Opcionalmente especifique ramas separadas por espacio aplicables para esta transición. Use '**', '*' o '?' para <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>coincidencia de comodines de ruta</a>. Prefijo con '-' para excluir. Déjelo vacío para coincidir con todas.");m.put("Optionally specify space-separated branches applicable for this trigger. Use '**', '*' or '?' for <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>path wildcard match</a>. Prefix with '-' to exclude. Leave empty for default branch",@@ -2734,8 +2728,6 @@ public class Translation_es extends TranslationResourceBundle {"Opcionalmente especifique el proyecto para publicar archivos del sitio. Deje vacío para publicar en el proyecto actual");m.put("Optionally specify uid:gid to run container as. <b class='text-warning'>Note:</b> This setting should be left empty if container runtime is rootless or using user namespace remapping","Opcionalmente especifique uid:gid para ejecutar el contenedor como. <b class='text-warning'>Nota:</b> Esta configuración debe dejarse vacía si el tiempo de ejecución del contenedor es sin raíz o utiliza remapeo de espacio de nombres de usuario");- m.put("Optionally specify uid:gid to run container as. <b class='text-warning'>Note:</b> This setting should be left empty if container runtime is rootless or using user namespace remapping\n",- "Opcionalmente especifique uid:gid para ejecutar el contenedor como. <b class='text-warning'>Nota:</b> Esta configuración debe dejarse vacía si el tiempo de ejecución del contenedor es sin root o usa remapeo de espacio de nombres de usuario\n");m.put("Optionally specify user name to access remote repository", "Opcionalmente especifique el nombre de usuario para acceder al repositorio remoto");m.put("Optionally specify valid scopes of conventional commits (hit ENTER to add value). Leave empty to allow arbitrary scope","Opcionalmente especifique alcances válidos de commits convencionales (presione ENTER para agregar valor). Deje vacío para permitir alcances arbitrarios");@@ -3949,6 +3941,7 @@ public class Translation_es extends TranslationResourceBundle {m.put("Specify timeout in seconds when communicating with mail server", "Especifique el tiempo de espera en segundos al comunicarse con el servidor de correo");m.put("Specify timeout in seconds. It counts from the time when job is submitted", "Especifique el tiempo de espera en segundos. Cuenta desde el momento en que se envía el trabajo");m.put("Specify title of the issue", "Especifique el título del problema");+ m.put("Specify uid:gid to run container as", "Especificar uid:gid para ejecutar el contenedor como");m.put("Specify url of YouTrack API. For instance <tt>http://localhost:8080/api</tt>", "Especifique la URL de la API de YouTrack. Por ejemplo <tt>http://localhost:8080/api</tt>");m.put("Specify user name of above machine for SSH authentication", "Especifique el nombre de usuario de la máquina anterior para la autenticación SSH");m.put("Specify user name of specified registry", "Especifique el nombre de usuario del registro especificado");diff --git a/server-core/src/main/java/io/onedev/server/web/translation/Translation_fr.java b/server-core/src/main/java/io/onedev/server/web/translation/Translation_fr.javaindex 63ea7d0d6e..ef431bf1ce 100644--- a/server-core/src/main/java/io/onedev/server/web/translation/Translation_fr.java+++ b/server-core/src/main/java/io/onedev/server/web/translation/Translation_fr.java@@ -575,6 +575,7 @@ public class Translation_fr extends TranslationResourceBundle {m.put("CPU Intensive Task Concurrency", "Concurrence des tâches intensives en CPU");m.put("CPU capability in millis. This is normally (CPU cores)*1000", "Capacité CPU en millis. Cela correspond normalement à (cœurs CPU)*1000");m.put("CPU cores", "Cœurs CPU");+ m.put("Cache \"{0} (checksum: {1})\" deleted", "Cache \"{0} (somme de contrôle : {1})\" supprimé");m.put("Cache \"{0}\" deleted", "Cache \"{0}\" supprimé");m.put("Cache Config", "Configuration de cache");m.put("Cache Key", "Clé de cache");@@ -1440,7 +1441,6 @@ public class Translation_fr extends TranslationResourceBundle {m.put("File is binary", "Le fichier est binaire");m.put("File is too large to be displayed", "Le fichier est trop grand pour être affiché");m.put("File is too large to edit here", "Le fichier est trop volumineux pour être édité ici");- m.put("File missing or obsolete", "Fichier manquant ou obsolète");m.put("File name", "Nom du fichier");m.put("File name patterns such as *.java, *.c", "Modèles de noms de fichiers tels que *.java, *.c");m.put("Files", "Fichiers");@@ -2514,8 +2514,6 @@ public class Translation_fr extends TranslationResourceBundle {m.put("Optionally specify Dockerfile relative to <a href='https://docs.onedev.io/concepts#job-workdir' target='_blank'>job working directory</a>. Leave empty to use file <tt>Dockerfile</tt> under build path specified above","Spécifiez éventuellement le Dockerfile relatif à <a href='https://docs.onedev.io/concepts#job-workdir' target='_blank'>l'espace de travail de la tâche</a>. Laissez vide pour utiliser le fichier <tt>Dockerfile</tt> sous le chemin de construction spécifié ci-dessus.");m.put("Optionally specify JavaScript config to be used by Renovate CLI", "Spécifiez éventuellement une configuration JavaScript à utiliser par Renovate CLI.");- m.put("Optionally specify PowerShell commands to run to set up the workspace. These commands\nwill run from working directory holding cloned repository files",- "Spécifiez éventuellement des commandes PowerShell à exécuter pour configurer l'espace de travail. Ces commandes\ns'exécuteront à partir du répertoire de travail contenant les fichiers du dépôt cloné");m.put("Optionally specify SSH root URL, which will be used to construct project clone url via SSH protocol. Leave empty to derive from server url","Spécifiez éventuellement une URL racine SSH, qui sera utilisée pour construire l'URL de clonage du projet via le protocole SSH. Laissez vide pour dériver de l'URL du serveur.");m.put("Optionally specify a <a href='http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html'>regular expression pattern</a> for valid values of the text input",@@ -2696,10 +2694,6 @@ public class Translation_fr extends TranslationResourceBundle {"Spécifiez éventuellement un répertoire séparé pour stocker les fichiers de package. Un répertoire non absolu est considéré comme relatif au répertoire du site.");m.put("Optionally specify services required by this job. <b class='text-warning'>NOTE:</b> Services are only supported by docker aware executors (server docker executor, remote docker executor, or kubernetes executor)","Spécifiez éventuellement les services requis par cette tâche. <b class='text-warning'>NOTE :</b> Les services ne sont pris en charge que par les exécuteurs compatibles avec docker (exécuteur docker serveur, exécuteur docker distant ou exécuteur Kubernetes).");- m.put("Optionally specify sh commands (on Linux/Unix) or batch commands (on Windows)\nto run to set up the workspace. These commands will run from working directory\nholding cloned repository files",- "Spécifiez éventuellement des commandes sh (sur Linux/Unix) ou des commandes batch (sur Windows)\nà exécuter pour configurer l'espace de travail. Ces commandes s'exécuteront à partir du répertoire de travail\ncontenant les fichiers du dépôt cloné");- m.put("Optionally specify shell commands to run to set up the workspace. These commands will\nrun from working directory holding cloned repository files",- "Spécifiez éventuellement des commandes shell à exécuter pour configurer l'espace de travail. Ces commandes s'exécuteront\nà partir du répertoire de travail contenant les fichiers du dépôt cloné");m.put("Optionally specify space-separated branches applicable for this transition. Use '**', '*' or '?' for <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>path wildcard match</a>. Prefix with '-' to exclude. Leave empty to match all","Spécifiez éventuellement les branches séparées par des espaces applicables à cette transition. Utilisez '**', '*' ou '?' pour <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>la correspondance de modèle de chemin</a>. Préfixez avec '-' pour exclure. Laissez vide pour correspondre à toutes.");m.put("Optionally specify space-separated branches applicable for this trigger. Use '**', '*' or '?' for <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>path wildcard match</a>. Prefix with '-' to exclude. Leave empty for default branch",@@ -2734,8 +2728,6 @@ public class Translation_fr extends TranslationResourceBundle {"Spécifiez éventuellement le projet pour publier les fichiers du site. Laissez vide pour publier dans le projet actuel");m.put("Optionally specify uid:gid to run container as. <b class='text-warning'>Note:</b> This setting should be left empty if container runtime is rootless or using user namespace remapping","Spécifiez éventuellement uid:gid pour exécuter le conteneur. <b class='text-warning'>Remarque :</b> Ce paramètre doit être laissé vide si le runtime du conteneur est sans privilège ou utilise le remappage de l'espace utilisateur");- m.put("Optionally specify uid:gid to run container as. <b class='text-warning'>Note:</b> This setting should be left empty if container runtime is rootless or using user namespace remapping\n",- "Spécifiez éventuellement uid:gid pour exécuter le conteneur en tant que tel. <b class='text-warning'>Remarque :</b> Ce paramètre doit être laissé vide si le runtime du conteneur est sans privilèges ou utilise le remappage de l'espace utilisateur\n");m.put("Optionally specify user name to access remote repository", "Spécifiez éventuellement le nom d'utilisateur pour accéder au dépôt distant");m.put("Optionally specify valid scopes of conventional commits (hit ENTER to add value). Leave empty to allow arbitrary scope","Spécifiez éventuellement des portées valides pour les commits conventionnels (appuyez sur ENTRÉE pour ajouter une valeur). Laissez vide pour autoriser une portée arbitraire");@@ -3949,6 +3941,7 @@ public class Translation_fr extends TranslationResourceBundle {m.put("Specify timeout in seconds when communicating with mail server", "Spécifiez le délai d'attente en secondes lors de la communication avec le serveur de messagerie");m.put("Specify timeout in seconds. It counts from the time when job is submitted", "Spécifiez le délai d'attente en secondes. Il commence à partir du moment où le travail est soumis");m.put("Specify title of the issue", "Spécifiez le titre du problème");+ m.put("Specify uid:gid to run container as", "Spécifiez uid:gid pour exécuter le conteneur en tant que");m.put("Specify url of YouTrack API. For instance <tt>http://localhost:8080/api</tt>", "Spécifiez l'URL de l'API YouTrack. Par exemple <tt>http://localhost:8080/api</tt>");m.put("Specify user name of above machine for SSH authentication", "Spécifiez le nom d'utilisateur de la machine ci-dessus pour l'authentification SSH");m.put("Specify user name of specified registry", "Spécifiez le nom d'utilisateur du registre spécifié");diff --git a/server-core/src/main/java/io/onedev/server/web/translation/Translation_it.java b/server-core/src/main/java/io/onedev/server/web/translation/Translation_it.javaindex 0e3b3546e7..683623b72f 100644--- a/server-core/src/main/java/io/onedev/server/web/translation/Translation_it.java+++ b/server-core/src/main/java/io/onedev/server/web/translation/Translation_it.java@@ -575,6 +575,7 @@ public class Translation_it extends TranslationResourceBundle {m.put("CPU Intensive Task Concurrency", "Concorrenza dei task intensivi per CPU");m.put("CPU capability in millis. This is normally (CPU cores)*1000", "Capacità della CPU in millis. Normalmente è (core CPU)*1000");m.put("CPU cores", "Core CPU");+ m.put("Cache \"{0} (checksum: {1})\" deleted", "Cache \"{0} (checksum: {1})\" eliminata");m.put("Cache \"{0}\" deleted", "Cache \"{0}\" eliminata");m.put("Cache Config", "Configurazione Cache");m.put("Cache Key", "Chiave della cache");@@ -1440,7 +1441,6 @@ public class Translation_it extends TranslationResourceBundle {m.put("File is binary", "Il file è binario");m.put("File is too large to be displayed", "Il file è troppo grande per essere visualizzato");m.put("File is too large to edit here", "Il file è troppo grande per essere modificato qui");- m.put("File missing or obsolete", "File mancante o obsoleto");m.put("File name", "nome file");m.put("File name patterns such as *.java, *.c", "modelli nome file come *.java, *.c");m.put("Files", "File");@@ -2514,8 +2514,6 @@ public class Translation_it extends TranslationResourceBundle {m.put("Optionally specify Dockerfile relative to <a href='https://docs.onedev.io/concepts#job-workdir' target='_blank'>job working directory</a>. Leave empty to use file <tt>Dockerfile</tt> under build path specified above","Specifica facoltativamente il Dockerfile relativo a <a href='https://docs.onedev.io/concepts#job-workdir' target='_blank'>job working directory</a>. Lascia vuoto per utilizzare il file <tt>Dockerfile</tt> sotto il percorso di build specificato sopra");m.put("Optionally specify JavaScript config to be used by Renovate CLI", "Specifica facoltativamente la configurazione JavaScript da utilizzare con la CLI di Renovate");- m.put("Optionally specify PowerShell commands to run to set up the workspace. These commands\nwill run from working directory holding cloned repository files",- "Specifica facoltativamente i comandi PowerShell da eseguire per configurare l'ambiente di lavoro. Questi comandi\nverranno eseguiti dalla directory di lavoro che contiene i file del repository clonato");m.put("Optionally specify SSH root URL, which will be used to construct project clone url via SSH protocol. Leave empty to derive from server url","Specifica facoltativamente l'URL root SSH, che verrà utilizzato per costruire l'URL di clonazione del progetto tramite protocollo SSH. Lascia vuoto per derivarlo dall'URL del server");m.put("Optionally specify a <a href='http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html'>regular expression pattern</a> for valid values of the text input",@@ -2696,10 +2694,6 @@ public class Translation_it extends TranslationResourceBundle {"Specifica facoltativamente una directory separata per archiviare i file dei pacchetti. Una directory non assoluta è considerata relativa alla directory del sito");m.put("Optionally specify services required by this job. <b class='text-warning'>NOTE:</b> Services are only supported by docker aware executors (server docker executor, remote docker executor, or kubernetes executor)","Specifica facoltativamente i servizi richiesti da questo job. <b class='text-warning'>NOTA:</b> I servizi sono supportati solo dagli esecutori consapevoli di docker (esecutore docker del server, esecutore docker remoto o esecutore Kubernetes)");- m.put("Optionally specify sh commands (on Linux/Unix) or batch commands (on Windows)\nto run to set up the workspace. These commands will run from working directory\nholding cloned repository files",- "Specifica facoltativamente i comandi sh (su Linux/Unix) o i comandi batch (su Windows)\nda eseguire per configurare l'ambiente di lavoro. Questi comandi verranno eseguiti dalla directory di lavoro\nche contiene i file del repository clonato");- m.put("Optionally specify shell commands to run to set up the workspace. These commands will\nrun from working directory holding cloned repository files",- "Specifica facoltativamente i comandi shell da eseguire per configurare l'ambiente di lavoro. Questi comandi verranno\neseguiti dalla directory di lavoro che contiene i file del repository clonato");m.put("Optionally specify space-separated branches applicable for this transition. Use '**', '*' or '?' for <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>path wildcard match</a>. Prefix with '-' to exclude. Leave empty to match all","Specifica facoltativamente i rami separati da spazio applicabili per questa transizione. Usa '**', '*' o '?' per <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>la corrispondenza dei modelli di percorso</a>. Prefissa con '-' per escludere. Lascia vuoto per corrispondere a tutti");m.put("Optionally specify space-separated branches applicable for this trigger. Use '**', '*' or '?' for <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>path wildcard match</a>. Prefix with '-' to exclude. Leave empty for default branch",@@ -2734,8 +2728,6 @@ public class Translation_it extends TranslationResourceBundle {"Specifica facoltativamente il progetto a cui pubblicare i file del sito. Lascia vuoto per pubblicare nel progetto corrente");m.put("Optionally specify uid:gid to run container as. <b class='text-warning'>Note:</b> This setting should be left empty if container runtime is rootless or using user namespace remapping","Specifica facoltativamente uid:gid per eseguire il container. <b class='text-warning'>Nota:</b> Questa impostazione dovrebbe essere lasciata vuota se il runtime del container è rootless o utilizza il remapping dello spazio utente");- m.put("Optionally specify uid:gid to run container as. <b class='text-warning'>Note:</b> This setting should be left empty if container runtime is rootless or using user namespace remapping\n",- "Specifica facoltativamente uid:gid per eseguire il container. <b class='text-warning'>Nota:</b> Questa impostazione dovrebbe essere lasciata vuota se il runtime del container è senza root o utilizza il remapping dello spazio dei nomi utente\n");m.put("Optionally specify user name to access remote repository", "Specifica facoltativamente il nome utente per accedere al repository remoto");m.put("Optionally specify valid scopes of conventional commits (hit ENTER to add value). Leave empty to allow arbitrary scope","Specifica facoltativamente ambiti validi per i commit convenzionali (premi INVIO per aggiungere un valore). Lascia vuoto per consentire ambiti arbitrari");@@ -3949,6 +3941,7 @@ public class Translation_it extends TranslationResourceBundle {m.put("Specify timeout in seconds when communicating with mail server", "Specifica il timeout in secondi durante la comunicazione con il server di posta");m.put("Specify timeout in seconds. It counts from the time when job is submitted", "Specifica il timeout in secondi. Si conta dal momento in cui il job viene inviato");m.put("Specify title of the issue", "Specifica il titolo dell'issue");+ m.put("Specify uid:gid to run container as", "Specificare uid:gid per eseguire il container come");m.put("Specify url of YouTrack API. For instance <tt>http://localhost:8080/api</tt>", "Specifica l'URL dell'API di YouTrack. Ad esempio <tt>http://localhost:8080/api</tt>");m.put("Specify user name of above machine for SSH authentication", "Specifica il nome utente della macchina sopra per l'autenticazione SSH");m.put("Specify user name of specified registry", "Specifica il nome utente del registro specificato");diff --git a/server-core/src/main/java/io/onedev/server/web/translation/Translation_ja.java b/server-core/src/main/java/io/onedev/server/web/translation/Translation_ja.javaindex 1aa5c30f87..9f5f8620fc 100644--- a/server-core/src/main/java/io/onedev/server/web/translation/Translation_ja.java+++ b/server-core/src/main/java/io/onedev/server/web/translation/Translation_ja.java@@ -575,6 +575,7 @@ public class Translation_ja extends TranslationResourceBundle {m.put("CPU Intensive Task Concurrency", "CPU集約タスクの並行性");m.put("CPU capability in millis. This is normally (CPU cores)*1000", "ミリ秒単位のCPU能力。通常は(CPUコア数)*1000");m.put("CPU cores", "CPUコア");+ m.put("Cache \"{0} (checksum: {1})\" deleted", "キャッシュ「{0} (チェックサム: {1})」が削除されました");m.put("Cache \"{0}\" deleted", "キャッシュ\"{0}\"が削除されました");m.put("Cache Config", "キャッシュ設定");m.put("Cache Key", "キャッシュキー");@@ -1440,7 +1441,6 @@ public class Translation_ja extends TranslationResourceBundle {m.put("File is binary", "ファイルはバイナリです");m.put("File is too large to be displayed", "ファイルが大きすぎて表示できません");m.put("File is too large to edit here", "ファイルが大きすぎてここでは編集できません");- m.put("File missing or obsolete", "ファイルが欠落しているか廃止されています");m.put("File name", "ファイル名");m.put("File name patterns such as *.java, *.c", "ファイル名パターン(例: *.java, *.c)");m.put("Files", "ファイル一覧");@@ -2514,8 +2514,6 @@ public class Translation_ja extends TranslationResourceBundle {m.put("Optionally specify Dockerfile relative to <a href='https://docs.onedev.io/concepts#job-workdir' target='_blank'>job working directory</a>. Leave empty to use file <tt>Dockerfile</tt> under build path specified above","オプションで、<a href='https://docs.onedev.io/concepts#job-workdir' target='_blank'>ジョブワークスペース</a>に対するDockerfileの相対パスを指定してください。上記で指定したビルドパスの下にある<tt>Dockerfile</tt>ファイルを使用する場合は空のままにしてください。");m.put("Optionally specify JavaScript config to be used by Renovate CLI", "オプションで、Renovate CLIで使用するJavaScript設定を指定してください。");- m.put("Optionally specify PowerShell commands to run to set up the workspace. These commands\nwill run from working directory holding cloned repository files",- "オプションでワークスペースをセットアップするために実行するPowerShellコマンドを指定します。これらのコマンドは\nクローンされたリポジトリファイルを保持する作業ディレクトリから実行されます");m.put("Optionally specify SSH root URL, which will be used to construct project clone url via SSH protocol. Leave empty to derive from server url","オプションで、SSHルートURLを指定してください。これはSSHプロトコルを介してプロジェクトクローンURLを構築するために使用されます。サーバーURLから派生する場合は空のままにしてください。");m.put("Optionally specify a <a href='http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html'>regular expression pattern</a> for valid values of the text input",@@ -2696,10 +2694,6 @@ public class Translation_ja extends TranslationResourceBundle {"オプションで、パッケージファイルを保存するための別のディレクトリを指定してください。絶対ディレクトリでない場合、サイトディレクトリに対する相対ディレクトリと見なされます。");m.put("Optionally specify services required by this job. <b class='text-warning'>NOTE:</b> Services are only supported by docker aware executors (server docker executor, remote docker executor, or kubernetes executor)","オプションで、このジョブに必要なサービスを指定してください。<b class='text-warning'>注意:</b> サービスはDocker対応エグゼキューター(サーバーDockerエグゼキューター、リモートDockerエグゼキューター、またはKubernetesエグゼキューター)のみでサポートされています。");- m.put("Optionally specify sh commands (on Linux/Unix) or batch commands (on Windows)\nto run to set up the workspace. These commands will run from working directory\nholding cloned repository files",- "ワークスペースをセットアップするために実行するshコマンド(Linux/Unix)またはバッチコマンド(Windows)をオプションで指定します。\nこれらのコマンドはクローンされたリポジトリファイルを保持する作業ディレクトリから実行されます\n");- m.put("Optionally specify shell commands to run to set up the workspace. These commands will\nrun from working directory holding cloned repository files",- "ワークスペースをセットアップするために実行するシェルコマンドをオプションで指定します。これらのコマンドは\nクローンされたリポジトリファイルを保持する作業ディレクトリから実行されます");m.put("Optionally specify space-separated branches applicable for this transition. Use '**', '*' or '?' for <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>path wildcard match</a>. Prefix with '-' to exclude. Leave empty to match all","オプションで、この遷移に適用されるスペース区切りのブランチを指定してください。<a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>パスワイルドカードマッチ</a>には'**'、'*'または'?'を使用してください。'-'で除外を指定してください。すべてに一致する場合は空のままにしてください。");m.put("Optionally specify space-separated branches applicable for this trigger. Use '**', '*' or '?' for <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>path wildcard match</a>. Prefix with '-' to exclude. Leave empty for default branch",@@ -2734,8 +2728,6 @@ public class Translation_ja extends TranslationResourceBundle {"必要に応じてサイトファイルを公開するプロジェクトを指定します。空欄の場合は現在のプロジェクトに公開されます");m.put("Optionally specify uid:gid to run container as. <b class='text-warning'>Note:</b> This setting should be left empty if container runtime is rootless or using user namespace remapping","必要に応じてコンテナを実行するuid:gidを指定します。<b class='text-warning'>注意:</b> コンテナランタイムがルートレスまたはユーザー名前空間リマッピングを使用している場合、この設定は空欄にする必要があります");- m.put("Optionally specify uid:gid to run container as. <b class='text-warning'>Note:</b> This setting should be left empty if container runtime is rootless or using user namespace remapping\n",- "コンテナを実行するためのuid:gidをオプションで指定します。<b class='text-warning'>注意:</b> コンテナランタイムがルートレスまたはユーザーネームスペースリマッピングを使用している場合、この設定は空のままにしてください\n");m.put("Optionally specify user name to access remote repository", "必要に応じてリモートリポジトリにアクセスするためのユーザー名を指定します");m.put("Optionally specify valid scopes of conventional commits (hit ENTER to add value). Leave empty to allow arbitrary scope","必要に応じて従来のコミットの有効なスコープを指定します(ENTERキーを押して値を追加)。空欄の場合は任意のスコープを許可します");@@ -3949,6 +3941,7 @@ public class Translation_ja extends TranslationResourceBundle {m.put("Specify timeout in seconds when communicating with mail server", "メールサーバーと通信する際のタイムアウトを秒単位で指定してください。");m.put("Specify timeout in seconds. It counts from the time when job is submitted", "ジョブが送信されてからのタイムアウトを秒単位で指定してください。");m.put("Specify title of the issue", "問題のタイトルを指定してください。");+ m.put("Specify uid:gid to run container as", "コンテナを実行するためのuid:gidを指定してください");m.put("Specify url of YouTrack API. For instance <tt>http://localhost:8080/api</tt>", "YouTrack APIのURLを指定してください。例: <tt>http://localhost:8080/api</tt>");m.put("Specify user name of above machine for SSH authentication", "SSH認証のための上記マシンのユーザー名を指定してください。");m.put("Specify user name of specified registry", "指定されたレジストリのユーザー名を指定してください。");diff --git a/server-core/src/main/java/io/onedev/server/web/translation/Translation_ko.java b/server-core/src/main/java/io/onedev/server/web/translation/Translation_ko.javaindex c26b72aa07..e625304b55 100644--- a/server-core/src/main/java/io/onedev/server/web/translation/Translation_ko.java+++ b/server-core/src/main/java/io/onedev/server/web/translation/Translation_ko.java@@ -575,6 +575,7 @@ public class Translation_ko extends TranslationResourceBundle {m.put("CPU Intensive Task Concurrency", "CPU 집약적 작업 동시성");m.put("CPU capability in millis. This is normally (CPU cores)*1000", "밀리초 단위의 CPU 성능. 일반적으로 (CPU 코어)*1000입니다");m.put("CPU cores", "CPU 코어");+ m.put("Cache \"{0} (checksum: {1})\" deleted", "캐시 \"{0} (체크섬: {1})\" 삭제됨");m.put("Cache \"{0}\" deleted", "캐시 \"{0}\" 삭제됨");m.put("Cache Config", "캐시 구성");m.put("Cache Key", "캐시 키");@@ -1440,7 +1441,6 @@ public class Translation_ko extends TranslationResourceBundle {m.put("File is binary", "파일이 바이너리입니다");m.put("File is too large to be displayed", "파일이 너무 커서 표시할 수 없습니다");m.put("File is too large to edit here", "파일이 너무 커서 여기서 편집할 수 없습니다");- m.put("File missing or obsolete", "파일 누락 또는 오래됨");m.put("File name", "파일 이름");m.put("File name patterns such as *.java, *.c", "파일 이름 패턴 예: *.java, *.c");m.put("Files", "파일들");@@ -2514,8 +2514,6 @@ public class Translation_ko extends TranslationResourceBundle {m.put("Optionally specify Dockerfile relative to <a href='https://docs.onedev.io/concepts#job-workdir' target='_blank'>job working directory</a>. Leave empty to use file <tt>Dockerfile</tt> under build path specified above","선택적으로 <a href='https://docs.onedev.io/concepts#job-workdir' target='_blank'>작업 워크스페이스</a>에 상대적인 Dockerfile을 지정하세요. 위에서 지정한 빌드 경로 아래의 <tt>Dockerfile</tt> 파일을 사용하려면 비워 두세요.");m.put("Optionally specify JavaScript config to be used by Renovate CLI", "선택적으로 Renovate CLI에서 사용할 JavaScript 구성을 지정하세요.");- m.put("Optionally specify PowerShell commands to run to set up the workspace. These commands\nwill run from working directory holding cloned repository files",- "워크스페이스를 설정하기 위해 실행할 PowerShell 명령을 선택적으로 지정합니다. 이러한 명령은\n클론된 저장소 파일을 보유한 작업 디렉토리에서 실행됩니다");m.put("Optionally specify SSH root URL, which will be used to construct project clone url via SSH protocol. Leave empty to derive from server url","선택적으로 SSH 루트 URL을 지정하세요. 이는 SSH 프로토콜을 통해 프로젝트 클론 URL을 구성하는 데 사용됩니다. 서버 URL에서 파생하려면 비워 두세요.");m.put("Optionally specify a <a href='http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html'>regular expression pattern</a> for valid values of the text input",@@ -2696,10 +2694,6 @@ public class Translation_ko extends TranslationResourceBundle {"선택적으로 패키지 파일을 저장할 별도의 디렉터리를 지정하세요. 절대 디렉터리가 아닌 경우 사이트 디렉터리에 상대적으로 간주됩니다.");m.put("Optionally specify services required by this job. <b class='text-warning'>NOTE:</b> Services are only supported by docker aware executors (server docker executor, remote docker executor, or kubernetes executor)","선택적으로 이 작업에 필요한 서비스를 지정하세요. <b class='text-warning'>참고:</b> 서비스는 Docker를 인식하는 실행자(서버 Docker 실행자, 원격 Docker 실행자 또는 Kubernetes 실행자)에서만 지원됩니다.");- m.put("Optionally specify sh commands (on Linux/Unix) or batch commands (on Windows)\nto run to set up the workspace. These commands will run from working directory\nholding cloned repository files",- "워크스페이스를 설정하기 위해 실행할 sh 명령(Linux/Unix) 또는 배치 명령(Windows)을 선택적으로 지정합니다.\n이러한 명령은 클론된 저장소 파일을 보유한 작업 디렉토리에서 실행됩니다");- m.put("Optionally specify shell commands to run to set up the workspace. These commands will\nrun from working directory holding cloned repository files",- "워크스페이스를 설정하기 위해 실행할 셸 명령을 선택적으로 지정합니다. 이러한 명령은\n클론된 저장소 파일을 보유한 작업 디렉토리에서 실행됩니다");m.put("Optionally specify space-separated branches applicable for this transition. Use '**', '*' or '?' for <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>path wildcard match</a>. Prefix with '-' to exclude. Leave empty to match all","선택적으로 이 전환에 적용 가능한 공백으로 구분된 브랜치를 지정하세요. <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>경로 와일드카드 매칭</a>을 위해 '**', '*' 또는 '?'를 사용하세요. 제외하려면 '-'로 접두어를 붙이세요. 모든 브랜치를 일치시키려면 비워 두세요.");m.put("Optionally specify space-separated branches applicable for this trigger. Use '**', '*' or '?' for <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>path wildcard match</a>. Prefix with '-' to exclude. Leave empty for default branch",@@ -2734,8 +2728,6 @@ public class Translation_ko extends TranslationResourceBundle {"선택적으로 사이트 파일을 게시할 프로젝트를 지정하십시오. 현재 프로젝트에 게시하려면 비워두십시오.");m.put("Optionally specify uid:gid to run container as. <b class='text-warning'>Note:</b> This setting should be left empty if container runtime is rootless or using user namespace remapping","선택적으로 컨테이너를 실행할 uid:gid를 지정하십시오. <b class='text-warning'>참고:</b> 컨테이너 런타임이 루트리스이거나 사용자 네임스페이스 리매핑을 사용하는 경우 이 설정을 비워두어야 합니다.");- m.put("Optionally specify uid:gid to run container as. <b class='text-warning'>Note:</b> This setting should be left empty if container runtime is rootless or using user namespace remapping\n",- "컨테이너를 실행할 uid:gid를 선택적으로 지정합니다. <b class='text-warning'>참고:</b> 컨테이너 런타임이 루트리스이거나 사용자 네임스페이스 리매핑을 사용하는 경우 이 설정을 비워 두어야 합니다\n");m.put("Optionally specify user name to access remote repository", "선택적으로 원격 저장소에 접근할 사용자 이름을 지정하십시오.");m.put("Optionally specify valid scopes of conventional commits (hit ENTER to add value). Leave empty to allow arbitrary scope","선택적으로 유효한 컨벤션 커밋 범위를 지정하십시오 (값을 추가하려면 ENTER를 누르십시오). 비워두면 임의의 범위를 허용합니다.");@@ -3949,6 +3941,7 @@ public class Translation_ko extends TranslationResourceBundle {m.put("Specify timeout in seconds when communicating with mail server", "메일 서버와 통신할 때의 타임아웃(초)을 지정하십시오.");m.put("Specify timeout in seconds. It counts from the time when job is submitted", "작업이 제출된 시점부터의 타임아웃(초)을 지정하십시오.");m.put("Specify title of the issue", "이슈 제목을 지정하십시오.");+ m.put("Specify uid:gid to run container as", "컨테이너를 실행할 uid:gid 지정");m.put("Specify url of YouTrack API. For instance <tt>http://localhost:8080/api</tt>", "YouTrack API의 URL을 지정하십시오. 예를 들어 <tt>http://localhost:8080/api</tt>.");m.put("Specify user name of above machine for SSH authentication", "SSH 인증을 위한 위 머신의 사용자 이름을 지정하십시오.");m.put("Specify user name of specified registry", "지정된 레지스트리의 사용자 이름을 지정하십시오.");diff --git a/server-core/src/main/java/io/onedev/server/web/translation/Translation_pt.java b/server-core/src/main/java/io/onedev/server/web/translation/Translation_pt.javaindex 608d982858..62bf176576 100644--- a/server-core/src/main/java/io/onedev/server/web/translation/Translation_pt.java+++ b/server-core/src/main/java/io/onedev/server/web/translation/Translation_pt.java@@ -575,6 +575,7 @@ public class Translation_pt extends TranslationResourceBundle {m.put("CPU Intensive Task Concurrency", "Concorrência de Tarefa Intensiva de CPU");m.put("CPU capability in millis. This is normally (CPU cores)*1000", "Capacidade de CPU em millis. Normalmente é (núcleos de CPU)*1000");m.put("CPU cores", "Núcleos de CPU");+ m.put("Cache \"{0} (checksum: {1})\" deleted", "Cache \"{0} (checksum: {1})\" excluído");m.put("Cache \"{0}\" deleted", "Cache \"{0}\" excluído");m.put("Cache Config", "Configuração de Cache");m.put("Cache Key", "Chave de Cache");@@ -1440,7 +1441,6 @@ public class Translation_pt extends TranslationResourceBundle {m.put("File is binary", "Arquivo é binário");m.put("File is too large to be displayed", "Arquivo é muito grande para ser exibido");m.put("File is too large to edit here", "Arquivo muito grande para editar aqui");- m.put("File missing or obsolete", "Arquivo ausente ou obsoleto");m.put("File name", "nome do arquivo");m.put("File name patterns such as *.java, *.c", "Padrões de nome de arquivo como *.java, *.c");m.put("Files", "Arquivos");@@ -2514,8 +2514,6 @@ public class Translation_pt extends TranslationResourceBundle {m.put("Optionally specify Dockerfile relative to <a href='https://docs.onedev.io/concepts#job-workdir' target='_blank'>job working directory</a>. Leave empty to use file <tt>Dockerfile</tt> under build path specified above","Opcionalmente especifique o Dockerfile relativo ao <a href='https://docs.onedev.io/concepts#job-workdir' target='_blank'>espaço de trabalho do trabalho</a>. Deixe vazio para usar o arquivo <tt>Dockerfile</tt> no caminho de construção especificado acima");m.put("Optionally specify JavaScript config to be used by Renovate CLI", "Opcionalmente especifique a configuração JavaScript a ser usada pelo Renovate CLI");- m.put("Optionally specify PowerShell commands to run to set up the workspace. These commands\nwill run from working directory holding cloned repository files",- "Opcionalmente especifique comandos PowerShell para executar a configuração do espaço de trabalho. Esses comandos\nserão executados a partir do diretório de trabalho que contém os arquivos do repositório clonado");m.put("Optionally specify SSH root URL, which will be used to construct project clone url via SSH protocol. Leave empty to derive from server url","Opcionalmente especifique a URL raiz SSH, que será usada para construir a URL de clonagem do projeto via protocolo SSH. Deixe vazio para derivar da URL do servidor");m.put("Optionally specify a <a href='http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html'>regular expression pattern</a> for valid values of the text input",@@ -2696,10 +2694,6 @@ public class Translation_pt extends TranslationResourceBundle {"Opcionalmente especifique diretório separado para armazenar arquivos de pacote. Diretório não absoluto é considerado relativo ao diretório do site");m.put("Optionally specify services required by this job. <b class='text-warning'>NOTE:</b> Services are only supported by docker aware executors (server docker executor, remote docker executor, or kubernetes executor)","Opcionalmente especifique serviços necessários para este trabalho. <b class='text-warning'>NOTA:</b> Serviços são suportados apenas por executores compatíveis com docker (executor docker do servidor, executor docker remoto, ou executor kubernetes)");- m.put("Optionally specify sh commands (on Linux/Unix) or batch commands (on Windows)\nto run to set up the workspace. These commands will run from working directory\nholding cloned repository files",- "Opcionalmente especifique comandos sh (em Linux/Unix) ou comandos batch (em Windows)\npara executar a configuração do espaço de trabalho. Esses comandos serão executados a partir do diretório de trabalho\nque contém os arquivos do repositório clonado");- m.put("Optionally specify shell commands to run to set up the workspace. These commands will\nrun from working directory holding cloned repository files",- "Opcionalmente especifique comandos de shell para executar a configuração do espaço de trabalho. Esses comandos serão\nexecutados a partir do diretório de trabalho que contém os arquivos do repositório clonado");m.put("Optionally specify space-separated branches applicable for this transition. Use '**', '*' or '?' for <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>path wildcard match</a>. Prefix with '-' to exclude. Leave empty to match all","Opcionalmente especifique branches separados por espaço aplicáveis para esta transição. Use '**', '*' ou '?' para <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>correspondência de curinga de caminho</a>. Prefixe com '-' para excluir. Deixe vazio para corresponder a todos");m.put("Optionally specify space-separated branches applicable for this trigger. Use '**', '*' or '?' for <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>path wildcard match</a>. Prefix with '-' to exclude. Leave empty for default branch",@@ -2734,8 +2728,6 @@ public class Translation_pt extends TranslationResourceBundle {"Opcionalmente especifique o projeto para publicar arquivos do site. Deixe vazio para publicar no projeto atual");m.put("Optionally specify uid:gid to run container as. <b class='text-warning'>Note:</b> This setting should be left empty if container runtime is rootless or using user namespace remapping","Opcionalmente especifique uid:gid para executar o contêiner. <b class='text-warning'>Nota:</b> Esta configuração deve ser deixada vazia se o runtime do contêiner for rootless ou estiver usando remapeamento de namespace de usuário");- m.put("Optionally specify uid:gid to run container as. <b class='text-warning'>Note:</b> This setting should be left empty if container runtime is rootless or using user namespace remapping\n",- "Opcionalmente especifique uid:gid para executar o contêiner como. <b class='text-warning'>Nota:</b> Esta configuração deve ser deixada vazia se o runtime do contêiner for rootless ou usar remapeamento de namespace de usuário\n");m.put("Optionally specify user name to access remote repository", "Opcionalmente especifique o nome de usuário para acessar o repositório remoto");m.put("Optionally specify valid scopes of conventional commits (hit ENTER to add value). Leave empty to allow arbitrary scope","Opcionalmente especifique escopos válidos de commits convencionais (pressione ENTER para adicionar valor). Deixe vazio para permitir escopo arbitrário");@@ -3949,6 +3941,7 @@ public class Translation_pt extends TranslationResourceBundle {m.put("Specify timeout in seconds when communicating with mail server", "Especifique o tempo limite em segundos ao se comunicar com o servidor de e-mail");m.put("Specify timeout in seconds. It counts from the time when job is submitted", "Especifique o tempo limite em segundos. Ele conta a partir do momento em que o trabalho é submetido");m.put("Specify title of the issue", "Especifique o título do problema");+ m.put("Specify uid:gid to run container as", "Especifique uid:gid para executar o contêiner como");m.put("Specify url of YouTrack API. For instance <tt>http://localhost:8080/api</tt>", "Especifique a URL da API do YouTrack. Por exemplo <tt>http://localhost:8080/api</tt>");m.put("Specify user name of above machine for SSH authentication", "Especifique o nome de usuário da máquina acima para autenticação SSH");m.put("Specify user name of specified registry", "Especifique o nome de usuário do registro especificado");diff --git a/server-core/src/main/java/io/onedev/server/web/translation/Translation_zh.java b/server-core/src/main/java/io/onedev/server/web/translation/Translation_zh.javaindex f7f3b45735..6f5bc108b0 100644--- a/server-core/src/main/java/io/onedev/server/web/translation/Translation_zh.java+++ b/server-core/src/main/java/io/onedev/server/web/translation/Translation_zh.java@@ -601,6 +601,7 @@ public class Translation_zh extends TranslationResourceBundle {m.put("CPU Intensive Task Concurrency", "CPU 密集型任务并发数");m.put("CPU capability in millis. This is normally (CPU cores)*1000", "CPU 能力(毫秒)。通常为 (CPU 核心数)*1000");m.put("CPU cores", "CPU 核心");+ m.put("Cache \"{0} (checksum: {1})\" deleted", "缓存 \"{0} (checksum: {1})\" 已删除");m.put("Cache \"{0}\" deleted", "缓存 \"{0}\" 已删除");m.put("Cache Config", "缓存配置");m.put("Cache Key", "缓存键");@@ -1466,7 +1467,6 @@ public class Translation_zh extends TranslationResourceBundle {m.put("File is binary", "文件是二进制的");m.put("File is too large to be displayed", "文件太大,无法显示");m.put("File is too large to edit here", "文件太大,无法在此编辑");- m.put("File missing or obsolete", "文件缺失或过时");m.put("File name", "文件名");m.put("File name patterns such as *.java, *.c", "文件名模式,如 *.java, *.c");m.put("Files", "文件");@@ -2540,8 +2540,6 @@ public class Translation_zh extends TranslationResourceBundle {m.put("Optionally specify Dockerfile relative to <a href='https://docs.onedev.io/concepts#job-workdir' target='_blank'>job working directory</a>. Leave empty to use file <tt>Dockerfile</tt> under build path specified above","可选择指定相对于 <a href='https://docs.onedev.io/concepts#job-workdir' target='_blank'>任务工作区</a> 的 Dockerfile。留空则使用上面指定的构建路径下的文件 <tt>Dockerfile</tt>");m.put("Optionally specify JavaScript config to be used by Renovate CLI", "可选择指定用于 Renovate CLI 的 JavaScript 配置");- m.put("Optionally specify PowerShell commands to run to set up the workspace. These commands\nwill run from working directory holding cloned repository files",- "可选地指定要运行的 PowerShell 命令以设置工作区。这些命令\n将从持有克隆代码库文件的工作目录运行。");m.put("Optionally specify SSH root URL, which will be used to construct project clone url via SSH protocol. Leave empty to derive from server url","可选择指定 SSH 根 URL,用于通过 SSH 协议构造项目克隆 URL。留空则从服务器 URL 推导");m.put("Optionally specify a <a href='http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html'>regular expression pattern</a> for valid values of the text input",@@ -2722,10 +2720,6 @@ public class Translation_zh extends TranslationResourceBundle {"可选择指定单独的目录来存储包文件。非绝对目录被视为相对于站点目录");m.put("Optionally specify services required by this job. <b class='text-warning'>NOTE:</b> Services are only supported by docker aware executors (server docker executor, remote docker executor, or kubernetes executor)","可选择指定此任务所需的服务。<b class='text-warning'>注意:</b> 服务仅由支持 docker 的执行器(服务器 docker 执行器、远程 docker 执行器或 kubernetes 执行器)支持");- m.put("Optionally specify sh commands (on Linux/Unix) or batch commands (on Windows)\nto run to set up the workspace. These commands will run from working directory\nholding cloned repository files",- "可选地指定要运行的 sh 命令(在 Linux/Unix 上)或批处理命令(在 Windows 上)\n以设置工作区。这些命令将从持有克隆代码库文件的工作目录运行。\n");- m.put("Optionally specify shell commands to run to set up the workspace. These commands will\nrun from working directory holding cloned repository files",- "可选地指定要运行的 shell 命令以设置工作区。这些命令将\n从持有克隆代码库文件的工作目录运行。");m.put("Optionally specify space-separated branches applicable for this transition. Use '**', '*' or '?' for <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>path wildcard match</a>. Prefix with '-' to exclude. Leave empty to match all","可选择指定适用于此转换的以空格分隔的分支。使用 '**'、'*' 或 '?' 进行 <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>路径通配符匹配</a>。前缀 '-' 表示排除。留空则匹配所有");m.put("Optionally specify space-separated branches applicable for this trigger. Use '**', '*' or '?' for <a href='https://docs.onedev.io/appendix/path-wildcard' target='_blank'>path wildcard match</a>. Prefix with '-' to exclude. Leave empty for default branch",@@ -2760,8 +2754,6 @@ public class Translation_zh extends TranslationResourceBundle {"可选择指定要发布站点文件的项目。留空则发布到当前项目");m.put("Optionally specify uid:gid to run container as. <b class='text-warning'>Note:</b> This setting should be left empty if container runtime is rootless or using user namespace remapping","可选择指定要作为容器运行的 uid:gid。<b class='text-warning'>注意:</b>如果容器运行时是 rootless 或使用用户命名空间重新映射,则应留空此设置");- m.put("Optionally specify uid:gid to run container as. <b class='text-warning'>Note:</b> This setting should be left empty if container runtime is rootless or using user namespace remapping\n",- "可选地指定 uid:gid 以运行容器。<b class='text-warning'>注意:</b>如果容器运行时是无根的或使用用户命名空间重映射,则应将此设置留空。\n");m.put("Optionally specify user name to access remote repository", "可选择指定用于访问远程仓库的用户名");m.put("Optionally specify valid scopes of conventional commits (hit ENTER to add value). Leave empty to allow arbitrary scope","可选择指定有效的常规提交范围(按 ENTER 添加值)。留空则允许任意范围");@@ -3975,6 +3967,7 @@ public class Translation_zh extends TranslationResourceBundle {m.put("Specify timeout in seconds when communicating with mail server", "指定与邮件服务器通信时的超时时间(秒)");m.put("Specify timeout in seconds. It counts from the time when job is submitted", "指定超时时间(秒)。从任务提交时开始计算");m.put("Specify title of the issue", "指定工单的标题");+ m.put("Specify uid:gid to run container as", "指定 uid:gid 以容器身份运行");m.put("Specify url of YouTrack API. For instance <tt>http://localhost:8080/api</tt>", "指定 YouTrack API 的 URL。例如 <tt>http://localhost:8080/api</tt>");m.put("Specify user name of above machine for SSH authentication", "指定上述机器的用户名用于 SSH 身份验证");m.put("Specify user name of specified registry", "指定指定注册表的用户名");diff --git a/server-core/src/main/java/io/onedev/server/workspace/DefaultWorkspaceService.java b/server-core/src/main/java/io/onedev/server/workspace/DefaultWorkspaceService.javaindex 478b09fb74..e196d54aff 100644--- a/server-core/src/main/java/io/onedev/server/workspace/DefaultWorkspaceService.java+++ b/server-core/src/main/java/io/onedev/server/workspace/DefaultWorkspaceService.java@@ -5,7 +5,6 @@ import static io.onedev.server.util.SiteSyncUtils.readVersion;import static io.onedev.server.util.SiteSyncUtils.writeVersion;import static java.nio.charset.StandardCharsets.UTF_8;-import java.io.ByteArrayOutputStream;import java.io.File;import java.io.IOException;import java.io.ObjectStreamException;@@ -13,7 +12,6 @@ import java.io.Serializable;import java.io.UncheckedIOException;import java.util.ArrayDeque;import java.util.ArrayList;-import java.util.Arrays;import java.util.Collection;import java.util.Comparator;import java.util.Date;@@ -21,6 +19,7 @@ import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Objects;+import java.util.concurrent.CancellationException;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ExecutorService;import java.util.concurrent.Future;@@ -78,7 +77,6 @@ import io.onedev.server.event.system.SystemStopping;import io.onedev.server.exception.ServerNotFoundException;import io.onedev.server.git.CommandUtils;import io.onedev.server.git.GitTask;-import io.onedev.server.git.hook.HookUtils;import io.onedev.server.logging.LogService;import io.onedev.server.model.AbstractEntity;import io.onedev.server.model.Project;@@ -575,7 +573,10 @@ public class DefaultWorkspaceService extends BaseEntityService<Workspace>future.get();logger.error("Workspace runtime stopped for unknown reason");} catch (Throwable t) {- log(logger, t);+ if (ExceptionUtils.find(t, CancellationException.class) != null)+ logger.error("Workspace runtime stopped due to server restart. You may reprovision the workspace to continue your work");+ else+ log(logger, t);} finally {it.remove();markWorkspaceError(workspace);@@ -1084,19 +1085,14 @@ public class DefaultWorkspaceService extends BaseEntityService<Workspace>@Overridepublic GitExecutionResult executeGitCommand(Workspace workspace, String[] gitArgs) {var projectId = workspace.getProject().getId();- var workspaceNumber = workspace.getNumber();- var workspaceToken = workspace.getToken();+ var workspaceId = workspace.getId();return projectService.runOnActiveServer(projectId, () -> {- var git = CommandUtils.newGit();- var workDir = Workspace.getWorkDir(projectId, workspaceNumber);- git.workingDir(workDir);- git.environments().putAll(HookUtils.getWorkspacePostCommitHookEnvs(workspaceToken));- git.arguments(Arrays.asList(gitArgs));-- var stdoutStream = new ByteArrayOutputStream();- var stderrStream = new ByteArrayOutputStream();- var returnCode = git.execute(stdoutStream, stderrStream).getReturnCode();- return new GitExecutionResult(stdoutStream.toByteArray(), stderrStream.toByteArray(), returnCode);+ var runtime = workspaceRuntimes.get(workspaceId);+ if (runtime != null) {+ return runtime.executeGitCommand(gitArgs);+ } else {+ return new GitExecutionResult(new byte[0], "Workspace no longer active".getBytes(UTF_8), 1);+ }});}diff --git a/server-core/src/main/java/io/onedev/server/workspace/WorkspaceRuntime.java b/server-core/src/main/java/io/onedev/server/workspace/WorkspaceRuntime.javaindex aac720a560..00772d6cee 100644--- a/server-core/src/main/java/io/onedev/server/workspace/WorkspaceRuntime.java+++ b/server-core/src/main/java/io/onedev/server/workspace/WorkspaceRuntime.java@@ -37,6 +37,8 @@ public abstract class WorkspaceRuntime {return shellId;}+ public abstract GitExecutionResult executeGitCommand(String[] gitArgs);+public synchronized Map<String, String> getShellLabels() {return new LinkedHashMap<>(labels);}diff --git a/server-ee b/server-eeindex 15b502bc4a..1c5e70c65a 160000--- a/server-ee+++ b/server-ee@@ -1 +1 @@-Subproject commit 15b502bc4a777eaec2d8db129058de78bb4dd585+Subproject commit 1c5e70c65a5cb62afeec50fd180a5f7feb6bb3e3diff --git a/server-plugin/server-plugin-executor-kubernetes/src/main/java/io/onedev/server/plugin/executor/kubernetes/KubernetesExecutor.java b/server-plugin/server-plugin-executor-kubernetes/src/main/java/io/onedev/server/plugin/executor/kubernetes/KubernetesExecutor.javaindex a4f82b1361..7c68a5fcb6 100644--- a/server-plugin/server-plugin-executor-kubernetes/src/main/java/io/onedev/server/plugin/executor/kubernetes/KubernetesExecutor.java+++ b/server-plugin/server-plugin-executor-kubernetes/src/main/java/io/onedev/server/plugin/executor/kubernetes/KubernetesExecutor.java@@ -726,6 +726,7 @@ public class KubernetesExecutor extends JobExecutor implements KubernetesAware,containerSpec.put("args", argList);}containerSpec.put("env", envs);+setupSecurityContext(containerSpec, jobService.getRunAs());podSpec.put("containers", Lists.<Object>newArrayList(containerSpec));@@ -849,14 +850,12 @@ public class KubernetesExecutor extends JobExecutor implements KubernetesAware,return map;}- private void setupSecurityContext(Map<Object, Object> containerSpec, @Nullable String runAs) {- if (runAs != null) {- var securityContext = new HashMap<>();- var fields = Splitter.on(':').trimResults().splitToList(runAs);- securityContext.put("runAsUser", parseInt(fields.get(0)));- securityContext.put("runAsGroup", parseInt(fields.get(1)));- containerSpec.put("securityContext", securityContext);- }+ private void setupSecurityContext(Map<Object, Object> containerSpec, String runAs) {+ var securityContext = new HashMap<>();+ var fields = Splitter.on(':').trimResults().splitToList(runAs);+ securityContext.put("runAsUser", parseInt(fields.get(0)));+ securityContext.put("runAsGroup", parseInt(fields.get(1)));+ containerSpec.put("securityContext", securityContext);}private boolean execute(TaskLogger jobLogger, Object executionContext) {@@ -932,7 +931,7 @@ public class KubernetesExecutor extends JobExecutor implements KubernetesAware,List<Map<Object, Object>> containerSpecs = new ArrayList<>();var containerBuildDirPath = "/onedev-build";- var containerWorkDirPath = containerBuildDirPath +"/work";+ var containerWorkDirPath = containerBuildDirPath + "/work";var containerCommandDirPath = containerBuildDirPath + "/command";var containerTrustCertsDirPath = containerBuildDirPath + "/trust-certs";@@ -998,7 +997,8 @@ public class KubernetesExecutor extends JobExecutor implements KubernetesAware,volumeMounts.addAll(commonVolumeMounts);stepContainerSpec.put("volumeMounts", SerializationUtils.clone(volumeMounts));stepContainerSpec.put("env", SerializationUtils.clone(commonEnvs));- setupSecurityContext(stepContainerSpec, commandFacade.getRunAs());+ var runAs = commandFacade.getRunAs();+ setupSecurityContext(stepContainerSpec, runAs);} else if (facade instanceof BuildImageFacade) {throw new ExplicitException("This step can only be executed by server docker executor or " +"remote docker executor. Use kaniko step instead to build image in kubernetes cluster");diff --git a/server-plugin/server-plugin-executor-kubernetes/src/main/java/io/onedev/server/plugin/executor/kubernetes/KubernetesResource.java b/server-plugin/server-plugin-executor-kubernetes/src/main/java/io/onedev/server/plugin/executor/kubernetes/KubernetesResource.javaindex 3e6f9a3051..d895cfe036 100644--- a/server-plugin/server-plugin-executor-kubernetes/src/main/java/io/onedev/server/plugin/executor/kubernetes/KubernetesResource.java+++ b/server-plugin/server-plugin-executor-kubernetes/src/main/java/io/onedev/server/plugin/executor/kubernetes/KubernetesResource.java@@ -172,16 +172,16 @@ public class KubernetesResource {@QueryParam("jobToken") String jobToken,@QueryParam("key") String key,@QueryParam("checksum") @Nullable String checksum,- @QueryParam("cachePathsString") String cachePathsString) {+ @QueryParam("path") String path) {return os -> {sessionService.closeSession();try {var jobContext = jobService.getJobContext(jobToken, true);- var cacheQueryResult = cacheService.queryCache(jobContext.getProjectId(), key, checksum);- if (cacheQueryResult != null) {- var activeServer = projectService.getActiveServer(cacheQueryResult.getProjectId(), true);+ var cacheFindResult = cacheService.findCache(jobContext.getProjectId(), key, checksum, path);+ if (cacheFindResult != null) {+ var activeServer = projectService.getActiveServer(cacheFindResult.getProjectId(), true);if (activeServer.equals(clusterService.getLocalServerAddress())) {- cacheService.downloadCache(cacheQueryResult, cachePathsString, os);+ cacheService.downloadCache(cacheFindResult, os);} else {Client client = ClientBuilder.newClient();client.property(ClientProperties.REQUEST_ENTITY_PROCESSING, "CHUNKED");@@ -189,10 +189,10 @@ public class KubernetesResource {String serverUrl = clusterService.getServerUrl(activeServer);var target = client.target(serverUrl).path("~api/cluster/cache")- .queryParam("projectId", cacheQueryResult.getProjectId())- .queryParam("cacheId", cacheQueryResult.getCacheId())- .queryParam("exactMatch", cacheQueryResult.isExactMatch())- .queryParam("cachePathsString", cachePathsString);+ .queryParam("projectId", cacheFindResult.getProjectId())+ .queryParam("dirName", cacheFindResult.getDirName())+ .queryParam("pathIndex", cacheFindResult.getPathIndex())+ .queryParam("exactMatch", cacheFindResult.isExactMatch());Invocation.Builder builder = target.request();builder.header(HttpHeaders.AUTHORIZATION,KubernetesHelper.BEARER + " " + clusterService.getCredential());@@ -247,15 +247,14 @@ public class KubernetesResource {@QueryParam("projectPath") @Nullable String projectPath,@QueryParam("key") String key,@QueryParam("checksum") @Nullable String checksum,- @QueryParam("cachePathsString") String cachePathsString,+ @QueryParam("path") String path,InputStream is) {var projectId = checkUploadCache(jobToken, projectPath);sessionService.closeSession();try {- Long cacheId = cacheService.createCache(projectId, key, checksum);var activeServer = projectService.getActiveServer(projectId, true);if (activeServer.equals(clusterService.getLocalServerAddress())) {- cacheService.uploadCache(projectId, cacheId, cachePathsString, is);+ cacheService.uploadCache(projectId, key, checksum, path, is);} else {Client client = ClientBuilder.newClient();client.property(ClientProperties.REQUEST_ENTITY_PROCESSING, "CHUNKED");@@ -264,8 +263,9 @@ public class KubernetesResource {var target = client.target(serverUrl).path("~api/cluster/cache").queryParam("projectId", projectId)- .queryParam("cacheId", cacheId)- .queryParam("cachePathsString", cachePathsString);+ .queryParam("key", key)+ .queryParam("checksum", checksum)+ .queryParam("path", path);Invocation.Builder builder = target.request();builder.header(HttpHeaders.AUTHORIZATION,KubernetesHelper.BEARER + " " + clusterService.getCredential());diff --git a/server-plugin/server-plugin-executor-serverdocker/src/main/java/io/onedev/server/plugin/executor/serverdocker/ServerDockerExecutor.java b/server-plugin/server-plugin-executor-serverdocker/src/main/java/io/onedev/server/plugin/executor/serverdocker/ServerDockerExecutor.javaindex ac503598f4..269ff7bc4b 100644--- a/server-plugin/server-plugin-executor-serverdocker/src/main/java/io/onedev/server/plugin/executor/serverdocker/ServerDockerExecutor.java+++ b/server-plugin/server-plugin-executor-serverdocker/src/main/java/io/onedev/server/plugin/executor/serverdocker/ServerDockerExecutor.java@@ -1,13 +1,13 @@package io.onedev.server.plugin.executor.serverdocker;import static io.onedev.agent.AgentUtils.buildImage;-import static io.onedev.agent.AgentUtils.callWithDockerConfig;+import static io.onedev.agent.AgentUtils.callWithRegistryLogins;import static io.onedev.agent.AgentUtils.changeOwner;import static io.onedev.agent.AgentUtils.createNetwork;import static io.onedev.agent.AgentUtils.deleteDir;import static io.onedev.agent.AgentUtils.deleteNetwork;import static io.onedev.agent.AgentUtils.getEntrypointArgs;-import static io.onedev.agent.AgentUtils.getOwner;+import static io.onedev.agent.AgentUtils.getOsIds;import static io.onedev.agent.AgentUtils.newDockerKiller;import static io.onedev.agent.AgentUtils.pruneBuilderCache;import static io.onedev.agent.AgentUtils.runImagetools;@@ -15,7 +15,6 @@ import static io.onedev.agent.AgentUtils.startService;import static io.onedev.k8shelper.KubernetesHelper.cloneRepository;import static io.onedev.k8shelper.KubernetesHelper.initRepository;import static io.onedev.k8shelper.KubernetesHelper.setupGitCerts;-import static io.onedev.k8shelper.KubernetesHelper.setupSafeDirectory;import static io.onedev.k8shelper.KubernetesHelper.stringifyStepPosition;import static io.onedev.k8shelper.RegistryLoginFacade.merge;import static java.util.stream.Collectors.toList;@@ -30,12 +29,12 @@ import java.util.List;import java.util.Map;import java.util.Set;import java.util.UUID;-import java.util.concurrent.atomic.AtomicBoolean;import javax.validation.ConstraintValidatorContext;import javax.validation.Valid;import javax.validation.constraints.NotEmpty;+import org.apache.commons.io.FilenameUtils;import org.apache.commons.lang3.SystemUtils;import org.jspecify.annotations.Nullable;@@ -303,7 +302,7 @@ public class ServerDockerExecutor extends JobExecutor implements DockerAware, TehostBuildDir = new File(Bootstrap.getTempDir(),"onedev-build-" + jobContext.getProjectId() + "-" + jobContext.getBuildNumber() + "-" + jobContext.getSubmitSequence());- FileUtils.createDir(hostBuildDir);+ FileUtils.createDir(hostBuildDir);SecretMasker.push(jobContext.getSecretMasker());try {String network = "build-"+ getName() + "-" + jobContext.getProjectId() + "-"@@ -319,7 +318,7 @@ public class ServerDockerExecutor extends JobExecutor implements DockerAware, Tefor (var jobService : jobContext.getServices()) {var docker = newDocker();var registryLogins = merge(jobService.getRegistryLogins(), getRegistryLogins(jobToken));- callWithDockerConfig(docker, registryLogins, () -> {+ callWithRegistryLogins(docker, registryLogins, () -> {startService(docker, network, jobService, getCpuLimit(), getMemoryLimit(), jobLogger);return null;});@@ -338,24 +337,22 @@ public class ServerDockerExecutor extends JobExecutor implements DockerAware, Tevar containerWorkDirPath = "/onedev-build/work";var containerTrustCertsFilePath = "/onedev-build/trust-certs.pem";- var ownerChanged = new AtomicBoolean(false);+ var osIds = getOsIds(jobLogger);getJobService().reportJobWorkDir(jobContext, containerWorkDirPath);CompositeFacade entryFacade = new CompositeFacade(jobContext.getActions());var successful = entryFacade.execute(new LeafHandler() {- private int runStepContainer(Commandline docker, String image, @Nullable String runAs,+ private int runStepContainer(Commandline docker, String image, String runAs,@Nullable String entrypoint, List<String> arguments,Map<String, String> environments, @Nullable String workingDir,Map<String, String> volumeMounts, List<Integer> position, boolean useTTY) {containerName = network + "-step-" + stringifyStepPosition(position);try {- docker.arguments("run", "--name=" + containerName, "--network=" + network);+ docker.args("run", "--name=" + containerName, "--network=" + network);if (isAlwaysPullImage())docker.addArgs("--pull=always");- if (runAs != null)- docker.addArgs("--user", runAs);- else- docker.addArgs("--user", "0:0");++ docker.addArgs("--user", runAs);if (getCpuLimit() != null)docker.addArgs("--cpus", getCpuLimit());@@ -378,8 +375,12 @@ public class ServerDockerExecutor extends JobExecutor implements DockerAware, Teelse if (workingDir != null)docker.addArgs("-w", workingDir);- for (var entry: cacheProvisioner.getPathMap().entrySet())- docker.addArgs("-v", getHostPath(entry.getValue().getAbsolutePath()) + ":" + entry.getKey());+ for (var allocation: cacheProvisioner.getAllocations()) {+ for (var entry: allocation.getPathMap().entrySet()) {+ if (FilenameUtils.getPrefixLength(entry.getKey()) > 0)+ docker.addArgs("-v", getHostPath(entry.getValue().getAbsolutePath()) + ":" + entry.getKey());+ }+ }if (isMountDockerSock()) {if (getDockerSockPath() != null)@@ -424,10 +425,6 @@ public class ServerDockerExecutor extends JobExecutor implements DockerAware, Te}private boolean doExecute(LeafFacade facade, List<Integer> position) {- if (ownerChanged.get() && !Bootstrap.isInDocker()) {- changeOwner(hostBuildDir, getOwner(jobLogger), newDocker(), false, jobLogger);- ownerChanged.set(false);- }if (facade instanceof CommandFacade) {CommandFacade commandFacade = ((CommandFacade) facade).replacePlaceholders(hostBuildDir);@@ -438,27 +435,35 @@ public class ServerDockerExecutor extends JobExecutor implements DockerAware, Tevar entrypointArgs = getEntrypointArgs(hostBuildDir, commandFacade, position);var docker = newDocker();- if (changeOwner(hostBuildDir, commandFacade.getRunAs(), docker, Bootstrap.isInDocker(), jobLogger))- ownerChanged.set(true);-var registryLogins = merge(commandFacade.getRegistryLogins(), getRegistryLogins(jobToken));-- docker.clearArgs();- int exitCode = callWithDockerConfig(docker, registryLogins, () -> {- return runStepContainer(docker, commandFacade.getImage(), commandFacade.getRunAs(),- "sh", entrypointArgs, commandFacade.getEnvMap(),- null, new HashMap<>(), position, commandFacade.isUseTTY());- });- if (exitCode != 0) {- jobLogger.error("Command exited with code " + exitCode);- return false;- }+ var runAs = commandFacade.getRunAs();+ if (SystemUtils.IS_OS_LINUX && !runAs.equals("0:0")) {+ jobLogger.log("Changing owner of build directory to container user...");+ changeOwner(docker, runAs, hostBuildDir, jobLogger);+ }+ try {+ int exitCode = callWithRegistryLogins(docker, registryLogins, () -> {+ return runStepContainer(docker, commandFacade.getImage(), runAs,+ "sh", entrypointArgs, commandFacade.getEnvMap(),+ null, new HashMap<>(), position, commandFacade.isUseTTY());+ });++ if (exitCode != 0) {+ jobLogger.error("Command exited with code " + exitCode);+ return false;+ }+ } finally {+ if (SystemUtils.IS_OS_LINUX && !osIds.equals("0:0")) {+ jobLogger.log("Changing owner of build directory to host user...");+ changeOwner(newDocker(), osIds, hostBuildDir, jobLogger);+ }+ }} else if (facade instanceof BuildImageFacade) {var buildImageFacade = (BuildImageFacade) facade;var docker = newDocker();var registryLogins = merge(buildImageFacade.getRegistryLogins(), getRegistryLogins(jobToken));- callWithDockerConfig(docker, registryLogins, () -> {+ callWithRegistryLogins(docker, registryLogins, () -> {buildImage(docker, getDockerBuilder(), buildImageFacade, hostBuildDir,isAlwaysPullImage(), jobLogger);return null;@@ -467,14 +472,14 @@ public class ServerDockerExecutor extends JobExecutor implements DockerAware, Tevar runImagetoolsFacade = (RunImagetoolsFacade) facade;var docker = newDocker();var registryLogins = merge(runImagetoolsFacade.getRegistryLogins(), getRegistryLogins(jobToken));- callWithDockerConfig(docker, registryLogins, () -> {+ callWithRegistryLogins(docker, registryLogins, () -> {runImagetools(docker, runImagetoolsFacade, hostBuildDir, jobLogger);return null;});} else if (facade instanceof PruneBuilderCacheFacade) {var pruneBuilderCacheFacade = (PruneBuilderCacheFacade) facade;var docker = newDocker();- callWithDockerConfig(docker, new ArrayList<>(), () -> {+ callWithRegistryLogins(docker, new ArrayList<>(), () -> {pruneBuilderCache(docker, getDockerBuilder(), pruneBuilderCacheFacade,hostBuildDir, jobLogger);return null;@@ -485,20 +490,29 @@ public class ServerDockerExecutor extends JobExecutor implements DockerAware, Teif (runContainerFacade.getArgs() != null)arguments.addAll(Arrays.asList(StringUtils.parseQuoteTokens(runContainerFacade.getArgs())));- var registryLogins = merge(runContainerFacade.getRegistryLogins(), getRegistryLogins(jobToken));var docker = newDocker();- if (changeOwner(hostBuildDir, runContainerFacade.getRunAs(), docker, Bootstrap.isInDocker(), jobLogger))- ownerChanged.set(true);-- docker.clearArgs();- int exitCode = callWithDockerConfig(docker, registryLogins, () -> {- return runStepContainer(docker, runContainerFacade.getImage(), runContainerFacade.getRunAs(), null,- arguments, runContainerFacade.getEnvMap(), runContainerFacade.getWorkingDir(), runContainerFacade.getVolumeMounts(),- position, runContainerFacade.isUseTTY());- });- if (exitCode != 0) {- jobLogger.error("Container exited with code " + exitCode);- return false;+ var registryLogins = merge(runContainerFacade.getRegistryLogins(), getRegistryLogins(jobToken));++ var runAs = runContainerFacade.getRunAs() != null ? runContainerFacade.getRunAs() : "0:0";+ if (SystemUtils.IS_OS_LINUX && !runAs.equals("0:0")) {+ jobLogger.log("Changing owner of build directory to container user...");+ changeOwner(docker, runAs, hostBuildDir, jobLogger);+ }+ try {+ int exitCode = callWithRegistryLogins(docker, registryLogins, () -> {+ return runStepContainer(docker, runContainerFacade.getImage(), runAs, null,+ arguments, runContainerFacade.getEnvMap(), runContainerFacade.getWorkingDir(), runContainerFacade.getVolumeMounts(),+ position, runContainerFacade.isUseTTY());+ });+ if (exitCode != 0) {+ jobLogger.error("Container exited with code " + exitCode);+ return false;+ }+ } finally {+ if (SystemUtils.IS_OS_LINUX && !osIds.equals("0:0")) {+ jobLogger.log("Changing owner of build directory to host user...");+ changeOwner(newDocker(), osIds, hostBuildDir, jobLogger);+ }}} else if (facade instanceof CheckoutFacade) {CheckoutFacade checkoutFacade = (CheckoutFacade) facade;@@ -512,11 +526,6 @@ public class ServerDockerExecutor extends JobExecutor implements DockerAware, TeinitRepository(git, infoLogger, warningLogger);- if (!Bootstrap.isInDocker()) {- setupSafeDirectory(git, containerWorkDirPath, checkoutFacade.getCheckoutPath(),- infoLogger, warningLogger);- }-var remoteAccessArgs = new ArrayList<String>();remoteAccessArgs.addAll(setupGitCerts(git, Bootstrap.getTrustCertsDir(),new File(hostBuildDir, "trust-certs.pem"),@@ -526,7 +535,7 @@ public class ServerDockerExecutor extends JobExecutor implements DockerAware, TeremoteAccessArgs.addAll(cloneInfo.setupGitAuth(git, hostBuildDir, containerBuildDirPath,infoLogger, warningLogger));- git.arguments(remoteAccessArgs);+ git.args(remoteAccessArgs);int cloneDepth = checkoutFacade.getCloneDepth();@@ -561,7 +570,7 @@ public class ServerDockerExecutor extends JobExecutor implements DockerAware, Te}, new ArrayList<>());- if (successful)+ if (successful)cacheProvisioner.uploadCaches();return successful;@@ -666,12 +675,12 @@ public class ServerDockerExecutor extends JobExecutor implements DockerAware, Tepublic void test(TestData testData, TaskLogger jobLogger) {checkApplicable();var docker = newDocker();- callWithDockerConfig(docker, getRegistryLogins(UUID.randomUUID().toString()), () -> {+ callWithRegistryLogins(docker, getRegistryLogins(UUID.randomUUID().toString()), () -> {File workDir = null;try {workDir = FileUtils.createTempDir("work");jobLogger.log("Testing specified docker image...");- docker.arguments("run", "--rm");+ docker.args("run", "--rm");if (getCpuLimit() != null)docker.addArgs("--cpus", getCpuLimit());if (getMemoryLimit() != null)@@ -706,7 +715,7 @@ public class ServerDockerExecutor extends JobExecutor implements DockerAware, Te}jobLogger.log("Checking busybox availability...");- docker.arguments("run", "--rm", "busybox", "sh", "-c", "echo hello from busybox");+ docker.args("run", "--rm", "busybox", "sh", "-c", "echo hello from busybox");docker.execute(new LineConsumer() {@Overridediff --git a/server-plugin/server-plugin-executor-servershell/src/main/java/io/onedev/server/plugin/executor/servershell/ServerShellExecutor.java b/server-plugin/server-plugin-executor-servershell/src/main/java/io/onedev/server/plugin/executor/servershell/ServerShellExecutor.javaindex 548ce154ec..89c34a540e 100644--- a/server-plugin/server-plugin-executor-servershell/src/main/java/io/onedev/server/plugin/executor/servershell/ServerShellExecutor.java+++ b/server-plugin/server-plugin-executor-servershell/src/main/java/io/onedev/server/plugin/executor/servershell/ServerShellExecutor.java@@ -185,7 +185,7 @@ public class ServerShellExecutor extends JobExecutor implements Testable<TestDatMap<String, String> envs = new HashMap<>();envs.put("ONEDEV_WORKDIR", workDir.getAbsolutePath());envs.putAll(commandFacade.getEnvMap());- cmdline.workingDir(workDir).environments(envs);+ cmdline.workingDir(workDir).envs(envs);cmdline.addArgs(stepScriptFile.getAbsolutePath());var result = cmdline.execute(newInfoLogger(jobLogger), newWarningLogger(jobLogger));@@ -218,7 +218,7 @@ public class ServerShellExecutor extends JobExecutor implements Testable<TestDatremoteAccessArgs.addAll(cloneInfo.setupGitAuth(git, buildDir, buildDir.getAbsolutePath(),infoLogger, warningLogger));- git.arguments(remoteAccessArgs);+ git.args(remoteAccessArgs);cloneRepository(git, jobContext.getProjectGitDir(), cloneInfo.getCloneUrl(),jobContext.getRefName(), jobContext.getCommitId().name(),diff --git a/server-plugin/server-plugin-provisioner-shell/src/main/java/io/onedev/server/plugin/provisioner/shell/ShellProvisioner.java b/server-plugin/server-plugin-provisioner-shell/src/main/java/io/onedev/server/plugin/provisioner/shell/ShellProvisioner.javaindex af2a0ef569..f1c95bb91a 100644--- a/server-plugin/server-plugin-provisioner-shell/src/main/java/io/onedev/server/plugin/provisioner/shell/ShellProvisioner.java+++ b/server-plugin/server-plugin-provisioner-shell/src/main/java/io/onedev/server/plugin/provisioner/shell/ShellProvisioner.java@@ -3,11 +3,15 @@ package io.onedev.server.plugin.provisioner.shell;import static io.onedev.agent.AgentUtils.newErrorLogger;import static io.onedev.agent.AgentUtils.newInfoLogger;+import java.io.ByteArrayOutputStream;import java.io.File;import java.io.IOException;import java.nio.charset.StandardCharsets;+import java.util.Arrays;import java.util.concurrent.CountDownLatch;+import io.onedev.server.git.hook.HookUtils;+import io.onedev.server.workspace.GitExecutionResult;import org.apache.commons.io.FilenameUtils;import io.onedev.commons.utils.ExplicitException;@@ -94,6 +98,8 @@ public class ShellProvisioner extends WorkspaceProvisioner implements Testable<TenvVars.put("TERM", "xterm-256color");envVars.put("LANG", "C.UTF-8");+ var workDir = new File(workspaceDir, "work");+ envVars.put("ONEDEV_WORKDIR", workDir.getAbsolutePath());logger.log("Setting up cache...");@@ -119,13 +125,26 @@ public class ShellProvisioner extends WorkspaceProvisioner implements Testable<Tvar cmdline = new Commandline(shell.getFacility().getExecutable());cmdline.addArgs(shell.getFacility().getScriptOptions());- cmdline.workingDir(new File(workspaceDir, "work")).environments(envVars);+ cmdline.workingDir(workDir).envs(envVars);cmdline.addArgs(scriptFile.getAbsolutePath());cmdline.execute(newInfoLogger(logger), newErrorLogger(logger)).checkReturnCode();}return new WorkspaceRuntime() {-++ @Override+ public GitExecutionResult executeGitCommand(String[] gitArgs) {+ var git = CommandUtils.newGit();+ git.workingDir(workDir);+ git.envs().putAll(HookUtils.getWorkspacePostCommitHookEnvs(context.getToken()));+ git.args(Arrays.asList(gitArgs));++ var stdoutStream = new ByteArrayOutputStream();+ var stderrStream = new ByteArrayOutputStream();+ var returnCode = git.execute(stdoutStream, stderrStream).getReturnCode();+ return new GitExecutionResult(stdoutStream.toByteArray(), stderrStream.toByteArray(), returnCode);+ }+@Overridepublic Shell doOpenShell(Terminal terminal) {var workDir = Workspace.getWorkDir(context.getProjectId(), context.getWorkspaceNumber());@@ -134,7 +153,7 @@ public class ShellProvisioner extends WorkspaceProvisioner implements Testable<Ttmux.addArgs("new-session").addArgs(context.getSpec().getShell().getFacility().getExecutable()).workingDir(workDir)- .environments(envVars);+ .envs(envVars);return new CommandlineShell(terminal, tmux);}