diff --git a/pom.xml b/pom.xml
index f08f518..d0a14b0 100644
--- a/pom.xml
+++ b/pom.xml
@@ -18,7 +18,6 @@
jnpf-admin
ssw-common
- ssw-dos
diff --git a/ssw-dos/pom.xml b/ssw-dos/pom.xml
deleted file mode 100644
index e8b2b8c..0000000
--- a/ssw-dos/pom.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-
-
- 4.0.0
-
- com.jnpf
- ssw-boot
- 6.2.0-RELEASE
-
- pom
- ssw-dos
-
-
- ssw-dos-entity
- ssw-dos-biz
-
-
diff --git a/ssw-dos/ssw-dos-biz/pom.xml b/ssw-dos/ssw-dos-biz/pom.xml
deleted file mode 100644
index 3080166..0000000
--- a/ssw-dos/ssw-dos-biz/pom.xml
+++ /dev/null
@@ -1,63 +0,0 @@
-
-
- 4.0.0
-
- ssw-dos
- com.jnpf
- 6.2.0-RELEASE
-
- ssw-dos-biz
-
-
-
- com.jnpf
- ssw-dos-entity
- ${project.version}
-
-
-
- com.jnpf
- ssw-common-biz
- ${project.version}
-
-
- com.jnpf
- jnpf-common-all
- ${project.version}
-
-
-
- io.weaviate
- client
- 5.1.3
-
-
-
- com.github.docker-java
- docker-java-core
- 3.4.0
-
-
- com.github.docker-java
- docker-java-api
- 3.4.0
-
-
- com.github.docker-java
- docker-java-transport-httpclient5
- 3.4.0
-
-
- org.apache.commons
- commons-compress
- 1.26.0
-
-
- io.kubernetes
- client-java
- 19.0.1
-
-
-
diff --git a/ssw-dos/ssw-dos-biz/src/main/java/ssw/agent/service/DialogController.java b/ssw-dos/ssw-dos-biz/src/main/java/ssw/agent/service/DialogController.java
deleted file mode 100644
index 6c0b733..0000000
--- a/ssw-dos/ssw-dos-biz/src/main/java/ssw/agent/service/DialogController.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package ssw.agent.service;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.*;
-
-@RestController
-@RequestMapping("/api/dos/dialog/run")
-public class DialogController {
-
- private final DialogService dialogService;
-
- @Autowired
- public DialogController(DialogService dialogService) {
- this.dialogService = dialogService;
- }
-
- @PostMapping
- public String getDialogResponse(@RequestBody String request) {
- return dialogService.generateDialogResponse(request);
- }
-}
diff --git a/ssw-dos/ssw-dos-biz/src/main/java/ssw/agent/service/DialogService.java b/ssw-dos/ssw-dos-biz/src/main/java/ssw/agent/service/DialogService.java
deleted file mode 100644
index bf41bbb..0000000
--- a/ssw-dos/ssw-dos-biz/src/main/java/ssw/agent/service/DialogService.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package ssw.agent.service;
-
-import io.weaviate.client.base.Result;
-import io.weaviate.client.v1.graphql.model.GraphQLResponse;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-
-@Service
-public class DialogService {
-
- private final WeaviateService weaviateService;
- private final OllamaService ollamaService;
-
- @Autowired
- public DialogService(WeaviateService weaviateService, OllamaService ollamaService) {
- this.weaviateService = weaviateService;
- this.ollamaService = ollamaService;
- }
-
- public String generateDialogResponse(String request) {
- Float[] vetor = ollamaService.getTextEmbeddingFromOllama(request);
- // 从Weaviate检索相关文档
- Result context = weaviateService.searchSimilarDocuments(vetor, 3);
-
- // 调用ollama生成回答
- String response = ollamaService.generateResponse(request, context);
-
- return response;
- }
-}
diff --git a/ssw-dos/ssw-dos-biz/src/main/java/ssw/agent/service/OllamaService.java b/ssw-dos/ssw-dos-biz/src/main/java/ssw/agent/service/OllamaService.java
deleted file mode 100644
index 1866b3f..0000000
--- a/ssw-dos/ssw-dos-biz/src/main/java/ssw/agent/service/OllamaService.java
+++ /dev/null
@@ -1,108 +0,0 @@
-package ssw.agent.service;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonObject;
-import com.google.gson.internal.LinkedTreeMap;
-import io.weaviate.client.base.Result;
-import io.weaviate.client.v1.graphql.model.GraphQLResponse;
-import org.springframework.http.*;
-import org.springframework.stereotype.Service;
-import org.springframework.web.client.RestTemplate;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-@Service
-public class OllamaService {
-
- private final RestTemplate restTemplate = new RestTemplate();
- private static final Gson gson = new Gson();
- private static final String OLLAMA_API_URL = "http://192.168.1.9:11434/v1/embeddings";
-
- public String generateResponse(String prompt, Result context) {
- // 构建上下文
- StringBuilder contextBuilder = new StringBuilder();
- LinkedTreeMap data = (LinkedTreeMap)context.getResult().getData();
- LinkedTreeMap Get = (LinkedTreeMap) data.get("Get");
- List c = (List) Get.get("Vector_index_b646fcf2_902d_4070_88cb_03e2873f578a_Node");
- for (int i = 0; i < c.size(); i++) {
- String s = ((LinkedTreeMap)c.get(i)).get("text").toString();
- contextBuilder.append(s).append("\n");
- }
-
- // 构建完整提示词
- String fullPrompt = "以下是相关知识库内容,回答用户问题时请参考这些内容:\n" +
- contextBuilder.toString() +
- "\n用户问题:\n" +
- prompt +
- "\n回答:";
-
- // 调用ollama API
- Map requestBody = new HashMap<>();
- requestBody.put("model", "openllama");
- requestBody.put("prompt", fullPrompt);
- requestBody.put("temperature", 0.7);
- requestBody.put("max_tokens", 200);
-
- // 替换为你的ollama服务地址
- String response = restTemplate.postForObject(
- "http://192.168.1.9:11434/completions",
- requestBody,
- String.class
- );
-
- // 解析响应
- if (response != null && response.contains("text")) {
- return response.split("text\": \"")[1].split("\"")[0];
- }
-
- return "抱歉,我无法回答这个问题。";
- }
-
- // 调用Ollama API获取文本向量
- public Float[] getTextEmbeddingFromOllama(String text) {
- try {
- // 构造请求体
- JsonObject requestBody = new JsonObject();
- JsonArray inputArray = new JsonArray();
- inputArray.add(text);
- requestBody.add("input", inputArray);
- requestBody.addProperty("model", "nomic-embed-text");
-
- // 创建HTTP请求
- RestTemplate restTemplate = new RestTemplate();
- HttpHeaders headers = new HttpHeaders();
- headers.setContentType(MediaType.APPLICATION_JSON);
-
- HttpEntity entity = new HttpEntity<>(gson.toJson(requestBody), headers);
-
- // 发送POST请求
- ResponseEntity response = restTemplate.postForEntity(OLLAMA_API_URL, entity, String.class);
-
- if (response.getStatusCode() != HttpStatus.OK) {
- System.out.println("Ollama API请求失败: " + response.getStatusCode());
- return new Float[0];
- }
-
- // 解析响应数据
- String responseBody = response.getBody();
- JsonObject jsonResponse = gson.fromJson(responseBody, JsonObject.class);
- JsonArray embeddingsArray = jsonResponse.getAsJsonArray("data")
- .get(0).getAsJsonObject().getAsJsonArray("embedding");
-
- // 将嵌入向量转换为float数组
- Float[] vector = new Float[embeddingsArray.size()];
- for (int i = 0; i < embeddingsArray.size(); i++) {
- vector[i] = embeddingsArray.get(i).getAsFloat();
- }
-
- return vector;
-
- } catch (Exception e) {
- e.printStackTrace();
- return new Float[0];
- }
- }
-}
diff --git a/ssw-dos/ssw-dos-biz/src/main/java/ssw/agent/service/WeaviateService.java b/ssw-dos/ssw-dos-biz/src/main/java/ssw/agent/service/WeaviateService.java
deleted file mode 100644
index 2357f48..0000000
--- a/ssw-dos/ssw-dos-biz/src/main/java/ssw/agent/service/WeaviateService.java
+++ /dev/null
@@ -1,56 +0,0 @@
-package ssw.agent.service;
-
-import io.weaviate.client.Config;
-import io.weaviate.client.WeaviateAuthClient;
-import io.weaviate.client.WeaviateClient;
-import io.weaviate.client.base.Result;
-import io.weaviate.client.v1.auth.exception.AuthException;
-import io.weaviate.client.v1.graphql.model.GraphQLResponse;
-import io.weaviate.client.v1.graphql.query.argument.NearVectorArgument;
-import io.weaviate.client.v1.graphql.query.fields.Field;
-
-import org.springframework.stereotype.Service;
-@Service
-public class WeaviateService {
-
- private final WeaviateClient client;
-
- public WeaviateService() throws AuthException {
- // 替换为你的Weaviate服务地址
- // 设置Weaviate的API密钥
- String weaviateApiKey = "WVF5YThaHlkYwhGUSmCRgsX3tD5ngdN8pkih"; // 替换为你的Weaviate API密钥
- // 创建Weaviate客户端配置
- Config config = new Config("http", "192.168.1.9:192");
- config.getHeaders().put("Content-Type","application/json; charset=UTF-8");
- // 设置API密钥作为请求头中的Bearer Token
-
- this.client = WeaviateAuthClient.apiKey(config, weaviateApiKey);
- }
-
- public Result searchSimilarDocuments(Float[] query, int k) {
- String className = "Vector_index_b646fcf2_902d_4070_88cb_03e2873f578a_Node";
- Field title = Field.builder().name("text").build();
- Field _additional = Field.builder()
- .name("_additional")
- .fields(new Field[]{
- Field.builder().name("certainty").build(), // only supported if distance==cosine
- Field.builder().name("distance").build() // always supported
- }).build();
-
- NearVectorArgument nearVector = NearVectorArgument.builder()
- .vector(query)
- .build();
-
- Result result = client.graphQL().get()
- .withClassName(className)
- .withFields(title, _additional)
- .withNearVector(nearVector)
- .run();
-
- if (result.hasErrors()) {
- System.out.println(result.getError());
- }
-
- return result;
- }
-}
diff --git a/ssw-dos/ssw-dos-biz/src/main/java/ssw/dos/sandbox/ContainerCache.java b/ssw-dos/ssw-dos-biz/src/main/java/ssw/dos/sandbox/ContainerCache.java
deleted file mode 100644
index 9c6aab5..0000000
--- a/ssw-dos/ssw-dos-biz/src/main/java/ssw/dos/sandbox/ContainerCache.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package ssw.dos.sandbox;
-import java.util.List;
-import java.util.Map;
-
-public class ContainerCache {
- public String id;
- public int port;
- public String host;
- public String url;
- public String test_url;
- public Map JsonDate;
-
- public int getExposedPort(String cPort) {
- // 获取 NetworkSettings 对象
- Map networkSettings = (Map)JsonDate.get("NetworkSettings");
-
- // 获取 Ports 对象
- Map ports = (Map)networkSettings.get("Ports");
-
- if (ports == null || !ports.containsKey(cPort))
- return 0;
-
- // 获取端口对应的数组
- List portArray = (List)ports.get(cPort);
-
- // 获取第一个元素
- if(portArray == null || portArray.isEmpty())
- return 0;
-
- Map portInfo = (Map)portArray.get(0);
-
- return Integer.parseInt(portInfo.get("HostPort").toString());
-
- }
-}
diff --git a/ssw-dos/ssw-dos-biz/src/main/java/ssw/dos/sandbox/ContainerManager.java b/ssw-dos/ssw-dos-biz/src/main/java/ssw/dos/sandbox/ContainerManager.java
deleted file mode 100644
index 5a77c49..0000000
--- a/ssw-dos/ssw-dos-biz/src/main/java/ssw/dos/sandbox/ContainerManager.java
+++ /dev/null
@@ -1,175 +0,0 @@
-package ssw.dos.sandbox;
-
-import lombok.extern.slf4j.Slf4j;
-
-
-import java.io.IOException;
-import java.net.HttpURLConnection;
-import java.net.Socket;
-import java.net.URL;
-import java.util.Random;
-import java.util.concurrent.ConcurrentHashMap;
-
-@Slf4j
-public class ContainerManager {
-
- private static ConcurrentHashMap containerMap = new ConcurrentHashMap<>();
-
- /**
- * 检查指定端口是否开放
- *
- * @param port 待检查的端口号
- * @return 如果端口开放,返回true;否则返回false
- */
- public static boolean PortChecker(String host,int port) {
- try (Socket socket = new Socket(host, port)) {
- return true;
- } catch (IOException e) {
- return false;
- }
- }
-
- /**
- * 创建一个配置信息。
- *
- * @param containerName
- * @param host 主机名或IP地址
- * @return 返回可用的端口号
- */
- private static ContainerCache newContainer(String containerName, String host){
- // 寻找一个空闲端口并存储到缓存
- ContainerCache c = new ContainerCache();
- containerMap.put(containerName, c);
- c.port = findAvailablePort(host);
- c.host = host;
- return c;
- }
-
- /**
- * 获取容器缓存(如果没有创建一个)
- * @param containerName
- * @param du
- * @param mHost
- * @param mAddress
- * @param cPort
- * @return
- * @throws Exception
- */
- public static ContainerCache getContainer(String containerName, SandBoxUtil du, String mHost, String mAddress,String cPort) throws Exception {
- ContainerCache container = containerMap.get(containerName);
- if(container == null){
- try {
- container = du.getContainer(containerName);
- }catch (Exception e){
- log.info("宿主机不存在该名称的容器:" +containerName );
- }
-
- if(container != null){
- container.host = mHost;
- container.port = container.getExposedPort(cPort);
- }
- }
-
- if(container == null)
- container = newContainer(containerName,mHost);
-
- container.url = String.format(mAddress,container.port);
- return container;
- }
-
- /**
- * 仅获得容器配置缓存
- * @param containerName
- * @return
- */
- public static ContainerCache getContainer(String containerName){
- return containerMap.get(containerName);
- }
-
- /**
- * 判断指定的HTTP服务器是否可用
- *
- * @param urlString HTTP服务器的URL字符串
- * @return 如果HTTP服务器可用,则返回true;否则返回false
- */
- public static boolean isHttpServerAvailable(String urlString) {
- try {
- URL url = new URL(urlString);
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- connection.setRequestMethod("HEAD");
- int responseCode = connection.getResponseCode();
- // 200-299之间的状态码通常表示成功
- return (responseCode >= 200 && responseCode <= 299);
- } catch (IOException e) {
- // 如果有异常,则服务器可能不可用
- log.error(e.toString());
- return false;
- }
- }
-
- /**
- * 检查端口或URL是否可用
- *
- * @param host 主机名或IP地址
- * @param port 端口号
- * @param urlString URL字符串
- * @return 如果端口可用或URL指向的HTTP服务器可用则返回true,否则返回false
- */
- public static Boolean checkPortOrUrl(String host,int port,String urlString){
- return PortChecker(host,port) || isHttpServerAvailable(urlString);
- }
-
- public static Boolean checkAndReUrl(ContainerCache c){
- return PortChecker(c.host,c.port) || isHttpServerAvailable(c.url);
- }
-
- /**
- * 重定向到指定URL地址
- *
- * @param url 要重定向到的URL地址
- * @return 返回包含JavaScript代码的字符串,用于在浏览器中执行重定向操作
- */
- public static String redir(String url) {
- return url;
- //return String.format("",url);
- }
-
-
- /**
- * 查找可用的端口号
- *
- * @param host 主机地址
- * @return 返回一个可用的端口号,如果未找到则返回0
- * @throws IllegalArgumentException 如果传入的host为空或非法
- */
- public static int findAvailablePort(String host) {
- // 这里为了简化,我们直接随机生成端口并检查(实际中可能需要更复杂的逻辑)
- int maxAttempts = 100; // 尝试次数
- int portRangeStart = 10000;
- int portRangeEnd = 29999;
-
- for (int i = 0; i < maxAttempts; i++) {
- int port = getRandomPort(portRangeStart, portRangeEnd);
-
- if (!PortChecker(host,port)) {
- // 检查端口是否真正被占用的逻辑(如使用Socket尝试连接)
- return port;
- }
- }
-
- return 0; // 如果没有找到空闲端口
- }
-
- /**
- * 生成指定范围内的随机端口号
- *
- * @param start 端口号范围的起始值(包含)
- * @param end 端口号范围的结束值(包含)
- * @return 返回生成的随机端口号
- * @throws IllegalArgumentException 如果起始值大于结束值,则抛出异常
- */
- private static int getRandomPort(int start, int end) {
- Random random = new Random();
- return start + random.nextInt(end - start + 1);
- }
-}
diff --git a/ssw-dos/ssw-dos-biz/src/main/java/ssw/dos/sandbox/DockerUtil.java b/ssw-dos/ssw-dos-biz/src/main/java/ssw/dos/sandbox/DockerUtil.java
deleted file mode 100644
index a897931..0000000
--- a/ssw-dos/ssw-dos-biz/src/main/java/ssw/dos/sandbox/DockerUtil.java
+++ /dev/null
@@ -1,292 +0,0 @@
-package ssw.dos.sandbox;
-
-import com.github.dockerjava.api.DockerClient;
-import com.github.dockerjava.api.command.*;
-import com.github.dockerjava.api.model.*;
-import com.github.dockerjava.core.DefaultDockerClientConfig;
-import com.github.dockerjava.core.DockerClientImpl;
-import com.github.dockerjava.transport.DockerHttpClient;
-import com.github.dockerjava.httpclient5.ApacheDockerHttpClient;
-import com.github.dockerjava.core.command.ExecStartResultCallback;
-import com.github.dockerjava.core.command.LogContainerResultCallback;
-import com.github.dockerjava.core.command.PullImageResultCallback;
-import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
-import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
-import ssw.dos.sandbox.TarUtil;
-
-import java.io.*;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Objects;
-
-@Slf4j
-public class DockerUtil {
- private final DockerClient dockerClient;
-
- /**
- * 创建一个DockerUtil对象示例 (适配 docker-java 3.4 API)
- *
- * @throws InterruptedException 如果在等待获取Docker客户端实例时线程被中断,则抛出此异常
- */
- public DockerUtil(String host,int port,String certPath) throws InterruptedException {
- DefaultDockerClientConfig config = DefaultDockerClientConfig
- .createDefaultConfigBuilder()
- .withDockerHost("tcp://" + host + ":" + port)
- .withDockerTlsVerify(true)
- .withDockerCertPath(certPath)
- .build();
- DockerHttpClient httpClient = new ApacheDockerHttpClient.Builder()
- .dockerHost(config.getDockerHost())
- .sslConfig(config.getSSLConfig())
- .build();
- dockerClient = DockerClientImpl.getInstance(config, httpClient);
- }
-
-
- public DockerUtil() {
- DefaultDockerClientConfig config = DefaultDockerClientConfig
- .createDefaultConfigBuilder()
- .withDockerHost("unix:///var/run/docker.sock").build();
- DockerHttpClient httpClient = new ApacheDockerHttpClient.Builder()
- .dockerHost(config.getDockerHost())
- .build();
- dockerClient = DockerClientImpl.getInstance(config, httpClient);
- }
-
- public DockerClient getClient( )
- {
- return dockerClient;
- }
-
- /**
- * 获取GPU设备配置信息(这里只用gup1,多卡服务器要分开来)
- *
- * @return 包含GPU设备请求的列表
- */
- public List setGpuDevices() {
- List list = new ArrayList<>();
- DeviceRequest deviceRequest = new DeviceRequest();
- deviceRequest.withCount(1);
- deviceRequest.withDriver("nvidia");
- List> capabilities = new ArrayList<>();
- List capability = new ArrayList<>();
- capability.add("gpu");
- capabilities.add (capability);
- deviceRequest.withCapabilities(capabilities);
- list.add(deviceRequest);
- return list;
- }
-
- /**
- * 根据名称查询容器
- *
- * @param containerName 容器名称
- * @return 返回查询到的容器对象,若未找到则返回null
- */
- public Container getContainerByName(String containerName) throws InterruptedException {
- List containerList = dockerClient.listContainersCmd()
- .withShowAll(Boolean.TRUE)
- .exec();
-
- for (int j = 0; j < containerList.size(); j++) {
- Container container = containerList.get(j);
- String[] labels = container.getNames();
- for (int i = 0; i < labels.length; i++)
- if(Objects.equals(labels[i],"/" + containerName)){
- log.info("通过名称查询到容器, containerName:" + containerName);
- return container;
- }
- }
-
- log.error("未找到指定镜像容器:"+ containerName);
- return null;
- }
-
- /**
- * 启动容器
- *
- * @param imageName 镜像名称
- * @param containerName 容器名称
- * @param hostConfig 主机配置
- * @return 返回启动的容器对象
- * @throws InterruptedException 如果等待容器启动的过程中被中断,则抛出此异常
- */
- public Container createContainer(String imageName, String containerName, HostConfig hostConfig, String[] envs, Boolean gpu, String...cmd) throws InterruptedException {
- //查找容器是否存在,如果存在则先清除,以确保配置更新
- dropContainer(containerName);
-
- //下载镜像(如果镜像未下载)
- pullImage(imageName);
-
- if (gpu) //是否gpu环境
- hostConfig.withDeviceRequests(setGpuDevices());
-
- CreateContainerCmd ccc = dockerClient.createContainerCmd(imageName)
- .withHostConfig(hostConfig)
- .withName(containerName);
-
- if (envs != null)
- ccc = ccc.withEnv(envs);
-
- if (cmd != null) //是否需要执行命令,则绑定启动项
- ccc = ccc.withCmd(cmd);
-
- ccc.exec();
- Container container = getContainerByName(containerName);
-
- //启动它
- dockerClient.startContainerCmd(container.getId()).exec();
-
- // 设置日志输出
- LogContainerCmd logContainerCmd = dockerClient.logContainerCmd(container.getId())
- .withStdOut(true)
- .withStdErr(true);
- logContainerCmd.exec(logContainerResultCallback);
-
- return container;
- }
-
- public Container createContainer(String imageName, String containerName, HostConfig hostConfig, Boolean gpu, String...cmd) throws InterruptedException {
- return createContainer(imageName, containerName,hostConfig,null,gpu, cmd);
- }
-
- /**
- * 从Docker仓库中拉取指定名称的镜像
- *
- * @param imageName 镜像名称
- * @throws InterruptedException 如果在拉取镜像过程中发生中断,则抛出此异常
- */
- public void pullImage(String imageName) throws InterruptedException {
- //判断镜像是否存在,如果存在就不再下载
- List images = dockerClient.listImagesCmd().exec();
- for(Image i : images){
- if(Arrays.asList(i.getRepoTags()).contains(imageName)){
- System.out.println("镜像已下载:" + imageName);
- return;
- }
- }
-
- PullImageCmd pullImageCmd = dockerClient.pullImageCmd(imageName);
- PullImageResultCallback pullImageResultCallback = new PullImageResultCallback(){
- @Override
- public void onNext(PullResponseItem item) {
- log.info("下载镜像状态:" + item.getStatus());
- super.onNext(item);
- }
- };
- pullImageCmd.exec(pullImageResultCallback)
- .awaitCompletion(); // 等待下载完成,不然一直阻塞
-
- log.info("镜像下载完成" + imageName);
- }
-
- /**
- * 启动指定名称的Docker容器(已经存在)
- *
- * @param containerName 要启动的Docker容器的名称
- * @throws Exception 如果在启动容器过程中发生任何异常,将抛出此异常
- */
- public void execStartContainer(String containerName){
- dockerClient.startContainerCmd(containerName).exec();
- }
-
- /**
- * 销毁指定的 Docker 容器
- *
- * @param containerName 要销毁的容器的名称
- * @return 返回销毁结果,成功返回"销毁环境成功!",失败返回"环境不存在!"
- * @throws InterruptedException 如果等待线程中断,则抛出 InterruptedException 异常
- */
- public String dropContainer(String containerName) throws InterruptedException {
- Container container = getContainerByName(containerName);
- if(container == null) {
- log.error("环境不存在!", containerName);
- return "环境不存在!";
- }
-
- if (Objects.equals(container.getState(), "running")) {
- dockerClient.stopContainerCmd(containerName).exec();
- log.info("停止环境成功!docker name:{}", containerName);
- }
-
- dockerClient.removeContainerCmd(containerName).exec();
- log.info("删除环境成功!docker name:{}", containerName);
- return "销毁环境成功!";
- }
-
- /**
- * 停止指定名称的Docker容器
- *
- * @param containerName 要停止的Docker容器的名称
- * @throws Exception 如果在停止容器过程中发生任何异常,将抛出此异常
- */
- public void execStopContainerCmd(String containerName) {
- dockerClient.stopContainerCmd(containerName).exec();
- }
-
- /**
- * 在指定的Docker容器中执行命令
- *
- * @param id 容器ID
- * @param cmd 要在容器中执行的命令
- * @throws InterruptedException 如果线程在等待时被中断,则抛出此异常
- */
- public void exec(String id, String cmd) throws InterruptedException {
- // 要在容器中执行的命令
- ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(id)
- .withAttachStdout(true).withCmd("bash", "-c", cmd).exec();
-
- dockerClient.execStartCmd(execCreateCmdResponse.getId()).withDetach(false).withTty(true)
- .exec(new ExecStartResultCallback(System.out, System.err)).awaitCompletion();
- }
-
-
- /**
- * 日志信息回调
- */
- static LogContainerResultCallback logContainerResultCallback = new LogContainerResultCallback() {
- /**
- * 当接收到下一个Frame对象时触发该方法
- *
- * @param item 接收到的Frame对象
- */
- @Override
- public void onNext(Frame item) {
- log.info(new String(item.getPayload()));
- super.onNext(item);
- }
- };
-
- /**
- * 压缩文件从输入流复制到Docker容器中指定路径下
- *
- * @param id Docker容器的ID
- * @param from 输入,需要复制的文件名(tar格式)
- * @param to Docker容器中的目标路径
- */
- public void copy(String id, String from, String to) throws IOException {
- FileInputStream f = new FileInputStream(from);
- CopyArchiveToContainerCmd cmd = dockerClient.copyArchiveToContainerCmd(id)
- .withTarInputStream(f)
- .withRemotePath(to);
- cmd.exec();
- }
-
- /**
- * 将多个文件复制到Docker容器的指定目录下
- *
- * @param id Docker容器的ID或名称
- * @param to 目标目录
- * @param files 要复制的文件列表,可变参数
- * @throws IOException 如果复制文件时发生IO异常
- */
- public void copyfs(String id, String to,String ...files) throws IOException {
- InputStream f = new ByteArrayInputStream(TarUtil.createTarStream(files));
- CopyArchiveToContainerCmd cmd = dockerClient.copyArchiveToContainerCmd(id)
- .withTarInputStream(f)
- .withRemotePath(to);
- cmd.exec();
- }
-}
diff --git a/ssw-dos/ssw-dos-biz/src/main/java/ssw/dos/sandbox/K8sUtil.java b/ssw-dos/ssw-dos-biz/src/main/java/ssw/dos/sandbox/K8sUtil.java
deleted file mode 100644
index 3aaf1d5..0000000
--- a/ssw-dos/ssw-dos-biz/src/main/java/ssw/dos/sandbox/K8sUtil.java
+++ /dev/null
@@ -1,169 +0,0 @@
-package ssw.dos.sandbox;
-
-import java.io.*;
-import java.net.URL;
-import java.util.Base64;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import javax.net.ssl.HttpsURLConnection;
-
-import com.alibaba.fastjson.JSON;
-import com.alibaba.fastjson.JSONArray;
-import com.alibaba.fastjson.JSONObject;
-
-public class K8sUtil {
-
- private static final Logger logger = Logger.getLogger(K8sUtil.class.getName());
- private final String apiServerUrl;
- private final String token;
- private final String namespace;
-
- public K8sUtil(String apiServerUrl, String token, String namespace) {
- this.apiServerUrl = apiServerUrl;
- this.token = token;
- this.namespace = namespace;
- }
-
- private HttpsURLConnection createConnection(String endpoint) throws IOException {
- URL url = new URL(apiServerUrl + "/api/v1/namespaces/" + namespace + endpoint);
- HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
- conn.setRequestProperty("Authorization", "Bearer " + token);
- conn.setRequestProperty("Content-Type", "application/json");
- return conn;
- }
-
- public JSONObject createPod(String podName, String imageName, String[] command) throws IOException {
- JSONObject podSpec = new JSONObject();
- podSpec.put("name", podName);
- podSpec.put("image", imageName);
- if (command != null) {
- podSpec.put("command", command);
- }
-
- JSONObject podBody = new JSONObject();
- podBody.put("apiVersion", "v1");
- podBody.put("kind", "Pod");
- podBody.put("metadata", new JSONObject().put("name", podName));
- podBody.put("spec", new JSONObject().put("containers", new JSONArray().add(podSpec)));
-
- HttpsURLConnection conn = (HttpsURLConnection) createConnection("/pods");
- conn.setRequestMethod("POST");
- conn.setDoOutput(true);
- OutputStream os = conn.getOutputStream();
- os.write(podBody.toJSONString().getBytes("UTF-8"));
- os.flush();
- os.close();
-
- if (conn.getResponseCode() >= 200 && conn.getResponseCode() < 300) {
- InputStream is = conn.getInputStream();
- String response = getResponseString(is);
- return JSON.parseObject(response);
- } else {
- InputStream errorStream = conn.getErrorStream();
- String error = getResponseString(errorStream != null ? errorStream : conn.getInputStream());
- logger.log(Level.SEVERE, "创建 Pod 失败: " + error);
- return null;
- }
- }
-
- public JSONObject getPod(String podName) throws IOException {
- HttpsURLConnection conn = (HttpsURLConnection) createConnection("/pods/" + podName);
- conn.setRequestMethod("GET");
-
- if (conn.getResponseCode() >= 200 && conn.getResponseCode() < 300) {
- InputStream is = conn.getInputStream();
- String response = getResponseString(is);
- return JSON.parseObject(response);
- } else {
- InputStream errorStream = conn.getErrorStream();
- String error = getResponseString(errorStream != null ? errorStream : conn.getInputStream());
- logger.log(Level.SEVERE, "获取 Pod 失败: " + error);
- return null;
- }
- }
-
- public boolean deletePod(String podName) throws IOException {
- HttpsURLConnection conn = (HttpsURLConnection) createConnection("/pods/" + podName);
- conn.setRequestMethod("DELETE");
-
- if (conn.getResponseCode() >= 200 && conn.getResponseCode() < 300) {
- return true;
- } else {
- InputStream errorStream = conn.getErrorStream();
- String error = getResponseString(errorStream != null ? errorStream : conn.getInputStream());
- logger.log(Level.SEVERE, "删除 Pod 失败: " + error);
- return false;
- }
- }
-
- public JSONObject execInPod(String podName, String command) throws IOException {
- String encodedCommand = Base64.getEncoder().encodeToString(command.getBytes("UTF-8"));
- HttpsURLConnection conn = (HttpsURLConnection) createConnection("/pods/" + podName + "/exec");
- conn.setRequestMethod("POST");
- conn.setDoOutput(true);
-
- JSONObject requestBody = new JSONObject();
- requestBody.put("container", podName);
- requestBody.put("command", new String[]{"/bin/sh", "-c", "echo " + encodedCommand + " | base64 -d | sh"});
- requestBody.put("stdin", true);
- requestBody.put("stdout", true);
- requestBody.put("stderr", true);
-
- OutputStream os = conn.getOutputStream();
- os.write(requestBody.toJSONString().getBytes("UTF-8"));
- os.flush();
- os.close();
-
- if (conn.getResponseCode() >= 200 && conn.getResponseCode() < 300) {
- InputStream is = conn.getInputStream();
- String response = getResponseString(is);
- return JSON.parseObject(response);
- } else {
- InputStream errorStream = conn.getErrorStream();
- String error = getResponseString(errorStream != null ? errorStream : conn.getInputStream());
- logger.log(Level.SEVERE, "在 Pod 中执行命令失败: " + error);
- return null;
- }
- }
-
- private String getResponseString(InputStream is) throws IOException {
- BufferedReader br = new BufferedReader(new InputStreamReader(is));
- StringBuilder response = new StringBuilder();
- String line;
- while ((line = br.readLine()) != null) {
- response.append(line);
- }
- br.close();
- return response.toString();
- }
-
- public static void test() {
- // 示例用法
- String apiServerUrl = "https://your-kubernetes-api-server:443";
- String token = "your-service-account-token";
- String namespace = "default";
-
- K8sUtil kubernetesUtil = new K8sUtil(apiServerUrl, token, namespace);
-
- try {
- // 创建一个 Pod
- JSONObject pod = kubernetesUtil.createPod("test-pod", "nginx:latest", new String[]{"/bin/sh", "-c", "nginx -g 'daemon off;'"});
- System.out.println("创建的 Pod: " + pod.toJSONString());
-
- // 获取 Pod 信息
- JSONObject podInfo = kubernetesUtil.getPod("test-pod");
- System.out.println("Pod 信息: " + podInfo.toJSONString());
-
- // 在 Pod 中执行命令
- JSONObject execResult = kubernetesUtil.execInPod("test-pod", "echo 'Hello from exec!'");
- System.out.println("执行结果: " + execResult.toJSONString());
-
- // 删除 Pod
- boolean deleted = kubernetesUtil.deletePod("test-pod");
- System.out.println("Pod 已删除: " + deleted);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-}
diff --git a/ssw-dos/ssw-dos-biz/src/main/java/ssw/dos/sandbox/SandBoxUtil.java b/ssw-dos/ssw-dos-biz/src/main/java/ssw/dos/sandbox/SandBoxUtil.java
deleted file mode 100644
index 9c41d23..0000000
--- a/ssw-dos/ssw-dos-biz/src/main/java/ssw/dos/sandbox/SandBoxUtil.java
+++ /dev/null
@@ -1,416 +0,0 @@
-package ssw.dos.sandbox;
-
-import java.io.*;
-import java.net.HttpURLConnection;
-import java.net.URL;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
-import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
-import ssw.dos.sandbox.TarUtil;
-
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.SSLContext;
-
-@Slf4j
-public class SandBoxUtil {
-
- private static final String DOCKER_API_VERSION = "/v1.41"; // 根据你的Docker版本调整API版本
- private static final String DEFAULT_DOCKER_HOST = "http://localhost:2375";
-
- private final String dockerHost;
- private final String dockerCertPath;
-
- public SandBoxUtil(String host, int port, String certPath) {
- this.dockerHost = "https://" + host + ":" + port;
- this.dockerCertPath = certPath;
- }
-
- public SandBoxUtil() {
- this.dockerHost = DEFAULT_DOCKER_HOST;
- this.dockerCertPath = null;
- }
-
- private HttpsURLConnection createConnection(String endpoint) throws Exception {
- URL url = new URL(dockerHost + DOCKER_API_VERSION + endpoint);
- HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
- conn.setRequestProperty("Content-Type", "application/json");
- SSLContext sslContext = TlsConfig.configureSSLContext(dockerCertPath, "abcvefdf");
- conn.setSSLSocketFactory(sslContext.getSocketFactory());
- return conn;
- }
-
- Map hostConfig = new HashMap<>();
- List Env = new ArrayList<>();
- List Cmd = new ArrayList<>();
-
-
- /**
- * 挂载目录
- * @param hostPath 宿主机目录
- * @param cpath 容器目录.如需要请在后面增加模式,如:ro 只读
- */
- public void addBinds(String hostPath,String cpath){
- if(!hostConfig.containsKey("Binds"))
- hostConfig.put("Binds",new ArrayList());
-
- ((ArrayList)hostConfig.get("Binds")).add(hostPath + ":" + cpath);
- }
-
- public void withShmSize(long l) {
- hostConfig.put("ShmSize",l);
- }
-
- public void addEnv(String env) {
- Env.add(env);
- }
-
- public void addCmd(String cmd) {
- Cmd.add(cmd);
- }
-
- public void addPortBindings(int export, int hostPort) {
- if (!hostConfig.containsKey("PortBindings"))
- hostConfig.put("PortBindings",new HashMap());
-
- List list = new ArrayList<>();
- Map host = new HashMap();
- host.put("HostIp","0.0.0.0");
- host.put("HostPort", String.valueOf(export));
- list.add(host);
-
- ((Map)hostConfig.get("PortBindings")).put(hostPort + "/tcp",list);
- }
-
- public String createContainer(String imageName, String Name) throws Exception {
- // 下载镜像(如果镜像未下载)
- pullImage(imageName);
-
- // 构建容器配置
- Map containerConfig = new HashMap<>();
- containerConfig.put("Image", imageName);
- containerConfig.put("Cmd", Cmd);
- containerConfig.put("Env", Env);
- containerConfig.put("HostConfig", hostConfig);
- ObjectMapper objectMapper = new ObjectMapper();
-
- // 发送创建容器请求
- HttpURLConnection conn = createConnection("/containers/create?name=" + Name);
- conn.setRequestMethod("POST");
- conn.setDoOutput(true);
- OutputStream os = conn.getOutputStream();
- os.write(objectMapper.writeValueAsBytes(containerConfig));
- os.flush();
- os.close();
-
- InputStream is = conn.getInputStream();
- // 处理响应
- if (conn.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
- Map ro = objectMapper.readValue(is, Map.class);
- return ro.get("Id").toString();
- } else {
- throw new Exception("创建容器失败: " + is);
- }
- }
-
- public void withGpu() {
- // 设置GPU设备
- List