|
| 1 | +/* |
| 2 | + * Copyright 2024-2025 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package com.alibaba.cloud.ai.graph.node.code; |
| 17 | + |
| 18 | +import com.alibaba.cloud.ai.graph.node.code.entity.CodeBlock; |
| 19 | +import com.alibaba.cloud.ai.graph.node.code.entity.CodeExecutionConfig; |
| 20 | +import com.alibaba.cloud.ai.graph.node.code.entity.CodeExecutionResult; |
| 21 | +import com.alibaba.cloud.ai.graph.utils.CodeUtils; |
| 22 | +import com.github.dockerjava.api.DockerClient; |
| 23 | +import com.github.dockerjava.api.async.ResultCallbackTemplate; |
| 24 | +import com.github.dockerjava.api.command.CreateContainerCmd; |
| 25 | +import com.github.dockerjava.api.command.CreateContainerResponse; |
| 26 | +import com.github.dockerjava.api.command.InspectContainerResponse; |
| 27 | +import com.github.dockerjava.api.model.Bind; |
| 28 | +import com.github.dockerjava.api.model.Frame; |
| 29 | +import com.github.dockerjava.api.model.Volume; |
| 30 | +import com.github.dockerjava.core.DockerClientBuilder; |
| 31 | +import org.slf4j.Logger; |
| 32 | +import org.slf4j.LoggerFactory; |
| 33 | +import org.apache.commons.codec.digest.DigestUtils; |
| 34 | +import com.alibaba.cloud.ai.graph.utils.FileUtils; |
| 35 | + |
| 36 | +import java.util.List; |
| 37 | +import java.util.Objects; |
| 38 | +import java.util.concurrent.TimeUnit; |
| 39 | + |
| 40 | +import static com.github.dockerjava.api.model.HostConfig.newHostConfig; |
| 41 | + |
| 42 | +/** |
| 43 | + * @author HeYQ |
| 44 | + * @since 2025-06-01 20:15 |
| 45 | + */ |
| 46 | + |
| 47 | +public class DockerCodeExecutor implements CodeExecutor { |
| 48 | + |
| 49 | + private static final Logger logger = LoggerFactory.getLogger(DockerCodeExecutor.class); |
| 50 | + |
| 51 | + @Override |
| 52 | + public CodeExecutionResult executeCodeBlocks(List<CodeBlock> codeBlockList, CodeExecutionConfig codeExecutionConfig) |
| 53 | + throws Exception { |
| 54 | + StringBuilder allLogs = new StringBuilder(); |
| 55 | + CodeExecutionResult result; |
| 56 | + |
| 57 | + // Create Docker client |
| 58 | + try (DockerClient dockerClient = DockerClientBuilder.getInstance().build()) { |
| 59 | + |
| 60 | + for (CodeBlock codeBlock : codeBlockList) { |
| 61 | + String language = codeBlock.language(); |
| 62 | + String code = codeBlock.code(); |
| 63 | + logger.info("\n>>>>>>>> EXECUTING CODE BLOCK (inferred language is {})...", language); |
| 64 | + |
| 65 | + // Generate unique filename for each code block |
| 66 | + String codeHash = DigestUtils.md5Hex(code); |
| 67 | + String fileExt = CodeUtils.getFileExtForLanguage(language); |
| 68 | + String filename = String.format("tmp_code_%s.%s", codeHash, fileExt); |
| 69 | + |
| 70 | + // Write code to working directory |
| 71 | + String hostWorkDir = codeExecutionConfig.getWorkDir(); |
| 72 | + FileUtils.writeCodeToFile(hostWorkDir, filename, code); |
| 73 | + |
| 74 | + // Create and configure container |
| 75 | + // Mount host directory to container's /workspace directory |
| 76 | + Volume containerVolume = new Volume("/workspace"); |
| 77 | + Bind volumeBind = new Bind(hostWorkDir, containerVolume); |
| 78 | + |
| 79 | + CreateContainerCmd createContainerCmd = dockerClient.createContainerCmd(codeExecutionConfig.getDocker()) |
| 80 | + .withName(codeExecutionConfig.getContainerName() + "_" + codeBlockList.indexOf(codeBlock)) |
| 81 | + .withCmd(CodeUtils.getExecutableForLanguage(language), filename) |
| 82 | + .withWorkingDir("/workspace") |
| 83 | + .withHostConfig(newHostConfig().withBinds(volumeBind)); |
| 84 | + CreateContainerResponse container = createContainerCmd.exec(); |
| 85 | + |
| 86 | + try { |
| 87 | + // Start container |
| 88 | + dockerClient.startContainerCmd(container.getId()).exec(); |
| 89 | + |
| 90 | + // Wait for container execution to complete |
| 91 | + dockerClient.waitContainerCmd(container.getId()) |
| 92 | + .start() |
| 93 | + .awaitCompletion(codeExecutionConfig.getTimeout(), TimeUnit.SECONDS); |
| 94 | + |
| 95 | + // Get container logs |
| 96 | + String logs = dockerClient.logContainerCmd(container.getId()) |
| 97 | + .withStdOut(true) |
| 98 | + .withStdErr(true) |
| 99 | + .exec(new LogContainerResultCallback()) |
| 100 | + .toString(); |
| 101 | + |
| 102 | + // Get container exit code |
| 103 | + InspectContainerResponse containerInfo = dockerClient.inspectContainerCmd(container.getId()).exec(); |
| 104 | + int exitCode = Objects.requireNonNull(containerInfo.getState().getExitCodeLong()).intValue(); |
| 105 | + |
| 106 | + // Append logs |
| 107 | + allLogs.append("\n").append(logs.trim()); |
| 108 | + |
| 109 | + // If execution failed, return result immediately |
| 110 | + if (exitCode != 0) { |
| 111 | + return new CodeExecutionResult(exitCode, allLogs.toString()); |
| 112 | + } |
| 113 | + } |
| 114 | + finally { |
| 115 | + // Clean up container |
| 116 | + dockerClient.removeContainerCmd(container.getId()).withForce(true).exec(); |
| 117 | + // Delete temporary file |
| 118 | + FileUtils.deleteFile(codeExecutionConfig.getWorkDir(), filename); |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + return new CodeExecutionResult(0, allLogs.toString()); |
| 123 | + } |
| 124 | + catch (Exception e) { |
| 125 | + logger.error("Error executing code in Docker container", e); |
| 126 | + throw new RuntimeException("Error executing code in Docker container: " + e.getMessage(), e); |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + @Override |
| 131 | + public void restart() { |
| 132 | + |
| 133 | + } |
| 134 | + |
| 135 | + private static class LogContainerResultCallback extends ResultCallbackTemplate<LogContainerResultCallback, Frame> { |
| 136 | + |
| 137 | + private final StringBuilder log = new StringBuilder(); |
| 138 | + |
| 139 | + @Override |
| 140 | + public void onNext(Frame frame) { |
| 141 | + log.append(new String(frame.getPayload())); |
| 142 | + } |
| 143 | + |
| 144 | + @Override |
| 145 | + public String toString() { |
| 146 | + return log.toString(); |
| 147 | + } |
| 148 | + |
| 149 | + } |
| 150 | + |
| 151 | +} |
0 commit comments