master
youys 2 years ago
commit 83de265d7e

18
.gitignore vendored

@ -0,0 +1,18 @@
/.classpath
/.project
/.settings/
/target/
/.idea
*.iml
.idea
*.project
*.classpath
.metadata
.settings
**/**/target
*.factorypath
out/
logs/
*.DS_Store
logs/
log/

@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.educoder</groupId>
<artifactId>sjtu-bridge</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.2</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.11</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,18 @@
package net.educoder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @Author: youys
* @Date: 2022/8/16
* @Description:
*/
@SpringBootApplication
public class SjtuBridgeApplication {
public static void main(String[] args) {
SpringApplication.run(SjtuBridgeApplication.class, args);
}
}

@ -0,0 +1,16 @@
package net.educoder.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author: youys
* @Date: 2022/8/16
* @Description:
*/
@RestController
@RequestMapping("/jcloud")
public class CloudController {
}

@ -0,0 +1,19 @@
package net.educoder.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author: youys
* @Date: 2022/8/16
* @Description:
*/
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "hello,world";
}
}

@ -0,0 +1,42 @@
package net.educoder.exception;
import com.alibaba.fastjson.JSONObject;
/**
* @Author: youys
* @Date: 2022/8/16
* @Description:
*/
public class BridgeException extends RuntimeException{
private int code;
private String msg;
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
public BridgeException(int code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
public BridgeException(String msg) {
super(msg);
this.code = -1;
this.msg = msg;
}
@Override
public String toString() {
JSONObject str = new JSONObject();
str.put("code", getCode());
str.put("msg", getMsg());
return str.toJSONString();
}
}

@ -0,0 +1,50 @@
package net.educoder.handler;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.educoder.exception.BridgeException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @Author: youys
* @Date: 2022/8/16
* @Description:
*/
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BridgeException.class)
@ResponseBody
public ResponseEntity<JSONObject> handleBridgeExceptions(BridgeException e) {
log.error("捕获到BridgeException", e);
JSONObject jsonObj = new JSONObject();
jsonObj.put("code", e.getCode());
jsonObj.put("msg", e.getMsg());
return new ResponseEntity<>(jsonObj, HttpStatus.OK);
}
@ExceptionHandler(Exception.class)
@ResponseBody
public ResponseEntity<JSONObject> handleOtherExceptions(Exception e) {
log.error("捕获到Exception", e);
JSONObject jsonObj = new JSONObject();
if (e.getMessage().contains("Maximum upload size exceeded")) {
jsonObj.put("code", -1);
jsonObj.put("msg", "未知错误!" + e.getMessage());
}
return new ResponseEntity<>(jsonObj, HttpStatus.OK);
}
}

@ -0,0 +1,29 @@
package net.educoder.model.param;
import lombok.Data;
/**
* @Author: youys
* @Date: 2022/8/16
* @Description:
*/
@Data
public class CreateCloudHostParam {
/**
*
*/
private String name;
/**
* id
*/
private String imageRef;
/**
* id xxG
*/
private String flavorRef;
/**
* id
*/
private String networkId;
}

