Skip to content

The Unified and Autonomous Development Platform

feat: Run CI/CD inside docker sandbox

Robin Shen346c51b31bfd
diff --git a/pom.xml b/pom.xml
index 883bdee3ab..640eae33ea 100644
--- a/pom.xml
+++ b/pom.xml
@@ -719,7 +719,7 @@
</repositories>
<properties>
<commons.version>4.2.9</commons.version>
- <agent.version>3.3.12</agent.version>
+ <agent.version>3.4.0</agent.version>
<slf4j.version>2.0.17</slf4j.version>
<logback.version>1.5.33</logback.version>
<antlr.version>4.13.2</antlr.version>
diff --git a/server-core/src/main/java/io/onedev/server/agent/AgentHelper.java b/server-core/src/main/java/io/onedev/server/agent/AgentHelper.java
index 626fa08ebf..ad3a895740 100644
--- a/server-core/src/main/java/io/onedev/server/agent/AgentHelper.java
+++ b/server-core/src/main/java/io/onedev/server/agent/AgentHelper.java
@@ -3,6 +3,8 @@ package io.onedev.server.agent;
import static io.onedev.agent.WebsocketUtils.call;
import java.io.Serializable;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
@@ -23,10 +25,17 @@ import io.onedev.server.service.ResourceService;
public class AgentHelper {
+ private static final Set<String> testTokens = ConcurrentHashMap.newKeySet();
+
+ public static boolean isTestRunning(String token) {
+ return getClusterService().runOnAllServers(() -> testTokens.contains(token)).containsValue(true);
+ }
+
public static void test(@Nullable String agentQuery, String resourceName, int concurrency,
TestData testData, TaskLogger logger) {
var token = testData.getToken();
getLogService().addLogger(token, logger);
+ testTokens.add(token);
try {
String testServer = getClusterService().getLocalServerAddress();
logger.log("Pending resource allocation...");
@@ -63,13 +72,16 @@ public class AgentHelper {
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
} finally {
+ testTokens.remove(token);
getLogService().removeLogger(token);
}
}
private static Void testCallAgent(Session agentSession, Serializable testData, String testToken) {
try {
- call(agentSession, testData);
+ // Pulling images and starting a sandbox can exceed the default RPC timeout.
+ // Agent housekeeping cancels executor tests when their token is no longer active.
+ call(agentSession, testData, 0);
return null;
} catch (InterruptedException | TimeoutException e) {
throw new RuntimeException(e);
diff --git a/server-core/src/main/java/io/onedev/server/buildspec/job/Job.java b/server-core/src/main/java/io/onedev/server/buildspec/job/Job.java
index 74b84d7954..83d77ef295 100644
--- a/server-core/src/main/java/io/onedev/server/buildspec/job/Job.java
+++ b/server-core/src/main/java/io/onedev/server/buildspec/job/Job.java
@@ -234,8 +234,7 @@ public class Job implements NamedElement, Validatable {
@Editable(order=9114, group="Dependencies & Services", placeholder="No required services",
description="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'>NOTE:</b> Services are supported by Docker, Kubernetes, and sandbox executors")
@ChoiceProvider("getServiceChoices")
public List<String> getRequiredServices() {
return requiredServices;
diff --git a/server-core/src/main/java/io/onedev/server/buildspec/step/BuildImageStep.java b/server-core/src/main/java/io/onedev/server/buildspec/step/BuildImageStep.java
index 8ed47d8c13..d2fc11e576 100644
--- a/server-core/src/main/java/io/onedev/server/buildspec/step/BuildImageStep.java
+++ b/server-core/src/main/java/io/onedev/server/buildspec/step/BuildImageStep.java
@@ -25,10 +25,11 @@ import io.onedev.server.model.Build;
import io.onedev.server.model.support.administration.DockerAware;
import io.onedev.server.model.support.administration.jobexecutor.JobExecutor;
import io.onedev.server.model.support.administration.jobexecutor.KubernetesAware;
+import io.onedev.server.model.support.administration.jobexecutor.SandboxAware;
@Editable(order=160, name="Build Image (Buildx)", group = DOCKER_IMAGE, description="Build docker image with buildx. " +
- "This step can only be executed by server docker executor or remote docker executor, and it uses the buildx " +
- "builder specified in these executors to do the job. To build image with Kubernetes executor, please use kaniko " +
+ "This step can be executed by docker or sandbox executors. Docker executors use their configured buildx " +
+ "builder; sandbox executors use the default builder inside the sandbox. To build image with Kubernetes executor, please use kaniko " +
"step instead")
public class BuildImageStep extends Step {
@@ -107,7 +108,7 @@ public class BuildImageStep extends Step {
@Editable(order=1400, group = "More Settings", description="Optionally specify additional options for " +
"buildx build command")
@Interpolative(variableSuggester="suggestVariables")
- @ReservedOptions({"--builder", "(--builder)=.*", "--platform", "(--platform)=.*", "--push", "-f", "--file", "(-f|--file)=.*", "-t", "--tag", "(-t|--tag)=.*", "-o", "--output", "(-o|--output)=.*"})
+ @ReservedOptions({"--", "(--builder|--platform|--push|--load|--file|--tag|--output)(=.*)?", "(-q*[fto]).*"})
public String getMoreOptions() {
return moreOptions;
}
@@ -129,7 +130,8 @@ public class BuildImageStep extends Step {
@Override
public boolean isApplicable(Build build, JobExecutor executor) {
- return executor instanceof DockerAware && !(executor instanceof KubernetesAware);
+ return executor instanceof SandboxAware
+ || executor instanceof DockerAware && !(executor instanceof KubernetesAware);
}
@Editable
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.java
index bc68f1e765..6f8a64389d 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
@@ -33,7 +33,7 @@ import io.onedev.server.buildspec.param.ParamCombination;
import io.onedev.server.buildspec.step.commandinterpreter.PosixInterpreter;
import io.onedev.server.buildspec.step.commandinterpreter.Interpreter;
import io.onedev.server.model.Build;
-import io.onedev.server.model.support.administration.DockerAware;
+import io.onedev.server.model.support.administration.RegistryLoginAware;
import io.onedev.server.model.support.administration.jobexecutor.JobExecutor;
@Editable(order=200, name="Build Image (Kaniko)", group = DOCKER_IMAGE, description="Build docker image with kaniko. " +
@@ -145,8 +145,7 @@ public class BuildImageWithKanikoStep extends CommandStep {
public StepFacade getFacade(Build build, JobExecutor jobExecutor, String jobToken, ParamCombination paramCombination,
List<RegistryLoginFacade> registryLogins, Map<String, String> envMap) {
var commandsBuilder = new StringBuilder();
- if (jobExecutor instanceof DockerAware) {
- DockerAware registryLoginAware = (DockerAware) jobExecutor;
+ if (jobExecutor instanceof RegistryLoginAware registryLoginAware) {
commandsBuilder.append("cat <<EOF>> /kaniko/.docker/config.json\n");
var mergedRegistryLogins = merge(registryLogins, registryLoginAware.getRegistryLogins(jobToken));
var configMap = new HashMap<String, Object>();
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.java
index e15d4c1037..98db3b1539 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
@@ -27,6 +27,7 @@ import io.onedev.server.buildspec.step.commandinterpreter.Interpreter;
import io.onedev.server.model.Build;
import io.onedev.server.model.support.administration.DockerAware;
import io.onedev.server.model.support.administration.jobexecutor.JobExecutor;
+import io.onedev.server.model.support.administration.jobexecutor.SandboxAware;
@Editable(order=100, name="Execute Commands")
public class CommandStep extends Step {
@@ -149,6 +150,8 @@ public class CommandStep extends Step {
@Override
public boolean isApplicable(Build build, JobExecutor executor) {
+ if (executor instanceof SandboxAware)
+ return true;
if (isRunInContainer())
return executor instanceof DockerAware;
else
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.java
index 7b12509fd3..87eaed5e36 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
@@ -22,7 +22,7 @@ import io.onedev.server.buildspec.param.ParamCombination;
import io.onedev.server.buildspec.step.commandinterpreter.PosixInterpreter;
import io.onedev.server.buildspec.step.commandinterpreter.Interpreter;
import io.onedev.server.model.Build;
-import io.onedev.server.model.support.administration.DockerAware;
+import io.onedev.server.model.support.administration.RegistryLoginAware;
import io.onedev.server.model.support.administration.jobexecutor.JobExecutor;
public abstract class CraneStep extends CommandStep {
@@ -92,8 +92,7 @@ public abstract class CraneStep extends CommandStep {
public StepFacade getFacade(Build build, JobExecutor jobExecutor, String jobToken, ParamCombination paramCombination,
List<RegistryLoginFacade> registryLogins, Map<String, String> envMap) {
var commandsBuilder = new StringBuilder();
- if (jobExecutor instanceof DockerAware) {
- DockerAware registryLoginAware = (DockerAware) jobExecutor;
+ if (jobExecutor instanceof RegistryLoginAware registryLoginAware) {
commandsBuilder.append("mkdir /root/.docker\n");
commandsBuilder.append("cat <<EOF>> /root/.docker/config.json\n");
var mergedRegistryLogins = merge(registryLogins, registryLoginAware.getRegistryLogins(jobToken));
diff --git a/server-core/src/main/java/io/onedev/server/buildspec/step/PruneBuilderCacheStep.java b/server-core/src/main/java/io/onedev/server/buildspec/step/PruneBuilderCacheStep.java
index bb3e3b82b9..4f33e61c88 100644
--- a/server-core/src/main/java/io/onedev/server/buildspec/step/PruneBuilderCacheStep.java
+++ b/server-core/src/main/java/io/onedev/server/buildspec/step/PruneBuilderCacheStep.java
@@ -11,10 +11,11 @@ import io.onedev.server.model.Build;
import io.onedev.server.model.support.administration.DockerAware;
import io.onedev.server.model.support.administration.jobexecutor.JobExecutor;
import io.onedev.server.model.support.administration.jobexecutor.KubernetesAware;
+import io.onedev.server.model.support.administration.jobexecutor.SandboxAware;
@Editable(order=260, name="Prune Builder Cache", group = DOCKER_IMAGE, description="" +
"Prune image cache of docker buildx builder. This step calls docker buildx prune command " +
- "to remove cache of buildx builder specified in server docker executor or remote docker executor")
+ "to remove cache of the builder used by the Docker or sandbox executor")
public class PruneBuilderCacheStep extends Step {
private static final long serialVersionUID = 1L;
@@ -38,7 +39,8 @@ public class PruneBuilderCacheStep extends Step {
@Override
public boolean isApplicable(Build build, JobExecutor executor) {
- return executor instanceof DockerAware && !(executor instanceof KubernetesAware);
+ return executor instanceof SandboxAware
+ || executor instanceof DockerAware && !(executor instanceof KubernetesAware);
}
}
diff --git a/server-core/src/main/java/io/onedev/server/buildspec/step/RunContainerStep.java b/server-core/src/main/java/io/onedev/server/buildspec/step/RunContainerStep.java
index 7b5908e99e..ce9c9ccd63 100644
--- a/server-core/src/main/java/io/onedev/server/buildspec/step/RunContainerStep.java
+++ b/server-core/src/main/java/io/onedev/server/buildspec/step/RunContainerStep.java
@@ -25,11 +25,11 @@ import io.onedev.server.model.Build;
import io.onedev.server.model.support.administration.DockerAware;
import io.onedev.server.model.support.administration.jobexecutor.JobExecutor;
import io.onedev.server.model.support.administration.jobexecutor.KubernetesAware;
+import io.onedev.server.model.support.administration.jobexecutor.SandboxAware;
@Editable(order=150, name="Run Docker Container", description="Run specified docker container. <a href='${docsite}/concepts#job-workdir' target='_blank'>Job workdir</a> "
+ "is mounted into the container and its path is placed in environment variable <code>ONEDEV_WORKDIR</code>. " +
- "<b class='text-warning'>Note: </b> this step can only be executed by server docker executor or remote " +
- "docker executor")
+ "This step can be executed by Docker or sandbox executors")
public class RunContainerStep extends Step {
private static final long serialVersionUID = 1L;
@@ -162,7 +162,8 @@ public class RunContainerStep extends Step {
@Override
public boolean isApplicable(Build build, JobExecutor executor) {
- return executor instanceof DockerAware && !(executor instanceof KubernetesAware);
+ return executor instanceof SandboxAware
+ || executor instanceof DockerAware && !(executor instanceof KubernetesAware);
}
}
diff --git a/server-core/src/main/java/io/onedev/server/buildspec/step/RunImagetoolsStep.java b/server-core/src/main/java/io/onedev/server/buildspec/step/RunImagetoolsStep.java
index b4b2887d16..3a299346e8 100644
--- a/server-core/src/main/java/io/onedev/server/buildspec/step/RunImagetoolsStep.java
+++ b/server-core/src/main/java/io/onedev/server/buildspec/step/RunImagetoolsStep.java
@@ -20,10 +20,10 @@ import io.onedev.server.model.Build;
import io.onedev.server.model.support.administration.DockerAware;
import io.onedev.server.model.support.administration.jobexecutor.JobExecutor;
import io.onedev.server.model.support.administration.jobexecutor.KubernetesAware;
+import io.onedev.server.model.support.administration.jobexecutor.SandboxAware;
@Editable(order=230, name="Run Buildx Image Tools", group = DOCKER_IMAGE, description="Run docker buildx imagetools " +
- "command with specified arguments. This step can only be executed by server docker executor " +
- "or remote docker executor")
+ "command with specified arguments. This step can be executed by Docker or sandbox executors")
public class RunImagetoolsStep extends Step {
private static final long serialVersionUID = 1L;
@@ -67,7 +67,8 @@ public class RunImagetoolsStep extends Step {
@Override
public boolean isApplicable(Build build, JobExecutor executor) {
- return executor instanceof DockerAware && !(executor instanceof KubernetesAware);
+ return executor instanceof SandboxAware
+ || executor instanceof DockerAware && !(executor instanceof KubernetesAware);
}
}
diff --git a/server-core/src/main/java/io/onedev/server/job/DefaultJobService.java b/server-core/src/main/java/io/onedev/server/job/DefaultJobService.java
index ef5ea99558..45117b520d 100644
--- a/server-core/src/main/java/io/onedev/server/job/DefaultJobService.java
+++ b/server-core/src/main/java/io/onedev/server/job/DefaultJobService.java
@@ -52,6 +52,7 @@ import io.onedev.server.model.*;
import io.onedev.server.model.Build.Status;
import io.onedev.server.model.support.administration.DockerAware;
import io.onedev.server.model.support.administration.jobexecutor.JobExecutor;
+import io.onedev.server.model.support.administration.jobexecutor.SandboxAware;
import io.onedev.server.model.support.build.StepExecution;
import io.onedev.server.persistence.SessionService;
import io.onedev.server.persistence.TransactionService;
@@ -441,7 +442,8 @@ public class DefaultJobService implements JobService, Runnable, CodePullAuthoriz
}
private boolean isApplicable(Build build, JobExecutor executor) {
- if (!build.getJob().getRequiredServices().isEmpty() && !(executor instanceof DockerAware))
+ if (!build.getJob().getRequiredServices().isEmpty()
+ && !(executor instanceof DockerAware) && !(executor instanceof SandboxAware))
return false;
for (var step: build.getJob().getSteps()) {
diff --git a/server-core/src/main/java/io/onedev/server/model/support/administration/DockerAware.java b/server-core/src/main/java/io/onedev/server/model/support/administration/DockerAware.java
index 4eb41d3e4a..7c1d410c97 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/administration/DockerAware.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/administration/DockerAware.java
@@ -1,11 +1,4 @@
package io.onedev.server.model.support.administration;
-import io.onedev.k8shelper.RegistryLoginFacade;
-
-import java.util.List;
-
-public interface DockerAware {
-
- List<RegistryLoginFacade> getRegistryLogins(String token);
-
+public interface DockerAware extends RegistryLoginAware {
}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/administration/RegistryLoginAware.java b/server-core/src/main/java/io/onedev/server/model/support/administration/RegistryLoginAware.java
new file mode 100644
index 0000000000..133dedac33
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/model/support/administration/RegistryLoginAware.java
@@ -0,0 +1,11 @@
+package io.onedev.server.model.support.administration;
+
+import java.util.List;
+
+import io.onedev.k8shelper.RegistryLoginFacade;
+
+public interface RegistryLoginAware {
+
+ List<RegistryLoginFacade> getRegistryLogins(String token);
+
+}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/administration/jobexecutor/SandboxAware.java b/server-core/src/main/java/io/onedev/server/model/support/administration/jobexecutor/SandboxAware.java
new file mode 100644
index 0000000000..fec68f156d
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/model/support/administration/jobexecutor/SandboxAware.java
@@ -0,0 +1,7 @@
+package io.onedev.server.model.support.administration.jobexecutor;
+
+import io.onedev.server.model.support.administration.RegistryLoginAware;
+
+/** Runs both shell and Docker steps inside an isolated sandbox. */
+public interface SandboxAware extends RegistryLoginAware {
+}
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/WorkerResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/WorkerResource.java
index 0637c24d4f..bae19d1492 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/WorkerResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/WorkerResource.java
@@ -42,6 +42,8 @@ import org.apache.shiro.authz.UnauthorizedException;
import org.glassfish.jersey.client.ClientProperties;
import org.jspecify.annotations.Nullable;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
import io.onedev.commons.utils.FileUtils;
import io.onedev.commons.utils.StringUtils;
import io.onedev.commons.utils.TarUtils;
@@ -50,6 +52,7 @@ import io.onedev.k8shelper.CacheAvailability;
import io.onedev.k8shelper.KubernetesHelper;
import io.onedev.k8shelper.KubernetesJobData;
import io.onedev.k8shelper.KubernetesWorkspaceData;
+import io.onedev.server.agent.AgentHelper;
import io.onedev.server.cluster.ClusterService;
import io.onedev.server.job.JobContext;
import io.onedev.server.job.JobService;
@@ -92,6 +95,16 @@ public class WorkerResource {
@Inject
private UserService userService;
+ @Inject
+ private ObjectMapper objectMapper;
+
+ @Path("job-workdir")
+ @PUT
+ public void reportJobWorkDir(@QueryParam("token") @NotEmpty String token,
+ @QueryParam("workDir") @NotEmpty String workDir) {
+ jobService.reportJobWorkDir(jobService.getJobContext(token, true), workDir);
+ }
+
@Path("job-data")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@GET
@@ -110,7 +123,8 @@ public class WorkerResource {
@Path("run-server-step")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@POST
- public StreamingOutput runServerStep(@QueryParam("token") @NotEmpty String token, InputStream is) {
+ public StreamingOutput runServerStep(@QueryParam("token") @NotEmpty String token,
+ @QueryParam("resultFormat") String resultFormat, InputStream is) {
JobContext jobContext = jobService.getJobContext(token, true);
return os -> {
File filesDir = FileUtils.createTempDir();
@@ -147,7 +161,11 @@ public class WorkerResource {
}
});
- byte[] bytes = SerializationUtils.serialize(result);
+ // The sandbox runner uses the same streaming protocol without a Java runtime.
+ byte[] bytes = "json".equals(resultFormat)
+ ? objectMapper.writeValueAsBytes(Map.of("successful", result.isSuccessful(),
+ "outputFiles", result.getOutputFiles()))
+ : SerializationUtils.serialize(result);
writeInt(os, 2);
writeInt(os, bytes.length);
os.write(bytes);
@@ -346,7 +364,7 @@ public class WorkerResource {
@Path("job-running")
@GET
public boolean isJobRunning(@QueryParam("token") @NotEmpty String token) {
- return jobService.getJobContext(token, false) != null;
+ return jobService.getJobContext(token, false) != null || AgentHelper.isTestRunning(token);
}
@Path("workspace-active")
diff --git a/server-core/src/main/java/io/onedev/server/service/impl/DefaultAgentTokenService.java b/server-core/src/main/java/io/onedev/server/service/impl/DefaultAgentTokenService.java
index bf1cf498e7..fc9c064f26 100644
--- a/server-core/src/main/java/io/onedev/server/service/impl/DefaultAgentTokenService.java
+++ b/server-core/src/main/java/io/onedev/server/service/impl/DefaultAgentTokenService.java
@@ -7,6 +7,8 @@ import java.util.List;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
+import io.onedev.server.event.Listen;
+import io.onedev.server.event.system.SystemStarted;
import io.onedev.server.persistence.dao.Restrictions;
import io.onedev.server.model.Agent;
@@ -23,6 +25,21 @@ public class DefaultAgentTokenService extends BaseEntityService<AgentToken> impl
@Inject
private AgentService agentService;
+ @Transactional
+ @Listen
+ public void on(SystemStarted event) {
+ var tokenValues = System.getenv("agent_tokens");
+ if (tokenValues != null) {
+ for (var value: tokenValues.split("\n")) {
+ if (!value.isEmpty() && find(value) == null) {
+ var token = new AgentToken();
+ token.setValue(value);
+ createOrUpdate(token);
+ }
+ }
+ }
+ }
+
@Transactional
@Override
public void createOrUpdate(AgentToken token) {
diff --git a/server-core/src/main/java/io/onedev/server/web/page/admin/buildsetting/jobexecutor/JobExecutorEditPanel.java b/server-core/src/main/java/io/onedev/server/web/page/admin/buildsetting/jobexecutor/JobExecutorEditPanel.java
index 558225da03..040e0a6273 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/admin/buildsetting/jobexecutor/JobExecutorEditPanel.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/admin/buildsetting/jobexecutor/JobExecutorEditPanel.java
@@ -1,8 +1,12 @@
package io.onedev.server.web.page.admin.buildsetting.jobexecutor;
+import io.onedev.server.OneDev;
+import io.onedev.server.SubscriptionService;
+import io.onedev.server.annotation.SubscriptionRequired;
import io.onedev.server.model.support.administration.jobexecutor.JobExecutor;
import io.onedev.server.util.Path;
import io.onedev.server.util.PathNode;
+import io.onedev.server.web.behavior.DisableAwareBehavior;
import io.onedev.server.web.component.taskbutton.TestButton;
import io.onedev.server.web.editable.BeanContext;
import io.onedev.server.web.editable.BeanEditor;
@@ -14,8 +18,10 @@ import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.event.IEvent;
import org.apache.wicket.feedback.FencedFeedbackPanel;
+import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.Panel;
+import org.apache.wicket.util.visit.IVisitor;
import org.jspecify.annotations.Nullable;
@@ -68,6 +74,19 @@ abstract class JobExecutorEditPanel extends Panel {
AjaxButton saveButton = new AjaxButton("save") {
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setEnabled(isExecutorLicensed(editor));
+ }
+
+ @Override
+ protected void onComponentTag(ComponentTag tag) {
+ super.onComponentTag(tag);
+ if (!isEnabled())
+ tag.put("disabled", "disabled");
+ }
+
@Override
protected void onSubmit(AjaxRequestTarget target) {
Form<?> form = getForm();
@@ -105,6 +124,8 @@ abstract class JobExecutorEditPanel extends Panel {
}
};
+ saveButton.add(new DisableAwareBehavior());
+
AjaxLink<Void> cancelButton = new AjaxLink<Void>("cancel") {
@Override
@@ -116,6 +137,19 @@ abstract class JobExecutorEditPanel extends Panel {
TestButton testButton = new TestButton("testingExecutor", editor, "Job executor tested successfully") {
+ @Override
+ protected void onComponentTag(ComponentTag tag) {
+ super.onComponentTag(tag);
+ if (!isEnabled())
+ tag.put("disabled", "disabled");
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setEnabled(isExecutorLicensed(editor));
+ }
+
@Override
protected Testable<?> getTestable() {
return (Testable<?>) bean.getExecutor();
@@ -131,6 +165,7 @@ abstract class JobExecutorEditPanel extends Panel {
if (event.getPayload() instanceof BeanUpdating) {
BeanUpdating beanUpdating = (BeanUpdating) event.getPayload();
+ beanUpdating.getHandler().add(saveButton);
beanUpdating.getHandler().add(testButton);
}
@@ -152,4 +187,13 @@ abstract class JobExecutorEditPanel extends Panel {
protected abstract void onSave(AjaxRequestTarget target);
protected abstract void onCancel(AjaxRequestTarget target);
+
+ private static boolean isExecutorLicensed(BeanEditor editor) {
+ BeanEditor beanEditor = editor.visitChildren(
+ BeanEditor.class,
+ (IVisitor<BeanEditor, BeanEditor>) (component, visit) -> visit.stop(component));
+ return beanEditor == null
+ || beanEditor.getDescriptor().getBeanClass().getAnnotation(SubscriptionRequired.class) == null
+ || OneDev.getInstance(SubscriptionService.class).isSubscriptionActive();
+ }
}
diff --git a/server-core/src/test/java/io/onedev/server/buildspec/step/SandboxStepTest.java b/server-core/src/test/java/io/onedev/server/buildspec/step/SandboxStepTest.java
new file mode 100644
index 0000000000..3976ec92dc
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/buildspec/step/SandboxStepTest.java
@@ -0,0 +1,51 @@
+package io.onedev.server.buildspec.step;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+import java.util.List;
+
+import org.junit.jupiter.api.Test;
+
+import io.onedev.server.model.support.administration.DockerAware;
+import io.onedev.server.model.support.administration.jobexecutor.JobExecutor;
+import io.onedev.server.model.support.administration.jobexecutor.KubernetesAware;
+import io.onedev.server.model.support.administration.jobexecutor.SandboxAware;
+import io.onedev.server.validation.HibernateValidationTestSupport;
+
+class SandboxStepTest extends HibernateValidationTestSupport {
+
+ @Test
+ void sandboxAcceptsShellAndDockerStepsWithoutEnablingOtherExecutors() {
+ var sandbox = mock(JobExecutor.class, withSettings().extraInterfaces(SandboxAware.class));
+ var docker = mock(JobExecutor.class, withSettings().extraInterfaces(DockerAware.class));
+ var kubernetes = mock(JobExecutor.class, withSettings().extraInterfaces(KubernetesAware.class));
+ var shell = mock(JobExecutor.class);
+ var command = new CommandStep();
+ for (boolean container : List.of(true, false)) {
+ command.setRunInContainer(container);
+ assertTrue(command.isApplicable(null, sandbox));
+ assertEquals(container, command.isApplicable(null, docker));
+ assertEquals(container, command.isApplicable(null, kubernetes));
+ assertEquals(!container, command.isApplicable(null, shell));
+ }
+ for (var step : List.of(new RunContainerStep(), new BuildImageStep(), new RunImagetoolsStep(), new PruneBuilderCacheStep())) {
+ assertTrue(step.isApplicable(null, sandbox));
+ assertTrue(step.isApplicable(null, docker));
+ assertFalse(step.isApplicable(null, shell));
+ assertFalse(step.isApplicable(null, kubernetes));
+ }
+ }
+
+ @Test
+ void buildOptionsAllowFileAccessButRejectSettingsOverrides() {
+ var step = new BuildImageStep();
+ step.setMoreOptions("--secret id=key,src=/tmp/key --metadata-file /tmp/metadata --cache-to type=local,dest=/tmp/cache");
+ assertTrue(validator.validateProperty(step, "moreOptions").isEmpty());
+ for (var option : List.of("--builder=other", "--platform=linux/arm64", "--push=false", "--load",
+ "-fOther", "--file Other", "-tother", "--tag=other", "-qotmp", "--output=type=local", "--")) {
+ step.setMoreOptions(option);
+ assertFalse(validator.validateProperty(step, "moreOptions").isEmpty(), option);
+ }
+ }
+}
diff --git a/server-ee b/server-ee
index 61aef6a4af..26fcec2c51 160000
--- a/server-ee
+++ b/server-ee
@@ -1 +1 @@
-Subproject commit 61aef6a4afb76b03ba310cc8ce3b46680843bc28
+Subproject commit 26fcec2c51ddb4a1aa9471867c75e824da9b340f
diff --git a/server-plugin/pom.xml b/server-plugin/pom.xml
index e87ca3d643..5be369ff4d 100644
--- a/server-plugin/pom.xml
+++ b/server-plugin/pom.xml
@@ -43,6 +43,7 @@
<module>server-plugin-executor-remotedocker</module>
<module>server-plugin-executor-servershell</module>
<module>server-plugin-executor-remoteshell</module>
+ <module>server-plugin-executor-serversandbox</module>
<module>server-plugin-provisioner-servershell</module>
<module>server-plugin-provisioner-serverdocker</module>
<module>server-plugin-report-unittest</module>
diff --git a/server-plugin/server-plugin-executor-remotedocker/src/main/java/io/onedev/server/plugin/executor/remotedocker/RemoteDockerExecutor.java b/server-plugin/server-plugin-executor-remotedocker/src/main/java/io/onedev/server/plugin/executor/remotedocker/RemoteDockerExecutor.java
index f51fd5f6a3..16d264fd55 100644
--- a/server-plugin/server-plugin-executor-remotedocker/src/main/java/io/onedev/server/plugin/executor/remotedocker/RemoteDockerExecutor.java
+++ b/server-plugin/server-plugin-executor-remotedocker/src/main/java/io/onedev/server/plugin/executor/remotedocker/RemoteDockerExecutor.java
@@ -16,6 +16,7 @@ import io.onedev.agent.job.JobDockerSettings;
import io.onedev.agent.job.JobResumeData;
import io.onedev.agent.job.TestDockerJobData;
import io.onedev.agent.shell.JobShellOpenData;
+import io.onedev.agent.shell.JobShellOpenData.Mode;
import io.onedev.commons.utils.ExplicitException;
import io.onedev.commons.utils.TaskLogger;
import io.onedev.server.OneDev;
@@ -136,7 +137,7 @@ public class RemoteDockerExecutor extends ServerDockerExecutor {
@Override
public Shell openShell(JobContext jobContext, JobTerminal terminal) {
if (agentSession != null) {
- var shellOpenData = new JobShellOpenData(true, jobContext.getJobToken(),
+ var shellOpenData = new JobShellOpenData(Mode.CONTAINER, jobContext.getJobToken(),
terminal.getSessionId(), jobContext.getProjectId(), jobContext.getBuildNumber(),
jobContext.getSubmitSequence(), getDockerSockPath());
return new JobAgentShell(terminal, agentSession, shellOpenData);
diff --git a/server-plugin/server-plugin-executor-remoteshell/src/main/java/io/onedev/server/plugin/executor/remoteshell/RemoteShellExecutor.java b/server-plugin/server-plugin-executor-remoteshell/src/main/java/io/onedev/server/plugin/executor/remoteshell/RemoteShellExecutor.java
index 7a027c104f..95d340c95d 100644
--- a/server-plugin/server-plugin-executor-remoteshell/src/main/java/io/onedev/server/plugin/executor/remoteshell/RemoteShellExecutor.java
+++ b/server-plugin/server-plugin-executor-remoteshell/src/main/java/io/onedev/server/plugin/executor/remoteshell/RemoteShellExecutor.java
@@ -14,6 +14,7 @@ import io.onedev.agent.job.JobResumeData;
import io.onedev.agent.job.ShellJobData;
import io.onedev.agent.job.TestShellJobData;
import io.onedev.agent.shell.JobShellOpenData;
+import io.onedev.agent.shell.JobShellOpenData.Mode;
import io.onedev.commons.utils.ExplicitException;
import io.onedev.commons.utils.TaskLogger;
import io.onedev.server.OneDev;
@@ -118,7 +119,7 @@ public class RemoteShellExecutor extends ServerShellExecutor {
@Override
public Shell openShell(JobContext jobContext, JobTerminal terminal) {
if (agentSession != null) {
- var shellOpenData = new JobShellOpenData(false, jobContext.getJobToken(),
+ var shellOpenData = new JobShellOpenData(Mode.HOST, jobContext.getJobToken(),
terminal.getSessionId(), jobContext.getProjectId(),
jobContext.getBuildNumber(), jobContext.getSubmitSequence(), null);
return new JobAgentShell(terminal, agentSession, shellOpenData);
@@ -160,4 +161,4 @@ public class RemoteShellExecutor extends ServerShellExecutor {
new TestShellJobData(UUID.randomUUID().toString()), jobLogger);
}
-}
\ No newline at end of file
+}
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.java
index dbb4e86fbf..a2957a1ad3 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
@@ -86,7 +86,9 @@ import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotEmpty;
@Editable(order=ServerDockerExecutor.ORDER, name="Server Docker Executor",
- description="This executor runs build jobs as docker containers on ${productName} server")
+ description="This executor runs build jobs as Docker containers on ${productName} server. "
+ + "<b class='text-warning'>WARNING:</b> For better security, use a Remote Docker Executor "
+ + "on a dedicated agent host, especially for untrusted jobs.")
@ClassValidating
public class ServerDockerExecutor extends JobExecutor implements DockerAware, Testable<TestData>, Validatable {
diff --git a/server-plugin/server-plugin-executor-serversandbox/pom.xml b/server-plugin/server-plugin-executor-serversandbox/pom.xml
new file mode 100644
index 0000000000..754bb1a32e
--- /dev/null
+++ b/server-plugin/server-plugin-executor-serversandbox/pom.xml
@@ -0,0 +1,13 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>server-plugin-executor-serversandbox</artifactId>
+ <parent>
+ <groupId>io.onedev</groupId>
+ <artifactId>server-plugin</artifactId>
+ <version>16.9.5</version>
+ </parent>
+ <properties>
+ <moduleClass>io.onedev.server.plugin.executor.serversandbox.ServerSandboxModule</moduleClass>
+ </properties>
+</project>
diff --git a/server-plugin/server-plugin-executor-serversandbox/src/main/java/io/onedev/server/plugin/executor/serversandbox/ServerSandboxExecutor.java b/server-plugin/server-plugin-executor-serversandbox/src/main/java/io/onedev/server/plugin/executor/serversandbox/ServerSandboxExecutor.java
new file mode 100644
index 0000000000..a4dbed04a6
--- /dev/null
+++ b/server-plugin/server-plugin-executor-serversandbox/src/main/java/io/onedev/server/plugin/executor/serversandbox/ServerSandboxExecutor.java
@@ -0,0 +1,330 @@
+package io.onedev.server.plugin.executor.serversandbox;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ExecutionException;
+
+import io.onedev.server.annotation.OmitName;
+import jakarta.validation.ConstraintValidatorContext;
+import jakarta.validation.Valid;
+import jakarta.validation.constraints.Min;
+import jakarta.validation.constraints.NotEmpty;
+
+import io.onedev.agent.SandboxSettings;
+import io.onedev.agent.job.SandboxJob;
+import io.onedev.agent.job.ShellJobData;
+import io.onedev.commons.bootstrap.Bootstrap;
+import io.onedev.commons.utils.ExplicitException;
+import io.onedev.commons.utils.TaskLogger;
+import io.onedev.k8shelper.RegistryLoginFacade;
+import io.onedev.server.OneDev;
+import io.onedev.server.annotation.ClassValidating;
+import io.onedev.server.annotation.Editable;
+import io.onedev.server.annotation.ReservedOptions;
+import io.onedev.server.cluster.ClusterTask;
+import io.onedev.server.job.JobContext;
+import io.onedev.server.job.JobRunnable;
+import io.onedev.server.job.JobService;
+import io.onedev.server.job.JobTerminal;
+import io.onedev.server.job.match.JobMatch;
+import io.onedev.server.job.match.JobMatchContext;
+import io.onedev.server.model.support.administration.jobexecutor.JobExecutor;
+import io.onedev.server.model.support.administration.jobexecutor.RegistryLogin;
+import io.onedev.server.model.support.administration.jobexecutor.SandboxAware;
+import io.onedev.server.service.ResourceService;
+import io.onedev.server.service.SettingService;
+import io.onedev.server.terminal.CommandlineShell;
+import io.onedev.server.terminal.Shell;
+import io.onedev.server.validation.Validatable;
+import io.onedev.server.web.util.Testable;
+
+@Editable(order=450, name="Server Sandbox Executor", description="Runs shell and Docker steps in a fresh Docker Sandbox on the server. "
+ + "Job services run inside the sandbox and are accessible by service name from shell and container steps. "
+ + "The sandbox and its services are deleted after each job. "
+ + "See <a href='${docsite}/tutorials/sandbox/working-with-sandbox' target='_blank'>Working with Sandbox</a> "
+ + "for host setup, login, and security practices. "
+ + "<b class='text-warning'>WARNING:</b> For better security, use a Remote Sandbox Executor "
+ + "on a dedicated agent host, especially for untrusted jobs.")
+@ClassValidating
+public class ServerSandboxExecutor extends JobExecutor implements SandboxAware, Testable<ServerSandboxExecutor.TestData>, Validatable {
+
+ private static final long serialVersionUID = 1L;
+
+ private String sandboxExecutable = "sbx";
+
+ private String template;
+
+ private boolean alwaysPullTemplateImage = true;
+
+ private Integer cpus;
+
+ private String memory;
+
+ private Integer concurrency;
+
+ private boolean alwaysPullContainerImage = true;
+
+ private String runOptions;
+
+ private String networkOptions;
+
+ private String cpuLimit;
+
+ private String memoryLimit;
+
+ private List<RegistryLogin> registryLogins = new ArrayList<>();
+
+ @Editable(order=500, group="Container Settings", description="Whether or not to always pull images when running containers or building images "
+ + "inside the sandbox. If disabled, cached images are used when available.")
+ public boolean isAlwaysPullContainerImage() {
+ return alwaysPullContainerImage;
+ }
+
+ public void setAlwaysPullContainerImage(boolean alwaysPullContainerImage) {
+ this.alwaysPullContainerImage = alwaysPullContainerImage;
+ }
+
+ @Editable(order=520, group="Container Settings", description="Optional registry logins for steps and services that use container images inside the sandbox. "
+ + "These logins are not used to pull the sandbox template image. "
+ + "Logins specified in a step or service override these for the same registry. For built-in registry, use "
+ + "<code>@server_url@</code> for registry url, <code>@job_token@</code> for user name, and access token for password.")
+ public List<@Valid RegistryLogin> getRegistryLogins() {
+ // Existing executor settings may predate registry logins.
+ if (registryLogins == null)
+ registryLogins = new ArrayList<>();
+ return registryLogins;
+ }
+
+ public void setRegistryLogins(List<RegistryLogin> registryLogins) {
+ this.registryLogins = registryLogins;
+ }
+
+ @Override
+ public List<RegistryLoginFacade> getRegistryLogins(String jobToken) {
+ return getRegistryLogins().stream().map(it -> it.getFacade(jobToken)).toList();
+ }
+
+ @Override
+ public boolean isValid(ConstraintValidatorContext context) {
+ var registryUrls = new HashSet<String>();
+ for (var login : getRegistryLogins()) {
+ if (!registryUrls.add(login.getRegistryUrl())) {
+ context.disableDefaultConstraintViolation();
+ var message = login.getRegistryUrl() != null
+ ? "Duplicate login entry for registry '" + login.getRegistryUrl() + "'"
+ : "Duplicate login entry for official registry";
+ context.buildConstraintViolationWithTemplate(message)
+ .addPropertyNode("registryLogins").addConstraintViolation();
+ return false;
+ }
+ }
+ return true;
+ }
+
+ @Editable(order=510, group="Container Settings", description="Optionally specify Docker options to run containers inside the sandbox. "
+ + "Multiple options should be separated by space, and single options containing spaces should be quoted. "
+ + "Do not specify <code>--network</code> or <code>--net</code> for jobs using services, as their network is managed automatically. "
+ + "File paths refer to the sandbox filesystem; relative file paths are resolved from the job working directory.")
+ @ReservedOptions({"--", "(--workdir|--detach|--attach|--tty|--interactive|--rm|--restart|--name|--user|--entrypoint|--stop-timeout)(=.*)?",
+ "(-[Pq]*[wdatiu]).*"})
+ public String getRunOptions() {
+ return runOptions;
+ }
+
+ public void setRunOptions(String runOptions) {
+ this.runOptions = runOptions;
+ }
+
+ @Editable(order=515, group="Container Settings", description="Optionally specify Docker options to create the network for jobs using services. "
+ + "Multiple options should be separated by space, and single options containing spaces should be quoted.")
+ @ReservedOptions({"--", "(-d).*", "--driver", "(--driver)=.*"})
+ public String getNetworkOptions() {
+ return networkOptions;
+ }
+
+ public void setNetworkOptions(String networkOptions) {
+ this.networkOptions = networkOptions;
+ }
+
+ @Editable(order=530, group="Container Settings", placeholder="No limit", description="Optionally specify the CPU limit of each container "
+ + "run by a step or service inside the sandbox, for example 0.5 or 2. This is passed to Docker as <code>--cpus</code>.")
+ public String getCpuLimit() {
+ return cpuLimit;
+ }
+
+ public void setCpuLimit(String cpuLimit) {
+ this.cpuLimit = cpuLimit;
+ }
+
+ @Editable(order=540, group="Container Settings", placeholder="No limit", description="Optionally specify the memory limit of each container "
+ + "run by a step or service inside the sandbox, for example 512m or 2g. This is passed to Docker as <code>--memory</code>.")
+ public String getMemoryLimit() {
+ return memoryLimit;
+ }
+
+ public void setMemoryLimit(String memoryLimit) {
+ this.memoryLimit = memoryLimit;
+ }
+
+ @Editable(order=50100, group="More Settings", name="Sandbox Executable", description="Path to the Docker Sandboxes sbx executable")
+ @NotEmpty
+ public String getSandboxExecutable() {
+ return sandboxExecutable;
+ }
+
+ public void setSandboxExecutable(String sandboxExecutable) {
+ this.sandboxExecutable = sandboxExecutable;
+ }
+
+ @Editable(order=110, placeholder="Use default template", description="""
+ Optional shell template image. Leave empty to use Docker Sandbox's built-in shell-docker \
+ template. For ordinary jobs, base custom templates on <code>docker/sandbox-templates:shell</code>, \
+ with Python 3 and Git. For jobs that need to interact with docker daemon or builder, \
+ use <code>docker/sandbox-templates:shell-docker</code> as the base image. Job setup, shell \
+ commands, and cache operations run as root inside the sandbox.""")
+ public String getTemplate() {
+ return template;
+ }
+
+ public void setTemplate(String template) {
+ this.template = template;
+ }
+
+ @Editable(order=600, group="More Settings", description="Whether or not to always pull the template image when "
+ + "creating a sandbox. If disabled, a cached image is used when available.")
+ public boolean isAlwaysPullTemplateImage() {
+ return alwaysPullTemplateImage;
+ }
+
+ public void setAlwaysPullTemplateImage(boolean alwaysPullTemplateImage) {
+ this.alwaysPullTemplateImage = alwaysPullTemplateImage;
+ }
+
+ @Editable(order=120, name="CPUs", placeholder = "Docker sandbox default", description="CPU count for each sandbox. Leave empty to use the Docker Sandboxes default (All CPUs).")
+ @Min(1)
+ public Integer getCpus() {
+ return cpus;
+ }
+
+ public void setCpus(Integer cpus) {
+ this.cpus = cpus;
+ }
+
+ @Editable(order=130, placeholder = "Docker sandbox default", description="Memory for each sandbox, for example 2g. Leave empty to use the Docker Sandboxes default (50% of host memory).")
+ public String getMemory() {
+ return memory;
+ }
+
+ public void setMemory(String memory) {
+ this.memory = memory;
+ }
+
+ @Editable(order=1000, description="Maximum concurrent jobs on each server. Leave empty to use its CPU count.")
+ @Min(1)
+ public Integer getConcurrency() {
+ return concurrency;
+ }
+
+ public void setConcurrency(Integer concurrency) {
+ this.concurrency = concurrency;
+ }
+
+ protected int getConcurrencyNumber() {
+ return concurrency != null ? concurrency : 0;
+ }
+
+ @Editable(order=10000, name="Applicable Jobs")
+ @io.onedev.server.annotation.JobMatch(withProjectCriteria=true, withJobCriteria=true)
+ public String getJobMatch() {
+ return jobMatch;
+ }
+
+ public void setJobMatch(String jobMatch) {
+ this.jobMatch = jobMatch;
+ }
+
+ @Override
+ public boolean isApplicable(JobMatchContext context) {
+ return jobMatch == null || JobMatch.parse(jobMatch, true, true).matches(context);
+ }
+
+ protected SandboxSettings getSandboxSettings(String jobToken) {
+ return new SandboxSettings(template, cpus, memory, alwaysPullTemplateImage, alwaysPullContainerImage,
+ OneDev.getInstance(SettingService.class).getSystemSetting().getServerUrl().toString(), cpuLimit, memoryLimit, runOptions, networkOptions,
+ getRegistryLogins(jobToken));
+ }
+
+ @Override
+ public boolean execute(JobContext context, TaskLogger logger) {
+ ClusterTask<Boolean> runnable = () -> OneDev.getInstance(JobService.class).runJob(context, new JobRunnable() {
+
+ private static final long serialVersionUID = 1L;
+
+ private transient volatile SandboxJob sandboxJob;
+
+ private transient TaskLogger sandboxLogger;
+
+ @Override
+ public boolean run(TaskLogger logger) {
+ notifyJobRunning(context.getBuildId(), null);
+ logger.log("Executing job with sandbox executor '" + getName() + "'...");
+ sandboxLogger = logger;
+ sandboxJob = new SandboxJob(getSandboxExecutable(), getSandboxSettings(context.getJobToken()));
+ var data = new ShellJobData(context.getJobToken(), getName(), context.getProjectPath(),
+ context.getProjectId(), context.getRefName(), context.getCommitId().name(),
+ context.getBuildNumber(), context.getSubmitSequence(), context.getActions(), context.getSecretMasker());
+ return sandboxJob.run(data, context.getServices(), Bootstrap.getTrustCertsDir(), Map.of(), logger);
+ }
+
+ @Override
+ public void resume(JobContext context) {
+ if (sandboxJob != null)
+ sandboxJob.resume(sandboxLogger);
+ }
+
+ @Override
+ public Shell openShell(JobContext context, JobTerminal terminal) {
+ if (sandboxJob == null)
+ throw new ExplicitException("Sandbox not running");
+ return new CommandlineShell(terminal, sandboxJob.openShell());
+ }
+ });
+ logger.log("Pending resource allocation...");
+ try {
+ return OneDev.getInstance(ResourceService.class).submitServerTask(null, getName(), getConcurrencyNumber(), 1, runnable).get();
+ } catch (InterruptedException | ExecutionException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public void test(TestData data, TaskLogger logger) {
+ new SandboxJob(getSandboxExecutable(), getSandboxSettings(UUID.randomUUID().toString()))
+ .test(data.getDockerImage(), Bootstrap.getTrustCertsDir(), logger);
+ }
+
+ @Editable(name="Test Sandbox Executor")
+ public static class TestData implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private String dockerImage;
+
+ @Editable(name="Optional Docker Image", description="""
+ Optionally specify a docker image to also test running commands in a \
+ container inside the sandbox. The image must contain sh.""")
+ @OmitName
+ public String getDockerImage() {
+ return dockerImage;
+ }
+
+ public void setDockerImage(String dockerImage) {
+ this.dockerImage = dockerImage;
+ }
+ }
+
+}
diff --git a/server-plugin/server-plugin-executor-serversandbox/src/main/java/io/onedev/server/plugin/executor/serversandbox/ServerSandboxModule.java b/server-plugin/server-plugin-executor-serversandbox/src/main/java/io/onedev/server/plugin/executor/serversandbox/ServerSandboxModule.java
new file mode 100644
index 0000000000..769b08dd96
--- /dev/null
+++ b/server-plugin/server-plugin-executor-serversandbox/src/main/java/io/onedev/server/plugin/executor/serversandbox/ServerSandboxModule.java
@@ -0,0 +1,35 @@
+package io.onedev.server.plugin.executor.serversandbox;
+
+import java.util.Collection;
+import java.util.Set;
+
+import io.onedev.commons.loader.AbstractPluginModule;
+import io.onedev.commons.loader.ImplementationProvider;
+import io.onedev.server.model.support.administration.jobexecutor.JobExecutor;
+
+/**
+ * NOTE: Do not forget to rename moduleClass property defined in the pom if you've renamed this class.
+ *
+ */
+public class ServerSandboxModule extends AbstractPluginModule {
+
+ @Override
+ protected void configure() {
+ super.configure();
+
+ contribute(ImplementationProvider.class, new ImplementationProvider() {
+
+ @Override
+ public Class<?> getAbstractClass() {
+ return JobExecutor.class;
+ }
+
+ @Override
+ public Collection<Class<?>> getImplementations() {
+ return Set.of(ServerSandboxExecutor.class);
+ }
+
+ });
+ }
+
+}
diff --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.java
index a8f9e37f9a..b98d0668c2 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
@@ -70,7 +70,9 @@ import io.onedev.server.terminal.Shell;
import io.onedev.server.web.util.Testable;
@Editable(order=ServerShellExecutor.ORDER, name="Server Shell Executor", description="" +
- "This executor runs build jobs with ${productName} server's shell facility")
+ "This executor runs build jobs with ${productName} server's shell facility. "
+ + "<b class='text-warning'>WARNING:</b> For better security, use a Remote Shell Executor "
+ + "on a dedicated agent host, especially for untrusted jobs.")
public class ServerShellExecutor extends JobExecutor implements Testable<Testable.None> {
private static final long serialVersionUID = 1L;
diff --git a/server-plugin/server-plugin-provisioner-serverdocker/src/main/java/io/onedev/server/plugin/provisioner/serverdocker/ServerDockerProvisioner.java b/server-plugin/server-plugin-provisioner-serverdocker/src/main/java/io/onedev/server/plugin/provisioner/serverdocker/ServerDockerProvisioner.java
index b1888d1a02..ace2e273d6 100644
--- a/server-plugin/server-plugin-provisioner-serverdocker/src/main/java/io/onedev/server/plugin/provisioner/serverdocker/ServerDockerProvisioner.java
+++ b/server-plugin/server-plugin-provisioner-serverdocker/src/main/java/io/onedev/server/plugin/provisioner/serverdocker/ServerDockerProvisioner.java
@@ -80,7 +80,9 @@ import io.onedev.server.workspace.WorkspaceContext;
import io.onedev.server.workspace.WorkspaceRuntime;
@Editable(order=ServerDockerProvisioner.ORDER, name="Server Docker Provisioner", description = """
- This provisioner creates workspaces inside Docker containers on ${productName} server""")
+ This provisioner creates workspaces inside Docker containers on ${productName} server.
+ <b class='text-warning'>WARNING:</b> For better security, use a Remote Docker Provisioner
+ on a dedicated agent host, especially for untrusted workspaces.""")
public class ServerDockerProvisioner extends WorkspaceProvisioner implements DockerAware, Testable<ServerDockerProvisioner.TestData> {
private static final long serialVersionUID = 1L;
diff --git a/server-plugin/server-plugin-provisioner-servershell/src/main/java/io/onedev/server/plugin/provisioner/servershell/ServerShellProvisioner.java b/server-plugin/server-plugin-provisioner-servershell/src/main/java/io/onedev/server/plugin/provisioner/servershell/ServerShellProvisioner.java
index e54b72a1a1..22ef4542e3 100644
--- a/server-plugin/server-plugin-provisioner-servershell/src/main/java/io/onedev/server/plugin/provisioner/servershell/ServerShellProvisioner.java
+++ b/server-plugin/server-plugin-provisioner-servershell/src/main/java/io/onedev/server/plugin/provisioner/servershell/ServerShellProvisioner.java
@@ -57,7 +57,9 @@ import io.onedev.server.workspace.WorkspaceRuntime;
@Editable(order=ServerShellProvisioner.ORDER, name="Server Shell Provisioner", description="""
This provisioner creates workspaces with ${productName} server's shell facility, and requires
- tmux to be installed on ${productName} server""")
+ tmux to be installed on ${productName} server.
+ <b class='text-warning'>WARNING:</b> For better security, use a Remote Shell Provisioner
+ on a dedicated agent host, especially for untrusted workspaces.""")
public class ServerShellProvisioner extends WorkspaceProvisioner implements Testable<Testable.None> {
private static final long serialVersionUID = 1L;
diff --git a/server-product/pom.xml b/server-product/pom.xml
index 5edd7d9ca7..4d08dee254 100644
--- a/server-product/pom.xml
+++ b/server-product/pom.xml
@@ -130,6 +130,11 @@
<artifactId>server-plugin-executor-remoteshell</artifactId>
<version>${project.version}</version>
</dependency>
+ <dependency>
+ <groupId>io.onedev</groupId>
+ <artifactId>server-plugin-executor-serversandbox</artifactId>
+ <version>${project.version}</version>
+ </dependency>
<dependency>
<groupId>io.onedev</groupId>
<artifactId>server-plugin-provisioner-servershell</artifactId>