往期开发(已经完成)

  • OJ 判题项目-介绍(一)
  • OJ 判题项目-初始化(二)
  • OJ 判题项目-前后端联调(三)
  • OJ 判题项目-简易判题机(四)
  • OJ 判题项目-原生代码沙箱(五)
  • OJ 判题项目-Docker 代码沙箱(六)
  • OJ 判题项目-微服务改造(七)

  • 今日后端开发

    • docker 容器

      docker 容器是可以独立的拥有一套运行环境,应用程序和服务的封装,从而把程序运行在一个隔离的、密闭的、隐私的空间内。

      每个容器都可以理解为一个新的电脑-定制化的操作系统

      • docker 基本概念

        镜像:用来创建容器的安装包,可以理解为给电脑安装操作系统的系统镜像
        容器:通过镜像来安装一套运行环境,容器内可以运行多个程序,可以理解为一个电脑实例
        镜像仓库:存放镜像的仓库,用户可以从仓库中进行下载镜像,可以把做好的镜像放入仓库中
        DockerFile:用来制作镜像的文件。可以理解为一个清单

      • docker 组成
        1. Docker:运行在 Linux 内核上
        2. CGroups:实现了容器的资源隔离,底层是使用了 Linux Cgroup 命令,控制进程资源
        3. NetWork 网络:实现容器的网络隔离,docker 容器内部的网络互相不影响
        4. Namespaces 命名空间:可以把进程隔离在不同的命名空间,每个容器他都可以有自己的命名空间,不同的命名空间互相不影响
        5. Storge 存储空间:容器内的文件是互相隔离的,也可以去使用宿主机的文件
      • docker 安装使用(命令行)
        本人使用的是 ubuntu 系统

        1
        apt-get install docker
        1. 拉取镜像
          1
          docker pull [images-name]
        2. 创建容器
          1
          docker create [images-name]
        3. 查看容器状态
          1
          docker ps -a
        4. 启动容器
          1
          docker start [container-name]
        5. 查看日志
          1
          docker logs [container-name]
        6. 删除容器
          1
          docker rm [container-name]
        7. 删除镜像
          1
          docker rmi images
    • Java 操作 Docker

      1. 引入依赖
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        <dependency>
        <groupId>com.github.docker-java</groupId>
        <artifactId>docker-java-transport-httpclient5</artifactId>
        <version>3.3.0</version>
        </dependency>
        <dependency>
        <groupId>com.github.docker-java</groupId>
        <artifactId>docker-java</artifactId>
        <version>3.3.0</version>
        </dependency>
      2. 测试使用 JAVA 拉取镜像
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        // 镜像名称
        String image = "openjdk:8-alpine";
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
        pullImageCmd.exec(new PullImageResultCallback() {
        @Override
        public void onNext(PullResponseItem item) {
        System.out.println("下载镜像中:" + item.getStatus());
        super.onNext(item);
        }
        }).awaitCompletion();
        System.out.println("下载镜像完成!");
      3. 创建容器
        1
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
      4. 查看容器状态
        1
        2
        3
        4
        5
        ListContainersCmd listContainersCmd = dockerClient.listContainersCmd();
        List<Container> containerList = listContainersCmd.withShowAll(true).exec();
        for (Container container : containerList) {
        System.out.println(container);
        }
      5. 启动容器
        1
        dockerClient.startContainerCmd(contarinerId).exec();
      6. 查看日志
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        dockerClient.logContainerCmd(containerId)
        .withStdErr(true)
        .withStdOut(true)
        .exec(new LogContainerResultCallback(){
        @Override
        public void onNext(Frame item) {
        System.out.println("日志类型:" + item.getStreamType());
        System.out.println("日志:" + new String(item.getPayload()));
        super.onNext(item);
        }
        })
        .awaitCompletion();
      7. 删除容器
        1
        dockerClient.removeContainerCmd(containerId).withForce(true).exec();
      8. 删除镜像
        1
        dockerClient.removeImageCmd(image).exec();
    • Docker 实现代码沙箱

      思路:使用 docker 拉取 java 运行环境镜像,创建容器,在容器内执行 java 代码 与原生的实现思路一样,只是将代码运行在 docker 容器中

      1. 创建 docker 容器并启动(上述已经拉取了镜像不必在程序中在拉取)
        完整代码
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
         // 1. 创建容器执行命令
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(IMAGES);
        // 2. 创建容器时候 进行配置 交互式容器withTty
        HostConfig hostConfig = new HostConfig();
        // 3. 100MB内存 1个CPU 内存交换 一定程度上防止文件写入
        hostConfig.withMemory(100 * 1000 * 1000L)
        .withCpuCount(1L)
        .withMemorySwap(0L);
        // 4. 存储本地文件映射
        hostConfig.setBinds(new Bind(userCodeFile.getParentFile().getAbsolutePath(), new Volume("/app")));
        CreateContainerResponse containerResponse = containerCmd
        .withHostConfig(hostConfig)
        .withNetworkDisabled(true)
        .withReadonlyRootfs(true)
        .withAttachStderr(true)
        .withAttachStdin(true)
        .withAttachStdout(true)
        .withTty(true)
        .exec();
        // 5. 启动容器
        String containerId = containerResponse.getId();
        dockerClient.startContainerCmd(containerId).exec();
        log.info("启动容器成功!容器ID:" + containerId);
        一定要开启 tty 模式,不然容器不能提供交互式,直接就停止了。
        setBinds 就是绑定了容器与本地文件的映射,映射到容器的工作目录中,在代码执行过程中去寻找可运行 class 文件
      2. 在容器中运行代码
        命令行的方式

        1
        docker exec [docker_name] java -cp [路径:是映射到容器内的路径] [类名] [参数]

        java 代码的形式

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        38
        39
        40
        41
        42
        43
        44
        45
        46
        47
        48
        49
        50
        51
        52
        53
        54
        55
        56
        57
        58
        59
        60
        61
        62
        63
        64
        65
        66
        67
        68
        // 4. 构建运行cmd参数 拆解输入示例
        String[] inputArgsArray = args.split(" ");
        String[] cmdArray = ArrayUtil.append(new String[]{"java", "-cp", "/app", "Main"}, inputArgsArray);
        log.info("构造的运行指令为:" + Arrays.toString(cmdArray));
        // 5. 构建运行命令
        ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
        .withCmd(cmdArray)
        .withAttachStderr(true)
        .withAttachStdin(true)
        .withAttachStdout(true)
        .exec();
        // 6. 执行命令
        String runCmdId = execCreateCmdResponse.getId();
        // 踩坑 打印结果就是frame 即可
        // 获取占用内存 监控
        StatsCmd statsCmd = dockerClient.statsCmd(containerId);
        ResultCallback<Statistics> statisticsResultCallback = statsCmd.exec(new ResultCallback<Statistics>() {
        @Override
        public void onStart(Closeable closeable) {

        }

        @Override
        public void onNext(Statistics statistics) {
        // 获取最大的内存占用
        maxMemory[0] = Math.max(statistics.getMemoryStats().getUsage() != null ? statistics.getMemoryStats(getUsage() : -1, maxMemory[0]);
        }

        @Override
        public void onError(Throwable throwable) {

        }

        @Override
        public void onComplete() {

        }

        @Override
        public void close() throws IOException {

        }
        });
        statsCmd.exec(statisticsResultCallback);
        Thread.sleep(1000);
        dockerClient.execStartCmd(runCmdId)
        .exec(new ExecStartResultCallback() {
        // 监控防止执行的程序一直执行 超时控制
        @Override
        public void onComplete() {
        timeout[0] = false;
        super.onComplete();
        }

        @Override
        public void onNext(Frame frame) {
        treamType streamType = frame.getStreamType();
        if (StreamType.STDERR.equals(streamType)) {
        errorMessage[0] = ("" + frame).replace("STDOUT: ", "");
        log.info("错误结果:" + frame);
        } else {
        message[0] = ("" + frame).replace("STDOUT: ", "");
        log.info("正确结果:" + frame);
        }
        super.onNext(frame);
        }
        }).awaitCompletion(TIME_OUT, TimeUnit.MILLISECONDS);
        ```

        需要将参数进行截取分开,不然传入整体就会被默认是一个参数比如 1 3 不切割传入那就是 1 空格 3
        构造完成执行命令之后,监听日志来获取程序输出的结果,正常 frame.payLoad()是结果,不知道是不是因为版本问题,frame 整体能拿到日志结果

    • Docker 容器的安全性

      1. 超时控制
        可以在执行命令时候,指定程序能够运行的时间,超时运行就做相应的处理

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        dockerClient.execStartCmd(runCmdId)
        .exec(new ExecStartResultCallback() {
        // 监控防止执行的程序一直执行 超时控制
        @Override
        public void onComplete() {
        timeout[0] = false;
        super.onComplete();
        }

        @Override
        public void onNext(Frame frame) {
        StreamType streamType = frame.getStreamType();
        if (StreamType.STDERR.equals(streamType)) {
        errorMessage[0] = ("" + frame).replace("STDOUT: ", "");
        log.info("错误结果:" + frame);
        } else {
        message[0] = ("" + frame).replace("STDOUT: ", "");
        log.info("正确结果:" + frame);
        }
        super.onNext(frame);
        }
        }).awaitCompletion(TIME_OUT, TimeUnit.MILLISECONDS);
      2. 内存监听

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        // 获取占用内存 监控
        StatsCmd statsCmd = dockerClient.statsCmd(containerId);
        ResultCallback<Statistics> statisticsResultCallback = statsCmd.exec(new ResultCallback<Statistics>() {
        @Override
        public void onStart(Closeable closeable) {

        }

        @Override
        public void onNext(Statistics statistics) {
        // 获取最大的内存占用
        maxMemory[0] = Math.max(statistics.getMemoryStats().getUsage() != null ? statistics.getMemoryStats().getUsage() : -1, maxMemory[0]);
        }

        @Override
        public void onError(Throwable throwable) {

        }

        @Override
        public void onComplete() {

        }

        @Override
        public void close() throws IOException {

        }
        });
        statsCmd.exec(statisticsResultCallback);
      3. 权限管理

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        // 100MB内存 1个CPU 内存交换 一定程度上防止文件写入
        hostConfig.withMemory(100 * 1000 * 1000L)
        .withCpuCount(1L)
        .withMemorySwap(0L);
        // 存储本地文件映射
        hostConfig.setBinds(new Bind(userCodeFile.getParentFile().getAbsolutePath(), new Volume("/app")));
        CreateContainerResponse containerResponse = containerCmd
        .withHostConfig(hostConfig)
        .withNetworkDisabled(true)
        .withReadonlyRootfs(true)
        .withAttachStderr(true)
        .withAttachStdin(true)
        .withAttachStdout(true)
        .withTty(true)
        .exec();
    • 完整的 docker 实现代码沙箱代码

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      71
      72
      73
      74
      75
      76
      77
      78
      79
      80
      81
      82
      83
      84
      85
      86
      87
      88
      89
      90
      91
      92
      93
      94
      95
      96
      97
      98
      99
      100
      101
      102
      103
      104
      105
      106
      107
      108
      109
      110
      111
      112
      113
      114
      115
      116
      117
      118
      119
      120
      121
      122
      123
      124
      125
      126
      127
      128
      129
      130
      131
      132
      133
      134
      135
      136
      137
      138
      139
      140
      141
      142
      143
      144
      145
      146
      147
      148
      149
      150
      151
      152
      153
      154
      155
      156
      157
      158
      159
      160
      161
      162
      163
      164
      165
      166
      167
      168
      169
      170
      171
      172
      173
      174
      175
      176
      177
      178
      179
      180
      181
      182
      183
      184
      185
      186
      187
      188
      189
      190
      191
      192
      193
      194
      195
      196
      197
      198
      199
      200
      201
      202
      203
      204
      205
      206
      207
      208
      209
      210
      211
      212
      213
      214
      215
      216
      217
      218
      219
      220
      221
      222
      223
      224
      225
      226
      227
      228
      229
      230
      231
      232
      233
      234
      235
      236
      237
      238
      239
      240
      241
      242
      243
      244
      245
      246
      247
      248
      249
      250
      251
      252
      253
      254
      255
      256
      257
      258
      259
      260
      261
      262
      263
      264
      265
      266
      267
      268
      269
      270
      271
      272
      273
      274
      275
      276
      277
      278
      279
      280
      281
      282
      283
      284
      285
      286
      287
      288
      289
      290
      291
      292
      293
      294
      295
      296
      297
      298
      299
      300
      301
      302
      303
      304
      305
      306
      307
      308
      309
      310
      311
      312
      313
      314
      315
      316
      317
      318
      319
      320
      321
      322
      323
      324
      325
      326
      327
      328
      329
      330
      331
      332
      333
      334
      335
      336
      337
      338
      339
      340
      341
      342
      343
      344
      345
      346
      347
      348
      349
      350
      351
      352
      353
      354
      355
      356
      357
      358
      359
      360
      361
      362
      363
      364
      365
      366
      367
      368
      369
      370
      371
      372
      373
      374
      375
      376
      377
      378
      379
      380
      381
      382
      383
      384
      385
      386
      387
      388
      389
      390
      391
      392
      393
      394
      395
      396
      397
      398
      399
      400
      401
      402
      403
      404
      405
      406
      407
      408
      409
      410
      411
      412
      413
      414
      415
      416
      417
      418
      419
      420
      421
      422
      423
      424
      接口
      @PostMapping("/exec")
      public ExecuteCodeResponse javaNativeExecCode(@RequestBody ExecuteCodeRequest executeCodeRequest) {
      return javaDockerCodeSandBox.doExecuteCode(executeCodeRequest);
      }
      模板代码(原生实现)
      package com.oj.codesandbox.template;

      import cn.hutool.core.date.StopWatch;
      import cn.hutool.core.io.FileUtil;
      import cn.hutool.core.util.ObjectUtil;
      import cn.hutool.core.util.StrUtil;
      import com.oj.codesandbox.model.ExecuteCodeRequest;
      import com.oj.codesandbox.model.ExecuteCodeResponse;
      import com.oj.codesandbox.model.ExecuteMessage;
      import com.oj.codesandbox.model.JudgeInfo;
      import com.oj.codesandbox.service.CodeSandBox;
      import com.oj.codesandbox.utils.ProcessUtils;
      import lombok.extern.slf4j.Slf4j;

      import java.io.File;
      import java.io.IOException;
      import java.nio.charset.StandardCharsets;
      import java.util.ArrayList;
      import java.util.List;
      import java.util.UUID;

      @Slf4j
      public abstract class JavaSandBoxTemplate implements CodeSandBox {


      private static final String GLOBAL_CODE_FILE_NAME = "codeTemplate";

      private static final String GLOBAL_CLASS_NAME = "Main.java";

      private static final Long TIME_OUT = 100000L;

      /**
      * 1. 保存用户的代码为文件
      *
      * @param code 用户代码
      * @return
      */
      public File oneStepSaveCodeFile(String code) {
      // 获取用户的工作目录
      String userDir = System.getProperty("user.dir");
      // 创建全局存储代码目录
      String globalCodePathName = userDir + File.separator + GLOBAL_CODE_FILE_NAME;
      // 没有的话创建目录
      if (!FileUtil.exist(globalCodePathName)) {
      FileUtil.mkdir(globalCodePathName);
      }
      // 创建用户单个目录存储代码文件 实现每个用户的代码隔离
      String userCodeFileParentPath = globalCodePathName + File.separator + UUID.randomUUID();
      // 创建用户的代码文件
      String userCodeFilePath = userCodeFileParentPath + File.separator + GLOBAL_CLASS_NAME;
      // 写入代码
      return FileUtil.writeString(code, userCodeFilePath, StandardCharsets.UTF_8);
      }

      /**
      * 2. 编译用户代码文件
      *
      * @param userCodeFile
      * @return
      */
      public ExecuteCodeResponse twoStepCompileUserCodeFile(File userCodeFile) {
      // 1. 构建编译指令
      String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
      // 2. 执行编译命令 得到结果
      try {
      Process compileProcess = Runtime.getRuntime().exec(compileCmd);
      ExecuteMessage compileExecuteMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
      log.info("编译的结果为:" + compileExecuteMessage);
      if (!StrUtil.isEmpty(compileExecuteMessage.getErrorMessage())) {
      ExecuteCodeResponse errorExecuteCodeResponse = ProcessUtils.getErrorExecuteCodeResponse(compileExecuteMessage);
      errorExecuteCodeResponse.setStatus(0);
      return errorExecuteCodeResponse;
      } else {
      return null;
      }
      } catch (IOException e) {
      e.printStackTrace();
      return null;
      }
      }

      /**
      * 运行用户代码文件
      *
      * @param userCodeFile
      * @param inputList
      * @return
      */
      public List<ExecuteMessage> threeStepRunUserCodeFile(File userCodeFile, List<String> inputList) {
      List<ExecuteMessage> runExecuteMessageList = null;
      try {
      runExecuteMessageList = new ArrayList<>(inputList.size());
      long runTime;
      for (String args : inputList) {
      // 1. 构建执行程序命令
      String runCmd = String.format("java -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeFile.getParentFile().getAbsolutePath(), args);
      // 2. 执行运行命令 得到结果
      Process runProcess = Runtime.getRuntime().exec(runCmd);
      StopWatch stopWatch = new StopWatch();
      stopWatch.start();
      Thread.sleep(1000);
      // 守护线程
      new Thread(() -> {
      try {
      Thread.sleep(TIME_OUT);
      System.out.println("超时了,中断");
      runProcess.destroy();
      } catch (Exception e) {
      throw new RuntimeException(e);
      }
      });
      ExecuteMessage runExecuteMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "运行");
      stopWatch.stop();
      runTime = stopWatch.getLastTaskTimeMillis();
      runExecuteMessage.setTime(runTime);
      runExecuteMessageList.add(runExecuteMessage);
      }
      } catch (Exception e) {
      e.printStackTrace();
      return null;
      }
      return runExecuteMessageList;
      }

      /**
      * 构建返回结果
      *
      * @param executeMessageList
      * @return
      */
      public ExecuteCodeResponse fourStepBuilderResponse(List<ExecuteMessage> executeMessageList) {
      ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
      // 判题信息
      JudgeInfo judgeInfo = new JudgeInfo();
      judgeInfo.setTime(0L);
      judgeInfo.setMemory(0L);
      // 输出结果
      List<String> outputList = new ArrayList<>();
      for (ExecuteMessage executeMessage : executeMessageList) {
      String errorMessage = executeMessage.getErrorMessage();
      // 遇到错误信息就中断 并返回
      if (StrUtil.isNotBlank(errorMessage)) {
      return ProcessUtils.getErrorExecuteCodeResponse(executeMessage);
      }
      // 不然则把结果给添加到outputList中
      outputList.add(executeMessage.getMessage());
      // 设置最大运行时间
      judgeInfo.setTime(Math.max(executeMessage.getTime(), judgeInfo.getTime()));
      // 设置最大内存占用
      judgeInfo.setMemory(Math.max(executeMessage.getMemory(), judgeInfo.getMemory()));
      }
      judgeInfo.setMessage("判题成功!");
      executeCodeResponse.setMessage("结果数量正确");
      executeCodeResponse.setOutputList(outputList);
      executeCodeResponse.setJudgeInfo(judgeInfo);
      executeCodeResponse.setStatus(1);
      return executeCodeResponse;
      }

      /**
      * 删除文件
      *
      * @param userCodeFile
      * @return
      */
      public boolean fiveStepDeleteUserCodeFile(File userCodeFile) {
      if (userCodeFile.getParentFile() != null) {
      return FileUtil.del(userCodeFile.getParentFile().getAbsolutePath());
      } else {
      return true;
      }
      }

      /**
      * 主程序
      *
      * @param executeCodeRequest
      * @return
      */
      @Override
      public ExecuteCodeResponse doExecuteCode(ExecuteCodeRequest executeCodeRequest) {
      List<String> inputList = executeCodeRequest.getInputList();
      String code = executeCodeRequest.getCode();
      // 1. 保存用户的代码为文件
      File userCodeFile = oneStepSaveCodeFile(code);
      // 2. 编译用户代码文件
      ExecuteCodeResponse errorCompileExecuteCodeResponse = twoStepCompileUserCodeFile(userCodeFile);
      // 2.1 判断是否为空 为空就正确 不为空就返回
      if (ObjectUtil.isNotEmpty(errorCompileExecuteCodeResponse)) {
      return errorCompileExecuteCodeResponse;
      }
      // 3. 运行用户代码文件
      List<ExecuteMessage> executeMessageList = threeStepRunUserCodeFile(userCodeFile, inputList);
      if (ObjectUtil.isEmpty(executeMessageList)) {
      ExecuteMessage executeMessage = new ExecuteMessage();
      executeMessage.setErrorMessage("用户代码运行失败!");
      return ProcessUtils.getErrorExecuteCodeResponse(executeMessage);
      }
      // 4. 封装返回结果
      ExecuteCodeResponse executeCodeResponse = fourStepBuilderResponse(executeMessageList);
      // 5. 删除代码文件 防止积攒过多
      boolean del = fiveStepDeleteUserCodeFile(userCodeFile);
      if (!del) {
      log.error("删除文件失败,文件路径为:{}", userCodeFile.getParentFile().getAbsolutePath());
      } else {
      log.info("删除文件成功,文件路径为:{}", userCodeFile.getParentFile().getAbsolutePath());
      }
      return executeCodeResponse;
      }
      }
      使用模板模式,重写方法
      package com.oj.codesandbox.service.impl;

      import cn.hutool.core.date.StopWatch;
      import cn.hutool.core.util.ArrayUtil;
      import com.github.dockerjava.api.DockerClient;
      import com.github.dockerjava.api.async.ResultCallback;
      import com.github.dockerjava.api.command.*;
      import com.github.dockerjava.api.model.*;
      import com.github.dockerjava.core.DockerClientBuilder;
      import com.github.dockerjava.core.command.ExecStartResultCallback;
      import com.github.dockerjava.core.command.LogContainerResultCallback;
      import com.oj.codesandbox.model.ExecuteCodeRequest;
      import com.oj.codesandbox.model.ExecuteCodeResponse;
      import com.oj.codesandbox.model.ExecuteMessage;
      import com.oj.codesandbox.template.JavaSandBoxTemplate;
      import lombok.extern.slf4j.Slf4j;
      import org.springframework.stereotype.Component;

      import java.io.Closeable;
      import java.io.File;
      import java.io.IOException;
      import java.util.ArrayList;
      import java.util.Arrays;
      import java.util.List;
      import java.util.concurrent.TimeUnit;

      @Slf4j
      @Component
      public class JavaDockerCodeSandBoxImpl extends JavaSandBoxTemplate {

      private static final String IMAGES = "openjdk:8-alpine";

      private static final Long TIME_OUT = 10000L;

      private static DockerClient GLOBAL_DOCKER_CLIENT = null;

      private static String CONTAINER_ID = null;

      /**
      * 抽离 启动容器方法
      *
      * @param dockerClient
      * @param userCodeFile
      * @return
      */
      public String createAndRunContainer(DockerClient dockerClient, File userCodeFile) {
      // 1. 创建容器执行命令
      CreateContainerCmd containerCmd = dockerClient.createContainerCmd(IMAGES);
      // 2. 创建容器时候 进行配置 交互式容器withTty
      HostConfig hostConfig = new HostConfig();
      // 3. 100MB内存 1个CPU 内存交换 一定程度上防止文件写入
      hostConfig.withMemory(100 * 1000 * 1000L)
      .withCpuCount(1L)
      .withMemorySwap(0L);
      // 4. 存储本地文件映射
      hostConfig.setBinds(new Bind(userCodeFile.getParentFile().getAbsolutePath(), new Volume("/app")));
      CreateContainerResponse containerResponse = containerCmd
      .withHostConfig(hostConfig)
      .withNetworkDisabled(true)
      .withReadonlyRootfs(true)
      .withAttachStderr(true)
      .withAttachStdin(true)
      .withAttachStdout(true)
      .withTty(true)
      .exec();
      log.info("创建容器成功!");
      // 3. 启动容器
      String containerId = containerResponse.getId();
      dockerClient.startContainerCmd(containerId).exec();
      log.info("启动容器成功!容器ID:" + containerId);
      return containerId;
      }

      /**
      * 重写运行逻辑 (Docker)
      *
      * @param userCodeFile
      * @param inputList
      * @return
      */
      @Override
      public List<ExecuteMessage> threeStepRunUserCodeFile(File userCodeFile, List<String> inputList) {
      // 存储执行信息
      List<ExecuteMessage> executeMessageList = new ArrayList<>();
      try {
      DockerClient dockerClient = DockerClientBuilder.getInstance().build();
      GLOBAL_DOCKER_CLIENT = dockerClient;
      log.info("创建客户端成功!");
      String containerId = createAndRunContainer(dockerClient, userCodeFile);
      CONTAINER_ID = containerId;
      // 存储执行信息
      final long[] maxMemory = {0L};
      // docker exec container_name java -cp /code Main 1 3
      for (String args : inputList) {
      // 4. 构建运行cmd参数 拆解输入示例
      String[] inputArgsArray = args.split(" ");
      String[] cmdArray = ArrayUtil.append(new String[]{"java", "-cp", "/app", "Main"}, inputArgsArray);
      log.info("构造的运行指令为:" + Arrays.toString(cmdArray));
      // 5. 构建运行命令
      ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
      .withCmd(cmdArray)
      .withAttachStderr(true)
      .withAttachStdin(true)
      .withAttachStdout(true)
      .exec();
      // 6. 执行命令
      String runCmdId = execCreateCmdResponse.getId();
      StopWatch stopWatch = new StopWatch();
      stopWatch.start();
      ExecuteMessage executeMessage = new ExecuteMessage();
      final String[] message = {null};
      final String[] errorMessage = {null};
      final boolean[] timeout = {true};
      // 踩坑 打印结果就是frame 即可
      // 获取占用内存 监控
      StatsCmd statsCmd = dockerClient.statsCmd(containerId);
      ResultCallback<Statistics> statisticsResultCallback = statsCmd.exec(new ResultCallback<Statistics>() {
      @Override
      public void onStart(Closeable closeable) {

      }

      @Override
      public void onNext(Statistics statistics) {
      // 获取最大的内存占用
      maxMemory[0] = Math.max(statistics.getMemoryStats().getUsage() != null ? statistics.getMemoryStats().getUsage() : -1, maxMemory[0]);
      }

      @Override
      public void onError(Throwable throwable) {

      }

      @Override
      public void onComplete() {

      }

      @Override
      public void close() throws IOException {

      }
      });
      statsCmd.exec(statisticsResultCallback);
      Thread.sleep(1000);
      dockerClient.execStartCmd(runCmdId)
      .exec(new ExecStartResultCallback() {
      // 监控防止执行的程序一直执行 超时控制
      @Override
      public void onComplete() {
      timeout[0] = false;
      super.onComplete();
      }

      @Override
      public void onNext(Frame frame) {
      StreamType streamType = frame.getStreamType();
      if (StreamType.STDERR.equals(streamType)) {
      errorMessage[0] = ("" + frame).replace("STDOUT: ", "");
      log.info("错误结果:" + frame);
      } else {
      message[0] = ("" + frame).replace("STDOUT: ", "");
      log.info("正确结果:" + frame);
      }
      super.onNext(frame);
      }
      }).awaitCompletion(TIME_OUT, TimeUnit.MILLISECONDS);
      statsCmd.close();
      stopWatch.stop();
      executeMessage.setTime(stopWatch.getLastTaskTimeMillis());
      // 封装每一次的执行信息
      executeMessage.setMemory(maxMemory[0]);
      executeMessage.setMessage(message[0]);
      if (timeout[0]) {
      executeMessage.setErrorMessage("超时");
      } else {
      executeMessage.setErrorMessage(errorMessage[0]);
      }
      executeMessageList.add(executeMessage);
      log.info("封装的单次结果为:" + executeMessage);
      }
      } catch (InterruptedException e) {
      e.printStackTrace();
      return null;
      }
      return executeMessageList;
      }

      @Override
      public boolean fiveStepDeleteUserCodeFile(File userCodeFile) {
      GLOBAL_DOCKER_CLIENT.removeContainerCmd(CONTAINER_ID).withForce(true).exec();
      log.info("删除容器成功!");
      return super.fiveStepDeleteUserCodeFile(userCodeFile);
      }

      /**
      * 主入口
      *
      * @param executeCodeRequest
      * @return
      */
      @Override
      public ExecuteCodeResponse doExecuteCode(ExecuteCodeRequest executeCodeRequest) {
      return super.doExecuteCode(executeCodeRequest);
      }
      }