@ -0,0 +1,279 @@
package net.educoder.util;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.educoder.exception.BridgeException;
import net.educoder.model.param.CreateCloudHostParam;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
/**
* @Author: youys
* @Date: 2022/7/14
* @Description:
*/
@Slf4j
public class JCloudUtil {
/**
*
*
* @param token
* @return
*/
public static String getCloudListDetail(String token) {
String url = "https://home.jcloud.sjtu.edu.cn:8774/v2.1/servers/detail";
long start = System.currentTimeMillis();
String result = HttpRequest.get(url).header("Content-Type", "application/json").header("X-Auth-Token", token).execute().body();
long end = System.currentTimeMillis();
log.info("交大云获取云主机列表详情返回结果:{},耗时:{}ms", result, (end - start));
return result;
}
/**
*
*
* @param token
* @param serverId
* @return
*/
public static JSONObject getCloudDetail(String token, String serverId) {
String url = "https://home.jcloud.sjtu.edu.cn:8774/v2.1/servers/{server_id}".replaceAll("\\{server_id}", serverId);
long start = System.currentTimeMillis();
String result = HttpRequest.get(url).header("Content-Type", "application/json").header("X-Auth-Token", token).execute().body();
long end = System.currentTimeMillis();
log.info("交大云获取云主机serverId:{}详情返回结果:{},耗时:{}ms", serverId, result, (end - start));
if (StringUtils.isNotBlank(result)) {
return JSONObject.parseObject(result);
}
throw new BridgeException("获取云主机详情失败");
}
/**
*
*
* @param createCloudHost
* @return
*/
public static String createCloudHost(String token, CreateCloudHostParam createCloudHost) {
String url = "https://home.jcloud.sjtu.edu.cn:8774/v2.1/servers";
// 默认
String body = "{\n" +
" \"server\":{\n" +
" \"name\": \"" + createCloudHost.getName() + "\",\n" +
" \"adminPass\": \"Educoder123\",\n" +
" \"imageRef\": \"" + createCloudHost.getImageRef() + "\",\n" +
" \"flavorRef\": \"" + createCloudHost.getFlavorRef() + "\",\n" +
" \"networks\":[\n" +
" {\n" +
" \"uuid\": \"" + createCloudHost.getNetworkId() + "\"\n" +
" }\n" +
" ],\n" +
" \"security_groups\": [\n" +
" {\n" +
" \"name\": \"default\"\n" +
" }\n" +
" ]" +
" }\n" +
"}";
long start = System.currentTimeMillis();
String result = HttpRequest.post(url).header("Content-Type", "application/json").header("X-Auth-Token", token).body(body).execute().body();
long end = System.currentTimeMillis();
log.info("交大云创建云主机返回结果:{},耗时:{}ms", result, (end - start));
return result;
}
/**
*
*
* @param token
* @param serverId
* @param password
* @return
*/
public static boolean changePassword(String token, String serverId, String password) {
String url = "https://home.jcloud.sjtu.edu.cn:8774/v2.1/servers/{server_id}/action".replaceAll("\\{server_id}", serverId);
/**
* {
* "changePassword" : {
* "adminPass" : "foo"
* }
* }
*/
JSONObject changePassword = new JSONObject();
changePassword.put("adminPass", password);
JSONObject requestBody = new JSONObject();
requestBody.put("changePassword", changePassword);
long start = System.currentTimeMillis();
String result = HttpRequest.post(url).header("Content-Type", "application/json").header("X-Auth-Token", token).body(requestBody.toJSONString()).execute().body();
long end = System.currentTimeMillis();
log.info("交大云更改云主机密码返回结果:{},耗时:{}ms", result, (end - start));
return StringUtils.isNotBlank(result);
}
/**
*
*
* @param token
* @param serverId
* @return
*/
public static boolean rebuildCloud(String token, String serverId) {
String url = "https://home.jcloud.sjtu.edu.cn:8774/v2.1/servers/{server_id}/action".replaceAll("\\{server_id}", serverId);
/**
* {
* "rebuild" : {
* "imageRef" : "70a599e0-31e7-49b7-b260-868f441e862b",
* "adminPass" : "seekr3t"
* }
* }
*/
JSONObject rebuild = new JSONObject();
rebuild.put("imageRef", "31a54313-bcfe-4c6e-9e19-dcad8360ef56");
rebuild.put("adminPass", "Educoder123");
JSONObject requestBody = new JSONObject();
requestBody.put("rebuild", rebuild);
long start = System.currentTimeMillis();
String result = HttpRequest.post(url).header("Content-Type", "application/json").header("X-Auth-Token", token).body(requestBody.toJSONString()).execute().body();
long end = System.currentTimeMillis();
log.info("交大云重新构建云主机密码返回结果:{},耗时:{}ms", result, (end - start));
return true;
}
/**
*
*
* @param serverId
* @param token
* @return
*/
public static boolean deleteCloudHost(String serverId, String token) {
String url = "https://home.jcloud.sjtu.edu.cn:8774/v2.1/servers/{server_id}".replaceAll("\\{server_id}", serverId);
long start = System.currentTimeMillis();
String result = HttpRequest.delete(url).header("Content-Type", "application/json").header("X-Auth-Token", token).execute().body();
long end = System.currentTimeMillis();
log.info("交大云删除云主机返回结果:{},耗时:{}ms", result, (end - start));
return StringUtils.isBlank(result);
}
/**
* api token
*
* @return token
*/
public static String getApiToken(String username, String password) {
/**
* {
* "auth": {
* "identity": {
* "methods": [
* "password"
* ],
* "password": {
* "user": {
* "name": "admin",
* "domain": {
* "name": "Default"
* },
* "password": "devstacker"
* }
* }
* }
* }
* }
*/
JSONObject domain = new JSONObject();
domain.put("name", "Default");
JSONObject user = new JSONObject();
user.put("name", username);
user.put("password", password);
user.put("domain", domain);
JSONObject passwordJson = new JSONObject();
passwordJson.put("user", user);
JSONObject identity = new JSONObject();
identity.put("methods", Arrays.asList("password"));
identity.put("password", passwordJson);
JSONObject auth = new JSONObject();
auth.put("identity", identity);
JSONObject requestBody = new JSONObject();
requestBody.put("auth", auth);
HttpResponse response = HttpRequest.post("https://home.jcloud.sjtu.edu.cn:5000/v3/auth/tokens").header("Content-Type", "application/json").body(requestBody.toJSONString()).execute();
if (response.isOk()) {
String token = response.header("X-Subject-Token");
log.info("交我算平台获取token成功,token: {}", token);
return token;
}
log.info("交我算平台获取token失败,body:{}", response.body());
return "";
}
public static void main(String[] args) {
String username = "educoder01";
String password = "Educoder123";
String apiToken = getApiToken(username, password);
// createCloudHost(apiToken, defaultCreateCloudHostParam());
String serverId = "7c91c97b-37a4-4cf2-85be-fdddaef44f2b";
/**
*
*/
// rebuildCloud(apiToken, serverId);
// changePassword(apiToken, serverId, "Educoder123");
// getCloudDetail(apiToken, serverId);
// deleteCloudHost("902d0100-745c-4ef5-af44-edca4b1410d9",apiToken);
}
/**
*
* centos7.9
* 48G
*
*
* @return
*/
public static CreateCloudHostParam defaultCreateCloudHostParam() {
CreateCloudHostParam createCloudHost = new CreateCloudHostParam();
createCloudHost.setName(RandomUtil.randomString(10));
createCloudHost.setImageRef("31a54313-bcfe-4c6e-9e19-dcad8360ef56");
createCloudHost.setFlavorRef("02723f5f-5518-4031-bd5e-dfecae675606");
createCloudHost.setNetworkId("f41ece4b-ff14-4444-8d1d-c730779a0df2");
return createCloudHost;
}
}

@ -0,0 +1,4 @@
server:
port: 8181
servlet:
context-path: /sjtu-bridge

@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- <springProperty scope="context" name="logPath" source="log.path"/>-->
<property name="logPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5level [%thread] %c -- %msg%n"/>
<property name="logPath" value="logs/"/>
<!-- 标准输出 -->
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${logPattern}</pattern>
</encoder>
</appender>
<!-- 日志按天生成 -->
<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder>
<pattern>${logPattern}</pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${logPath}/info_%d{yyyy-MM-dd}_%i.log</fileNamePattern>
<maxHistory>30</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>10MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>
<!-- 错误日志单独再记录,以便当前的日志分析报警 -->
<appender name="error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
<encoder>
<pattern>${logPattern}</pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${logPath}/error_%d{yyyy-MM-dd}_%i.log</fileNamePattern>
<maxHistory>30</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>10MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>
<!-- 屏蔽框架输出 -->
<logger name="org.mybatis.spring" level="INFO"/>
<root>
<level value="INFO"/>
<appender-ref ref="file"/>
<appender-ref ref="error"/>
<appender-ref ref="stdout"/>
</root>
</configuration>
Loading…
Cancel
Save