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
| package com.winterchen.jenkinsauto.controller;
import com.winterchen.jenkinsauto.dto.APIRespose; import com.winterchen.jenkinsauto.dto.ShellRequestDTO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.MessageFormat; import java.util.List; import java.util.Map;
@RestController @RequestMapping("/shell") public class BaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(BaseController.class);
@PostMapping("") public APIRespose executeShell( @RequestBody @Validated ShellRequestDTO requestDTO ) { LOGGER.info("当前请求参数:" + requestDTO.toString()); StringBuilder sb = new StringBuilder(); try { doExecuteShell(requestDTO, sb); return APIRespose.success(sb.toString()); } catch (Exception e) { return APIRespose.fail(e.getMessage()); } }
private synchronized void doExecuteShell(ShellRequestDTO requestDTO, StringBuilder sb) throws Exception{ stopContainer(requestDTO.getSimpleImageName(), sb); removeContainer(requestDTO.getSimpleImageName(), sb); removeImage(requestDTO.getImageName(), sb); removeNoneImages(sb); pullImage(requestDTO.getImageName(), requestDTO.getTag(), sb); runImage(requestDTO, sb); }
private void pullImage(String imageName, String tag, StringBuilder sb) throws Exception{ execute(MessageFormat.format("docker pull {0}:{1}", imageName, tag), sb); }
private void stopContainer(String simpleImageName, StringBuilder sb) { try { execute("docker stop " + simpleImageName, sb); } catch (Exception e) { LOGGER.error("停止容器失败", e); } }
private void removeImage(String imageName, StringBuilder sb) { try { execute("docker rmi -f " + imageName, sb); } catch (Exception e) { LOGGER.error("删除镜像失败", e); } }
private void removeNoneImages(StringBuilder sb) { try{ execute("docker ps -a | grep `docker images -f 'dangling=true' -q` | awk '{print $1}'", sb); execute("docker stop $(docker ps -a | grep `docker images -f 'dangling=true' -q` | awk '{print $1}')", sb); execute("docker ps -a | grep `docker images -f 'dangling=true' -q` | awk '{print $1}'",sb); execute("docker rm $(docker ps -a | grep `docker images -f 'dangling=true' -q` | awk '{print $1}')", sb); execute("docker images -f 'dangling=true'|awk '{print $3}'", sb); execute("docker image rm -f `docker images -f 'dangling=true'|awk '{print $3}'`", sb); } catch (Exception e) { LOGGER.error("删除none镜像失败", e); } }
private void removeContainer(String simpleImageName, StringBuilder sb) { try { execute("docker rm " + simpleImageName, sb); } catch (Exception e) { LOGGER.error("删除容器失败", e); } }
private void runImage(ShellRequestDTO requestDTO, StringBuilder sb) throws Exception{ StringBuilder shell = new StringBuilder(); shell.append("docker run -p ").append(requestDTO.getPort()).append(":").append(requestDTO.getPort()); shell.append(" --network=host "); shell.append(" --name=").append(requestDTO.getSimpleImageName()); shell.append(" -d "); formatEnv(requestDTO.getEnvs(), shell); formatVolumes(requestDTO.getVolumes(), shell); shell.append(requestDTO.getImageName()).append(":").append(requestDTO.getTag()); execute(shell.toString(), sb); }
private void formatVolumes(List<String> volumes, StringBuilder shell) { if (volumes == null || 0 == volumes.size()) { return; } volumes.forEach(volume -> { shell.append(" -v "); shell.append(" '").append(volume).append("' "); }); }
private void formatEnv(Map<String, String> env, StringBuilder shell) { if (env == null || env.isEmpty()) { return; } for (Map.Entry<String, String> entry : env.entrySet()) { shell.append(" -e "); shell.append(entry.getKey()).append("='").append(entry.getValue()).append("' "); } }
private void execute(String command, StringBuilder sb) throws Exception { BufferedReader infoInput = null; BufferedReader errorInput = null; try { LOGGER.info("======================当前执行命令======================"); LOGGER.info(command); LOGGER.info("======================当前执行命令======================"); String[] commands = { "/bin/sh", "-c", command }; Process process = Runtime.getRuntime().exec(commands); infoInput = new BufferedReader(new InputStreamReader(process.getInputStream())); errorInput = new BufferedReader(new InputStreamReader(process.getErrorStream())); String line = ""; while ((line = infoInput.readLine()) != null) { sb.append(line).append(System.lineSeparator()); LOGGER.info(line); } while ((line = errorInput.readLine()) != null) { sb.append(line).append(System.lineSeparator()); LOGGER.error(line); } process.waitFor(); } finally { try { if (infoInput != null) { infoInput.close(); } if (errorInput != null) { errorInput.close(); } } catch (IOException e) {
} } } }
|