Compare commits
224 Commits
master
...
dev_monito
| Author | SHA1 | Date |
|---|---|---|
|
|
4ada9fc829 | |
|
|
e8bdc8fc92 | |
|
|
3a0f0d84c5 | |
|
|
569eaa14ff | |
|
|
33e77ed05b | |
|
|
7c785d4743 | |
|
|
c890870e09 | |
|
|
07a70f12ce | |
|
|
5daaa3d54a | |
|
|
e87484b1e1 | |
|
|
02791388bd | |
|
|
5d14d5e56a | |
|
|
e3ddab5ceb | |
|
|
587a2707a7 | |
|
|
992c17b4c8 | |
|
|
0aa96e853a | |
|
|
34ab56eb8a | |
|
|
bdbd2da88d | |
|
|
30f8ce8184 | |
|
|
7fbfbdaf8d | |
|
|
93ed7838e6 | |
|
|
68988926b9 | |
|
|
5485d39894 | |
|
|
2516ba038e | |
|
|
bb9b4f05da | |
|
|
4bbf3c91e2 | |
|
|
00bde1ad9a | |
|
|
092d566de4 | |
|
|
27c5e64e1a | |
|
|
71f4e4bc8f | |
|
|
8c8e13a5e1 | |
|
|
82c74b9184 | |
|
|
290fc64c88 | |
|
|
b0aede3f93 | |
|
|
902f961469 | |
|
|
e904d854f6 | |
|
|
3dbdef7ab8 | |
|
|
072e85de82 | |
|
|
8f48c1030a | |
|
|
9380081443 | |
|
|
0646a3b773 | |
|
|
43e75440d5 | |
|
|
0ca345d200 | |
|
|
83c1457c50 | |
|
|
3f208de48a | |
|
|
bce79534bd | |
|
|
f402ec1748 | |
|
|
7de259d088 | |
|
|
1c9bc630d8 | |
|
|
c13748d494 | |
|
|
69e789d856 | |
|
|
02f215c2e4 | |
|
|
d1076e48d5 | |
|
|
b25411e35c | |
|
|
1f3d65fd39 | |
|
|
3f155f2270 | |
|
|
ee77bdb8a1 | |
|
|
631f6752a6 | |
|
|
39a8dde543 | |
|
|
0f0a639bf4 | |
|
|
cf2c5cffa3 | |
|
|
b89c235df3 | |
|
|
2d5d43b37e | |
|
|
32b58df5d1 | |
|
|
555ef0fc80 | |
|
|
46cbaccf64 | |
|
|
ebf1dc53cf | |
|
|
e6dadf2ccd | |
|
|
71cf4fb6fc | |
|
|
eed4b9d9eb | |
|
|
cad9ea1247 | |
|
|
02e369849d | |
|
|
f7e9d9350e | |
|
|
356b85fd35 | |
|
|
19a32e2f7c | |
|
|
b2f9921664 | |
|
|
2567386baa | |
|
|
8e10fee65f | |
|
|
310b423ec9 | |
|
|
705823ec3f | |
|
|
172e0ee92e | |
|
|
726ece8af9 | |
|
|
82f180d31c | |
|
|
e91ee14d63 | |
|
|
10a1b3f5cf | |
|
|
7f22a2c6ec | |
|
|
9c76980bdc | |
|
|
a861d69061 | |
|
|
53274c3b0e | |
|
|
32ded69b77 | |
|
|
36e9d84dd8 | |
|
|
4e0d281bf7 | |
|
|
fbcbe63ad4 | |
|
|
48e0510bb3 | |
|
|
3726e4b294 | |
|
|
335d05d2c3 | |
|
|
fa4ee4526b | |
|
|
405b2e07c1 | |
|
|
c6fd9a1c9d | |
|
|
bfbaa3491d | |
|
|
c97b64f3bc | |
|
|
83c8d5fe3e | |
|
|
7cff154598 | |
|
|
d0fcf1fbce | |
|
|
3cf7ced976 | |
|
|
ddb1a06acc | |
|
|
0c94e636e1 | |
|
|
0f2d37babe | |
|
|
6e72d6f762 | |
|
|
d330e7a56d | |
|
|
29dbc84989 | |
|
|
f055d0f28e | |
|
|
20ce451a9a | |
|
|
629822dcb9 | |
|
|
e7ca96f280 | |
|
|
f9956c305e | |
|
|
d13b38e980 | |
|
|
45c84d17b6 | |
|
|
71ec75c3e5 | |
|
|
0d0b0072c3 | |
|
|
8f84d425c8 | |
|
|
1cb6c3e758 | |
|
|
17a911c54e | |
|
|
adc86b04c9 | |
|
|
cd19bd94cc | |
|
|
dc814cffff | |
|
|
92bfd2c7f2 | |
|
|
6a71629784 | |
|
|
1e016300c7 | |
|
|
fdf61667f7 | |
|
|
22f350510c | |
|
|
2566f119d3 | |
|
|
19718b6123 | |
|
|
3fa2daac28 | |
|
|
2d304cfae0 | |
|
|
1f2f48c120 | |
|
|
19e298b67a | |
|
|
f70681d783 | |
|
|
8abb5a38bd | |
|
|
9eb10143f7 | |
|
|
9865c8bad9 | |
|
|
bc92fb8419 | |
|
|
a25048faad | |
|
|
8c068c4b79 | |
|
|
735d7fd9e9 | |
|
|
705a9241b6 | |
|
|
03b7c170e4 | |
|
|
0c0f27810e | |
|
|
4fd5c1cc4d | |
|
|
65a5b5d081 | |
|
|
e97b972f31 | |
|
|
828901d322 | |
|
|
33185a1d0c | |
|
|
29b6b2bbae | |
|
|
2883029641 | |
|
|
5eed69522c | |
|
|
c5d99153b8 | |
|
|
6f4a10f1cb | |
|
|
c6f58972a6 | |
|
|
53795b1b88 | |
|
|
1f653894cd | |
|
|
5af3df62ee | |
|
|
fde9893840 | |
|
|
e44f63a4c6 | |
|
|
6d47364cca | |
|
|
128a107f8f | |
|
|
65aaa7df5b | |
|
|
b1da0ba006 | |
|
|
ad3625a823 | |
|
|
115a3cbe12 | |
|
|
c9d08ef3d5 | |
|
|
3f795fadb5 | |
|
|
672476ba53 | |
|
|
1f55a7835e | |
|
|
0b16dbf195 | |
|
|
8111f6db61 | |
|
|
ae073b68bc | |
|
|
14072b1dff | |
|
|
12eecde9c4 | |
|
|
66e1b9aca6 | |
|
|
93e56ed555 | |
|
|
13d5e7aa46 | |
|
|
dc9a537feb | |
|
|
3d5d6bfc6e | |
|
|
bac9eeda5f | |
|
|
18f89d1b8e | |
|
|
c3b5dcafba | |
|
|
a0aec9bf88 | |
|
|
a511f39a13 | |
|
|
75f828b76c | |
|
|
4b1042c25d | |
|
|
e9c41768e1 | |
|
|
15aa7016b9 | |
|
|
f96cee3f4a | |
|
|
055b26ee29 | |
|
|
368a45e8b2 | |
|
|
2c5f0518ca | |
|
|
06fbbf7208 | |
|
|
6613950ff8 | |
|
|
8184eb2401 | |
|
|
213aee5587 | |
|
|
274af358dd | |
|
|
58bf8326c5 | |
|
|
5e19e53b94 | |
|
|
2be36ca12e | |
|
|
ad405c912e | |
|
|
6ef1fafac8 | |
|
|
39d43e3d68 | |
|
|
1eefa65c32 | |
|
|
c6b4a1bd80 | |
|
|
21ba1ce6bd | |
|
|
dd870b3cd3 | |
|
|
417d440549 | |
|
|
67b2e9ce7c | |
|
|
32b83749e2 | |
|
|
010d5e5354 | |
|
|
94e0be0e71 | |
|
|
2845d19aae | |
|
|
97b1c9437c | |
|
|
b0f9e06e18 | |
|
|
f58af4b0b5 | |
|
|
78cbd4b0ee | |
|
|
fca8490bdd | |
|
|
616bf1229f |
|
|
@ -14,6 +14,7 @@ import org.springframework.web.multipart.MultipartFile;
|
|||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 文件服务
|
||||
|
|
@ -34,6 +35,17 @@ public interface RemoteFileService {
|
|||
@RequestParam("hierarchy") String hierarchy,
|
||||
@RequestHeader(SecurityConstants.FROM_SOURCE) String source);
|
||||
|
||||
/**
|
||||
* Base64 图片上传(HashMap 版本)
|
||||
*/
|
||||
@PostMapping(value = "/upload/base64")
|
||||
R<SysFileInfo> uploadBase64(
|
||||
@RequestBody Map<String, Object> params,
|
||||
@RequestParam("type") String type,
|
||||
@RequestParam("hierarchy") String hierarchy,
|
||||
@RequestHeader(SecurityConstants.FROM_SOURCE) String source
|
||||
);
|
||||
|
||||
/**
|
||||
* 根据文件Id列表获取文件列表
|
||||
*
|
||||
|
|
|
|||
|
|
@ -2,13 +2,13 @@ package com.microservices.system.api;
|
|||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.microservices.common.core.constant.ServiceNameConstants;
|
||||
import com.microservices.common.core.constant.TokenConstants;
|
||||
import com.microservices.system.api.factory.RemoteGatewayFallbackFactory;
|
||||
import com.microservices.system.api.model.GraphqlQueryVo;
|
||||
import feign.Response;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
|
|
@ -28,6 +28,14 @@ public interface RemoteGatewayService {
|
|||
@PostMapping("/sentinel/auth/login")
|
||||
Response loginSentinel(@RequestParam("username") String username, @RequestParam("password") String password);
|
||||
|
||||
/**
|
||||
* 登录Rancher
|
||||
*
|
||||
* @return 响应
|
||||
*/
|
||||
@PostMapping("/rancher/v3-public/localProviders/local?action=login")
|
||||
Response loginRancher(@RequestBody JSONObject loginBody);
|
||||
|
||||
/**
|
||||
* 登录Nacos
|
||||
*
|
||||
|
|
@ -43,4 +51,45 @@ public interface RemoteGatewayService {
|
|||
*/
|
||||
@PostMapping("/portainer/api/auth")
|
||||
Response loginPortainer(@RequestBody JSONObject loginBody);
|
||||
|
||||
@GetMapping("/prometheus/api/v1/query")
|
||||
JSONObject getPrometheusQueryRes(@RequestParam("query") String query,
|
||||
@RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
@GetMapping("/prometheus/api/v1/query_range")
|
||||
JSONObject getPrometheusQueryRangeRes(@RequestParam("query") String query,
|
||||
@RequestParam("step") Long step,
|
||||
@RequestParam("start") Long start,
|
||||
@RequestParam("end") Long end,
|
||||
@RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
@PostMapping("/skywalking/graphql")
|
||||
JSONObject executeSkywalkingGql(@RequestBody GraphqlQueryVo gqlBody);
|
||||
|
||||
@GetMapping("/sentinel/app/briefinfos.json")
|
||||
JSONObject getSentinelAppList(@RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
@GetMapping("/nacos/v1/ns/catalog/services?pageNo=1&pageSize=999")
|
||||
JSONObject getNacosServiceList(@RequestParam("serviceNameParam") String serviceNameParam, @RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
@GetMapping("/nacos/v1/cs/configs?types=yaml&search=blur&group=&pageNo=1&pageSize=10")
|
||||
JSONObject getGatewayNacosConfigList(@RequestParam("dataId") String dataId, @RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
@GetMapping("/nacos/v1/cs/listener")
|
||||
JSONObject getNacosConfigList(@RequestParam("ip") String ip, @RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
@GetMapping("/nacos/v1/cs/configs")
|
||||
String getNacosConfigDetail(@RequestParam("dataId") String dataId, @RequestParam("group") String group, @RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
@PostMapping(value = "/nacos/v1/cs/configs", consumes = {"application/x-www-form-urlencoded"})
|
||||
Response updateNacosConfig(Map<String, ?> formParams, @RequestHeader(TokenConstants.AUTHENTICATION) String userKey);
|
||||
|
||||
@PostMapping("/es/{esIndex}/_search")
|
||||
JSONObject executeElasticsearchQuery(@PathVariable("esIndex") String esIndex, @RequestBody JSONObject esBody);
|
||||
|
||||
@PostMapping("/es/{esIndex}/_doc/{docId}/_update")
|
||||
JSONObject executeElasticsearchUpdate(@PathVariable("esIndex") String esIndex,@PathVariable("docId") String docId, @RequestBody JSONObject esBody);
|
||||
|
||||
@PostMapping("/gns/notification/gitlink")
|
||||
JSONObject sendNotification(@RequestBody JSONObject body);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,124 @@
|
|||
package com.microservices.system.api;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.microservices.common.core.constant.Constants;
|
||||
import com.microservices.common.core.constant.SecurityConstants;
|
||||
import com.microservices.common.core.constant.ServiceNameConstants;
|
||||
import com.microservices.common.core.constant.TokenConstants;
|
||||
import com.microservices.system.api.factory.RemoteGatewayFallbackFactory;
|
||||
import com.microservices.system.api.factory.RemoteRancherFallbackFactory;
|
||||
import feign.Response;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 网关
|
||||
*
|
||||
* @author microservices
|
||||
*/
|
||||
@Component
|
||||
@FeignClient(contextId = "RemoteRancherService", value = ServiceNameConstants.GATEWAY_SERVICE, fallbackFactory = RemoteRancherFallbackFactory.class)
|
||||
public interface RemoteRancherService {
|
||||
@GetMapping("/rancher/v3/clusters/{cluster_id}/namespaces")
|
||||
Response getK8sNamespaceList(@PathVariable("cluster_id") String cluster_id,
|
||||
@RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
@GetMapping("/rancher/k8s/clusters/{cluster_id}/v1/apps.daemonsets?exclude=metadata.managedFields")
|
||||
Response getK8sDaemonsetsList(@PathVariable("cluster_id") String cluster_id,
|
||||
@RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
@GetMapping("/rancher/k8s/clusters/{cluster_id}/v1/apps.deployments?exclude=metadata.managedFields")
|
||||
Response getK8sDeployList(@PathVariable("cluster_id") String cluster_id,
|
||||
@RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
@GetMapping("/rancher/k8s/clusters/{cluster_id}/v1/apps.statefulsets?exclude=metadata.managedFields")
|
||||
Response getK8sStatefulList(@PathVariable("cluster_id") String cluster_id,
|
||||
@RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
@GetMapping("/rancher/k8s/clusters/{cluster_id}/v1/nodes?exclude=metadata.managedFields")
|
||||
Response getK8sClusterNodeList(@PathVariable("cluster_id") String cluster_id,
|
||||
@RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
@GetMapping("/rancher/k8s/clusters/{cluster_id}/v1/{fullKind}/{namespace}/{applicationName}")
|
||||
Response getK8sApplicationDetail(@PathVariable("cluster_id") String cluster_id,
|
||||
@PathVariable("fullKind") String fullKind,
|
||||
@PathVariable("namespace") String namespace,
|
||||
@PathVariable("applicationName") String applicationName,
|
||||
@RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
@GetMapping("/rancher/k8s/clusters/{cluster_id}/v1/pods/{namespace}")
|
||||
Response getK8sPodListByNamespace(@PathVariable("cluster_id") String cluster_id,
|
||||
@PathVariable("namespace") String namespace,
|
||||
@RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
@GetMapping("/rancher/k8s/clusters/{cluster_id}/v1/pods")
|
||||
Response getK8sPodList(@PathVariable("cluster_id") String cluster_id,
|
||||
@RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
@GetMapping("/rancher/k8s/clusters/{cluster_id}/v1/services/{nginxApplicationId}")
|
||||
Response getK8sServiceByApplicationId(@PathVariable("cluster_id") String cluster_id,
|
||||
@PathVariable("nginxApplicationId") String nginxApplicationId,
|
||||
@RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
@DeleteMapping("/rancher/v1/pods/{namespace}/{podName}")
|
||||
Response deletePod(@PathVariable("namespace") String namespace,
|
||||
@PathVariable("podName") String podName,
|
||||
@RequestBody JSONObject deletePodBody,
|
||||
@RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
@PutMapping("/rancher/v1/{fullKind}/{namespace}/{applicationName}")
|
||||
Response updateK8sApplication(@PathVariable("fullKind") String fullKind,
|
||||
@PathVariable("namespace") String namespace,
|
||||
@PathVariable("applicationName") String applicationName,
|
||||
@RequestBody JSONObject applicationDetail,
|
||||
@RequestHeader(TokenConstants.AUTHENTICATION) String userKey);
|
||||
|
||||
@PostMapping(value = "/rancher/v1/{fullKind}", consumes = {Constants.YAML_CONTENT_TYPE})
|
||||
Response createK8sApplication(@PathVariable("fullKind") String fullName,
|
||||
@RequestBody String yamlContent,
|
||||
@RequestHeader(TokenConstants.AUTHENTICATION) String userKey);
|
||||
|
||||
@PostMapping(value = "/rancher/v1/management.cattle.io.clusters/{cluster_id}?action=apply")
|
||||
Response applyK8sYaml(@PathVariable("cluster_id") String cluster_id,
|
||||
@RequestBody JSONObject yamlContent,
|
||||
@RequestHeader(TokenConstants.AUTHENTICATION) String userKey);
|
||||
|
||||
@GetMapping("/rancher/apis/apps/v1/namespaces/{namespace}/{kindName}/{applicationName}")
|
||||
Response getApplicationYamlFile(@PathVariable("kindName") String kindName,
|
||||
@PathVariable("namespace") String namespace,
|
||||
@PathVariable("applicationName") String applicationName,
|
||||
@RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
@PutMapping(value = "/rancher/v1/{fullKind}/{namespace}/{applicationName}", consumes = {Constants.YAML_CONTENT_TYPE})
|
||||
Response editK8sApplication(@PathVariable("fullKind") String fullKind,
|
||||
@PathVariable("namespace") String namespace,
|
||||
@PathVariable("applicationName") String applicationName,
|
||||
@RequestBody String yamlContent,
|
||||
@RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
@DeleteMapping("/rancher/v1/{fullKind}/{namespace}/{applicationName}")
|
||||
Response deleteApplication(@PathVariable("fullKind") String fullKind,
|
||||
@PathVariable("namespace") String namespace,
|
||||
@PathVariable("applicationName") String applicationName,
|
||||
@RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
@GetMapping("/rancher/v1/configmaps/{namespace}")
|
||||
Response getK8sConfigmapByNamespace(@PathVariable("namespace") String namespace,
|
||||
@RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
@GetMapping("/rancher/v1/secrets/{namespace}")
|
||||
Response getK8sSecretByNamespace(@PathVariable("namespace") String namespace,
|
||||
@RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
@GetMapping("/rancher/k8s/clusters/{cluster_id}/v1/services/{namespace}")
|
||||
Response getK8sServiceByNamespace(@PathVariable("cluster_id") String cluster_id,
|
||||
@PathVariable("namespace") String namespace,
|
||||
@RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
|
||||
|
||||
@DeleteMapping("/rancher/v1/services/{serviceId}")
|
||||
Response deleteK8sService(@PathVariable("serviceId") String serviceId,@RequestHeader(TokenConstants.AUTHENTICATION) String token);
|
||||
}
|
||||
|
|
@ -14,6 +14,7 @@ import org.springframework.web.multipart.MultipartFile;
|
|||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 文件服务降级处理
|
||||
|
|
@ -36,6 +37,11 @@ public class RemoteFileFallbackFactory implements FallbackFactory<RemoteFileServ
|
|||
return R.fail("上传文件失败:" + throwable.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public R<SysFileInfo> uploadBase64(Map<String, Object> params, String type, String hierarchy, String source) {
|
||||
return R.fail("上传base64文件失败:" + throwable.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public R<List<SysFileInfo>> getFileList(String fileIds) {
|
||||
return R.fail("获取文件列表失败:" + throwable.getMessage());
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
package com.microservices.system.api.factory;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.microservices.common.core.exception.ServiceException;
|
||||
import com.microservices.system.api.RemoteGatewayService;
|
||||
import com.microservices.system.api.model.GraphqlQueryVo;
|
||||
import feign.Response;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
|
@ -25,7 +27,12 @@ public class RemoteGatewayFallbackFactory implements FallbackFactory<RemoteGatew
|
|||
return new RemoteGatewayService() {
|
||||
|
||||
@Override
|
||||
public Response loginSentinel(String password, String username) {
|
||||
public Response loginSentinel(String username, String password) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response loginRancher(JSONObject loginBody) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
|
@ -36,7 +43,66 @@ public class RemoteGatewayFallbackFactory implements FallbackFactory<RemoteGatew
|
|||
|
||||
@Override
|
||||
public Response loginPortainer(JSONObject loginBody) {
|
||||
System.out.println(throwable.getMessage());
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject getPrometheusQueryRes(String query, String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject getPrometheusQueryRangeRes(String query, Long step, Long start, Long end, String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject executeSkywalkingGql(GraphqlQueryVo gqlBody) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject getSentinelAppList(String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject getNacosServiceList(String serviceNameParam, String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject getGatewayNacosConfigList(String dataId, String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject getNacosConfigList(String ip, String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getNacosConfigDetail(String dataId, String group, String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response updateNacosConfig(Map<String, ?> formParams, String userKey) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject executeElasticsearchQuery(String esIndex, JSONObject esBody) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject executeElasticsearchUpdate(String esIndex, String docId, JSONObject esBody) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject sendNotification(JSONObject body) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -0,0 +1,133 @@
|
|||
package com.microservices.system.api.factory;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.microservices.common.core.exception.ServiceException;
|
||||
import com.microservices.system.api.RemoteGatewayService;
|
||||
import com.microservices.system.api.RemoteRancherService;
|
||||
import com.microservices.system.api.utils.FeignUtils;
|
||||
import feign.FeignException;
|
||||
import feign.Response;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.cloud.openfeign.FallbackFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 用户服务降级处理
|
||||
*
|
||||
* @author microservices
|
||||
*/
|
||||
@Component
|
||||
public class RemoteRancherFallbackFactory implements FallbackFactory<RemoteRancherService> {
|
||||
private static final Logger log = LoggerFactory.getLogger(RemoteRancherFallbackFactory.class);
|
||||
|
||||
@Override
|
||||
public RemoteRancherService create(Throwable throwable) {
|
||||
log.error("Rancher服务调用失败:{}", throwable.getMessage());
|
||||
|
||||
return new RemoteRancherService() {
|
||||
@Override
|
||||
public Response getK8sNamespaceList(String cluster_id, String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response getK8sDaemonsetsList(String cluster_id, String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response getK8sDeployList(String cluster_id, String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response getK8sStatefulList(String cluster_id, String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response getK8sClusterNodeList(String cluster_id, String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response getK8sApplicationDetail(String cluster_id, String fullKind, String namespace, String applicationName, String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response getK8sPodListByNamespace(String cluster_id, String namespace, String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response getK8sPodList(String cluster_id, String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response getK8sServiceByApplicationId(String cluster_id, String nginxApplicationId, String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response deletePod(String namespace, String podName, JSONObject deletePodBody, String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response updateK8sApplication(String fullKind, String namespace, String applicationName, JSONObject applicationDetail, String userKey) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response createK8sApplication(String fullName, String yamlContent, String userKey) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response applyK8sYaml(String cluster_id, JSONObject yamlContent, String userKey) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response getApplicationYamlFile(String kindName, String namespace, String applicationName, String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response editK8sApplication(String fullKind, String namespace, String applicationName, String yamlContent, String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response deleteApplication(String fullKind, String namespace, String applicationName, String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response getK8sConfigmapByNamespace(String namespace, String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response getK8sSecretByNamespace(String namespace, String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response getK8sServiceByNamespace(String cluster_id, String namespace, String token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response deleteK8sService(String serviceId, String token) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
package com.microservices.system.api.model;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class GraphqlQueryVo {
|
||||
String operationName;
|
||||
String query;
|
||||
JSONObject variables;
|
||||
}
|
||||
|
|
@ -3,20 +3,24 @@ package com.microservices.system.api.utils;
|
|||
import com.microservices.common.core.domain.R;
|
||||
import com.microservices.common.core.exception.ServiceException;
|
||||
import com.microservices.common.core.utils.StringUtils;
|
||||
import feign.Response;
|
||||
|
||||
/**
|
||||
* @author otto
|
||||
*/
|
||||
public class FeignUtils {
|
||||
public static <T> T getReturnData(R<T> result){
|
||||
public static <T> T getReturnData(R<T> result) {
|
||||
if (StringUtils.isNull(result)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (R.FAIL == result.getCode())
|
||||
{
|
||||
if (R.FAIL == result.getCode()) {
|
||||
throw new ServiceException(result.getMsg());
|
||||
}
|
||||
return result.getData();
|
||||
}
|
||||
|
||||
public static Boolean isSuccess(Response response) {
|
||||
return response != null && response.status() >= 200 && response.status() < 300;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,62 @@
|
|||
package com.microservices.system.api.utils;
|
||||
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
public class StandardMultipartFile implements MultipartFile {
|
||||
|
||||
private final byte[] content;
|
||||
private final String name;
|
||||
private final String originalFilename;
|
||||
private final String contentType;
|
||||
|
||||
public StandardMultipartFile(byte[] content, String name, String originalFilename, String contentType) {
|
||||
this.content = content != null ? content : new byte[0];
|
||||
this.name = name;
|
||||
this.originalFilename = originalFilename;
|
||||
this.contentType = contentType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getOriginalFilename() {
|
||||
return originalFilename;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getContentType() {
|
||||
return contentType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return content.length == 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getSize() {
|
||||
return content.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] getBytes() throws IOException {
|
||||
return content;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getInputStream() throws IOException {
|
||||
return new ByteArrayInputStream(content);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void transferTo(File dest) throws IOException, IllegalStateException {
|
||||
try (FileOutputStream fos = new FileOutputStream(dest)) {
|
||||
fos.write(content);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -6,3 +6,4 @@ com.microservices.system.api.factory.RemoteCmsFallbackFactory
|
|||
com.microservices.system.api.factory.RemoteZoneFallbackFactory
|
||||
com.microservices.system.api.factory.RemotePmsFallbackFactory
|
||||
com.microservices.system.api.factory.RemoteGatewayFallbackFactory
|
||||
com.microservices.system.api.factory.RemoteRancherFallbackFactory
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Tomcat
|
||||
server:
|
||||
port: 9110
|
||||
port: 8080
|
||||
|
||||
# Spring
|
||||
spring:
|
||||
|
|
|
|||
|
|
@ -213,6 +213,11 @@ public class CacheConstants {
|
|||
*/
|
||||
public final static String SENTINEL_TOKEN = "sentinel_token";
|
||||
|
||||
/**
|
||||
* Rancher Token缓存Key
|
||||
*/
|
||||
public final static String RANCHER_TOKEN = "rancher_token";
|
||||
|
||||
|
||||
/**
|
||||
* Nacos Token缓存Key
|
||||
|
|
|
|||
|
|
@ -5,8 +5,7 @@ package com.microservices.common.core.constant;
|
|||
*
|
||||
* @author microservices
|
||||
*/
|
||||
public class Constants
|
||||
{
|
||||
public class Constants {
|
||||
/**
|
||||
* UTF-8 字符集
|
||||
*/
|
||||
|
|
@ -125,6 +124,10 @@ public class Constants
|
|||
* JSON类型
|
||||
*/
|
||||
public static final String JSON_CONTENT_TYPE = "application/json";
|
||||
/**
|
||||
* Yaml类型
|
||||
*/
|
||||
public static final String YAML_CONTENT_TYPE = "application/yaml";
|
||||
/**
|
||||
* 文本类型
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -37,6 +37,11 @@ public class SecurityConstants
|
|||
*/
|
||||
public static final String USER_KEY = "user_key";
|
||||
|
||||
/**
|
||||
* 用户Token
|
||||
*/
|
||||
public static final String TOKEN = "token";
|
||||
|
||||
/**
|
||||
* 组织ID
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -22,9 +22,16 @@ public class TokenConstants {
|
|||
* Sentinel令牌标识
|
||||
*/
|
||||
public static final String Sentinel_Token_Key = "sentinel_dashboard_cookie";
|
||||
/**
|
||||
* Rancher令牌标识
|
||||
*/
|
||||
public static final String Rancher_Cookie_Token_Key = "R_SESS";
|
||||
/**
|
||||
* Portainer令牌标识
|
||||
*/
|
||||
public static final String Portainer_Token_Key = "portainer_api_key";
|
||||
/**
|
||||
* Sentinel令牌标识
|
||||
* Nacos令牌标识
|
||||
*/
|
||||
public static final String Nacos_Token_Key = "Accesstoken";
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
package com.microservices.common.core.threadPool;
|
||||
|
||||
import com.microservices.common.core.constant.TokenConstants;
|
||||
import com.microservices.common.core.context.SecurityContextHolder;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
|
@ -37,6 +38,9 @@ public class ThreadPoolExecutorWrap extends ThreadPoolExecutor {
|
|||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
if(contextValue != null&&contextValue.containsKey("user_key")){
|
||||
contextValue.put(TokenConstants.AUTHENTICATION, contextValue.get("user_key"));
|
||||
}
|
||||
SecurityContextHolder.setLocalMap(contextValue);
|
||||
// 用户任务逻辑
|
||||
task.run();
|
||||
|
|
|
|||
|
|
@ -13,17 +13,19 @@ import com.microservices.common.core.utils.reflect.ReflectUtils;
|
|||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.RegExUtils;
|
||||
import org.apache.commons.lang3.reflect.FieldUtils;
|
||||
import org.apache.poi.hssf.usermodel.*;
|
||||
import org.apache.poi.ss.usermodel.*;
|
||||
import org.apache.poi.ss.util.CellRangeAddress;
|
||||
import org.apache.poi.ss.util.CellRangeAddressList;
|
||||
import org.apache.poi.util.IOUtils;
|
||||
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
|
||||
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
|
||||
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
|
||||
import org.apache.poi.xssf.usermodel.*;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.lang.reflect.Field;
|
||||
|
|
@ -1458,4 +1460,288 @@ public class ExcelUtil<T>
|
|||
}
|
||||
return method;
|
||||
}
|
||||
|
||||
// 存储Excel中的图片(key: 行号_列号,value: MultipartFile)
|
||||
private final Map<String, MultipartFile> excelImageMap = new HashMap<>();
|
||||
|
||||
/**
|
||||
* 获取解析后的Excel图片映射表(行号_列号 -> MultipartFile)
|
||||
* <p>对外返回不可修改的Map,避免外部篡改,同时让静态检查识别到该集合被查询</p>
|
||||
* @return 图片映射表
|
||||
*/
|
||||
public Map<String, MultipartFile> getExcelImageMap() {
|
||||
// 返回不可修改的Map,提升代码安全性,同时让静态检查识别到集合被读取
|
||||
return Collections.unmodifiableMap(excelImageMap);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析Excel中的图片并转换为MultipartFile,存入{@link #excelImageMap}
|
||||
* @param sheet Excel工作表
|
||||
* @throws IOException 解析图片失败时抛出
|
||||
*/
|
||||
private void parseExcelImages(Sheet sheet) throws IOException {
|
||||
if (wb instanceof XSSFWorkbook) {
|
||||
parseXSSFImages((XSSFSheet) sheet);
|
||||
} else if (wb instanceof HSSFWorkbook) {
|
||||
parseHSSFImages((HSSFWorkbook) wb, sheet);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析XSSF格式(xlsx)图片
|
||||
*/
|
||||
private void parseXSSFImages(XSSFSheet sheet) {
|
||||
XSSFDrawing drawing = sheet.createDrawingPatriarch();
|
||||
List<XSSFShape> shapes = drawing.getShapes();
|
||||
|
||||
for (XSSFShape shape : shapes) {
|
||||
if (shape instanceof XSSFPicture) {
|
||||
XSSFPicture picture = (XSSFPicture) shape;
|
||||
XSSFPictureData pictureData = picture.getPictureData();
|
||||
XSSFClientAnchor anchor = picture.getPreferredSize();
|
||||
|
||||
// 获取图片所在单元格位置
|
||||
int row = anchor.getRow1();
|
||||
int col = anchor.getCol1();
|
||||
String cellKey = row + "_" + col;
|
||||
|
||||
// 转换为MultipartFile并存储
|
||||
MultipartFile multipartFile = bytesToMultipartFile(pictureData.getData(), "xlsx_image.png");
|
||||
excelImageMap.put(cellKey, multipartFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析HSSF格式(xls)图片
|
||||
*/
|
||||
private void parseHSSFImages(HSSFWorkbook workbook, Sheet sheet) {
|
||||
List<HSSFPictureData> pictureDataList = workbook.getAllPictures();
|
||||
|
||||
for (int i = 0; i < pictureDataList.size(); i++) {
|
||||
HSSFPictureData pictureData = pictureDataList.get(i);
|
||||
HSSFPatriarch patriarch = (HSSFPatriarch) sheet.createDrawingPatriarch();
|
||||
List<HSSFShape> shapes = patriarch.getChildren();
|
||||
|
||||
for (HSSFShape shape : shapes) {
|
||||
if (shape instanceof HSSFPicture) {
|
||||
HSSFPicture picture = (HSSFPicture) shape;
|
||||
if (picture.getPictureIndex() == i) {
|
||||
HSSFClientAnchor anchor = picture.getClientAnchor();
|
||||
int row = anchor.getRow1();
|
||||
int col = anchor.getCol1();
|
||||
String cellKey = row + "_" + col;
|
||||
|
||||
// 转换为MultipartFile并存储
|
||||
MultipartFile multipartFile = bytesToMultipartFile(pictureData.getData(), "xls_image.png");
|
||||
excelImageMap.put(cellKey, multipartFile);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义MultipartFile实现(通用版,无外部依赖)
|
||||
*/
|
||||
public static class CustomMultipartFile implements MultipartFile {
|
||||
private final byte[] content;
|
||||
private final String filename;
|
||||
private final String contentType;
|
||||
|
||||
public CustomMultipartFile(byte[] content, String filename, String contentType) {
|
||||
this.content = content;
|
||||
this.filename = filename;
|
||||
this.contentType = contentType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "file";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getOriginalFilename() {
|
||||
return filename;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getContentType() {
|
||||
return contentType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return content == null || content.length == 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getSize() {
|
||||
return content.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] getBytes() throws IOException {
|
||||
return content;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getInputStream() throws IOException {
|
||||
return new ByteArrayInputStream(content);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void transferTo(java.io.File dest) throws IOException, IllegalStateException {
|
||||
try (java.io.OutputStream os = new java.io.FileOutputStream(dest)) {
|
||||
os.write(content);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将字节数组转换为MultipartFile(核心工具方法)
|
||||
*/
|
||||
public MultipartFile bytesToMultipartFile(byte[] bytes, String fileName) {
|
||||
try {
|
||||
String suffix = "png";
|
||||
if (fileName != null && fileName.contains(".")) {
|
||||
suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
|
||||
}
|
||||
String finalFileName = UUID.randomUUID().toString() + "." + suffix;
|
||||
String contentType = "image/" + suffix;
|
||||
|
||||
return new CustomMultipartFile(bytes, finalFileName, contentType);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("转换图片为MultipartFile失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
// 导入包含图片的excel
|
||||
public List<T> importExcelWithImages(String sheetName, InputStream is, int titleNum) throws Exception {
|
||||
this.type = Type.IMPORT;
|
||||
this.wb = WorkbookFactory.create(is);
|
||||
List<T> list = new ArrayList<T>();
|
||||
|
||||
Sheet sheet = StringUtils.isNotEmpty(sheetName) ? wb.getSheet(sheetName) : wb.getSheetAt(0);
|
||||
if (sheet == null) {
|
||||
throw new IOException("文件sheet不存在");
|
||||
}
|
||||
|
||||
// 1. 解析Excel中的图片,生成imageMap(行号_列号 -> MultipartFile)
|
||||
parseExcelImages(sheet);
|
||||
|
||||
int rows = sheet.getLastRowNum();
|
||||
if (rows > 0) {
|
||||
// ========== 参考原有逻辑:构建表头列名和下标映射 ==========
|
||||
Map<String, Integer> cellMap = new HashMap<>();
|
||||
Row heard = sheet.getRow(titleNum);
|
||||
for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++) {
|
||||
Cell cell = heard.getCell(i);
|
||||
if (StringUtils.isNotNull(cell)) {
|
||||
String columnName = this.getCellValue(heard, i).toString().trim();
|
||||
cellMap.put(columnName, i);
|
||||
} else {
|
||||
cellMap.put(null, i);
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 参考原有逻辑:构建字段映射(通过Excel注解匹配列名) ==========
|
||||
List<Object[]> fields = this.getFields();
|
||||
Map<Integer, Object[]> fieldsMap = new HashMap<Integer, Object[]>();
|
||||
for (Object[] objects : fields) {
|
||||
Excel attr = (Excel) objects[1];
|
||||
Integer column = cellMap.get(attr.name());
|
||||
if (column != null) {
|
||||
fieldsMap.put(column, objects);
|
||||
}
|
||||
}
|
||||
|
||||
// 找到「图片」列的下标(关键:和Excel模板的列名对应)
|
||||
Integer imageColumnIndex = cellMap.get("图片");
|
||||
|
||||
// ========== 遍历数据行(参考原有逻辑) ==========
|
||||
for (int i = titleNum + 1; i <= rows; i++) {
|
||||
Row row = sheet.getRow(i);
|
||||
if (isRowEmpty(row)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
T entity = null;
|
||||
// 生成当前行的图片key:行号_图片列下标(i是数据行号,对应Excel的行)
|
||||
String imageCellKey = i + "_" + imageColumnIndex;
|
||||
|
||||
// ========== 参考原有逻辑:遍历字段映射赋值 ==========
|
||||
for (Map.Entry<Integer, Object[]> entry : fieldsMap.entrySet()) {
|
||||
Integer columnIndex = entry.getKey();
|
||||
Object val = this.getCellValue(row, columnIndex);
|
||||
|
||||
// 如果不存在实例则新建
|
||||
entity = (entity == null ? clazz.newInstance() : entity);
|
||||
|
||||
// 从map中得到对应列的field和Excel注解
|
||||
Field field = (Field) entry.getValue()[0];
|
||||
Excel attr = (Excel) entry.getValue()[1];
|
||||
|
||||
// ========== 关键修改:如果是「图片」列,替换值为图片key ==========
|
||||
if (imageColumnIndex != null && columnIndex.equals(imageColumnIndex)) {
|
||||
val = imageCellKey; // 将单元格原始值替换为图片key(如1_12)
|
||||
}
|
||||
|
||||
// ========== 原有类型转换逻辑(完全复用) ==========
|
||||
Class<?> fieldType = field.getType();
|
||||
if (String.class == fieldType) {
|
||||
String s = Convert.toStr(val);
|
||||
if (StringUtils.endsWith(s, ".0")) {
|
||||
val = StringUtils.substringBefore(s, ".0");
|
||||
} else {
|
||||
String dateFormat = field.getAnnotation(Excel.class).dateFormat();
|
||||
if (StringUtils.isNotEmpty(dateFormat)) {
|
||||
val = parseDateToStr(dateFormat, val);
|
||||
} else {
|
||||
val = Convert.toStr(val);
|
||||
}
|
||||
}
|
||||
} else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val))) {
|
||||
val = Convert.toInt(val);
|
||||
} else if ((Long.TYPE == fieldType || Long.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val))) {
|
||||
val = Convert.toLong(val);
|
||||
} else if (Double.TYPE == fieldType || Double.class == fieldType) {
|
||||
val = Convert.toDouble(val);
|
||||
} else if (Float.TYPE == fieldType || Float.class == fieldType) {
|
||||
val = Convert.toFloat(val);
|
||||
} else if (BigDecimal.class == fieldType) {
|
||||
val = Convert.toBigDecimal(val);
|
||||
} else if (Date.class == fieldType) {
|
||||
if (val instanceof String) {
|
||||
val = DateUtils.parseDate(val);
|
||||
} else if (val instanceof Double) {
|
||||
val = DateUtil.getJavaDate((Double) val);
|
||||
}
|
||||
} else if (Boolean.TYPE == fieldType || Boolean.class == fieldType) {
|
||||
val = Convert.toBool(val, false);
|
||||
}
|
||||
|
||||
// ========== 原有反射赋值逻辑(完全复用) ==========
|
||||
if (StringUtils.isNotNull(fieldType)) {
|
||||
String propertyName = field.getName();
|
||||
if (StringUtils.isNotEmpty(attr.targetAttr())) {
|
||||
propertyName = field.getName() + "." + attr.targetAttr();
|
||||
} else if (StringUtils.isNotEmpty(attr.readConverterExp())) {
|
||||
val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator());
|
||||
} else if (!attr.handler().equals(ExcelHandlerAdapter.class)) {
|
||||
val = dataFormatHandlerAdapter(val, attr);
|
||||
}
|
||||
// 使用原有工具类反射赋值(核心:替换自定义setEntityFieldValue)
|
||||
ReflectUtils.invokeSetter(entity, propertyName, val);
|
||||
}
|
||||
}
|
||||
|
||||
if (entity != null) {
|
||||
list.add(entity);
|
||||
}
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -51,7 +51,7 @@ public class GenericsTableDataInfo<T> implements Serializable {
|
|||
/**
|
||||
* 面包屑数据
|
||||
*/
|
||||
@ApiModelProperty("面包屑数据")
|
||||
@ApiModelProperty(value = "面包屑数据",hidden = true)
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL) //为空时隐藏
|
||||
private List<Breadcrumb> breadcrumb;
|
||||
|
||||
|
|
|
|||
|
|
@ -79,7 +79,7 @@ public class GitLinkRequestHelper {
|
|||
HashMap<String, String> headers = prepareAuthenticationHeaders(gitLinkRequestUrl);
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
String path = gitLinkRequestUrl.getPath();
|
||||
logger.info("[{}]通过HttpClient向平台发起请求,请求方法为:{},请求网站为:{},请求路由为:{},请求载体为:{},请求头为:{}"
|
||||
logger.debug("[{}]通过HttpClient向平台发起请求,请求方法为:{},请求网站为:{},请求路由为:{},请求载体为:{},请求头为:{}"
|
||||
, requestId
|
||||
, requestType
|
||||
, gitLinkUrl
|
||||
|
|
@ -111,7 +111,7 @@ public class GitLinkRequestHelper {
|
|||
default:
|
||||
throw new ServiceException("不支持该请求方式:" + requestType.name());
|
||||
}
|
||||
logger.info("[{}]请求响应为:{}"
|
||||
logger.debug("[{}]请求响应为:{}"
|
||||
, requestId
|
||||
, result);
|
||||
} catch (Exception e) {
|
||||
|
|
|
|||
|
|
@ -34,6 +34,12 @@
|
|||
<artifactId>microservices-common-redis</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- SpringCloud Alibaba Sentinel -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,47 @@
|
|||
package com.microservices.common.security.handler;
|
||||
|
||||
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
|
||||
import com.alibaba.csp.sentinel.slots.block.BlockException;
|
||||
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
|
||||
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
|
||||
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
|
||||
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
|
||||
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.microservices.common.core.domain.R;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
@Component
|
||||
public class SentinelBlockExceptionHandler implements BlockExceptionHandler {
|
||||
|
||||
@Override
|
||||
public void handle(HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
BlockException ex) throws Exception {
|
||||
|
||||
R<?> body;
|
||||
if (ex instanceof FlowException) { // 限流
|
||||
body = R.fail(429, "请求过于频繁,请稍后重试");
|
||||
} else if (ex instanceof DegradeException) { // 熔断
|
||||
body = R.fail(500, "服务暂时不可用,请稍后重试");
|
||||
} else if (ex instanceof ParamFlowException) { // 热点参数限流
|
||||
body = R.fail(400, "热点参数限流");
|
||||
} else if (ex instanceof AuthorityException) { // 授权规则
|
||||
body = R.fail(403, "无权限访问该资源");
|
||||
} else if (ex instanceof SystemBlockException) { // 系统规则
|
||||
body = R.fail(500, "系统规则限制,无法访问");
|
||||
} else { // 兜底
|
||||
body = R.fail(500, "服务繁忙,请稍后重试");
|
||||
}
|
||||
|
||||
response.setStatus(HttpStatus.OK.value());
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
response.getWriter().write(JSONObject.toJSONString(body));
|
||||
}
|
||||
}
|
||||
|
|
@ -4,3 +4,4 @@ com.microservices.common.security.service.impl.RequestCustomServiceImpl
|
|||
com.microservices.common.security.aspect.PreAuthorizeAspect
|
||||
com.microservices.common.security.aspect.InnerAuthAspect
|
||||
com.microservices.common.security.handler.GlobalExceptionHandler
|
||||
com.microservices.common.security.handler.SentinelBlockExceptionHandler
|
||||
|
|
|
|||
|
|
@ -90,7 +90,7 @@ public class AuthFilter implements GlobalFilter, Ordered {
|
|||
try {
|
||||
claims = JwtUtils.parseToken(token);
|
||||
} catch (Exception e) {
|
||||
log.error("令牌解析失败:{}", e.getMessage());
|
||||
log.error("[鉴权异常处理]令牌解析失败:{}", e.getMessage());
|
||||
return unauthorizedResponse(exchange, "令牌格式不正确!");
|
||||
}
|
||||
if (claims == null) {
|
||||
|
|
@ -139,7 +139,7 @@ public class AuthFilter implements GlobalFilter, Ordered {
|
|||
);
|
||||
redisService.setCacheObject(redisKey, feignResult);
|
||||
} catch (Exception e) {
|
||||
log.error("获取用户【{}】身份列表时发生异常:{}", username, e.getMessage());
|
||||
log.error("[鉴权异常处理]获取用户【{}】身份列表时发生异常:{}", username, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -167,7 +167,7 @@ public class AuthFilter implements GlobalFilter, Ordered {
|
|||
}
|
||||
return genCookieByToken(token);
|
||||
} catch (Exception e) {
|
||||
log.error("检查该gitlink token【{}】是否登录时发生异常:{}", token, e.getMessage());
|
||||
log.error("[鉴权异常处理]检查该token【{}】是否登录时发生异常:{}", token, e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
@ -215,11 +215,11 @@ public class AuthFilter implements GlobalFilter, Ordered {
|
|||
try {
|
||||
feignResult = future.get();
|
||||
} catch (Exception e) {
|
||||
log.error("异步请求获取本系统Token出错:{}", e.getMessage());
|
||||
log.error("[鉴权异常处理]异步请求获取本系统Token出错:{}", e.getMessage());
|
||||
throw new ServiceException("内部服务错误");
|
||||
}
|
||||
if (StringUtils.isNull(feignResult) || R.FAIL == feignResult.getCode()) {
|
||||
log.error("Token获取出错:{}", feignResult.getMsg());
|
||||
log.error("[鉴权异常处理]Token获取出错:{}", feignResult.getMsg());
|
||||
throw new ServiceException("内部服务错误");
|
||||
}
|
||||
if (R.SUCCESS == feignResult.getCode()) {
|
||||
|
|
|
|||
|
|
@ -42,6 +42,7 @@ public class GlobalResponseFilter implements GlobalFilter, Ordered {
|
|||
String lowerUrl = request.getURI().getPath().toLowerCase();
|
||||
ServerHttpResponse originalResponse = exchange.getResponse();
|
||||
DataBufferFactory bufferFactory = originalResponse.bufferFactory();
|
||||
|
||||
// 当请求为Nacos时,Nacos返回的所有非JSON响应都会被自动转换为结构化的错误信息,同时将HTTP状态码设置为200,适合用于规范化微服务架构的响应格式。
|
||||
if (lowerUrl.startsWith("/nacos")) {
|
||||
|
||||
|
|
@ -53,7 +54,7 @@ public class GlobalResponseFilter implements GlobalFilter, Ordered {
|
|||
return super.writeWith(body);
|
||||
}
|
||||
if (status == HttpStatus.FORBIDDEN) {
|
||||
log.error("nacos鉴权异常,已清理redis中nacos token");
|
||||
log.error("[网关转发异常处理]nacos鉴权异常,已清理redis中nacos token");
|
||||
// 设置新的状态码为 200
|
||||
setStatusCode(HttpStatus.OK);
|
||||
// 设置响应内容类型为 JSON
|
||||
|
|
@ -125,7 +126,7 @@ public class GlobalResponseFilter implements GlobalFilter, Ordered {
|
|||
}
|
||||
synchronousSink.complete();
|
||||
}).flatMap(resStr -> {
|
||||
log.error("Portainer响应处理异常,异常信息:{}", resStr);
|
||||
log.error("[网关转发异常处理]Portainer响应处理异常,异常信息:{}", resStr);
|
||||
originalResponse.setStatusCode(HttpStatus.OK);
|
||||
byte[] bytes;
|
||||
if (JSON.isValid(resStr)) {
|
||||
|
|
@ -133,7 +134,7 @@ public class GlobalResponseFilter implements GlobalFilter, Ordered {
|
|||
if (resJson.containsKey("message")) {
|
||||
String message = resJson.getString("message");
|
||||
if (StringUtils.isNotBlank(message) && message.contains("A valid authorisation token is missing")) {
|
||||
log.error("Portainer鉴权异常,已清理redis中Portainer token");
|
||||
log.error("[网关转发异常处理]Portainer鉴权异常,已清理redis中Portainer token");
|
||||
//token失效清除redis缓存
|
||||
redisService.deleteObject(CacheConstants.PORTAINER_TOKEN);
|
||||
bytes = JSON.toJSONBytes(AjaxResult.error(ExceptionMsgConstants.RETRY_ERROR));
|
||||
|
|
@ -160,12 +161,12 @@ public class GlobalResponseFilter implements GlobalFilter, Ordered {
|
|||
ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
|
||||
@Override
|
||||
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
|
||||
HttpStatus status = getStatusCode() != null ? getStatusCode() : HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
HttpStatus status = getStatusCode();
|
||||
if (!status.isError()) {
|
||||
return super.writeWith(body);
|
||||
}
|
||||
if (status == HttpStatus.UNAUTHORIZED) {
|
||||
log.error("sentinel鉴权异常,已清理redis中sentinel token");
|
||||
log.error("[网关转发异常处理]sentinel鉴权异常,已清理redis中sentinel token");
|
||||
// 设置新的状态码为 200
|
||||
setStatusCode(HttpStatus.OK);
|
||||
// 设置响应内容类型为 JSON
|
||||
|
|
@ -192,7 +193,7 @@ public class GlobalResponseFilter implements GlobalFilter, Ordered {
|
|||
}
|
||||
synchronousSink.complete();
|
||||
}).flatMap(resStr -> {
|
||||
log.error("Sentinel响应处理异常,异常信息:{}", resStr);
|
||||
log.error("[网关转发异常处理]Sentinel响应处理异常,异常信息:{}", resStr);
|
||||
byte[] bytes;
|
||||
bytes = JSON.toJSONBytes(AjaxResult.error(ExceptionMsgConstants.SYSTEM_EXEC_ERROR));
|
||||
setStatusCode(HttpStatus.OK);
|
||||
|
|
|
|||
|
|
@ -53,8 +53,14 @@ public class ThirdPartyToolServiceImpl implements ThirdPartyToolService {
|
|||
public String portainerUsername;
|
||||
@Value("${thirdPartyTools.portainer.auth.password:}")
|
||||
public String portainerPassword;
|
||||
@Value("${thirdPartyTools.rancher.auth.username:}")
|
||||
public String rancherUsername;
|
||||
@Value("${thirdPartyTools.rancher.auth.password:}")
|
||||
public String rancherPassword;
|
||||
@Value("${thirdPartyTools.portainer.endpoints:}")
|
||||
public Integer portainerEndpoints;
|
||||
@Value("${thirdPartyTools.retryTimes:1}")
|
||||
public Integer retryTimes;
|
||||
ThreadPoolExecutor threadPoolExecutor = CustomExecutorFactory.threadPoolExecutor;
|
||||
@Lazy
|
||||
@Autowired
|
||||
|
|
@ -83,27 +89,81 @@ public class ThirdPartyToolServiceImpl implements ThirdPartyToolService {
|
|||
if (redisService.hasKey(CacheConstants.SENTINEL_TOKEN)) {
|
||||
sentinelCookie = redisService.getCacheObject(CacheConstants.SENTINEL_TOKEN);
|
||||
} else {
|
||||
// 网关采用异步架构,所以此处需要通过异步请求获取Sentinel Token
|
||||
Future<Response> future = threadPoolExecutor.submit(() -> remoteGatewayService.loginSentinel(sentinelUsername, sentinelPassword));
|
||||
try {
|
||||
Response response = future.get(1, TimeUnit.SECONDS);
|
||||
Map<String, Collection<String>> header = response.headers();
|
||||
if (header != null && header.containsKey("set-cookie")) {
|
||||
sentinelCookie = header.get("set-cookie").iterator().next();
|
||||
//Sentinel登录状态默认30分钟失效,将Sentinel Token缓存过期时间调整为28分钟
|
||||
redisService.setCacheObject(CacheConstants.SENTINEL_TOKEN, sentinelCookie, 28L, TimeUnit.MINUTES);
|
||||
for (int i = 0; i < retryTimes; i++) {
|
||||
// 网关采用异步架构,所以此处需要通过异步请求获取Sentinel Token
|
||||
Future<Response> future = threadPoolExecutor.submit(() -> remoteGatewayService.loginSentinel(sentinelUsername, sentinelPassword));
|
||||
try {
|
||||
Response response = future.get(3, TimeUnit.SECONDS);
|
||||
Map<String, Collection<String>> header = response.headers();
|
||||
if (header != null && header.containsKey("set-cookie")) {
|
||||
sentinelCookie = header.get("set-cookie").iterator().next();
|
||||
//Sentinel登录状态默认30分钟失效,将Sentinel Token缓存过期时间调整为28分钟
|
||||
redisService.setCacheObject(CacheConstants.SENTINEL_TOKEN, sentinelCookie, 28L, TimeUnit.MINUTES);
|
||||
}
|
||||
} catch (TimeoutException e) {
|
||||
log.error("[网关转发异常处理]获取Sentinel Token超时");
|
||||
} catch (InterruptedException | ExecutionException e) {
|
||||
log.error("[网关转发异常处理]获取Sentinel Token失败:{}", e.getMessage());
|
||||
}
|
||||
} catch (TimeoutException e) {
|
||||
log.error("获取Sentinel Token超时");
|
||||
} catch (InterruptedException | ExecutionException e) {
|
||||
log.error("获取Sentinel Token失败:{}", e.getMessage());
|
||||
|
||||
if (StringUtils.isNotEmpty(sentinelCookie)) {
|
||||
break;
|
||||
}
|
||||
|
||||
log.warn("[网关转发异常处理]获取Sentinel Token失败,进行第{}次重试中", i + 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (StringUtils.isNotEmpty(sentinelCookie)) {
|
||||
ServletUtils.removeHeader(mutate, TokenConstants.Cookie);
|
||||
mutate.header(TokenConstants.Cookie, String.format("%s;%s;", cookie, sentinelCookie));
|
||||
} else {
|
||||
throw new ServiceException("Sentinel服务获取Token失败");
|
||||
throw new ServiceException("[网关转发异常处理]Sentinel服务获取Token失败");
|
||||
}
|
||||
}
|
||||
|
||||
// 处理Rancher请求
|
||||
if (lowerUrl.startsWith("/rancher")) {
|
||||
String rancherToken = null;
|
||||
if (redisService.hasKey(CacheConstants.RANCHER_TOKEN)) {
|
||||
rancherToken = redisService.getCacheObject(CacheConstants.RANCHER_TOKEN);
|
||||
} else {
|
||||
for (int i = 0; i < retryTimes; i++) {
|
||||
JSONObject loginRancherBody = new JSONObject();
|
||||
loginRancherBody.put("description", "api session");
|
||||
loginRancherBody.put("responseType", "cookie");
|
||||
loginRancherBody.put("username", rancherUsername);
|
||||
loginRancherBody.put("password", rancherPassword);
|
||||
|
||||
// 网关采用异步架构,所以此处需要通过异步请求获取Rancher Token
|
||||
Future<Response> future = threadPoolExecutor.submit(() -> remoteGatewayService.loginRancher(loginRancherBody));
|
||||
try {
|
||||
Response response = future.get(3, TimeUnit.SECONDS);
|
||||
Map<String, Collection<String>> header = response.headers();
|
||||
if (header != null && header.containsKey("set-cookie")) {
|
||||
String rancherCookie = header.get("set-cookie").iterator().next();
|
||||
rancherToken = getValueByCookieKey(rancherCookie, TokenConstants.Rancher_Cookie_Token_Key);
|
||||
//Rancher登录状态默认15小时失效,将Rancher Token缓存过期时间调整为14分钟
|
||||
redisService.setCacheObject(CacheConstants.RANCHER_TOKEN, rancherToken, 14L, TimeUnit.HOURS);
|
||||
|
||||
}
|
||||
} catch (TimeoutException e) {
|
||||
log.error("[网关转发异常处理]获取Rancher Token超时");
|
||||
} catch (InterruptedException | ExecutionException e) {
|
||||
log.error("[网关转发异常处理]获取Rancher Token失败:{}", e.getMessage());
|
||||
}
|
||||
if (StringUtils.isNotEmpty(rancherToken)) {
|
||||
break;
|
||||
}
|
||||
|
||||
log.warn("[网关转发异常处理]获取Rancher Token失败,进行第{}次重试中", i + 1);
|
||||
}
|
||||
}
|
||||
if (StringUtils.isNotEmpty(rancherToken)) {
|
||||
ServletUtils.removeHeader(mutate, TokenConstants.AUTHENTICATION);
|
||||
mutate.header(TokenConstants.AUTHENTICATION, TokenConstants.PREFIX + rancherToken);
|
||||
} else {
|
||||
throw new ServiceException("[网关转发异常处理]Rancher服务获取Token失败");
|
||||
}
|
||||
}
|
||||
// 处理Nacos请求
|
||||
|
|
@ -112,38 +172,44 @@ public class ThirdPartyToolServiceImpl implements ThirdPartyToolService {
|
|||
if (redisService.hasKey(CacheConstants.NACOS_TOKEN)) {
|
||||
nacosToken = redisService.getCacheObject(CacheConstants.NACOS_TOKEN);
|
||||
} else {
|
||||
Map<String, String> nacosMap = new HashMap<>();
|
||||
nacosMap.put("username", nacosUsername);
|
||||
nacosMap.put("password", nacosPassword);
|
||||
// 网关采用异步架构,所以此处需要通过异步请求获取Nacos Token
|
||||
Future<Response> future = threadPoolExecutor.submit(() -> remoteGatewayService.loginNacos(nacosMap));
|
||||
try {
|
||||
Response res = future.get(1, TimeUnit.SECONDS);
|
||||
StringWriter writer = new StringWriter();
|
||||
IOUtils.copy(res.body().asInputStream(), writer, StandardCharsets.UTF_8.name());
|
||||
String str = writer.toString();
|
||||
if (!JSON.isValid(str)) {
|
||||
return exceptionResponse(exchange, str, res.status());
|
||||
for (int i = 0; i < retryTimes; i++) {
|
||||
Map<String, String> nacosMap = new HashMap<>();
|
||||
nacosMap.put("username", nacosUsername);
|
||||
nacosMap.put("password", nacosPassword);
|
||||
// 网关采用异步架构,所以此处需要通过异步请求获取Nacos Token
|
||||
Future<Response> future = threadPoolExecutor.submit(() -> remoteGatewayService.loginNacos(nacosMap));
|
||||
try {
|
||||
Response res = future.get(3, TimeUnit.SECONDS);
|
||||
StringWriter writer = new StringWriter();
|
||||
IOUtils.copy(res.body().asInputStream(), writer, StandardCharsets.UTF_8.name());
|
||||
String str = writer.toString();
|
||||
if (!JSON.isValid(str)) {
|
||||
return exceptionResponse(exchange, str, res.status());
|
||||
}
|
||||
JSONObject resJsonObject = JSONObject.parseObject(str);
|
||||
if (resJsonObject == null) {
|
||||
return exceptionResponse(exchange, str, res.status());
|
||||
}
|
||||
nacosToken = resJsonObject.getString("accessToken");
|
||||
Long tokenTtl = resJsonObject.getLong("tokenTtl");
|
||||
if (nacosToken != null && tokenTtl != null) {
|
||||
redisService.setCacheObject(CacheConstants.NACOS_TOKEN, nacosToken, tokenTtl - 10, TimeUnit.SECONDS);
|
||||
}
|
||||
} catch (TimeoutException e) {
|
||||
log.error("[网关转发异常处理]获取Nacos Token超时");
|
||||
} catch (InterruptedException | ExecutionException | IOException | NullPointerException e) {
|
||||
log.error("[网关转发异常处理]获取Nacos Token失败:{}", e.getMessage());
|
||||
}
|
||||
JSONObject resJsonObject = JSONObject.parseObject(str);
|
||||
if (resJsonObject == null) {
|
||||
return exceptionResponse(exchange, str, res.status());
|
||||
if (StringUtils.isNotEmpty(nacosToken)) {
|
||||
break;
|
||||
}
|
||||
nacosToken = resJsonObject.getString("accessToken");
|
||||
Long tokenTtl = resJsonObject.getLong("tokenTtl");
|
||||
if (nacosToken != null && tokenTtl != null) {
|
||||
redisService.setCacheObject(CacheConstants.NACOS_TOKEN, nacosToken, tokenTtl - 10, TimeUnit.SECONDS);
|
||||
}
|
||||
} catch (TimeoutException e) {
|
||||
log.error("获取Nacos Token超时");
|
||||
} catch (InterruptedException | ExecutionException | IOException | NullPointerException e) {
|
||||
log.error("获取Nacos Token失败:{}", e.getMessage());
|
||||
log.warn("[网关转发异常处理]获取Nacos Token失败,进行第{}次重试中", i + 1);
|
||||
}
|
||||
}
|
||||
if (StringUtils.isNotEmpty(nacosToken)) {
|
||||
mutate.header(TokenConstants.Nacos_Token_Key, nacosToken);
|
||||
} else {
|
||||
throw new ServiceException("Nacos服务获取Token失败");
|
||||
throw new ServiceException("[网关转发异常处理]Nacos服务获取Token失败");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -163,7 +229,7 @@ public class ThirdPartyToolServiceImpl implements ThirdPartyToolService {
|
|||
try {
|
||||
mutate.uri(new URI(url));
|
||||
} catch (URISyntaxException e) {
|
||||
log.error("替换Portainer请求中Endpoints时发生异常:{}", e.getMessage());
|
||||
log.error("[网关转发异常处理]替换Portainer请求中Endpoints时发生异常:{}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -178,38 +244,44 @@ public class ThirdPartyToolServiceImpl implements ThirdPartyToolService {
|
|||
if (redisService.hasKey(CacheConstants.PORTAINER_TOKEN)) {
|
||||
portainerToken = redisService.getCacheObject(CacheConstants.PORTAINER_TOKEN);
|
||||
} else {
|
||||
// 网关采用异步架构,所以此处需要通过异步请求获取Portainer Token
|
||||
JSONObject loginPortainerBody = new JSONObject();
|
||||
loginPortainerBody.put("username", portainerUsername);
|
||||
loginPortainerBody.put("password", portainerPassword);
|
||||
Future<Response> future = threadPoolExecutor.submit(() -> remoteGatewayService.loginPortainer(loginPortainerBody));
|
||||
try {
|
||||
Response res = future.get(1, TimeUnit.SECONDS);
|
||||
StringWriter writer = new StringWriter();
|
||||
IOUtils.copy(res.body().asInputStream(), writer, StandardCharsets.UTF_8.name());
|
||||
String str = writer.toString();
|
||||
if (!JSON.isValid(str)) {
|
||||
return exceptionResponse(exchange, str, res.status());
|
||||
}
|
||||
JSONObject resJsonObject = JSONObject.parseObject(str);
|
||||
portainerToken = resJsonObject.getString("jwt");
|
||||
if (portainerToken == null) {
|
||||
return exceptionResponse(exchange, str, res.status());
|
||||
}
|
||||
String[] tokenSplit = portainerToken.split("\\.");
|
||||
String tokenBodyStr = new String(Base64.getDecoder().decode(tokenSplit[1]), StandardCharsets.UTF_8);
|
||||
JSONObject tokenBody = JSONObject.parseObject(tokenBodyStr);
|
||||
Long expiration = tokenBody.getLong("exp");
|
||||
Long now = new Date().getTime() / 1000;
|
||||
for (int i = 0; i < 5; i++) {
|
||||
// 网关采用异步架构,所以此处需要通过异步请求获取Portainer Token
|
||||
JSONObject loginPortainerBody = new JSONObject();
|
||||
loginPortainerBody.put("username", portainerUsername);
|
||||
loginPortainerBody.put("password", portainerPassword);
|
||||
Future<Response> future = threadPoolExecutor.submit(() -> remoteGatewayService.loginPortainer(loginPortainerBody));
|
||||
try {
|
||||
Response res = future.get(1, TimeUnit.SECONDS);
|
||||
StringWriter writer = new StringWriter();
|
||||
IOUtils.copy(res.body().asInputStream(), writer, StandardCharsets.UTF_8.name());
|
||||
String str = writer.toString();
|
||||
if (!JSON.isValid(str)) {
|
||||
return exceptionResponse(exchange, str, res.status());
|
||||
}
|
||||
JSONObject resJsonObject = JSONObject.parseObject(str);
|
||||
portainerToken = resJsonObject.getString("jwt");
|
||||
if (portainerToken == null) {
|
||||
return exceptionResponse(exchange, str, res.status());
|
||||
}
|
||||
String[] tokenSplit = portainerToken.split("\\.");
|
||||
String tokenBodyStr = new String(Base64.getDecoder().decode(tokenSplit[1]), StandardCharsets.UTF_8);
|
||||
JSONObject tokenBody = JSONObject.parseObject(tokenBodyStr);
|
||||
Long expiration = tokenBody.getLong("exp");
|
||||
Long now = new Date().getTime() / 1000;
|
||||
|
||||
long portainerTokenTtl = expiration - now;
|
||||
if (portainerTokenTtl > 20) {
|
||||
redisService.setCacheObject(CacheConstants.PORTAINER_TOKEN, portainerToken, portainerTokenTtl - 10, TimeUnit.SECONDS);
|
||||
long portainerTokenTtl = expiration - now;
|
||||
if (portainerTokenTtl > 20) {
|
||||
redisService.setCacheObject(CacheConstants.PORTAINER_TOKEN, portainerToken, portainerTokenTtl - 10, TimeUnit.SECONDS);
|
||||
}
|
||||
} catch (TimeoutException e) {
|
||||
log.error("[网关转发异常处理]获取Portainer Token超时");
|
||||
} catch (InterruptedException | ExecutionException | IOException | NullPointerException e) {
|
||||
log.error("[网关转发异常处理]获取Portainer Token失败:{}", e.getMessage());
|
||||
}
|
||||
} catch (TimeoutException e) {
|
||||
log.error("获取Portainer Token超时");
|
||||
} catch (InterruptedException | ExecutionException | IOException | NullPointerException e) {
|
||||
log.error("获取Portainer Token失败:{}", e.getMessage());
|
||||
if (StringUtils.isNotEmpty(portainerToken)) {
|
||||
break;
|
||||
}
|
||||
log.warn("[网关转发异常处理]获取Portainer Token失败,进行第{}次重试中", i + 1);
|
||||
}
|
||||
}
|
||||
if (StringUtils.isNotEmpty(portainerToken)) {
|
||||
|
|
@ -218,7 +290,7 @@ public class ThirdPartyToolServiceImpl implements ThirdPartyToolService {
|
|||
mutate.header(TokenConstants.AUTHENTICATION, TokenConstants.PREFIX + portainerToken);
|
||||
mutate.header(TokenConstants.Cookie, String.format("%s;%s;", cookie, portainerToken));
|
||||
} else {
|
||||
throw new ServiceException("Portainer服务获取Token失败");
|
||||
throw new ServiceException("[网关转发异常处理]Portainer服务获取Token失败");
|
||||
}
|
||||
}
|
||||
return null;
|
||||
|
|
@ -226,7 +298,23 @@ public class ThirdPartyToolServiceImpl implements ThirdPartyToolService {
|
|||
|
||||
|
||||
private Mono<Void> exceptionResponse(ServerWebExchange exchange, String msg, int code) {
|
||||
log.error("[第三方工具请求处理异常]请求路径:{},异常信息:{}", exchange.getRequest().getPath(), msg);
|
||||
log.error("[网关转发异常处理]请求路径:{},异常信息:{}", exchange.getRequest().getPath(), msg);
|
||||
return ServletUtils.webFluxResponseWriter(exchange.getResponse(), ExceptionMsgConstants.SYSTEM_EXEC_ERROR, code);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过指定Key获取Cookie中指定值
|
||||
*/
|
||||
private static String getValueByCookieKey(String cookie, String key) {
|
||||
if (cookie != null) {
|
||||
String[] cookies = StringUtils.split(cookie, ';');
|
||||
for (String cookieItem : cookies) {
|
||||
if (cookieItem.contains(key)) {
|
||||
String token = StringUtils.remove(cookieItem, key + "=");
|
||||
return StringUtils.remove(token, " ");
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Tomcat
|
||||
server:
|
||||
port: 9116
|
||||
port: 8080
|
||||
|
||||
# Spring
|
||||
spring:
|
||||
|
|
|
|||
|
|
@ -87,10 +87,18 @@
|
|||
<groupId>com.microservices</groupId>
|
||||
<artifactId>microservices-common-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.microservices</groupId>
|
||||
<artifactId>microservices-common-swagger</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.microservices</groupId>
|
||||
<artifactId>microservices-common-log</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.microservices</groupId>
|
||||
<artifactId>microservices-common-core</artifactId>
|
||||
|
|
@ -125,7 +133,7 @@
|
|||
<dependency>
|
||||
<groupId>com.hankcs</groupId>
|
||||
<artifactId>hanlp</artifactId>
|
||||
<version>portable-1.8.4</version>
|
||||
<version>portable-1.3.4</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import com.microservices.common.core.web.domain.AjaxResult;
|
|||
import com.microservices.common.core.web.page.TableDataInfo;
|
||||
import com.microservices.common.log.annotation.Log;
|
||||
import com.microservices.common.log.enums.BusinessType;
|
||||
import com.microservices.common.security.utils.SecurityUtils;
|
||||
import com.microservices.dms.achievementLibrary.domain.SchoolEnterpriseAchievements;
|
||||
import com.microservices.dms.achievementLibrary.service.ISchoolEnterpriseAchievementsService;
|
||||
import io.swagger.annotations.Api;
|
||||
|
|
@ -15,9 +16,11 @@ import io.swagger.annotations.ApiImplicitParams;
|
|||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 校企成果Controller
|
||||
|
|
@ -90,6 +93,21 @@ public class SchoolEnterpriseAchievementsController extends BaseController
|
|||
return AjaxResult.success(schoolEnterpriseAchievementsService.insertSchoolEnterpriseAchievements(schoolEnterpriseAchievements));
|
||||
}
|
||||
|
||||
@PostMapping("/importData")
|
||||
@Log(title = "校企成果", businessType = BusinessType.INSERT)
|
||||
public AjaxResult importData(@RequestPart("file") MultipartFile file,
|
||||
@RequestParam(value = "updateSupport", defaultValue = "false") boolean updateSupport) throws Exception {
|
||||
ExcelUtil<SchoolEnterpriseAchievements> util = new ExcelUtil<>(SchoolEnterpriseAchievements.class);
|
||||
// 1. 解析Excel,获取实体列表和图片Map
|
||||
List<SchoolEnterpriseAchievements> list = util.importExcelWithImages(StringUtils.EMPTY, file.getInputStream(), 0);
|
||||
Map<String, MultipartFile> imageMap = util.getExcelImageMap();
|
||||
// 2. 调用业务层处理(传入实体列表和图片Map)
|
||||
String operName = SecurityUtils.getUsername();
|
||||
String message = schoolEnterpriseAchievementsService.batchInsertSchoolEnterpriseAchievements(list, imageMap, updateSupport, operName);
|
||||
|
||||
return AjaxResult.success(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改校企成果
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -167,7 +167,7 @@ public class Achievements extends BaseEntity {
|
|||
/**
|
||||
* 成果图片
|
||||
*/
|
||||
@Excel(name = "成果图片")
|
||||
@Excel(name = "图片")
|
||||
private String images;
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -32,7 +32,10 @@ public class SchoolEnterpriseAchievements extends BaseEntity {
|
|||
/**
|
||||
* 成果领域1
|
||||
*/
|
||||
@Excel(name = "成果领域1")
|
||||
@Excel(
|
||||
name = "成果领域",
|
||||
readConverterExp = "1=理论研究,2=政策法规,3=医学,4=电子信息,5=通信工程,6=计算机科学,7=软件工程,9=人工智能,10=知识图谱,12=大数据,23=机器人,24=无人系统,25=创意征集,26=文献翻译,27=成果转化,28=科技协同,29=科研组织模式,30=新兴领域,31=其他,32=电子元器件,33=测试仪器,34=军事历史,35=计算机网络"
|
||||
)
|
||||
private String field1;
|
||||
|
||||
/**
|
||||
|
|
@ -50,7 +53,7 @@ public class SchoolEnterpriseAchievements extends BaseEntity {
|
|||
/**
|
||||
* 成果类型
|
||||
*/
|
||||
@Excel(name = "成果类型")
|
||||
@Excel(name = "成果类型", readConverterExp = "1=理论成果,2=技术成果,3=应用成果,4=软科学成果,5=文化艺术成果,6=社会服务成果,7=交叉领域成果")
|
||||
private String achievementType;
|
||||
|
||||
/**
|
||||
|
|
@ -74,7 +77,10 @@ public class SchoolEnterpriseAchievements extends BaseEntity {
|
|||
/**
|
||||
* 成果标签
|
||||
*/
|
||||
@Excel(name = "成果标签")
|
||||
@Excel(
|
||||
name = "成果标签",
|
||||
readConverterExp = "1=高校,2=企业,3=其他"
|
||||
)
|
||||
private String tags;
|
||||
|
||||
/**
|
||||
|
|
@ -159,7 +165,7 @@ public class SchoolEnterpriseAchievements extends BaseEntity {
|
|||
/**
|
||||
* 成果图片
|
||||
*/
|
||||
@Excel(name = "成果图片")
|
||||
@Excel(name = "图片")
|
||||
private String images;
|
||||
|
||||
/**
|
||||
|
|
@ -169,10 +175,18 @@ public class SchoolEnterpriseAchievements extends BaseEntity {
|
|||
private String attachments;
|
||||
private Integer achievementStatus;
|
||||
//成果小类型
|
||||
@Excel(
|
||||
name = "成果小类型",
|
||||
readConverterExp = "7=学术论文,8=学术专著,9=理论模型,10=发明专利,11=技术标准,12=软件系统,13=技术原型,14=产品设备,15=解决方案,16=示范工程,17=政策建议,18=咨询报告,19=行业标准,20=管理办法,21=文学作品,22=艺术作品,23=公益项目,24=社会调查报告,25=教育培训成果,26=理论模型+产品设备,27=学术论文+技术原型"
|
||||
)
|
||||
private String achievementLittleType;
|
||||
//成果状态
|
||||
@Excel(
|
||||
name = "成果状态",
|
||||
readConverterExp = "1=已有阶段性成果,2=已有成熟成果,3=已公开发表,4=已对外发布,5=已开展应用,6=已形成商业化产品"
|
||||
)
|
||||
private String achievementCurStatus;
|
||||
//团队名称
|
||||
@Excel(name = "成果团队名称")
|
||||
private String teamName;
|
||||
|
||||
private List<AchievementTeam> teamList;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,10 @@
|
|||
package com.microservices.dms.achievementLibrary.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.microservices.dms.achievementLibrary.domain.SchoolEnterpriseAchievements;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
/**
|
||||
* 校企成果Service接口
|
||||
|
|
@ -64,4 +67,6 @@ public interface ISchoolEnterpriseAchievementsService
|
|||
List<SchoolEnterpriseAchievements> listFront(SchoolEnterpriseAchievements schoolEnterpriseAchievements);
|
||||
|
||||
boolean getCheckSchoolAchName(SchoolEnterpriseAchievements schoolEnterpriseAchievements);
|
||||
|
||||
String batchInsertSchoolEnterpriseAchievements(List<SchoolEnterpriseAchievements> list, Map<String, MultipartFile> imageMap, boolean updateSupport, String operName);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,25 +1,34 @@
|
|||
package com.microservices.dms.achievementLibrary.service.impl;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.microservices.common.core.constant.SecurityConstants;
|
||||
import com.microservices.common.core.constant.UserConstants;
|
||||
import com.microservices.common.core.domain.R;
|
||||
import com.microservices.common.core.exception.ServiceException;
|
||||
import com.microservices.common.core.utils.DateUtils;
|
||||
import com.microservices.common.core.utils.StringUtils;
|
||||
import com.microservices.common.datasource.annotation.Slave;
|
||||
import com.microservices.common.security.utils.SecurityUtils;
|
||||
import com.microservices.dms.achievementLibrary.domain.AchievementTeam;
|
||||
import com.microservices.dms.achievementLibrary.domain.Achievements;
|
||||
import com.microservices.dms.achievementLibrary.mapper.AchievementTeamMapper;
|
||||
import com.microservices.dms.achievementLibrary.mapper.AchievementsMapper;
|
||||
import com.microservices.dms.achievementLibrary.service.IAchievementsService;
|
||||
import com.microservices.system.api.domain.SysUser;
|
||||
import com.microservices.system.api.RemoteFileService;
|
||||
import com.microservices.system.api.model.LoginUser;
|
||||
import org.apache.commons.fileupload.FileItem;
|
||||
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import com.microservices.dms.achievementLibrary.mapper.SchoolEnterpriseAchievementsMapper;
|
||||
import com.microservices.dms.achievementLibrary.domain.SchoolEnterpriseAchievements;
|
||||
import com.microservices.dms.achievementLibrary.service.ISchoolEnterpriseAchievementsService;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.multipart.commons.CommonsMultipartFile;
|
||||
|
||||
/**
|
||||
* 校企成果Service业务层处理
|
||||
|
|
@ -41,6 +50,9 @@ public class SchoolEnterpriseAchievementsServiceImpl implements ISchoolEnterpris
|
|||
@Autowired
|
||||
private AchievementsMapper achievementsMapper;
|
||||
|
||||
@Autowired
|
||||
private RemoteFileService remoteFileService;
|
||||
|
||||
/**
|
||||
* 查询校企成果
|
||||
*
|
||||
|
|
@ -124,6 +136,144 @@ public class SchoolEnterpriseAchievementsServiceImpl implements ISchoolEnterpris
|
|||
return UserConstants.UNIQUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* 导入成果数据(包含图片处理)
|
||||
*/
|
||||
@Override
|
||||
@Transactional
|
||||
@Slave
|
||||
public String batchInsertSchoolEnterpriseAchievements(List<SchoolEnterpriseAchievements> list,
|
||||
Map<String, MultipartFile> imageMap,
|
||||
boolean updateSupport,
|
||||
String operName) {
|
||||
if (list == null || list.isEmpty()) {
|
||||
throw new RuntimeException("导入成果数据不能为空!");
|
||||
}
|
||||
int successNum = 0;
|
||||
int failureNum = 0;
|
||||
int imageErrorNum = 0; // 新增:图片处理失败数
|
||||
StringBuilder successMsg = new StringBuilder();
|
||||
StringBuilder failureMsg = new StringBuilder();
|
||||
StringBuilder imageErrorMsg = new StringBuilder(); // 新增:图片错误信息
|
||||
|
||||
for (SchoolEnterpriseAchievements schoolEnterpriseAchievement : list) {
|
||||
try {
|
||||
// 处理图片字段(优化后:返回处理结果,不抛出异常)
|
||||
String imageHandleResult = handleAchievementImage(schoolEnterpriseAchievement, imageMap);
|
||||
if (imageHandleResult.contains("失败") || imageHandleResult.contains("异常")) {
|
||||
imageErrorNum++;
|
||||
imageErrorMsg.append("<br/>").append(imageErrorNum).append("、成果 ").append(schoolEnterpriseAchievement.getAchievementName()).append(" 图片处理失败:").append(imageHandleResult);
|
||||
}
|
||||
|
||||
// 原有查重和入库逻辑(不受图片处理影响)
|
||||
SchoolEnterpriseAchievements exist = schoolEnterpriseAchievementsMapper.selectSchoolEnterpriseAchievementsByName(schoolEnterpriseAchievement.getAchievementName());
|
||||
if (exist == null) {
|
||||
schoolEnterpriseAchievement.setCreateBy(operName);
|
||||
schoolEnterpriseAchievement.setCreateTime(new Date());
|
||||
schoolEnterpriseAchievement.setUpdateBy(operName);
|
||||
schoolEnterpriseAchievement.setUpdateTime(new Date());
|
||||
schoolEnterpriseAchievement.setStatus("2");
|
||||
schoolEnterpriseAchievementsMapper.insertSchoolEnterpriseAchievements(schoolEnterpriseAchievement);
|
||||
successNum++;
|
||||
successMsg.append("<br/>").append(successNum).append("、成果 ").append(schoolEnterpriseAchievement.getAchievementName()).append(" 导入成功");
|
||||
} else {
|
||||
if (updateSupport) {
|
||||
schoolEnterpriseAchievement.setId(exist.getId());
|
||||
schoolEnterpriseAchievement.setCreateBy(exist.getCreateBy());
|
||||
schoolEnterpriseAchievement.setCreateTime(exist.getCreateTime());
|
||||
schoolEnterpriseAchievement.setUpdateBy(operName);
|
||||
schoolEnterpriseAchievement.setUpdateTime(new Date());
|
||||
schoolEnterpriseAchievementsMapper.updateSchoolEnterpriseAchievements(schoolEnterpriseAchievement);
|
||||
successNum++;
|
||||
successMsg.append("<br/>").append(successNum).append("、成果 ").append(schoolEnterpriseAchievement.getAchievementName()).append(" 更新成功");
|
||||
} else {
|
||||
failureNum++;
|
||||
failureMsg.append("<br/>").append(failureNum).append("、成果 ").append(schoolEnterpriseAchievement.getAchievementName()).append(" 已存在(未开启更新)");
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
failureNum++;
|
||||
String msg = "<br/>" + failureNum + "、成果 " + schoolEnterpriseAchievement.getAchievementName() + " 导入失败:";
|
||||
failureMsg.append(msg).append(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// 组装最终提示信息(包含图片处理错误)
|
||||
StringBuilder finalMsg = new StringBuilder();
|
||||
if (successNum > 0) {
|
||||
finalMsg.append("共 ").append(successNum).append(" 条数据导入/更新成功:").append(successMsg);
|
||||
}
|
||||
if (failureNum > 0) {
|
||||
finalMsg.append("<br/>共 ").append(failureNum).append(" 条数据导入失败:").append(failureMsg);
|
||||
}
|
||||
if (imageErrorNum > 0) {
|
||||
finalMsg.append("<br/>共 ").append(imageErrorNum).append(" 条数据图片处理失败:").append(imageErrorMsg);
|
||||
}
|
||||
|
||||
return finalMsg.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理成果图片:上传并格式化存储(FastJSON解析版)
|
||||
* @param achievement 成果实体
|
||||
* @param imageMap Excel解析出的图片映射表
|
||||
* @return 图片处理结果提示(成功/失败信息)
|
||||
*/
|
||||
private String handleAchievementImage(SchoolEnterpriseAchievements achievement, Map<String, MultipartFile> imageMap) {
|
||||
String imageCellKey = achievement.getImages();
|
||||
if (StringUtils.isEmpty(imageCellKey) || !imageMap.containsKey(imageCellKey)) {
|
||||
achievement.setImages("[]");
|
||||
return "无图片,跳过处理";
|
||||
}
|
||||
|
||||
try {
|
||||
MultipartFile file = imageMap.get(imageCellKey);
|
||||
byte[] fileBytes = file.getBytes();
|
||||
|
||||
if (fileBytes == null || fileBytes.length == 0) {
|
||||
return "图片文件为空,跳过处理";
|
||||
}
|
||||
|
||||
// 构建 HashMap 参数
|
||||
String originalFilename = StringUtils.isEmpty(file.getOriginalFilename())
|
||||
? "excel_import_image_" + System.currentTimeMillis() + ".png"
|
||||
: file.getOriginalFilename();
|
||||
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
params.put("base64Data", Base64.getEncoder().encodeToString(fileBytes));
|
||||
params.put("fileName", originalFilename);
|
||||
params.put("contentType", file.getContentType());
|
||||
params.put("size", fileBytes.length);
|
||||
|
||||
// 调用 Base64 上传接口
|
||||
R<?> fileResult = remoteFileService.uploadBase64(params, "dms", "import", SecurityConstants.INNER);
|
||||
|
||||
// 解析结果(与原逻辑相同)
|
||||
if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData())) {
|
||||
String errorMsg = !StringUtils.isNull(fileResult) ? fileResult.getMsg() : "接口返回异常";
|
||||
return "图片上传失败:" + errorMsg;
|
||||
}
|
||||
|
||||
JSONObject resultJson = JSONObject.parseObject(JSONObject.toJSONString(fileResult.getData()));
|
||||
String fileOriginName = resultJson.getString("fileOriginName");
|
||||
String url = resultJson.getString("downloadUrl");
|
||||
Integer fileId = resultJson.getInteger("fileId");
|
||||
|
||||
if (StringUtils.isEmpty(fileOriginName) || StringUtils.isEmpty(url) || fileId == null) {
|
||||
return "图片上传成功,但返回数据不完整";
|
||||
}
|
||||
|
||||
String imageJson = String.format("[{\"k\":\"%s\",\"v\":\"%s\",\"id\":%d}]",
|
||||
fileOriginName, url, fileId);
|
||||
achievement.setImages(imageJson);
|
||||
|
||||
return "图片处理成功";
|
||||
|
||||
} catch (Exception e) {
|
||||
return "图片处理异常:" + e.getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 修改校企成果
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Tomcat
|
||||
server:
|
||||
port: 9119
|
||||
port: 8080
|
||||
|
||||
# Spring
|
||||
spring:
|
||||
|
|
|
|||
|
|
@ -473,7 +473,7 @@
|
|||
from (
|
||||
(select count(1) as "auditSum"
|
||||
from memos
|
||||
where destroy_status is null and hidden = 0 and published_at is not null) a,
|
||||
where destroy_status is null and hidden = 0 and published_at is not null AND root_id IS NULL) a,
|
||||
(select count(1) as "allSum" from memos) b,
|
||||
(select count(1) as "currentYearSum"
|
||||
from memos
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Tomcat
|
||||
server:
|
||||
port: 9198
|
||||
port: 8080
|
||||
|
||||
# Spring
|
||||
spring:
|
||||
|
|
|
|||
|
|
@ -1,20 +1,26 @@
|
|||
package com.microservices.file.controller;
|
||||
|
||||
import com.microservices.common.core.domain.R;
|
||||
import com.microservices.common.core.utils.StringUtils;
|
||||
import com.microservices.common.core.web.controller.BaseController;
|
||||
import com.microservices.common.security.annotation.InnerAuth;
|
||||
import com.microservices.file.service.ISysFileInfoService;
|
||||
import com.microservices.system.api.domain.SysFile;
|
||||
import com.microservices.system.api.domain.SysFileInfo;
|
||||
import com.microservices.system.api.utils.StandardMultipartFile;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import springfox.documentation.annotations.ApiIgnore;
|
||||
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 文件请求处理
|
||||
*
|
||||
|
|
@ -49,4 +55,56 @@ public class SysFileController extends BaseController {
|
|||
return R.fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@InnerAuth
|
||||
@PostMapping("/upload/base64")
|
||||
public R<SysFileInfo> uploadBase64(@RequestBody Map<String, Object> params,
|
||||
@RequestParam("type") String type,
|
||||
@RequestParam("hierarchy") String hierarchy) {
|
||||
try {
|
||||
// 1. 提取参数
|
||||
String base64Data = (String) params.get("base64Data");
|
||||
String fileName = (String) params.get("fileName");
|
||||
String contentType = (String) params.get("contentType");
|
||||
|
||||
// 2. 参数校验
|
||||
if (StringUtils.isEmpty(base64Data)) {
|
||||
return R.fail("base64Data不能为空");
|
||||
}
|
||||
|
||||
// 3. Base64解码
|
||||
byte[] fileBytes;
|
||||
try {
|
||||
fileBytes = Base64.getDecoder().decode(base64Data);
|
||||
} catch (IllegalArgumentException e) {
|
||||
log.error("Base64解码失败", e);
|
||||
return R.fail("图片数据格式错误");
|
||||
}
|
||||
|
||||
if (fileBytes.length == 0) {
|
||||
return R.fail("解码后文件为空");
|
||||
}
|
||||
|
||||
// 4. 构造MultipartFile
|
||||
String originalFilename = StringUtils.isEmpty(fileName)
|
||||
? "base64_image_" + System.currentTimeMillis() + ".png"
|
||||
: fileName;
|
||||
|
||||
MultipartFile multipartFile = new StandardMultipartFile(
|
||||
fileBytes,
|
||||
"file", // 字段名,与原接口一致
|
||||
originalFilename,
|
||||
contentType
|
||||
);
|
||||
|
||||
// 5. 复用原有上传逻辑
|
||||
SysFileInfo fileInfo = sysFileInfoService.upload(multipartFile, type, hierarchy);
|
||||
|
||||
return R.ok(fileInfo);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Base64上传文件失败", e);
|
||||
return R.fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
# Tomcat
|
||||
server:
|
||||
port: 9111
|
||||
port: 8080
|
||||
|
||||
# Spring
|
||||
spring:
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Tomcat
|
||||
server:
|
||||
port: 9113
|
||||
port: 8080
|
||||
|
||||
# Spring
|
||||
spring:
|
||||
|
|
|
|||
|
|
@ -0,0 +1,127 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>com.microservices</groupId>
|
||||
<artifactId>microservices-modules</artifactId>
|
||||
<version>3.6.2</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>microservices-modules-mon</artifactId>
|
||||
|
||||
<description>
|
||||
microservices-modules-mon运维监控模块
|
||||
</description>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<!-- SpringCloud Alibaba Nacos -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- SpringCloud Alibaba Nacos Config -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- SpringCloud Alibaba Sentinel -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- SpringBoot Actuator -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Swagger UI -->
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger-ui</artifactId>
|
||||
<version>${swagger.fox.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Mysql Connector -->
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Microservices Common Async -->
|
||||
<dependency>
|
||||
<groupId>com.microservices</groupId>
|
||||
<artifactId>microservices-common-async</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Microservices Common DataSource -->
|
||||
<dependency>
|
||||
<groupId>com.microservices</groupId>
|
||||
<artifactId>microservices-common-datasource</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Microservices Common DataScope -->
|
||||
<dependency>
|
||||
<groupId>com.microservices</groupId>
|
||||
<artifactId>microservices-common-datascope</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Microservices Common Log -->
|
||||
<dependency>
|
||||
<groupId>com.microservices</groupId>
|
||||
<artifactId>microservices-common-log</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Microservices Common Swagger -->
|
||||
<dependency>
|
||||
<groupId>com.microservices</groupId>
|
||||
<artifactId>microservices-common-swagger</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.microservices</groupId>
|
||||
<artifactId>microservices-common-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.microservices</groupId>
|
||||
<artifactId>microservices-common-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.microservices</groupId>
|
||||
<artifactId>microservices-common-httpClient</artifactId>
|
||||
<version>3.6.2</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>${project.artifactId}</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
package com.microservices.mon;
|
||||
|
||||
import com.microservices.common.security.annotation.EnableCustomConfig;
|
||||
import com.microservices.common.security.annotation.EnableRyFeignClients;
|
||||
import com.microservices.common.swagger.annotation.EnableCustomSwagger2;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
/**
|
||||
* 运维监控模块
|
||||
*
|
||||
* @author otto
|
||||
*/
|
||||
@EnableCustomConfig
|
||||
@EnableCustomSwagger2
|
||||
@EnableRyFeignClients
|
||||
@SpringBootApplication
|
||||
@EnableScheduling
|
||||
public class MicroservicesMonApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(MicroservicesMonApplication.class, args);
|
||||
System.out.println("(♥◠‿◠)ノ゙ 运维监控模块启动成功 ლ(´ڡ`ლ)゙ \n");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,83 @@
|
|||
package com.microservices.mon.k8s.controller;
|
||||
|
||||
import com.microservices.common.core.web.controller.BaseController;
|
||||
import com.microservices.common.core.web.domain.AjaxResult;
|
||||
import com.microservices.common.core.web.domain.GenericsAjaxResult;
|
||||
import com.microservices.common.core.web.page.GenericsTableDataInfo;
|
||||
import com.microservices.mon.k8s.domain.*;
|
||||
import com.microservices.mon.k8s.service.IK8sDashboardService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import io.swagger.annotations.ApiParam;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cloud.context.config.annotation.RefreshScope;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("dashboard")
|
||||
@Api(tags = "微服务大屏")
|
||||
@RefreshScope
|
||||
public class DashboardController extends BaseController {
|
||||
@Autowired
|
||||
private IK8sDashboardService k8sDashboardService;
|
||||
|
||||
/**
|
||||
* 获取命名空间列表
|
||||
*/
|
||||
@ApiOperation(value = "获取命名空间列表")
|
||||
@GetMapping("/namespace/list")
|
||||
public GenericsTableDataInfo<K8sNamespace> namespaceList(@RequestParam(value = "search", required = false) @ApiParam(value = "根据应用名称查找") String search) {
|
||||
return new GenericsTableDataInfo<>(k8sDashboardService.getNamespaceDetailList(true,search));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取集群节点列表")
|
||||
@GetMapping("/cluster/Nodelist")
|
||||
public GenericsTableDataInfo<K8sClusterNode> clusterNodeList() {
|
||||
return new GenericsTableDataInfo<>(k8sDashboardService.getClusterNodeList());
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取应用容器Ip列表")
|
||||
@GetMapping("/application/{kind}/{namespace}/{applicationName}/podIdList")
|
||||
public GenericsTableDataInfo<String> applicationPodIdList(@PathVariable("kind") String kind, @PathVariable("namespace") String namespace, @PathVariable("applicationName") String applicationName) {
|
||||
return new GenericsTableDataInfo<>(k8sDashboardService.getApplicationPodIdList(kind, namespace, applicationName));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取集群状态数据")
|
||||
@GetMapping("/cluster/status")
|
||||
public GenericsAjaxResult<K8sClusterStatus> clusterStatus() {
|
||||
return GenericsAjaxResult.success(k8sDashboardService.getClusterStatus());
|
||||
}
|
||||
|
||||
@ApiOperation(value = "集群每秒请求率(QPS)")
|
||||
@GetMapping("/cluster/qps")
|
||||
public GenericsTableDataInfo<MetricCommonData> clusterQps() {
|
||||
return new GenericsTableDataInfo<>(k8sDashboardService.getClusterQps());
|
||||
}
|
||||
|
||||
@ApiOperation(value = "最近24小时应用接口请求次数")
|
||||
@GetMapping("/cluster/applicationRequestCount")
|
||||
public GenericsTableDataInfo<ApplicationRequestCountData> applicationRequestCount() {
|
||||
return new GenericsTableDataInfo<>(k8sDashboardService.getApplicationRequestCount());
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取Pod容器状态")
|
||||
@GetMapping("/cluster/podContainerStatus/{podName}")
|
||||
public GenericsAjaxResult<K8sPodContainerStatus> podContainerStatus(@PathVariable("podName") String podName) {
|
||||
return GenericsAjaxResult.success(k8sDashboardService.getPodContainerStatus(podName));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取服务器节点状态")
|
||||
@GetMapping("/cluster/nodeStatus/{nodeIp}")
|
||||
public GenericsAjaxResult<K8sNodeStatus> nodeStatus(@PathVariable("nodeIp") String nodeIp) {
|
||||
return GenericsAjaxResult.success(k8sDashboardService.getNodeStatus(nodeIp));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取微服务应用功能列表")
|
||||
@GetMapping("/applicationFunction/{kind}/{namespace}/{applicationName}")
|
||||
public GenericsTableDataInfo<ApplicationFunction> applicationFunction(@PathVariable("kind") String kind,
|
||||
@PathVariable("namespace") String namespace,
|
||||
@PathVariable("applicationName") String applicationName,
|
||||
@RequestParam("podIpList") @ApiParam(value = "Pod Ip列表(使用逗号分割的ip列表字符串)") String podIpList) {
|
||||
return new GenericsTableDataInfo<>(k8sDashboardService.getApplicationFunction(kind, namespace, applicationName, podIpList));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,247 @@
|
|||
package com.microservices.mon.k8s.controller;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.microservices.common.core.utils.PageUtils;
|
||||
import com.microservices.common.core.web.controller.BaseController;
|
||||
import com.microservices.common.core.web.domain.AjaxResult;
|
||||
import com.microservices.common.core.web.domain.GenericsAjaxResult;
|
||||
import com.microservices.common.core.web.page.GenericsTableDataInfo;
|
||||
import com.microservices.mon.k8s.domain.*;
|
||||
import com.microservices.mon.k8s.domain.vo.ApplicationEnvTypeVo;
|
||||
import com.microservices.mon.k8s.domain.vo.ApplicationTypeVo;
|
||||
import com.microservices.mon.k8s.domain.vo.CommonTypeVo;
|
||||
import com.microservices.mon.k8s.service.IMicroManagementService;
|
||||
import io.swagger.annotations.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cloud.context.config.annotation.RefreshScope;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("micro")
|
||||
@Api(tags = "微服务管理")
|
||||
@RefreshScope
|
||||
public class MicroManagementController extends BaseController {
|
||||
@Autowired
|
||||
private IMicroManagementService microManagementService;
|
||||
|
||||
@ApiOperation(value = "获取可视化面板容器列表")
|
||||
@GetMapping("/pod/list")
|
||||
public GenericsTableDataInfo<K8sApplicationPod> podList() {
|
||||
return new GenericsTableDataInfo<>(microManagementService.getPodList());
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取微服务运行状态监控数据")
|
||||
@GetMapping("/pod/status/{podName}")
|
||||
public GenericsAjaxResult<K8sPodContainerMetricOverview> podStatus(@PathVariable("podName") String podName,
|
||||
@RequestParam(value = "step", required = false) @ApiParam(value = "统计频率") Long step) {
|
||||
return GenericsAjaxResult.success(microManagementService.getPodStatus(podName, step));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取微服务应用详情")
|
||||
@GetMapping("/application/{kind}/{namespace}/{applicationName}/detail")
|
||||
public GenericsAjaxResult<K8sApplication> applicationDetail(@PathVariable("kind") String kind,
|
||||
@PathVariable("namespace") String namespace,
|
||||
@PathVariable("applicationName") String applicationName) {
|
||||
return GenericsAjaxResult.success(microManagementService.getApplicationDetail(kind, namespace, applicationName));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "删除POD容器")
|
||||
@DeleteMapping("/pod/{namespace}/{podName}")
|
||||
public AjaxResult applicationDetail(@PathVariable("namespace") String namespace,
|
||||
@PathVariable("podName") String podName,
|
||||
@RequestParam(value = "isForce", required = false) @ApiParam(value = "是否强制删除") Boolean isForce) {
|
||||
return toAjax(microManagementService.deletePod(namespace, podName, isForce));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "操作应用")
|
||||
@PutMapping("/application/{kind}/{namespace}/{applicationName}/operate/{operationKey}")
|
||||
public AjaxResult operateApplication(@PathVariable("kind") String kind,
|
||||
@PathVariable("namespace") String namespace,
|
||||
@PathVariable("applicationName") String applicationName,
|
||||
@PathVariable("operationKey") String operationKey) {
|
||||
return toAjax(microManagementService.operateApplication(kind, namespace, applicationName, operationKey));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取应用类型")
|
||||
@GetMapping("/applicationType")
|
||||
public GenericsTableDataInfo<ApplicationTypeVo> applicationType() {
|
||||
return new GenericsTableDataInfo<>(microManagementService.getApplicationTypeList());
|
||||
}
|
||||
|
||||
@ApiOperation(value = "创建应用")
|
||||
@PostMapping("/application/{kind}")
|
||||
public AjaxResult createApplication(@PathVariable("kind") String kind,
|
||||
@RequestBody String yamlContent) {
|
||||
return AjaxResult.success(microManagementService.createApplication(kind, yamlContent));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取应用Yaml文件")
|
||||
@GetMapping(value = "/application/{kind}/{namespace}/{applicationName}/yamlFile", produces = "application/yaml")
|
||||
public JSONObject getApplicationYamlFile(@PathVariable("kind") String kind,
|
||||
@PathVariable("namespace") String namespace,
|
||||
@PathVariable("applicationName") String applicationName) {
|
||||
return microManagementService.getApplicationYamlFile(kind, namespace, applicationName);
|
||||
}
|
||||
|
||||
@ApiOperation(value = "编辑应用Yaml文件")
|
||||
@PutMapping("/application/{kind}/{namespace}/{applicationName}")
|
||||
public AjaxResult editApplication(@PathVariable("kind") String kind,
|
||||
@PathVariable("namespace") String namespace,
|
||||
@PathVariable("applicationName") String applicationName,
|
||||
@RequestBody String yamlContent) {
|
||||
return toAjax(microManagementService.editApplication(kind, namespace, applicationName, yamlContent));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "删除应用")
|
||||
@DeleteMapping("/application/{kind}/{namespace}/{applicationName}")
|
||||
public AjaxResult deleteApplication(@PathVariable("kind") String kind,
|
||||
@PathVariable("namespace") String namespace,
|
||||
@PathVariable("applicationName") String applicationName) {
|
||||
return toAjax(microManagementService.deleteApplication(kind, namespace, applicationName));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取应用环境变量")
|
||||
@GetMapping(value = "/application/{kind}/{namespace}/{applicationName}/env")
|
||||
public GenericsTableDataInfo<K8sApplicationEnv> getApplicationEnv(@PathVariable("kind") String kind,
|
||||
@PathVariable("namespace") String namespace,
|
||||
@PathVariable("applicationName") String applicationName) {
|
||||
return new GenericsTableDataInfo<>(microManagementService.getApplicationEnv(kind, namespace, applicationName));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取应用环境变量相关可选参数")
|
||||
@GetMapping(value = "/application/{namespace}/envOptionalParameters")
|
||||
public GenericsTableDataInfo<K8sApplicationEnvOptionalParameter> getEnvOptionalParameters(@PathVariable("namespace") String namespace) {
|
||||
return new GenericsTableDataInfo<>(microManagementService.getEnvOptionalParameters(namespace));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "更新应用环境变量")
|
||||
@PutMapping("/application/{kind}/{namespace}/{applicationName}/env")
|
||||
public AjaxResult updateApplicationEnv(@PathVariable("kind") String kind,
|
||||
@PathVariable("namespace") String namespace,
|
||||
@PathVariable("applicationName") String applicationName,
|
||||
@RequestBody List<K8sApplicationEnv> k8sApplicationEnvList) {
|
||||
return toAjax(microManagementService.updateApplicationEnv(kind, namespace, applicationName, k8sApplicationEnvList));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取应用环境变量类型")
|
||||
@GetMapping(value = "/application/envTypes")
|
||||
public GenericsTableDataInfo<ApplicationEnvTypeVo> getEnvTypes() {
|
||||
return new GenericsTableDataInfo<>(microManagementService.getEnvTypes());
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取网关路由配置")
|
||||
@GetMapping(value = "/gateway/routeConfig")
|
||||
public GenericsTableDataInfo<GatewayRouteConfig> getGatewayRouteConfig() {
|
||||
return new GenericsTableDataInfo<>(microManagementService.getGatewayRouteConfig());
|
||||
}
|
||||
|
||||
@ApiOperation(value = "更新网关路由配置")
|
||||
@PutMapping(value = "/gateway/routeConfig")
|
||||
public AjaxResult updateGatewayRouteConfig(@RequestBody List<GatewayRouteConfig> gatewayRouteConfigList) {
|
||||
return toAjax(microManagementService.updateGatewayRouteConfig(gatewayRouteConfigList));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取网关安全认证配置")
|
||||
@GetMapping(value = "/gateway/safetyConfig")
|
||||
public GenericsAjaxResult<GatewaySafetyConfig> getGatewaySafetyConfig() {
|
||||
return GenericsAjaxResult.success(microManagementService.getGatewaySafetyConfig());
|
||||
}
|
||||
|
||||
@ApiOperation(value = "更新网关安全认证配置")
|
||||
@PutMapping(value = "/gateway/safetyConfig")
|
||||
public AjaxResult updateGatewaySafetyConfig(@RequestBody GatewaySafetyConfig gatewaySafetyConfig) {
|
||||
return toAjax(microManagementService.updateGatewaySafetyConfig(gatewaySafetyConfig));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取网关白名单配置")
|
||||
@GetMapping(value = "/gateway/whitelistConfig")
|
||||
public GenericsAjaxResult<GatewayWhitelistConfig> getGatewayWhitelistConfig() {
|
||||
return GenericsAjaxResult.success(microManagementService.getGatewayWhitelistConfig());
|
||||
}
|
||||
|
||||
@ApiOperation(value = "更新网关白名单配置")
|
||||
@PutMapping(value = "/gateway/whitelistConfig")
|
||||
public AjaxResult updateGatewayWhitelistConfig(@RequestBody GatewayWhitelistConfig gatewayWhitelistConfig) {
|
||||
return toAjax(microManagementService.updateGatewayWhitelistConfig(gatewayWhitelistConfig));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取存在网关异常处理记录的日期列表")
|
||||
@GetMapping(value = "/gateway/exceptionHandingDateList")
|
||||
public GenericsTableDataInfo<String> getExceptionHandingDateList() {
|
||||
return new GenericsTableDataInfo<>(microManagementService.getExceptionHandingDateList());
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取网关异常处理记录")
|
||||
@GetMapping(value = "/gateway/exceptionHandingRecordList")
|
||||
public GenericsTableDataInfo<String> getExceptionHandingRecordList(@RequestParam(value = "date", required = false) @ApiParam(value = "查看日期") String date) {
|
||||
return new GenericsTableDataInfo<>(microManagementService.getExceptionHandingRecordList(date));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取网关限流跳转参数")
|
||||
@GetMapping(value = "/gateway/flowLimitingPara")
|
||||
public GenericsAjaxResult<JSONObject> getGatewayFlowLimitingPara() {
|
||||
return GenericsAjaxResult.success(microManagementService.getGatewayFlowLimitingPara());
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取链路追踪应用列表")
|
||||
@GetMapping(value = "/application/linkTrackingList")
|
||||
public GenericsTableDataInfo<LinkTrackingApplication> getLinkTrackingList(@RequestParam(value = "applicationName", required = false) @ApiParam(value = "应用名称") String applicationName) {
|
||||
return new GenericsTableDataInfo<>(microManagementService.getLinkTrackingList(applicationName));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取K8S事件关键活动操作列表")
|
||||
@GetMapping(value = "/k8sEvent/keyActivitiesOperationList")
|
||||
public GenericsTableDataInfo<CommonTypeVo> getKeyActivitiesOperationList() {
|
||||
return new GenericsTableDataInfo<>(microManagementService.getK8SEventReasonList("Normal"));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取K8S事件关键活动列表")
|
||||
@GetMapping(value = "/k8sEvent/keyActivitiesList")
|
||||
public GenericsTableDataInfo<K8SEvent> getKeyActivitiesList(@RequestParam(value = "reason", required = false) @ApiParam(value = "操作类型") String reason,
|
||||
@RequestParam(value = "startTime", required = false) @ApiParam(value = "开始时间") Date startTime,
|
||||
@RequestParam(value = "endTime", required = false) @ApiParam(value = "结束时间") Date endTime,
|
||||
@RequestParam(value = "isAscOrderByOccurredTime", required = false) @ApiParam(value = "是否根据发生时间升序排序(默认根据发生时间降序排序)") Boolean isAscOrderByOccurredTime,
|
||||
@RequestParam(value = "pageNum", required = false) @ApiParam(value = "当前记录起始索引") Integer pageNum,
|
||||
@RequestParam(value = "pageSize", required = false) @ApiParam(value = "每页显示记录数") Integer pageSize) {
|
||||
return microManagementService.getK8SEventList("Normal", reason, startTime, endTime, isAscOrderByOccurredTime, pageNum, pageSize);
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取K8S事异常结束事件原因列表")
|
||||
@GetMapping(value = "/k8sEvent/exceptionEndReasonList")
|
||||
public GenericsTableDataInfo<CommonTypeVo> getExceptionEndReasonList() {
|
||||
return new GenericsTableDataInfo<>(microManagementService.getK8SEventReasonList("Warning"));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取K8S事件异常结束事件列表")
|
||||
@GetMapping(value = "/k8sEvent/exceptionEndList")
|
||||
public GenericsTableDataInfo<K8SEvent> getExceptionEndListList(@RequestParam(value = "reason", required = false) @ApiParam(value = "操作类型") String reason,
|
||||
@RequestParam(value = "startTime", required = false) @ApiParam(value = "开始时间") Date startTime,
|
||||
@RequestParam(value = "endTime", required = false) @ApiParam(value = "结束时间") Date endTime,
|
||||
@RequestParam(value = "isAscOrderByOccurredTime", required = false) @ApiParam(value = "是否根据发生时间升序排序(默认根据发生时间降序排序)") Boolean isAscOrderByOccurredTime,
|
||||
@RequestParam(value = "pageNum", required = false) @ApiParam(value = "当前记录起始索引") Integer pageNum,
|
||||
@RequestParam(value = "pageSize", required = false) @ApiParam(value = "每页显示记录数") Integer pageSize) {
|
||||
return microManagementService.getK8SEventList("Warning", reason, startTime, endTime, isAscOrderByOccurredTime, pageNum, pageSize);
|
||||
}
|
||||
|
||||
|
||||
@ApiOperation(value = "获取K8S资源对象列表")
|
||||
@GetMapping(value = "/k8sEvent/resourceObjectList")
|
||||
public GenericsTableDataInfo<CommonTypeVo> getResourceObjectList() {
|
||||
return new GenericsTableDataInfo<>(microManagementService.getResourceObjectList());
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取K8S资源占用列表")
|
||||
@GetMapping(value = "/k8sEvent/resourceUsageList")
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name = "pageNum", value = "当前记录起始索引", paramType = "query", dataType = "Integer"),
|
||||
@ApiImplicitParam(name = "pageSize", value = "每页显示记录数", paramType = "query", dataType = "Integer")
|
||||
})
|
||||
public GenericsTableDataInfo<K8SResourceUsage> getResourceUsageList(@RequestParam(value = "searchResourceObject", required = false) @ApiParam(value = "资源对象") String searchResourceObject,
|
||||
@RequestParam(value = "startTime", required = false) @ApiParam(value = "开始时间") Date startTime,
|
||||
@RequestParam(value = "endTime", required = false) @ApiParam(value = "结束时间") Date endTime) {
|
||||
return getAllGenericsDataTableToPage(microManagementService.getResourceUsageList(searchResourceObject, startTime, endTime));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
package com.microservices.mon.k8s.controller;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.microservices.common.core.web.controller.BaseController;
|
||||
import com.microservices.common.core.web.domain.AjaxResult;
|
||||
import com.microservices.common.core.web.domain.GenericsAjaxResult;
|
||||
import com.microservices.common.core.web.page.GenericsTableDataInfo;
|
||||
import com.microservices.mon.k8s.domain.*;
|
||||
import com.microservices.mon.k8s.domain.vo.ApplicationEnvTypeVo;
|
||||
import com.microservices.mon.k8s.domain.vo.ApplicationTypeVo;
|
||||
import com.microservices.mon.k8s.service.IMicroManagementService;
|
||||
import com.microservices.mon.k8s.service.IMicroStatusService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import io.swagger.annotations.ApiParam;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cloud.context.config.annotation.RefreshScope;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("microStatus")
|
||||
@Api(tags = "微服务状态监控")
|
||||
@RefreshScope
|
||||
public class MicroStatusController extends BaseController {
|
||||
@Autowired
|
||||
private IMicroStatusService microStatusService;
|
||||
|
||||
@ApiOperation(value = "获取容器启停状态")
|
||||
@GetMapping("/podStartStopStatus")
|
||||
public GenericsAjaxResult<K8sPodStartStopStatus> getPodStartStopStatus() {
|
||||
return GenericsAjaxResult.success(microStatusService.getPodStartStopStatus());
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取容器CPU使用率")
|
||||
@GetMapping("/podCpuUsage")
|
||||
public GenericsTableDataInfo<K8sPodContainerMetric> getPodCpuUsage(@RequestParam(value = "step", required = false) @ApiParam(value = "统计频率") Long step) {
|
||||
return new GenericsTableDataInfo<>(microStatusService.getPodCpuUsage(step));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取容器内存使用情况")
|
||||
@GetMapping("/podMemoryUsage")
|
||||
public GenericsTableDataInfo<K8sPodContainerMetric> getPodMemoryUsage(@RequestParam(value = "step", required = false) @ApiParam(value = "统计频率") Long step) {
|
||||
return new GenericsTableDataInfo<>(microStatusService.getPodMemoryUsage(step));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取容器硬盘读取情况")
|
||||
@GetMapping("/podDiskReads")
|
||||
public GenericsTableDataInfo<K8sPodContainerMetric> getPodDiskReads(@RequestParam(value = "step", required = false) @ApiParam(value = "统计频率") Long step) {
|
||||
return new GenericsTableDataInfo<>(microStatusService.getPodDiskReads(step));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取容器硬盘写入情况")
|
||||
@GetMapping("/podDiskWrites")
|
||||
public GenericsTableDataInfo<K8sPodContainerMetric> getPodDiskWrites(@RequestParam(value = "step", required = false) @ApiParam(value = "统计频率") Long step) {
|
||||
return new GenericsTableDataInfo<>(microStatusService.getPodDiskWrites(step));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取容器网络接收情况")
|
||||
@GetMapping("/podNetworkReception")
|
||||
public GenericsTableDataInfo<K8sPodContainerMetric> getPodNetworkReception(@RequestParam(value = "step", required = false) @ApiParam(value = "统计频率") Long step) {
|
||||
return new GenericsTableDataInfo<>(microStatusService.getPodNetworkReception(step));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取容器网络发送情况")
|
||||
@GetMapping("/podNetworkTransmission")
|
||||
public GenericsTableDataInfo<K8sPodContainerMetric> getPodNetworkTransmission(@RequestParam(value = "step", required = false) @ApiParam(value = "统计频率") Long step) {
|
||||
return new GenericsTableDataInfo<>(microStatusService.getPodNetworkTransmission(step));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import com.microservices.common.core.exception.ServiceException;
|
||||
import com.microservices.common.core.utils.StringUtils;
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* @author OTTO
|
||||
*/
|
||||
@Getter
|
||||
public enum ApplicationEnvType {
|
||||
|
||||
KEY_VALUE_PAIR("keyValuePair", "键值对"),
|
||||
RESOURCE("resource", "资源字段"),
|
||||
CONFIG_MAP_KEY("configMapKey", "ConfigMap键"),
|
||||
SECRET_KEY("secretKey", "Secret键"),
|
||||
POD_FIELD("podField", "容器字段"),
|
||||
SECRET("secret", "Secret整体"),
|
||||
CONFIGMAP("configMap", "ConfigMap整体");
|
||||
|
||||
private final String key;
|
||||
private final String alias;
|
||||
|
||||
ApplicationEnvType(String key, String alias) {
|
||||
this.key = key;
|
||||
this.alias = alias;
|
||||
}
|
||||
|
||||
public static ApplicationEnvType getApplicationEnvTypeByKey(String type) {
|
||||
for (ApplicationEnvType applicationEnvType : ApplicationEnvType.values()) {
|
||||
if (StringUtils.equals(applicationEnvType.getKey(), type)) {
|
||||
return applicationEnvType;
|
||||
}
|
||||
}
|
||||
throw new ServiceException("该应用环境变量类型不存在(环境变量类型[%s])", type);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@ApiModel("应用功能")
|
||||
public class ApplicationFunction {
|
||||
@ApiModelProperty(value = "应用功能标识")
|
||||
private String key;
|
||||
@ApiModelProperty(value = "应用功能名称")
|
||||
private String name;
|
||||
@ApiModelProperty(value = "应用功能访问所需参数")
|
||||
private JSONObject variables;
|
||||
|
||||
public void setKeyAndName(ApplicationFunctionType applicationFunctionType) {
|
||||
this.key = applicationFunctionType.getKey();
|
||||
this.name = applicationFunctionType.getName();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import com.microservices.common.core.exception.ServiceException;
|
||||
import com.microservices.common.core.utils.StringUtils;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author OTTO
|
||||
*/
|
||||
@Getter
|
||||
public enum ApplicationFunctionType {
|
||||
LINK_TRACKING("LinkTracking", "链路追踪", "mon-skywalking-key"),
|
||||
FLOW_CONTROL("FlowControl", "流量控制", "mon-sentinel-key"),
|
||||
CONFIGURATION_MANAGEMENT("ConfigurationManagement", "配置管理", ""),
|
||||
REGISTRATION_CENTER("RegistrationCenter", "注册中心", "mon-nacos-key"),
|
||||
GATEWAY_MANAGEMENT("GatewayManagement", "网关管理", "mon-gateway-key"),
|
||||
START_AND_STOP_MANAGEMENT("StartAndStopManagement", "启停管理", "");
|
||||
private final String key;
|
||||
private final String name;
|
||||
private final String k8sLabel;
|
||||
|
||||
ApplicationFunctionType(String key, String name, String k8sLabel) {
|
||||
this.key = key;
|
||||
this.name = name;
|
||||
this.k8sLabel = k8sLabel;
|
||||
}
|
||||
|
||||
public static ApplicationFunctionType getByLabelsKey(String k8sLabel) {
|
||||
if (StringUtils.isNotEmpty(k8sLabel)) {
|
||||
for (ApplicationFunctionType type : ApplicationFunctionType.values()) {
|
||||
if (type.getK8sLabel().equals(k8sLabel)) {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@ApiModel("应用请求次数对象")
|
||||
public class ApplicationRequestCountData {
|
||||
|
||||
@ApiModelProperty(value = "序号")
|
||||
private Integer number;
|
||||
|
||||
@ApiModelProperty(value = "应用名称")
|
||||
private String applicationAlias;
|
||||
|
||||
@ApiModelProperty(value = "请求次数")
|
||||
private Long requestCount;
|
||||
}
|
||||
|
|
@ -0,0 +1,93 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.microservices.common.core.utils.StringUtils;
|
||||
import com.microservices.mon.k8s.domain.vo.RancherApplicationVo;
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* @author OTTO
|
||||
*/
|
||||
@Getter
|
||||
public enum ApplicationStartAndStopType {
|
||||
START("start", "启动", false),
|
||||
STOP("stop", "停止", false),
|
||||
FORCE_STOP("forceStop", "强制停止", false),
|
||||
RESTART("restart", "重启", true),
|
||||
PAUSED("paused", "暂停", true),
|
||||
RESUME("resume", "恢复", true);
|
||||
private final String key;
|
||||
private final String name;
|
||||
private final Boolean isDaemonSetOperation;
|
||||
|
||||
ApplicationStartAndStopType(String key, String name, Boolean isDaemonSetOperation) {
|
||||
this.key = key;
|
||||
this.name = name;
|
||||
this.isDaemonSetOperation = isDaemonSetOperation;
|
||||
}
|
||||
|
||||
public static JSONArray getOperationList(String kind, K8sApplication k8sApplication) {
|
||||
JSONArray jsonArray = new JSONArray();
|
||||
if (k8sApplication == null) {
|
||||
return jsonArray;
|
||||
}
|
||||
for (ApplicationStartAndStopType value : values()) {
|
||||
if ("DaemonSet".equals(kind) && !value.isDaemonSetOperation) {
|
||||
continue;
|
||||
}
|
||||
boolean shouldAdd = false;
|
||||
|
||||
switch (value) {
|
||||
case START:
|
||||
if (k8sApplication.getReplicas() == null || k8sApplication.getReplicas() == 0) {
|
||||
shouldAdd = true;
|
||||
}
|
||||
break;
|
||||
case STOP:
|
||||
case FORCE_STOP:
|
||||
case RESTART:
|
||||
if (k8sApplication.getReplicas() != null && k8sApplication.getReplicas() > 0) {
|
||||
shouldAdd = true;
|
||||
}
|
||||
break;
|
||||
case PAUSED:
|
||||
if (!k8sApplication.getPaused()) {
|
||||
shouldAdd = true;
|
||||
}
|
||||
break;
|
||||
case RESUME:
|
||||
if (k8sApplication.getPaused()) {
|
||||
shouldAdd = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
if (shouldAdd) {
|
||||
JSONObject jsonObject = new JSONObject();
|
||||
jsonObject.put("operationKey", value.getKey());
|
||||
jsonObject.put("operationName", value.getName());
|
||||
jsonArray.add(jsonObject);
|
||||
}
|
||||
}
|
||||
return jsonArray;
|
||||
}
|
||||
|
||||
public static boolean containsKey(String operationKey) {
|
||||
for (ApplicationStartAndStopType value : values()) {
|
||||
if (StringUtils.equals(value.getKey(), operationKey)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static ApplicationStartAndStopType getByKey(String operationKey) {
|
||||
for (ApplicationStartAndStopType value : values()) {
|
||||
if (StringUtils.equals(value.getKey(), operationKey)) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import com.microservices.common.core.exception.ServiceException;
|
||||
import com.microservices.common.core.utils.StringUtils;
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* @author OTTO
|
||||
*/
|
||||
@Getter
|
||||
public enum ApplicationType {
|
||||
DAEMON_SET("DaemonSet", "apps.daemonsets", "确保每个节点(或指定节点)上都运行一个容器副本", "daemonsets"),
|
||||
DEPLOYMENT("Deployment", "apps.deployments", "管理无状态应用的容器副本,支持声明式更新和回滚", "deployments"),
|
||||
STATEFUL_SET("StatefulSet", "apps.statefulsets", "管理有状态应用,为容器提供稳定的标识和持久化存储", "statefulsets");
|
||||
private final String key;
|
||||
private final String fullName;
|
||||
private final String description;
|
||||
private final String name;
|
||||
|
||||
ApplicationType(String key, String fullName, String description, String name) {
|
||||
this.key = key;
|
||||
this.fullName = fullName;
|
||||
this.description = description;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public static ApplicationType getApplicationTypeByKey(String key) {
|
||||
for (ApplicationType value : ApplicationType.values()) {
|
||||
if (StringUtils.equalsIgnoreCase(value.getKey(), key)) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
throw new ServiceException("该应用类型不存在(应用类型[%s])", key);
|
||||
}
|
||||
|
||||
public static Boolean isApplicationType(String key) {
|
||||
for (ApplicationType value : ApplicationType.values()) {
|
||||
if (StringUtils.equalsIgnoreCase(value.getKey(), key)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@ApiModel("网关路由配置")
|
||||
public class GatewayRouteConfig {
|
||||
@ApiModelProperty(value = "路由标识")
|
||||
private String id;
|
||||
@ApiModelProperty(value = "目标地址")
|
||||
private String uri;
|
||||
@ApiModelProperty(value = "转发规则")
|
||||
private List<String> predicates;
|
||||
@ApiModelProperty(value = "过滤规则")
|
||||
private List<String> filters;
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@ApiModel("网关安全认证配置")
|
||||
public class GatewaySafetyConfig {
|
||||
@ApiModelProperty(value = "允许请求来源")
|
||||
private List<String> allowedOriginPatterns;
|
||||
@ApiModelProperty(value = "允许请求头")
|
||||
private List<String> allowedHeaders;
|
||||
@ApiModelProperty(value = "预检请求缓存时间")
|
||||
private Integer maxAge=360000;
|
||||
@ApiModelProperty(value = "允许请求方法")
|
||||
private List<String> allowedMethods;
|
||||
@ApiModelProperty(value = "允许证书")
|
||||
private Boolean allowCredentials = true;
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@ApiModel("网关白名单配置")
|
||||
public class GatewayWhitelistConfig {
|
||||
@ApiModelProperty(value = "白名单列表")
|
||||
private List<String> whites;
|
||||
}
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.microservices.common.core.web.page.GenericsTableDataInfo;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@ApiModel("K8S事件")
|
||||
public class K8SEvent {
|
||||
@ApiModelProperty(value = "事件id")
|
||||
private String docId;
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
@ApiModelProperty(value = "发生时间")
|
||||
private Date occurredTime;
|
||||
@ApiModelProperty(value = "操作类型/异常原因")
|
||||
private String reason;
|
||||
@ApiModelProperty(value = "事件发生对象")
|
||||
private String object;
|
||||
@ApiModelProperty(value = "事件发生子对象")
|
||||
private String childObject;
|
||||
@ApiModelProperty(value = "所处命名空间")
|
||||
private String namespace;
|
||||
@ApiModelProperty(value = "运行结果/详细信息")
|
||||
private String message;
|
||||
|
||||
public static GenericsTableDataInfo<K8SEvent> toK8SEventTable(JSONObject esQueryRes) {
|
||||
List<K8SEvent> k8SEventList = new ArrayList<>();
|
||||
Long total = getK8SEventTotal(esQueryRes, k8SEventList);
|
||||
return new GenericsTableDataInfo<>(k8SEventList, total);
|
||||
}
|
||||
|
||||
public static List<K8SEvent> toK8SEventList(JSONObject esQueryRes) {
|
||||
List<K8SEvent> k8SEventList = new ArrayList<>();
|
||||
getK8SEventTotal(esQueryRes, k8SEventList);
|
||||
return k8SEventList;
|
||||
}
|
||||
|
||||
private static Long getK8SEventTotal(JSONObject esQueryRes, List<K8SEvent> k8SEventList) {
|
||||
Long total = 0L;
|
||||
if (esQueryRes.getJSONObject("hits") != null && esQueryRes.getJSONObject("hits").getJSONArray("hits") != null) {
|
||||
JSONObject hits = esQueryRes.getJSONObject("hits");
|
||||
JSONArray dataHits = hits.getJSONArray("hits");
|
||||
|
||||
for (int i = 0; i < dataHits.size(); i++) {
|
||||
JSONObject dataHit = dataHits.getJSONObject(i);
|
||||
K8SEvent k8SEvent = new K8SEvent();
|
||||
k8SEvent.setDocId(dataHit.getString("_id"));
|
||||
JSONObject source = dataHit.getJSONObject("_source");
|
||||
k8SEvent.setOccurredTime(source.getDate("lastTimestamp"));
|
||||
k8SEvent.setReason(source.getString("reason"));
|
||||
if (source.getJSONObject("involvedObject") != null) {
|
||||
JSONObject involvedObject = source.getJSONObject("involvedObject");
|
||||
k8SEvent.setObject(String.format("%s:%s", involvedObject.getString("kind"), involvedObject.getString("name")));
|
||||
k8SEvent.setChildObject(involvedObject.getString("fieldPath"));
|
||||
k8SEvent.setNamespace(involvedObject.getString("namespace"));
|
||||
}
|
||||
|
||||
k8SEvent.setMessage(source.getString("message"));
|
||||
k8SEventList.add(k8SEvent);
|
||||
}
|
||||
total = hits.getJSONObject("total").getLong("value");
|
||||
}
|
||||
return total;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@ApiModel("K8S资源占用情况")
|
||||
public class K8SResourceUsage {
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
@ApiModelProperty(value = "发生时间")
|
||||
private Date occurredTime;
|
||||
@ApiModelProperty(value = "资源类型")
|
||||
private String resourceType;
|
||||
@ApiModelProperty(value = "资源对象")
|
||||
private String resourceObject;
|
||||
@ApiModelProperty(value = "资源占用情况")
|
||||
private String message;
|
||||
}
|
||||
|
|
@ -0,0 +1,59 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import com.microservices.mon.k8s.utils.MonUtils;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@Data
|
||||
@ApiModel("K8S应用")
|
||||
public class K8sApplication {
|
||||
|
||||
@ApiModelProperty(value = "应用Id")
|
||||
private String id;
|
||||
|
||||
@ApiModelProperty(value = "应用名称")
|
||||
private String name;
|
||||
|
||||
@ApiModelProperty(value = "应用别名")
|
||||
private String alias;
|
||||
|
||||
@ApiModelProperty(value = "应用类型")
|
||||
private String kind;
|
||||
|
||||
@ApiModelProperty(value = "所属命名空间")
|
||||
private String namespace;
|
||||
|
||||
@ApiModelProperty(value = "副本数量")
|
||||
private Integer replicas;
|
||||
|
||||
@ApiModelProperty(value = "有效副本数量(当有效副本数为0时代表应用失败呈现红色;当有效副本数大于0但小于副本数时代表应用部分失败呈现橙色;当有效副本数等于副本数代表应用正常呈现蓝色)")
|
||||
private Integer readyReplicas;
|
||||
|
||||
@ApiModelProperty(value = "容器选择器")
|
||||
private String podSelector;
|
||||
|
||||
@ApiModelProperty(value = "Docker镜像")
|
||||
private String dockerImage;
|
||||
|
||||
@ApiModelProperty(value = "重启次数")
|
||||
private Integer restartCount;
|
||||
|
||||
@ApiModelProperty(value = "存活时间")
|
||||
private String survivalTime;
|
||||
|
||||
@ApiModelProperty(value = "运行状态")
|
||||
private K8sApplicationAndPodState state;
|
||||
|
||||
@ApiModelProperty(value = "暂停编排")
|
||||
private Boolean paused;
|
||||
|
||||
private List<K8sApplicationPod> podList;
|
||||
|
||||
// public void setDockerImage(String dockerImage) {
|
||||
// this.dockerImage = MonUtils.getDockerImage(dockerImage);
|
||||
// }
|
||||
}
|
||||
|
|
@ -0,0 +1,121 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
|
||||
@Data
|
||||
@ApiModel("应用状态")
|
||||
public class K8sApplicationAndPodState {
|
||||
|
||||
@ApiModelProperty(value = "状态标识")
|
||||
private String name;
|
||||
|
||||
@ApiModelProperty(value = "应用展示名称(中文)")
|
||||
private String alias;
|
||||
|
||||
@ApiModelProperty(value = "是否错误")
|
||||
private Boolean isError;
|
||||
|
||||
@ApiModelProperty(value = "状态消息")
|
||||
private String message;
|
||||
|
||||
public static K8sApplicationAndPodState k8sApplicationStopState(String stateName) {
|
||||
K8sApplicationAndPodState state = new K8sApplicationAndPodState();
|
||||
state.setName(stateName);
|
||||
state.setIsError(false);
|
||||
state.setMessage("");
|
||||
state.setApplicationAliasByName(stateName);
|
||||
return state;
|
||||
}
|
||||
|
||||
public void setApplicationAliasByName(String name) {
|
||||
this.name = name;
|
||||
if ("active".equalsIgnoreCase(name)) {
|
||||
this.alias = "运行中";
|
||||
} else if ("updating".equalsIgnoreCase(name)) {
|
||||
this.alias = "更新中";
|
||||
} else if ("in-progress".equalsIgnoreCase(name)) {
|
||||
this.alias = "处理中";
|
||||
} else if ("error".equalsIgnoreCase(name)) {
|
||||
this.alias = "运行失败";
|
||||
} else if ("paused".equalsIgnoreCase(name)) {
|
||||
this.alias = "暂停编排";
|
||||
} else if ("pending".equalsIgnoreCase(name)) {
|
||||
this.alias = "等待中";
|
||||
} else if ("stop".equalsIgnoreCase(name)) {
|
||||
this.alias = "已停止运行";
|
||||
} else {
|
||||
this.alias = name;
|
||||
}
|
||||
}
|
||||
|
||||
public void setPodAliasAndErrorByName(String name) {
|
||||
this.name = name;
|
||||
this.isError=true;
|
||||
|
||||
if ("imagePullBackOff".equalsIgnoreCase(name)) {
|
||||
this.alias = "镜像拉取失败";
|
||||
} else if ("pending".equalsIgnoreCase(name)) {
|
||||
this.alias = "等待中";
|
||||
this.isError=false;
|
||||
} else if ("running".equalsIgnoreCase(name)) {
|
||||
this.alias = "运行中";
|
||||
this.isError=false;
|
||||
} else if ("podScheduled".equalsIgnoreCase(name)) {
|
||||
this.alias = "容器已调度";
|
||||
this.isError=false;
|
||||
} else if ("containersReady".equalsIgnoreCase(name)) {
|
||||
this.alias = "容器已就绪";
|
||||
this.isError=false;
|
||||
} else if ("initialized".equalsIgnoreCase(name)) {
|
||||
this.alias = "容器已初始化";
|
||||
this.isError=false;
|
||||
} else if ("ready".equalsIgnoreCase(name)) {
|
||||
this.alias = "容器已准备就绪";
|
||||
this.isError=false;
|
||||
} else if ("crashLoopBackOff".equalsIgnoreCase(name)) {
|
||||
this.alias = "容器崩溃循环重启";
|
||||
} else if ("invalidImageName".equalsIgnoreCase(name)) {
|
||||
this.alias = "无法解析镜像名称";
|
||||
} else if ("imageInspectError".equalsIgnoreCase(name)) {
|
||||
this.alias = "无法校验镜像";
|
||||
} else if ("errImageNeverPull".equalsIgnoreCase(name)) {
|
||||
this.alias = "策略禁止拉取镜像";
|
||||
} else if ("registryUnavailable".equalsIgnoreCase(name)) {
|
||||
this.alias = "连接不到镜像中心";
|
||||
} else if ("errImagePull".equalsIgnoreCase(name)) {
|
||||
this.alias = "拉取镜像出错";
|
||||
} else if ("createContainerConfigError".equalsIgnoreCase(name)) {
|
||||
this.alias = "不能创建容器配置";
|
||||
} else if ("createContainerError".equalsIgnoreCase(name)) {
|
||||
this.alias = "创建容器失败";
|
||||
} else if ("runContainerError".equalsIgnoreCase(name)) {
|
||||
this.alias = "启动容器失败";
|
||||
} else if ("postStartHookError".equalsIgnoreCase(name)) {
|
||||
this.alias = "执行hook报错";
|
||||
} else if ("containersNotInitialized".equalsIgnoreCase(name)) {
|
||||
this.alias = "容器未初始化完毕";
|
||||
} else if ("containersNotReady".equalsIgnoreCase(name)) {
|
||||
this.alias = "容器未准备完毕";
|
||||
} else if ("containerCreating".equalsIgnoreCase(name)) {
|
||||
this.alias = "容器创建中";
|
||||
this.isError=false;
|
||||
} else if ("podInitializing".equalsIgnoreCase(name)) {
|
||||
this.alias = "Pod 初始化中";
|
||||
this.isError=false;
|
||||
} else if ("dockerDaemonNotReady".equalsIgnoreCase(name)) {
|
||||
this.alias = "Docker 未完全启动";
|
||||
} else if ("networkPluginNotReady".equalsIgnoreCase(name)) {
|
||||
this.alias = "网络插件未完全启动";
|
||||
} else if ("evicted".equalsIgnoreCase(name)) {
|
||||
this.alias = "Pod 被驱赶";
|
||||
} else if ("terminating".equalsIgnoreCase(name)) {
|
||||
this.alias = "删除中";
|
||||
this.isError=false;
|
||||
} else {
|
||||
this.alias = name;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,122 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
|
||||
@Data
|
||||
@ApiModel("K8S应用环境变量")
|
||||
public class K8sApplicationEnv {
|
||||
|
||||
@ApiModelProperty(value = "环境变量类型")
|
||||
private String type;
|
||||
|
||||
@ApiModelProperty(value = "环境变量键")
|
||||
private String key;
|
||||
|
||||
@ApiModelProperty(value = "环境变量值")
|
||||
private JSONObject valueObj;
|
||||
|
||||
/**
|
||||
* 将 Kubernetes 容器 env 数组中的单个元素(JSONObject 形式)转换成内部统一的 K8sApplicationEnv 对象。
|
||||
*
|
||||
* <p>支持解析以下四种 value 来源:</p>
|
||||
* <ul>
|
||||
* <li>普通键值对:{@code {"name":"KEY","value":"VAL"}}</li>
|
||||
* <li>资源字段引用:{@code {"name":"CPU_LIMIT","valueFrom":{"resourceFieldRef":{...}}}}</li>
|
||||
* <li>ConfigMap 键引用:{@code {"name":"CM_KEY","valueFrom":{"configMapKeyRef":{...}}}}</li>
|
||||
* <li>Secret 键引用:{@code {"name":"SECRET_KEY","valueFrom":{"secretKeyRef":{...}}}}</li>
|
||||
* <li>Pod 字段引用:{@code {"name":"POD_IP","valueFrom":{"fieldRef":{...}}}}</li>
|
||||
* </ul>
|
||||
*
|
||||
* @param envJsonObject 单条 env 的原始 JSON 对象;允许为 null
|
||||
* @return 转换后的 K8sApplicationEnv 实例;无法识别或入参为 null 时返回 null
|
||||
*/
|
||||
public static K8sApplicationEnv envJsonObjectToK8sApplicationEnv(JSONObject envJsonObject) {
|
||||
K8sApplicationEnv k8sApplicationEnv = null;
|
||||
if (envJsonObject != null) {
|
||||
JSONObject valueObj = new JSONObject();
|
||||
if (envJsonObject.containsKey("value")) {
|
||||
k8sApplicationEnv = new K8sApplicationEnv();
|
||||
k8sApplicationEnv.setKey(envJsonObject.getString("name"));
|
||||
k8sApplicationEnv.setType(ApplicationEnvType.KEY_VALUE_PAIR.getKey());
|
||||
valueObj.put("value", envJsonObject.getString("value"));
|
||||
k8sApplicationEnv.setValueObj(valueObj);
|
||||
} else if (envJsonObject.containsKey("valueFrom")) {
|
||||
JSONObject valueFromJson = envJsonObject.getJSONObject("valueFrom");
|
||||
if (valueFromJson.containsKey("resourceFieldRef")) {
|
||||
k8sApplicationEnv = new K8sApplicationEnv();
|
||||
k8sApplicationEnv.setKey(envJsonObject.getString("name"));
|
||||
k8sApplicationEnv.setType(ApplicationEnvType.RESOURCE.getKey());
|
||||
JSONObject resourceFieldRef = valueFromJson.getJSONObject("resourceFieldRef");
|
||||
valueObj.put("name", resourceFieldRef.getString("containerName"));
|
||||
valueObj.put("key", resourceFieldRef.getString("resource"));
|
||||
k8sApplicationEnv.setValueObj(valueObj);
|
||||
} else if (valueFromJson.containsKey("configMapKeyRef")) {
|
||||
k8sApplicationEnv = new K8sApplicationEnv();
|
||||
k8sApplicationEnv.setKey(envJsonObject.getString("name"));
|
||||
k8sApplicationEnv.setType(ApplicationEnvType.CONFIG_MAP_KEY.getKey());
|
||||
JSONObject configMapKeyRef = valueFromJson.getJSONObject("configMapKeyRef");
|
||||
valueObj.put("name", configMapKeyRef.getString("name"));
|
||||
valueObj.put("key", configMapKeyRef.getString("key"));
|
||||
k8sApplicationEnv.setValueObj(valueObj);
|
||||
} else if (valueFromJson.containsKey("secretKeyRef")) {
|
||||
k8sApplicationEnv = new K8sApplicationEnv();
|
||||
k8sApplicationEnv.setKey(envJsonObject.getString("name"));
|
||||
k8sApplicationEnv.setType(ApplicationEnvType.SECRET_KEY.getKey());
|
||||
JSONObject secretKeyRef = valueFromJson.getJSONObject("secretKeyRef");
|
||||
valueObj.put("name", secretKeyRef.getString("name"));
|
||||
valueObj.put("key", secretKeyRef.getString("key"));
|
||||
k8sApplicationEnv.setValueObj(valueObj);
|
||||
} else if (valueFromJson.containsKey("fieldRef")) {
|
||||
k8sApplicationEnv = new K8sApplicationEnv();
|
||||
k8sApplicationEnv.setKey(envJsonObject.getString("name"));
|
||||
k8sApplicationEnv.setType(ApplicationEnvType.POD_FIELD.getKey());
|
||||
JSONObject fieldRef = valueFromJson.getJSONObject("fieldRef");
|
||||
valueObj.put("value", fieldRef.getString("fieldPath"));
|
||||
k8sApplicationEnv.setValueObj(valueObj);
|
||||
}
|
||||
}
|
||||
}
|
||||
return k8sApplicationEnv;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 Kubernetes 容器 envFrom 数组中的单个元素(JSONObject 形式)转换成内部统一的 K8sApplicationEnv 对象。
|
||||
*
|
||||
* <p>支持解析以下两种来源:</p>
|
||||
* <ul>
|
||||
* <li>整个 ConfigMap:{@code {"prefix":"PRE_","configMapRef":{"name":"cm-name"}}}</li>
|
||||
* <li>整个 Secret:{@code {"prefix":"PRE_","secretRef":{"name":"secret-name"}}}</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>注意:prefix 可能为 null。</p>
|
||||
*
|
||||
* @param envFromJson 单条 envFrom 的原始 JSON 对象;允许为 null
|
||||
* @return 转换后的 K8sApplicationEnv 实例;无法识别或入参为 null 时返回 null
|
||||
*/
|
||||
public static K8sApplicationEnv envFromJsonObjectToK8sApplicationEnv(JSONObject envFromJson) {
|
||||
K8sApplicationEnv k8sApplicationEnv = null;
|
||||
if (envFromJson != null) {
|
||||
JSONObject valueObj = new JSONObject();
|
||||
if (envFromJson.containsKey("configMapRef")) {
|
||||
k8sApplicationEnv = new K8sApplicationEnv();
|
||||
k8sApplicationEnv.setKey(envFromJson.getString("prefix"));
|
||||
k8sApplicationEnv.setType(ApplicationEnvType.CONFIGMAP.getKey());
|
||||
JSONObject configMapRef = envFromJson.getJSONObject("configMapRef");
|
||||
valueObj.put("name", configMapRef.getString("name"));
|
||||
k8sApplicationEnv.setValueObj(valueObj);
|
||||
} else if (envFromJson.containsKey("secretRef")) {
|
||||
k8sApplicationEnv = new K8sApplicationEnv();
|
||||
k8sApplicationEnv.setKey(envFromJson.getString("prefix"));
|
||||
k8sApplicationEnv.setType(ApplicationEnvType.SECRET.getKey());
|
||||
JSONObject secretRef = envFromJson.getJSONObject("secretRef");
|
||||
valueObj.put("name", secretRef.getString("name"));
|
||||
k8sApplicationEnv.setValueObj(valueObj);
|
||||
}
|
||||
}
|
||||
return k8sApplicationEnv;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@Data
|
||||
@ApiModel("K8S应用环境变量")
|
||||
public class K8sApplicationEnvOptionalParameter {
|
||||
|
||||
@ApiModelProperty(value = "环境变量参数类型")
|
||||
private String type;
|
||||
|
||||
@ApiModelProperty(value = "环境变量参数名称")
|
||||
private String name;
|
||||
|
||||
@ApiModelProperty(value = "环境变量参数键值")
|
||||
private List<String> keys;
|
||||
}
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.microservices.mon.k8s.utils.MonUtils;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
|
||||
@Data
|
||||
@ApiModel("K8S容器")
|
||||
public class K8sApplicationPod {
|
||||
|
||||
@ApiModelProperty(value = "容器Id")
|
||||
private String id;
|
||||
|
||||
@ApiModelProperty(value = "容器名称")
|
||||
private String name;
|
||||
|
||||
@ApiModelProperty(value = "所属命名空间")
|
||||
private String namespace;
|
||||
|
||||
@ApiModelProperty(value = "容器Ip")
|
||||
private String ip;
|
||||
|
||||
@ApiModelProperty(value = "重启次数")
|
||||
private Integer restartCount;
|
||||
|
||||
@ApiModelProperty(value = "运行状态")
|
||||
private K8sApplicationAndPodState state;
|
||||
|
||||
@ApiModelProperty(value = "是否正常运行")
|
||||
private Boolean isRunning;
|
||||
|
||||
@ApiModelProperty(value = "存活时间")
|
||||
private String survivalTime;
|
||||
|
||||
@ApiModelProperty(value = "所有权")
|
||||
private String serviceAccountName;
|
||||
|
||||
@ApiModelProperty(value = "容器端口")
|
||||
private String ports;
|
||||
|
||||
@ApiModelProperty(value = "Docker镜像")
|
||||
private String dockerImage;
|
||||
|
||||
@ApiModelProperty(value = "副本数量")
|
||||
private Integer replicas;
|
||||
|
||||
@ApiModelProperty(value = "有效副本数量")
|
||||
private Integer readyReplicas;
|
||||
|
||||
@ApiModelProperty(value = "所属堆栈")
|
||||
private String stack;
|
||||
|
||||
@ApiModelProperty(value = "创建时间")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private Date createdTime;
|
||||
|
||||
// public void setDockerImage(String dockerImage) {
|
||||
// this.dockerImage = MonUtils.getDockerImage(dockerImage);
|
||||
// }
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@Data
|
||||
@ApiModel("集群节点")
|
||||
public class K8sClusterNode {
|
||||
@ApiModelProperty(value = "节点标识")
|
||||
private String id;
|
||||
|
||||
@ApiModelProperty(value = "节点名称")
|
||||
private String name;
|
||||
|
||||
@ApiModelProperty(value = "节点IP")
|
||||
private String ip;
|
||||
|
||||
@ApiModelProperty(value = "节点角色(Master/Worker)")
|
||||
private String role;
|
||||
|
||||
@ApiModelProperty(value = "是否就绪")
|
||||
private Boolean Ready;
|
||||
}
|
||||
|
|
@ -0,0 +1,116 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.microservices.mon.k8s.domain.vo.PrometheusResVo;
|
||||
import com.microservices.mon.k8s.domain.vo.PrometheusResultVo;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@Data
|
||||
@ApiModel("集群状态")
|
||||
public class K8sClusterStatus {
|
||||
@ApiModelProperty(value = "集群节点数量")
|
||||
private Integer nodeCount;
|
||||
|
||||
@ApiModelProperty(value = "不可用节点数量")
|
||||
private Integer unavailableNodeCount;
|
||||
|
||||
@ApiModelProperty(value = "容器使用率")
|
||||
private Float podUsage;
|
||||
|
||||
@ApiModelProperty(value = "CPU使用率")
|
||||
private Float cpuUsage;
|
||||
|
||||
@ApiModelProperty(value = "内存使用率")
|
||||
private Float memoryUsage;
|
||||
|
||||
@ApiModelProperty(value = "最近24小时请求总数")
|
||||
private Long totalRequestCountToday;
|
||||
|
||||
@ApiModelProperty(value = "最近24小时请求平均处理时间(单位:ms)")
|
||||
private Float averageRequestProcessingTimeToday;
|
||||
|
||||
@ApiModelProperty(value = "最近24小时请求成功率")
|
||||
private Float requestSuccessRateToday;
|
||||
|
||||
@ApiModelProperty(value = "微服务应用数量")
|
||||
private Integer microserviceApplicationCount;
|
||||
|
||||
@ApiModelProperty(value = "最近24小时微服务重启次数")
|
||||
private Integer microserviceRestartCountToday;
|
||||
|
||||
@ApiModelProperty(value = "微服务Pod运行状态(Key代表状态,Value代表数量)")
|
||||
private HashMap<String, Integer> podStatus;
|
||||
|
||||
public void setNodeCount(PrometheusResVo prometheusResVo) {
|
||||
this.nodeCount = Integer.parseInt(PrometheusResVo.getPromStringValue(prometheusResVo));
|
||||
}
|
||||
|
||||
public void setUnavailableNodeCount(PrometheusResVo prometheusResVo) {
|
||||
this.unavailableNodeCount = Integer.parseInt(PrometheusResVo.getPromStringValue(prometheusResVo));
|
||||
}
|
||||
|
||||
public void setCpuUsage(PrometheusResVo prometheusResVo) {
|
||||
this.cpuUsage = Float.parseFloat(PrometheusResVo.getPromStringValue(prometheusResVo));
|
||||
}
|
||||
|
||||
public void setPodUsage(PrometheusResVo prometheusResVo) {
|
||||
this.podUsage = Float.parseFloat(PrometheusResVo.getPromStringValue(prometheusResVo));
|
||||
}
|
||||
|
||||
public void setMemoryUsage(PrometheusResVo prometheusResVo) {
|
||||
this.memoryUsage = Float.parseFloat(PrometheusResVo.getPromStringValue(prometheusResVo));
|
||||
}
|
||||
|
||||
public void setTotalRequestCountToday(PrometheusResVo prometheusResVo) {
|
||||
this.totalRequestCountToday = Long.parseLong(PrometheusResVo.getPromStringValue(prometheusResVo));
|
||||
}
|
||||
|
||||
public void setAverageRequestProcessingTimeToday(PrometheusResVo prometheusResVo) {
|
||||
this.averageRequestProcessingTimeToday = Float.parseFloat(PrometheusResVo.getPromStringValue(prometheusResVo));
|
||||
}
|
||||
|
||||
public void setRequestSuccessRateToday(PrometheusResVo prometheusResVo) {
|
||||
this.requestSuccessRateToday = Float.parseFloat(PrometheusResVo.getPromStringValue(prometheusResVo));
|
||||
}
|
||||
|
||||
public void setMicroserviceApplicationCount(List<K8sNamespace> k8sNamespaceList) {
|
||||
this.microserviceApplicationCount = k8sNamespaceList.stream().map(x -> x.getApplicationList().size()).reduce(0, Integer::sum);
|
||||
}
|
||||
|
||||
public void setMicroserviceRestartCountToday(PrometheusResVo prometheusResVo) {
|
||||
this.microserviceRestartCountToday = (int) Float.parseFloat(PrometheusResVo.getPromStringValue(prometheusResVo));
|
||||
}
|
||||
|
||||
public void setPodStatus(PrometheusResVo prometheusResVo) {
|
||||
HashMap<String, Integer> podStatus = new HashMap<>();
|
||||
List<PrometheusResultVo> resultList = PrometheusResVo.getPrometheusResultVoList(prometheusResVo);
|
||||
for (PrometheusResultVo result : resultList) {
|
||||
Integer value = result.getValue().getIntValue(1);
|
||||
switch (result.getMetric().getString("phase")) {
|
||||
case "Running":
|
||||
podStatus.put("运行中", value);
|
||||
break;
|
||||
case "Pending":
|
||||
podStatus.put("等待中", value);
|
||||
break;
|
||||
case "Succeeded":
|
||||
podStatus.put("运行已完成", value);
|
||||
break;
|
||||
case "Unknown":
|
||||
podStatus.put("未知", value);
|
||||
break;
|
||||
case "Failed":
|
||||
podStatus.put("运行失败", value);
|
||||
}
|
||||
}
|
||||
this.podStatus = podStatus;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@Data
|
||||
@ApiModel("命名空间")
|
||||
public class K8sNamespace {
|
||||
@ApiModelProperty(value = "命名空间标识")
|
||||
private String id;
|
||||
|
||||
@ApiModelProperty(value = "命名空间键值")
|
||||
private String key;
|
||||
|
||||
@ApiModelProperty(value = "命名空间名称")
|
||||
private String name;
|
||||
|
||||
@ApiModelProperty(value = "命名空间别名(中文)")
|
||||
private String alias;
|
||||
|
||||
@ApiModelProperty(value = "应用列表")
|
||||
private List<K8sApplication> applicationList;
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
|
||||
@Data
|
||||
@ApiModel("K8S Node状态")
|
||||
public class K8sNodeStatus {
|
||||
@ApiModelProperty(value = "节点IP")
|
||||
private String nodeIp;
|
||||
|
||||
@ApiModelProperty(value = "CPU使用率")
|
||||
private Float cpuUsage;
|
||||
|
||||
@ApiModelProperty(value = "内存使用率")
|
||||
private Float memoryUsage;
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@Data
|
||||
@ApiModel("K8S容器运行状态监控")
|
||||
public class K8sPodContainerMetric {
|
||||
@ApiModelProperty(value = "容器名称")
|
||||
private String podName;
|
||||
|
||||
@ApiModelProperty(value = "指标值")
|
||||
private List<MetricCommonData> data;
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@Data
|
||||
@ApiModel("K8S容器运行状态监控总览")
|
||||
public class K8sPodContainerMetricOverview {
|
||||
@ApiModelProperty(value = "容器名称")
|
||||
private String podName;
|
||||
|
||||
@ApiModelProperty(value = "CPU使用率(单位:%)")
|
||||
private List<MetricCommonData> cpuUsage;
|
||||
|
||||
@ApiModelProperty(value = "内存使用情况(单位:byte,需前端换算)")
|
||||
private List<MetricCommonData> memoryUsage;
|
||||
|
||||
@ApiModelProperty(value = "磁盘写入情况(单位:byte/s,需前端换算)")
|
||||
private List<MetricCommonData> diskWrites;
|
||||
|
||||
@ApiModelProperty(value = "磁盘读取情况(单位:byte/s,需前端换算)")
|
||||
private List<MetricCommonData> diskReads;
|
||||
|
||||
@ApiModelProperty(value = "网络接收情况(单位:byte/s,需前端换算)")
|
||||
private List<MetricCommonData> networkReception;
|
||||
|
||||
@ApiModelProperty(value = "网络发送情况(单位:byte/s,需前端换算)")
|
||||
private List<MetricCommonData> networkTransmission;
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import com.microservices.mon.k8s.domain.vo.PrometheusResVo;
|
||||
import com.microservices.mon.k8s.domain.vo.PrometheusResultVo;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
|
||||
@Data
|
||||
@ApiModel("K8S容器状态")
|
||||
public class K8sPodContainerStatus {
|
||||
@ApiModelProperty(value = "容器名称")
|
||||
private String podName;
|
||||
|
||||
@ApiModelProperty(value = "CPU使用率")
|
||||
private Float cpuUsage;
|
||||
|
||||
@ApiModelProperty(value = "内存使用情况")
|
||||
private String memoryUsage;
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
|
||||
@Data
|
||||
@ApiModel("K8S容器启停时间")
|
||||
public class K8sPodStartStopDate {
|
||||
@ApiModelProperty(value = "容器名称")
|
||||
private String podName;
|
||||
|
||||
@ApiModelProperty(value = "启动时间")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private Date startDate;
|
||||
|
||||
@ApiModelProperty(value = "停止时间")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private Date stopDate;
|
||||
|
||||
private Boolean isRunning = true;
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@Data
|
||||
@ApiModel("K8S容器启停状态")
|
||||
public class K8sPodStartStopStatus {
|
||||
@ApiModelProperty(value = "启动数")
|
||||
private Integer startCount;
|
||||
|
||||
@ApiModelProperty(value = "总数")
|
||||
private Integer podCount;
|
||||
|
||||
@ApiModelProperty(value = "启停时间列表")
|
||||
private List<K8sPodStartStopDate> podStartStopDateList;
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@ApiModel("链路追踪应用")
|
||||
public class LinkTrackingApplication {
|
||||
@ApiModelProperty(value = "序号")
|
||||
private Integer index;
|
||||
@ApiModelProperty(value = "应用Id")
|
||||
private String id;
|
||||
@ApiModelProperty(value = "应用标识")
|
||||
private String key;
|
||||
@ApiModelProperty(value = "应用名称")
|
||||
private String applicationName;
|
||||
@ApiModelProperty(value = "负载")
|
||||
private Float load;
|
||||
@ApiModelProperty(value = "成功率")
|
||||
private Float successRate;
|
||||
@ApiModelProperty(value = "延迟")
|
||||
private Float latency;
|
||||
}
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@Data
|
||||
@ApiModel("指标通用对象")
|
||||
public class MetricCommonData {
|
||||
|
||||
@ApiModelProperty(value = "时间")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private Date date;
|
||||
|
||||
@ApiModelProperty(value = "指标值")
|
||||
private Float value;
|
||||
|
||||
public static List<MetricCommonData> prometheusResultVoToMetric(JSONArray prometheusResultValues) {
|
||||
List<MetricCommonData> metricCommonDataList = new ArrayList<>();
|
||||
for (int i = 0; i < prometheusResultValues.size(); i++) {
|
||||
JSONArray value = prometheusResultValues.getJSONArray(i);
|
||||
MetricCommonData metricCommonData = new MetricCommonData();
|
||||
metricCommonData.setDate(new Date(value.getLong(0) * 1000));
|
||||
String valueStr = String.format("%.2f", value.getFloatValue(1));
|
||||
metricCommonData.setValue(Float.parseFloat(valueStr));
|
||||
metricCommonDataList.add(metricCommonData);
|
||||
}
|
||||
metricCommonDataList.sort(Comparator.comparing(MetricCommonData::getDate));
|
||||
return metricCommonDataList;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
package com.microservices.mon.k8s.domain;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public enum SkywalkingMetricType {
|
||||
SERVICE_CPM("cpmFunction", "cpmVariable", "service_cpm"),
|
||||
SERVICE_SLA("slaFunction", "slaVariable", "service_sla"),
|
||||
SERVICE_RESP_TIME("respTimeFunction", "respTimeVariable", "service_resp_time");
|
||||
private final String functionName;
|
||||
private final String functionVariable;
|
||||
private final String metricKey;
|
||||
|
||||
SkywalkingMetricType(String functionName, String functionVariable, String metricKey) {
|
||||
this.functionName = functionName;
|
||||
this.functionVariable = functionVariable;
|
||||
this.metricKey = metricKey;
|
||||
}
|
||||
public String getFunctionVariable(Integer index) {
|
||||
return this.functionVariable+index;
|
||||
}
|
||||
public String getFunctionName(Integer index) {
|
||||
return this.functionName+index;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
package com.microservices.mon.k8s.domain.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* @author OTTO
|
||||
*/
|
||||
@Data
|
||||
public class ApplicationEnvTypeVo {
|
||||
private String key;
|
||||
private String alias;
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
package com.microservices.mon.k8s.domain.vo;
|
||||
|
||||
import com.microservices.common.core.exception.ServiceException;
|
||||
import com.microservices.common.core.utils.StringUtils;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* @author OTTO
|
||||
*/
|
||||
@Data
|
||||
public class ApplicationTypeVo {
|
||||
private String key;
|
||||
private String fullName;
|
||||
private String description;
|
||||
}
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
package com.microservices.mon.k8s.domain.vo;
|
||||
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class CommonTypeVo {
|
||||
|
||||
private String name;
|
||||
private String key;
|
||||
|
||||
public static List<CommonTypeVo> eventReasonListToCommonTypeVoList(JSONObject eventReasonListQueryRes) {
|
||||
List<CommonTypeVo> commonTypeVoList = new ArrayList<>();
|
||||
if (eventReasonListQueryRes != null && eventReasonListQueryRes.getJSONObject("aggregations") != null
|
||||
&& eventReasonListQueryRes.getJSONObject("aggregations").getJSONObject("distinct_reasons") != null
|
||||
&& eventReasonListQueryRes.getJSONObject("aggregations").getJSONObject("distinct_reasons").getJSONArray("buckets") != null) {
|
||||
JSONArray eventReasonList = eventReasonListQueryRes.getJSONObject("aggregations").getJSONObject("distinct_reasons").getJSONArray("buckets");
|
||||
for (int i = 0; i < eventReasonList.size(); i++) {
|
||||
JSONObject eventReason = eventReasonList.getJSONObject(i);
|
||||
CommonTypeVo commonTypeVo = new CommonTypeVo();
|
||||
commonTypeVo.setName(eventReason.getString("key"));
|
||||
commonTypeVo.setKey(eventReason.getString("key"));
|
||||
commonTypeVoList.add(commonTypeVo);
|
||||
}
|
||||
}
|
||||
return commonTypeVoList;
|
||||
}
|
||||
|
||||
public static List<CommonTypeVo> resourceObjectToCommonTypeVoList(List<PrometheusResultVo> resultList) {
|
||||
List<CommonTypeVo> commonTypeVoList = new ArrayList<>();
|
||||
for (PrometheusResultVo resultVo : resultList) {
|
||||
JSONObject metric = resultVo.getMetric();
|
||||
String nodeInstance = metric.getString("instance");
|
||||
String nodeIp = metric.getString("ip");
|
||||
CommonTypeVo commonTypeVo = new CommonTypeVo();
|
||||
commonTypeVo.setName(String.format("%s(%s)", nodeInstance, nodeIp));
|
||||
commonTypeVo.setKey(nodeIp);
|
||||
commonTypeVoList.add(commonTypeVo);
|
||||
}
|
||||
return commonTypeVoList;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
package com.microservices.mon.k8s.domain.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class PrometheusDataVo {
|
||||
// 查询结果类型
|
||||
String resultType;
|
||||
// 应用类型
|
||||
List<PrometheusResultVo> result;
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
package com.microservices.mon.k8s.domain.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class PrometheusResVo {
|
||||
// 状态(success代表成功)
|
||||
String status;
|
||||
// 数据
|
||||
PrometheusDataVo data;
|
||||
|
||||
public boolean isSuccess() {
|
||||
return "success".equals(status)
|
||||
&& data != null
|
||||
&& data.getResult() != null
|
||||
&& !data.getResult().isEmpty();
|
||||
}
|
||||
|
||||
public static String getPromStringValue(PrometheusResVo prometheusResVo) {
|
||||
String value = "";
|
||||
if (prometheusResVo != null && prometheusResVo.isSuccess()) {
|
||||
PrometheusResultVo result = prometheusResVo.getData().getResult().get(0);
|
||||
return result.getValue().getString(1);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public static List<PrometheusResultVo> getPrometheusResultVoList(PrometheusResVo prometheusResVo) {
|
||||
if (prometheusResVo != null && prometheusResVo.isSuccess()) {
|
||||
return prometheusResVo.getData().getResult();
|
||||
}
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
package com.microservices.mon.k8s.domain.vo;
|
||||
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class PrometheusResultVo {
|
||||
// 指标数据
|
||||
JSONObject metric;
|
||||
// 指标值
|
||||
JSONArray value;
|
||||
// 范围查询时指标值
|
||||
JSONArray values;
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
package com.microservices.mon.k8s.domain.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class RancherApplicationStateVo {
|
||||
|
||||
// Daemonsets-期望数量
|
||||
Integer desiredNumberScheduled;
|
||||
|
||||
// Daemonsets-就绪数量
|
||||
Integer numberReady;
|
||||
|
||||
// Deploy/Stateful-就绪副本数
|
||||
Integer readyReplicas;
|
||||
|
||||
// Stateful-有效副本数
|
||||
Integer availableReplicas;
|
||||
|
||||
// Deploy/Stateful-副本数量
|
||||
Integer replicas;
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,113 @@
|
|||
package com.microservices.mon.k8s.domain.vo;
|
||||
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.microservices.common.core.context.SecurityContextHolder;
|
||||
import com.microservices.common.core.utils.DateUtils;
|
||||
import com.microservices.common.core.utils.StringUtils;
|
||||
import com.microservices.common.core.utils.bean.BeanUtils;
|
||||
import com.microservices.mon.k8s.domain.K8sApplication;
|
||||
import com.microservices.mon.k8s.domain.K8sApplicationAndPodState;
|
||||
import com.microservices.mon.k8s.domain.K8sApplicationPod;
|
||||
import com.microservices.mon.k8s.utils.MonUtils;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Data
|
||||
public class RancherApplicationVo {
|
||||
// 标识
|
||||
String id;
|
||||
// 应用类型
|
||||
String kind;
|
||||
// 元数据
|
||||
RancherMetadataVo metadata;
|
||||
// 状态
|
||||
RancherApplicationStateVo status;
|
||||
// 规格
|
||||
JSONObject spec;
|
||||
|
||||
|
||||
public K8sApplication toK8sApplication() {
|
||||
K8sApplication target = new K8sApplication();
|
||||
BeanUtils.copyProperties(this, target);
|
||||
|
||||
if ("DaemonSet".equals(kind)) {
|
||||
target.setReplicas(status.getDesiredNumberScheduled());
|
||||
target.setReadyReplicas(status.getNumberReady());
|
||||
} else if ("StatefulSet".equals(kind)) {
|
||||
target.setReplicas(status.getReplicas());
|
||||
target.setReadyReplicas(status.getAvailableReplicas());
|
||||
} else {
|
||||
target.setReplicas(status.getReplicas());
|
||||
target.setReadyReplicas(status.getReadyReplicas());
|
||||
}
|
||||
|
||||
if (spec != null) {
|
||||
JSONObject templateObj = spec.getJSONObject("template");
|
||||
if (templateObj != null) {
|
||||
JSONObject specObj = templateObj.getJSONObject("spec");
|
||||
if (specObj != null) {
|
||||
JSONArray containersArray = specObj.getJSONArray("containers");
|
||||
if (containersArray != null && !containersArray.isEmpty()) {
|
||||
JSONObject firstContainer = containersArray.getJSONObject(0);
|
||||
if (firstContainer != null && firstContainer.containsKey("image")) {
|
||||
target.setDockerImage(firstContainer.getString("image"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (spec.containsKey("paused")) {
|
||||
target.setPaused(spec.getBoolean("paused"));
|
||||
} else {
|
||||
target.setPaused(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (metadata != null) {
|
||||
target.setName(metadata.getName());
|
||||
target.setAlias(metadata.getName());
|
||||
if (metadata.getAnnotations() != null && metadata.getAnnotations().containsKey("mon-name")) {
|
||||
target.setAlias(metadata.getAnnotations().getString("mon-name"));
|
||||
}
|
||||
|
||||
if (metadata.getState() != null) {
|
||||
target.setState(metadata.getState().toK8sApplicationState());
|
||||
}
|
||||
target.setSurvivalTime(
|
||||
MonUtils.getTimeDifferenceDescription(metadata.getCreationTimestamp())
|
||||
);
|
||||
target.setNamespace(metadata.getNamespace());
|
||||
|
||||
JSONArray relationships = metadata.getRelationships();
|
||||
for (int i = 0; i < relationships.size(); i++) {
|
||||
JSONObject relationship = relationships.getJSONObject(i);
|
||||
if (relationship.containsKey("toType") && "pod".equals(relationship.getString("toType"))) {
|
||||
String selector = relationship.getString("selector");
|
||||
if (StringUtils.isNotEmpty(selector) && selector.contains("=") && selector.split("=").length >= 2) {
|
||||
target.setPodSelector(selector);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(target.getReplicas()==null){
|
||||
target.setReplicas(0);
|
||||
}
|
||||
if(target.getReadyReplicas()==null){
|
||||
target.setReadyReplicas(0);
|
||||
}
|
||||
|
||||
if (target.getReplicas() == 0) {
|
||||
target.setState(K8sApplicationAndPodState.k8sApplicationStopState("stop"));
|
||||
}
|
||||
if(target.getPaused()){
|
||||
target.setState(K8sApplicationAndPodState.k8sApplicationStopState("paused"));
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
package com.microservices.mon.k8s.domain.vo;
|
||||
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class RancherClusterNodeStateVo {
|
||||
|
||||
// ip地址
|
||||
JSONArray addresses;
|
||||
|
||||
// 资源分配
|
||||
JSONObject allocatable;
|
||||
|
||||
// 节点状况
|
||||
JSONArray conditions;
|
||||
|
||||
// 节点信息
|
||||
JSONObject nodeInfo;
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
package com.microservices.mon.k8s.domain.vo;
|
||||
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.microservices.common.core.utils.bean.BeanUtils;
|
||||
import com.microservices.mon.k8s.domain.K8sApplication;
|
||||
import com.microservices.mon.k8s.domain.K8sClusterNode;
|
||||
import com.microservices.mon.k8s.domain.K8sNamespace;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
@Data
|
||||
public class RancherClusterNodeVo {
|
||||
// 标识
|
||||
String id;
|
||||
// 元数据
|
||||
RancherMetadataVo metadata;
|
||||
// 节点状态
|
||||
RancherClusterNodeStateVo status;
|
||||
|
||||
public K8sClusterNode toK8sClusterNode() {
|
||||
K8sClusterNode target = new K8sClusterNode();
|
||||
BeanUtils.copyProperties(this, target);
|
||||
if (metadata.getLabels() != null && metadata.getLabels().containsKey("node-role.kubernetes.io/control-plane")) {
|
||||
target.setRole("Master");
|
||||
}else{
|
||||
target.setRole("Worker");
|
||||
}
|
||||
target.setName(metadata.getName());
|
||||
if(status!=null&&status.getAddresses()!=null){
|
||||
JSONArray addresses=status.getAddresses();
|
||||
for (int i = 0; i < addresses.size(); i++) {
|
||||
JSONObject jsonObject = addresses.getJSONObject(i);
|
||||
if (jsonObject.getString("type").equals("InternalIP")) {
|
||||
target.setIp(jsonObject.getString("address"));
|
||||
}
|
||||
}
|
||||
JSONArray conditions=status.getConditions();
|
||||
for (int i = 0; i < conditions.size(); i++) {
|
||||
JSONObject jsonObject = conditions.getJSONObject(i);
|
||||
if (jsonObject.getString("type").equals("Ready")) {
|
||||
target.setReady(jsonObject.getBoolean("status"));
|
||||
}
|
||||
}
|
||||
}
|
||||
return target;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
package com.microservices.mon.k8s.domain.vo;
|
||||
|
||||
import com.microservices.mon.k8s.domain.K8sApplicationAndPodState;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class RancherMetadataState {
|
||||
// 是否错误
|
||||
Boolean error;
|
||||
// 状态消息
|
||||
String message;
|
||||
// 状态名称
|
||||
// 应用状态(name -> active、name -> updating、name -> in-progress、name -> error)
|
||||
// pod状态(name -> imagePullBackOff、name -> containerCreating)
|
||||
String name;
|
||||
// 是否过渡状态
|
||||
Boolean transitioning;
|
||||
|
||||
public K8sApplicationAndPodState toK8sApplicationState() {
|
||||
K8sApplicationAndPodState state = new K8sApplicationAndPodState();
|
||||
state.setName(name);
|
||||
state.setIsError(error);
|
||||
state.setMessage(message);
|
||||
state.setApplicationAliasByName(name);
|
||||
return state;
|
||||
}
|
||||
public K8sApplicationAndPodState toK8sPodState() {
|
||||
K8sApplicationAndPodState state = new K8sApplicationAndPodState();
|
||||
state.setName(name);
|
||||
state.setMessage(message);
|
||||
state.setPodAliasAndErrorByName(name);
|
||||
return state;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
package com.microservices.mon.k8s.domain.vo;
|
||||
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
@Data
|
||||
public class RancherMetadataVo {
|
||||
// 所属命名空间
|
||||
String namespace;
|
||||
// 创建时间
|
||||
Date creationTimestamp;
|
||||
// 描述
|
||||
JSONObject annotations;
|
||||
// 关联数据
|
||||
JSONArray relationships;
|
||||
// 标签
|
||||
JSONObject labels;
|
||||
// 名称
|
||||
String name;
|
||||
// 状态
|
||||
RancherMetadataState state;
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
package com.microservices.mon.k8s.domain.vo;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.microservices.common.core.utils.bean.BeanUtils;
|
||||
import com.microservices.mon.k8s.domain.K8sNamespace;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class RancherNamespaceVo {
|
||||
// 描述
|
||||
JSONObject annotations;
|
||||
//创建时间
|
||||
Date created;
|
||||
// 标识
|
||||
String id;
|
||||
// 标签
|
||||
JSONObject labels;
|
||||
// 名称
|
||||
String name;
|
||||
// 状态
|
||||
String state;
|
||||
|
||||
public K8sNamespace toK8sNamespace() {
|
||||
K8sNamespace target = new K8sNamespace();
|
||||
BeanUtils.copyProperties(this, target);
|
||||
target.setKey(labels.getString("mon-key"));
|
||||
target.setAlias(annotations.getString("mon-name"));
|
||||
return target;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
package com.microservices.mon.k8s.domain.vo;
|
||||
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class RancherPodStateVo {
|
||||
|
||||
// Pod状况
|
||||
JSONArray conditions;
|
||||
|
||||
// Pod Ip
|
||||
String podIP;
|
||||
|
||||
// 启动时间
|
||||
Date startTime;
|
||||
|
||||
// 容器状态
|
||||
List<JSONObject> containerStatuses;
|
||||
|
||||
// 运行阶段
|
||||
String phase;
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
package com.microservices.mon.k8s.domain.vo;
|
||||
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.microservices.common.core.utils.StringUtils;
|
||||
import com.microservices.common.core.utils.bean.BeanUtils;
|
||||
import com.microservices.mon.k8s.domain.K8sApplication;
|
||||
import com.microservices.mon.k8s.domain.K8sApplicationPod;
|
||||
import com.microservices.mon.k8s.utils.MonUtils;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class RancherPodVo {
|
||||
// 标识
|
||||
String id;
|
||||
// 元数据
|
||||
RancherMetadataVo metadata;
|
||||
// 状态
|
||||
RancherPodStateVo status;
|
||||
// 状态
|
||||
JSONObject spec;
|
||||
|
||||
public K8sApplicationPod toK8sApplicationPod() {
|
||||
K8sApplicationPod target = new K8sApplicationPod();
|
||||
BeanUtils.copyProperties(this, target);
|
||||
target.setIp(status.getPodIP());
|
||||
if (metadata != null) {
|
||||
target.setName(metadata.getName());
|
||||
if (metadata.getState() != null) {
|
||||
target.setState(metadata.getState().toK8sPodState());
|
||||
}
|
||||
if (metadata.getLabels() != null) {
|
||||
target.setStack(metadata.getLabels().getString("stack"));
|
||||
}
|
||||
target.setNamespace(metadata.getNamespace());
|
||||
target.setCreatedTime(metadata.getCreationTimestamp());
|
||||
}
|
||||
target.setIsRunning(false);
|
||||
if (status != null) {
|
||||
if (status.getContainerStatuses() != null && !status.getContainerStatuses().isEmpty()) {
|
||||
target.setRestartCount(status.getContainerStatuses().stream().mapToInt(x -> x.getInteger("restartCount")).sum());
|
||||
target.setReadyReplicas(Math.toIntExact(status.getContainerStatuses().stream().filter(x -> x.containsKey("ready") && x.getBoolean("ready")).count()));
|
||||
target.setReplicas(status.getContainerStatuses().size());
|
||||
}
|
||||
if (StringUtils.isNotEmpty(status.phase) && status.phase.equals("Running")) {
|
||||
target.setIsRunning(true);
|
||||
}
|
||||
}
|
||||
List<String> ports = new ArrayList<>();
|
||||
List<String> dockerImages = new ArrayList<>();
|
||||
if (spec != null) {
|
||||
if (spec.containsKey("containers")) {
|
||||
JSONArray containers = spec.getJSONArray("containers");
|
||||
for (int i = 0; i < containers.size(); i++) {
|
||||
JSONObject container = containers.getJSONObject(i);
|
||||
// 设置镜像
|
||||
if (container.containsKey("image")) {
|
||||
dockerImages.add(container.getString("image"));
|
||||
}
|
||||
// 设置端口
|
||||
if (container.containsKey("ports")) {
|
||||
JSONArray portsArray = container.getJSONArray("ports");
|
||||
for (int j = 0; j < portsArray.size(); j++) {
|
||||
JSONObject port = portsArray.getJSONObject(j);
|
||||
String containerPort = port.getString("containerPort");
|
||||
if (StringUtils.isNotEmpty(containerPort)) {
|
||||
ports.add(containerPort);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (spec.containsKey("serviceAccountName")) {
|
||||
target.setServiceAccountName(spec.getString("serviceAccountName"));
|
||||
}
|
||||
}
|
||||
target.setPorts(StringUtils.join(ports, ","));
|
||||
target.setDockerImage(StringUtils.join(dockerImages, ","));
|
||||
|
||||
target.setSurvivalTime(
|
||||
MonUtils.getTimeDifferenceDescription(metadata.getCreationTimestamp())
|
||||
);
|
||||
return target;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
package com.microservices.mon.k8s.domain.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class RancherServicePortsVo {
|
||||
|
||||
// 端口名称
|
||||
String name;
|
||||
|
||||
// 映射端口
|
||||
Integer nodePort;
|
||||
|
||||
// 内部端口
|
||||
Integer port;
|
||||
|
||||
// 协议
|
||||
String protocol;
|
||||
|
||||
// 目标端口
|
||||
String targetPort;
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
package com.microservices.mon.k8s.domain.vo;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class RancherServiceSpecVo {
|
||||
|
||||
// 端口映射列表
|
||||
List<RancherServicePortsVo> ports;
|
||||
JSONObject selector;
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
package com.microservices.mon.k8s.domain.vo;
|
||||
|
||||
import com.microservices.common.core.utils.bean.BeanUtils;
|
||||
import com.microservices.mon.k8s.domain.K8sApplication;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class RancherServiceVo {
|
||||
// 标识
|
||||
String id;
|
||||
// 元数据
|
||||
RancherMetadataVo metadata;
|
||||
// 规格
|
||||
RancherServiceSpecVo spec;
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
package com.microservices.mon.k8s.service;
|
||||
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.microservices.mon.k8s.domain.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface IK8sDashboardService {
|
||||
List<K8sNamespace> getNamespaceDetailList(boolean needPod, String search);
|
||||
|
||||
List<K8sClusterNode> getClusterNodeList();
|
||||
|
||||
List<String> getApplicationPodIdList(String kind, String namespace,String applicationName);
|
||||
|
||||
K8sClusterStatus getClusterStatus();
|
||||
|
||||
List<MetricCommonData> getClusterQps();
|
||||
|
||||
List<ApplicationRequestCountData> getApplicationRequestCount();
|
||||
|
||||
K8sPodContainerStatus getPodContainerStatus(String podName);
|
||||
|
||||
K8sNodeStatus getNodeStatus(String nodeIp);
|
||||
|
||||
List<ApplicationFunction> getApplicationFunction(String kind, String namespace, String applicationName, String podIpList);
|
||||
|
||||
List<K8sNamespace> getK8sNamespaceList();
|
||||
|
||||
List<MetricCommonData> getMetricCommonDataList(JSONObject metricResJson);
|
||||
|
||||
JSONArray getSentinelAppList();
|
||||
}
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
package com.microservices.mon.k8s.service;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.microservices.common.core.web.page.GenericsTableDataInfo;
|
||||
import com.microservices.mon.k8s.domain.*;
|
||||
import com.microservices.mon.k8s.domain.vo.ApplicationEnvTypeVo;
|
||||
import com.microservices.mon.k8s.domain.vo.ApplicationTypeVo;
|
||||
import com.microservices.mon.k8s.domain.vo.CommonTypeVo;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
public interface IMicroManagementService {
|
||||
List<K8sApplicationPod> getPodList();
|
||||
|
||||
K8sPodContainerMetricOverview getPodStatus(String podName, Long step);
|
||||
|
||||
K8sApplication getApplicationDetail(String kind, String namespace, String applicationName);
|
||||
|
||||
Boolean deletePod(String namespace, String podName, Boolean isForce);
|
||||
|
||||
List<K8sApplicationPod> getK8sApplicationPodList(K8sApplication k8sApplication);
|
||||
|
||||
Boolean operateApplication(String kind, String namespace, String applicationName, String operationKey);
|
||||
|
||||
List<ApplicationTypeVo> getApplicationTypeList();
|
||||
|
||||
String createApplication(String kind, String yamlContent);
|
||||
|
||||
JSONObject getApplicationYamlFile(String kind, String namespace, String applicationName);
|
||||
|
||||
Boolean editApplication(String kind, String namespace, String applicationName, String yamlContent);
|
||||
|
||||
Boolean deleteApplication(String kind, String namespace, String applicationName);
|
||||
|
||||
List<K8sApplicationEnv> getApplicationEnv(String kind, String namespace, String applicationName);
|
||||
|
||||
List<K8sApplicationEnvOptionalParameter> getEnvOptionalParameters(String namespace);
|
||||
|
||||
Boolean updateApplicationEnv(String kind, String namespace, String applicationName, List<K8sApplicationEnv> k8sApplicationEnvList);
|
||||
|
||||
List<ApplicationEnvTypeVo> getEnvTypes();
|
||||
|
||||
List<GatewayRouteConfig> getGatewayRouteConfig();
|
||||
|
||||
GatewaySafetyConfig getGatewaySafetyConfig();
|
||||
|
||||
GatewayWhitelistConfig getGatewayWhitelistConfig();
|
||||
|
||||
Boolean updateGatewayRouteConfig(List<GatewayRouteConfig> gatewayRouteConfigList);
|
||||
|
||||
Boolean updateGatewaySafetyConfig(GatewaySafetyConfig gatewaySafetyConfig);
|
||||
|
||||
Boolean updateGatewayWhitelistConfig(GatewayWhitelistConfig gatewayWhitelistConfig);
|
||||
|
||||
List<String> getExceptionHandingDateList();
|
||||
|
||||
List<String> getExceptionHandingRecordList(String date);
|
||||
|
||||
List<LinkTrackingApplication> getLinkTrackingList(String applicationName);
|
||||
|
||||
JSONObject getGatewayFlowLimitingPara();
|
||||
|
||||
GenericsTableDataInfo<K8SEvent> getK8SEventList(String eventType, String reason, Date startTime, Date endTime, Boolean isAscOrderByOccurredTime, Integer pageNum, Integer pageSize);
|
||||
|
||||
List<K8SResourceUsage> getResourceUsageList(String resourceObject, Date startTime, Date endTime);
|
||||
|
||||
List<CommonTypeVo> getK8SEventReasonList(String eventType);
|
||||
|
||||
List<CommonTypeVo> getResourceObjectList();
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
package com.microservices.mon.k8s.service;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.microservices.mon.k8s.domain.*;
|
||||
import com.microservices.mon.k8s.domain.vo.ApplicationEnvTypeVo;
|
||||
import com.microservices.mon.k8s.domain.vo.ApplicationTypeVo;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface IMicroStatusService {
|
||||
K8sPodStartStopStatus getPodStartStopStatus();
|
||||
|
||||
List<K8sPodContainerMetric> getPodCpuUsage(Long step);
|
||||
|
||||
List<K8sPodContainerMetric> getPodMemoryUsage(Long step);
|
||||
|
||||
List<K8sPodContainerMetric> getPodDiskReads(Long step);
|
||||
|
||||
List<K8sPodContainerMetric> getPodDiskWrites(Long step);
|
||||
|
||||
List<K8sPodContainerMetric> getPodNetworkReception(Long step);
|
||||
|
||||
List<K8sPodContainerMetric> getPodNetworkTransmission(Long step);
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
package com.microservices.mon.k8s.service;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.microservices.mon.k8s.domain.*;
|
||||
import com.microservices.mon.k8s.domain.vo.PrometheusResultVo;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 运维监控Service异步接口
|
||||
*/
|
||||
public interface IMonCommonAsyncService {
|
||||
|
||||
K8sClusterStatus getClusterStatus(String query);
|
||||
|
||||
List<K8sNamespace> getNamespaceDetailList(boolean needPod, String search);
|
||||
|
||||
List<K8sApplicationPod> getPodList();
|
||||
|
||||
K8sPodContainerMetricOverview getPodStatus(String podName, Long step);
|
||||
|
||||
List<K8SResourceUsage> getResourceUsageList(List<JSONObject> metricList, Date[] startAndEndDates, Long step);
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
package com.microservices.mon.k8s.service.impl;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public abstract class CommonService {
|
||||
@Value("${rancher.cluster_id}")
|
||||
public String cluster_id;
|
||||
|
||||
@Value("${rancher.nginxApplicationId}")
|
||||
public String nginxApplicationId;
|
||||
|
||||
@Value("${skywalking.group}")
|
||||
public String skywalkingGroup;
|
||||
|
||||
@Value("${nacos.gatewayConfigId}")
|
||||
public String nacosGatewayConfigId;
|
||||
|
||||
@Value("${nacos.defaultGroup}")
|
||||
public String nacosDefaultGroup;
|
||||
|
||||
@Value("${gateway.logPath}")
|
||||
public String gatewayLogPath;
|
||||
|
||||
@Value("${elasticsearch.k8sEventIndex}")
|
||||
public String esK8sEventIndex;
|
||||
}
|
||||
|
|
@ -0,0 +1,364 @@
|
|||
package com.microservices.mon.k8s.service.impl;
|
||||
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.microservices.common.core.context.SecurityContextHolder;
|
||||
import com.microservices.common.core.utils.DateUtils;
|
||||
import com.microservices.common.core.utils.StringUtils;
|
||||
import com.microservices.mon.k8s.domain.*;
|
||||
import com.microservices.mon.k8s.domain.vo.*;
|
||||
import com.microservices.mon.k8s.service.IK8sDashboardService;
|
||||
import com.microservices.mon.k8s.service.IMonCommonAsyncService;
|
||||
import com.microservices.mon.k8s.utils.PromQLConstant;
|
||||
import com.microservices.mon.k8s.utils.RancherResponseHandler;
|
||||
import com.microservices.mon.k8s.utils.SkywalkingGQLConstant;
|
||||
import com.microservices.system.api.RemoteGatewayService;
|
||||
import com.microservices.system.api.RemoteRancherService;
|
||||
import com.microservices.system.api.model.GraphqlQueryVo;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cloud.context.config.annotation.RefreshScope;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@RefreshScope
|
||||
public class K8SDashboardServiceImpl extends CommonService implements IK8sDashboardService {
|
||||
@Autowired
|
||||
private RemoteRancherService remoteRancherService;
|
||||
@Autowired
|
||||
private IMonCommonAsyncService monCommonAsyncService;
|
||||
@Autowired
|
||||
private RemoteGatewayService remoteGatewayService;
|
||||
|
||||
@Override
|
||||
public List<K8sNamespace> getNamespaceDetailList(boolean needPod, String search) {
|
||||
return monCommonAsyncService.getNamespaceDetailList(needPod, search);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<K8sClusterNode> getClusterNodeList() {
|
||||
List<RancherClusterNodeVo> rancherClusterNodeVoList;
|
||||
//调用rancher远程接口获取集群节点列表
|
||||
JSONObject clusterNodeJsonObject = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sClusterNodeList(cluster_id, SecurityContextHolder.getUserKey()), "获取K8S集群节点");
|
||||
if (clusterNodeJsonObject != null && clusterNodeJsonObject.containsKey("data")) {
|
||||
rancherClusterNodeVoList = clusterNodeJsonObject.getJSONArray("data").toList(RancherClusterNodeVo.class);
|
||||
return rancherClusterNodeVoList.stream().map(RancherClusterNodeVo::toK8sClusterNode).collect(Collectors.toList());
|
||||
}
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getApplicationPodIdList(String kind, String namespace, String applicationName) {
|
||||
ApplicationType applicationType = ApplicationType.getApplicationTypeByKey(kind);
|
||||
JSONObject applicationJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sApplicationDetail(cluster_id, applicationType.getFullName(), namespace, applicationName, SecurityContextHolder.getUserKey()), "获取应用详情");
|
||||
RancherApplicationVo rancherApplicationVo = applicationJson.toJavaObject(RancherApplicationVo.class);
|
||||
if (rancherApplicationVo != null && rancherApplicationVo.getMetadata() != null && rancherApplicationVo.getMetadata().getRelationships() != null) {
|
||||
JSONArray relationships = rancherApplicationVo.getMetadata().getRelationships();
|
||||
for (int i = 0; i < relationships.size(); i++) {
|
||||
JSONObject relationship = relationships.getJSONObject(i);
|
||||
if (relationship.containsKey("toType") && "pod".equals(relationship.getString("toType"))) {
|
||||
String selector = relationship.getString("selector");
|
||||
if (StringUtils.isNotEmpty(selector) && selector.contains("app=")) {
|
||||
String appName = selector.substring(selector.indexOf("=") + 1);
|
||||
JSONObject podListJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sPodListByNamespace(cluster_id, namespace, SecurityContextHolder.getUserKey()), "获取容器列表");
|
||||
if (podListJson != null && podListJson.containsKey("data")) {
|
||||
List<RancherPodVo> rancherPodVoList = podListJson.getJSONArray("data").toList(RancherPodVo.class);
|
||||
List<RancherPodVo> applicationToPodList = rancherPodVoList.stream()
|
||||
.filter(rancherPodVo -> rancherPodVo.getMetadata().getLabels().containsKey("app") && rancherPodVo.getMetadata().getLabels().get("app").equals(appName))
|
||||
.collect(Collectors.toList());
|
||||
return applicationToPodList.stream().map(x -> x.getStatus().getPodIP()).collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public K8sClusterStatus getClusterStatus() {
|
||||
return monCommonAsyncService.getClusterStatus(PromQLConstant.CLUSTER_NODE_COUNT(cluster_id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<MetricCommonData> getClusterQps() {
|
||||
Date now = DateUtils.getNowDate();
|
||||
long endTime = now.getTime() / 1000;
|
||||
// 开始时间为当前时间减去1小时
|
||||
Long startTime = now.getTime() / 1000 - 60 * 60;
|
||||
JSONObject metricResJson = remoteGatewayService.getPrometheusQueryRangeRes(PromQLConstant.CLUSTER_QPS, 14L, startTime, endTime, SecurityContextHolder.getUserKey());
|
||||
List<MetricCommonData> metricCommonDataList = getMetricCommonDataList(metricResJson);
|
||||
if (metricCommonDataList.isEmpty()) {
|
||||
for (int i = 0; i < 7; i++) {
|
||||
MetricCommonData metricCommonData = new MetricCommonData();
|
||||
metricCommonData.setDate(new Date(endTime * 1000));
|
||||
metricCommonData.setValue(0F);
|
||||
metricCommonDataList.add(metricCommonData);
|
||||
endTime -= 60 * 10;
|
||||
}
|
||||
}
|
||||
metricCommonDataList.sort(Comparator.comparing(MetricCommonData::getDate));
|
||||
return metricCommonDataList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ApplicationRequestCountData> getApplicationRequestCount() {
|
||||
List<ApplicationRequestCountData> applicationRequestCountDataList = new ArrayList<>();
|
||||
HashMap<String, String> portMap = new HashMap<>();
|
||||
JSONObject nginxSvcJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sServiceByApplicationId(cluster_id, nginxApplicationId, SecurityContextHolder.getUserKey()), "获取统一请求入口服务");
|
||||
if (nginxSvcJson != null) {
|
||||
RancherServiceVo rancherServiceVo = nginxSvcJson.toJavaObject(RancherServiceVo.class);
|
||||
for (RancherServicePortsVo rancherServicePortsVo : rancherServiceVo.getSpec().getPorts()) {
|
||||
// 获取端口描述
|
||||
String portAlias = rancherServiceVo.getMetadata().getAnnotations().getString(rancherServicePortsVo.getName());
|
||||
portMap.put(String.valueOf(rancherServicePortsVo.getPort()), portAlias);
|
||||
}
|
||||
}
|
||||
JSONObject applicationRequestCountJson = remoteGatewayService.getPrometheusQueryRes(PromQLConstant.APPLICATION_REQUEST_COUNT, SecurityContextHolder.getUserKey());
|
||||
if (applicationRequestCountJson != null) {
|
||||
PrometheusResVo prometheusResVo = applicationRequestCountJson.toJavaObject(PrometheusResVo.class);
|
||||
if (prometheusResVo != null && prometheusResVo.isSuccess()) {
|
||||
List<PrometheusResultVo> resultList = prometheusResVo.getData().getResult();
|
||||
int number = 1;
|
||||
for (PrometheusResultVo result : resultList) {
|
||||
ApplicationRequestCountData applicationRequestCountData = new ApplicationRequestCountData();
|
||||
applicationRequestCountData.setNumber(number++);
|
||||
JSONObject metric = result.getMetric();
|
||||
String port = metric.getString("server_port");
|
||||
applicationRequestCountData.setApplicationAlias(port);
|
||||
if (portMap.containsKey(port)) {
|
||||
applicationRequestCountData.setApplicationAlias(portMap.get(port));
|
||||
}
|
||||
Long value = result.getValue().getLongValue(1);
|
||||
applicationRequestCountData.setRequestCount(value);
|
||||
applicationRequestCountDataList.add(applicationRequestCountData);
|
||||
}
|
||||
}
|
||||
}
|
||||
return applicationRequestCountDataList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public K8sPodContainerStatus getPodContainerStatus(String podName) {
|
||||
K8sPodContainerStatus k8sPodContainerStatus = new K8sPodContainerStatus();
|
||||
k8sPodContainerStatus.setPodName(podName);
|
||||
JSONObject cpuUsageJson = remoteGatewayService.getPrometheusQueryRes(PromQLConstant.POD_CPU_USAGE(podName), SecurityContextHolder.getUserKey());
|
||||
PrometheusResVo cpuPrometheusResVo = cpuUsageJson.toJavaObject(PrometheusResVo.class);
|
||||
if (cpuPrometheusResVo != null && cpuPrometheusResVo.isSuccess()) {
|
||||
PrometheusResultVo result = cpuPrometheusResVo.getData().getResult().get(0);
|
||||
k8sPodContainerStatus.setCpuUsage(result.getValue().getFloatValue(1));
|
||||
}
|
||||
JSONObject memoryUsageJson = remoteGatewayService.getPrometheusQueryRes(PromQLConstant.POD_MEMORY_USAGE(podName), SecurityContextHolder.getUserKey());
|
||||
PrometheusResVo memoryPrometheusResVo = memoryUsageJson.toJavaObject(PrometheusResVo.class);
|
||||
if (memoryPrometheusResVo != null && memoryPrometheusResVo.isSuccess()) {
|
||||
PrometheusResultVo result = memoryPrometheusResVo.getData().getResult().get(0);
|
||||
Long memoryByte = result.getValue().getLong(1);
|
||||
float memoryMb = (float) memoryByte / 1024 / 1024;
|
||||
if (memoryMb > 1024) {
|
||||
k8sPodContainerStatus.setMemoryUsage(String.format("%.2f GiB", memoryMb / 1024));
|
||||
} else {
|
||||
k8sPodContainerStatus.setMemoryUsage(String.format("%.2f mib", memoryMb));
|
||||
}
|
||||
}
|
||||
return k8sPodContainerStatus;
|
||||
}
|
||||
|
||||
@Override
|
||||
public K8sNodeStatus getNodeStatus(String nodeIp) {
|
||||
K8sNodeStatus k8sNodeStatus = new K8sNodeStatus();
|
||||
k8sNodeStatus.setNodeIp(nodeIp);
|
||||
JSONObject cpuUsageJson = remoteGatewayService.getPrometheusQueryRes(PromQLConstant.NODE_CPU_USAGE(nodeIp), SecurityContextHolder.getUserKey());
|
||||
PrometheusResVo cpuPrometheusResVo = cpuUsageJson.toJavaObject(PrometheusResVo.class);
|
||||
if (cpuPrometheusResVo != null && cpuPrometheusResVo.isSuccess()) {
|
||||
PrometheusResultVo result = cpuPrometheusResVo.getData().getResult().get(0);
|
||||
k8sNodeStatus.setCpuUsage(result.getValue().getFloatValue(1));
|
||||
}
|
||||
JSONObject memoryUsageJson = remoteGatewayService.getPrometheusQueryRes(PromQLConstant.NODE_MEMORY_USAGE(nodeIp), SecurityContextHolder.getUserKey());
|
||||
PrometheusResVo memoryPrometheusResVo = memoryUsageJson.toJavaObject(PrometheusResVo.class);
|
||||
if (memoryPrometheusResVo != null && memoryPrometheusResVo.isSuccess()) {
|
||||
PrometheusResultVo result = memoryPrometheusResVo.getData().getResult().get(0);
|
||||
k8sNodeStatus.setMemoryUsage(result.getValue().getFloatValue(1));
|
||||
}
|
||||
return k8sNodeStatus;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ApplicationFunction> getApplicationFunction(String kind, String namespace, String applicationName, String podIpList) {
|
||||
ApplicationType applicationType = ApplicationType.getApplicationTypeByKey(kind);
|
||||
List<ApplicationFunction> applicationFunctionsList = new ArrayList<>();
|
||||
JSONObject applicationJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sApplicationDetail(cluster_id, applicationType.getFullName(), namespace, applicationName, SecurityContextHolder.getUserKey()), "获取应用详情");
|
||||
if (applicationJson == null) {
|
||||
return applicationFunctionsList;
|
||||
}
|
||||
RancherApplicationVo rancherApplicationVo = applicationJson.toJavaObject(RancherApplicationVo.class);
|
||||
if (rancherApplicationVo != null) {
|
||||
K8sApplication k8sApplication = rancherApplicationVo.toK8sApplication();
|
||||
// 所有应用添加启停管理功能
|
||||
ApplicationFunction applicationFunction = new ApplicationFunction();
|
||||
applicationFunction.setKeyAndName(ApplicationFunctionType.START_AND_STOP_MANAGEMENT);
|
||||
JSONObject functionVariables = new JSONObject();
|
||||
functionVariables.put("namespace", namespace);
|
||||
functionVariables.put("applicationName", applicationName);
|
||||
functionVariables.put("operationList", ApplicationStartAndStopType.getOperationList(kind, k8sApplication));
|
||||
applicationFunction.setVariables(functionVariables);
|
||||
applicationFunctionsList.add(applicationFunction);
|
||||
|
||||
// 根据应用POD Ip在Nacos上检查监听的配置列表,如果存在配置则增加配置管理按钮
|
||||
List<JSONObject> configList = new ArrayList<>();
|
||||
String[] podIpStr = podIpList.split(",");
|
||||
for (String podIp : podIpStr) {
|
||||
JSONObject nacosConfigListResJson = remoteGatewayService.getNacosConfigList(podIp, SecurityContextHolder.getUserKey());
|
||||
if (nacosConfigListResJson.containsKey("collectStatus") && 200 == nacosConfigListResJson.getIntValue("collectStatus")) {
|
||||
JSONObject nacosConfigListJson = nacosConfigListResJson.getJSONObject("lisentersGroupkeyStatus");
|
||||
for (String key : nacosConfigListJson.keySet()) {
|
||||
String nacosConfigMd5 = nacosConfigListJson.getString(key);
|
||||
if (!StringUtils.isEmpty(nacosConfigMd5) && configList.stream().noneMatch(x -> nacosConfigMd5.equals(x.getString("configMd5")))) {
|
||||
String[] configNames = key.split("\\+");
|
||||
JSONObject config = new JSONObject();
|
||||
config.put("configName", configNames[0]);
|
||||
config.put("configMd5", nacosConfigMd5);
|
||||
config.put("configGroup", configNames[1]);
|
||||
configList.add(config);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!configList.isEmpty()) {
|
||||
// 检查应用是否有配置管理功能
|
||||
applicationFunction = new ApplicationFunction();
|
||||
applicationFunction.setKeyAndName(ApplicationFunctionType.CONFIGURATION_MANAGEMENT);
|
||||
functionVariables = new JSONObject();
|
||||
functionVariables.put("configList", configList);
|
||||
applicationFunction.setVariables(functionVariables);
|
||||
applicationFunctionsList.add(applicationFunction);
|
||||
}
|
||||
|
||||
|
||||
if (rancherApplicationVo.getMetadata() != null && rancherApplicationVo.getMetadata().getLabels() != null) {
|
||||
JSONObject LabelsJson = rancherApplicationVo.getMetadata().getLabels();
|
||||
for (String key : LabelsJson.keySet()) {
|
||||
String k8sLabelValue = LabelsJson.getString(key);
|
||||
ApplicationFunctionType applicationFunctionType = ApplicationFunctionType.getByLabelsKey(key);
|
||||
if (applicationFunctionType != null) {
|
||||
switch (applicationFunctionType) {
|
||||
case LINK_TRACKING:
|
||||
// 处理应用链路追踪功能相关逻辑
|
||||
GraphqlQueryVo gqlQueryVo = SkywalkingGQLConstant.getAllServicesByGroup(skywalkingGroup);
|
||||
JSONObject skywalkingServices = remoteGatewayService.executeSkywalkingGql(gqlQueryVo);
|
||||
if (skywalkingServices != null
|
||||
&& skywalkingServices.getJSONObject("data") != null
|
||||
&& skywalkingServices.getJSONObject("data").getJSONArray(gqlQueryVo.getOperationName()) != null) {
|
||||
JSONArray skywalkingServicesArray = skywalkingServices.getJSONObject("data").getJSONArray(gqlQueryVo.getOperationName());
|
||||
for (int i = 0; i < skywalkingServicesArray.size(); i++) {
|
||||
JSONObject skywalkingService = skywalkingServicesArray.getJSONObject(i);
|
||||
if (k8sLabelValue.equals(skywalkingService.getString("shortName"))) {
|
||||
applicationFunction = new ApplicationFunction();
|
||||
applicationFunction.setKeyAndName(applicationFunctionType);
|
||||
functionVariables = new JSONObject();
|
||||
functionVariables.put("serviceId", skywalkingService.getString("id"));
|
||||
applicationFunction.setVariables(functionVariables);
|
||||
applicationFunctionsList.add(applicationFunction);
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
case FLOW_CONTROL:
|
||||
// 处理应用流量控制功能相关逻辑
|
||||
JSONArray sentinelAppListArray = getSentinelAppList();
|
||||
for (int i = 0; i < sentinelAppListArray.size(); i++) {
|
||||
JSONObject sentinelApp = sentinelAppListArray.getJSONObject(i);
|
||||
if (k8sLabelValue.equals(sentinelApp.getString("app"))) {
|
||||
applicationFunction = new ApplicationFunction();
|
||||
applicationFunction.setKeyAndName(applicationFunctionType);
|
||||
functionVariables = new JSONObject();
|
||||
functionVariables.put("app", k8sLabelValue);
|
||||
functionVariables.put("appType", sentinelApp.getLongValue("appType"));
|
||||
applicationFunction.setVariables(functionVariables);
|
||||
applicationFunctionsList.add(applicationFunction);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case REGISTRATION_CENTER:
|
||||
// 处理应用注册中心功能相关逻辑
|
||||
JSONObject nacosServiceList = remoteGatewayService.getNacosServiceList(k8sLabelValue, SecurityContextHolder.getUserKey());
|
||||
if (nacosServiceList != null && nacosServiceList.getJSONArray("serviceList") != null && !nacosServiceList.getJSONArray("serviceList").isEmpty()) {
|
||||
JSONArray nacosServiceListArray = nacosServiceList.getJSONArray("serviceList");
|
||||
for (int i = 0; i < nacosServiceListArray.size(); i++) {
|
||||
JSONObject nacosService = nacosServiceListArray.getJSONObject(i);
|
||||
if (k8sLabelValue.equals(nacosService.getString("name"))) {
|
||||
applicationFunction = new ApplicationFunction();
|
||||
applicationFunction.setKeyAndName(applicationFunctionType);
|
||||
functionVariables = new JSONObject();
|
||||
functionVariables.put("name", k8sLabelValue);
|
||||
applicationFunction.setVariables(functionVariables);
|
||||
applicationFunctionsList.add(applicationFunction);
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
case GATEWAY_MANAGEMENT:
|
||||
// 处理应用网关管理功能相关逻辑
|
||||
applicationFunction = new ApplicationFunction();
|
||||
applicationFunction.setKeyAndName(applicationFunctionType);
|
||||
functionVariables = new JSONObject();
|
||||
functionVariables.put("dataId", nacosGatewayConfigId);
|
||||
functionVariables.put("group", nacosDefaultGroup);
|
||||
applicationFunction.setVariables(functionVariables);
|
||||
applicationFunctionsList.add(applicationFunction);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return applicationFunctionsList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<K8sNamespace> getK8sNamespaceList() {
|
||||
List<K8sNamespace> k8sNamespaceList = new ArrayList<>();
|
||||
List<RancherNamespaceVo> rancherNamespaceVoList;
|
||||
//调用rancher远程接口获取所有命名空间列表
|
||||
JSONObject namespaceJsonObject = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sNamespaceList(cluster_id, SecurityContextHolder.getUserKey()), "获取K8S命名空间列表");
|
||||
if (namespaceJsonObject != null && namespaceJsonObject.containsKey("data")) {
|
||||
rancherNamespaceVoList = namespaceJsonObject.getJSONArray("data").toList(RancherNamespaceVo.class);
|
||||
for (RancherNamespaceVo rancherNamespaceVo : rancherNamespaceVoList) {
|
||||
// 仅获取拥有mon-key标签的命名空间
|
||||
if (rancherNamespaceVo.getLabels().containsKey("mon-key")) {
|
||||
K8sNamespace k8sNamespace = rancherNamespaceVo.toK8sNamespace();
|
||||
k8sNamespaceList.add(k8sNamespace);
|
||||
}
|
||||
}
|
||||
}
|
||||
return k8sNamespaceList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<MetricCommonData> getMetricCommonDataList(JSONObject metricResJson) {
|
||||
List<MetricCommonData> metricCommonDataList = new ArrayList<>();
|
||||
if (metricResJson != null && metricResJson.containsKey("data")) {
|
||||
PrometheusResVo prometheusResVo = metricResJson.toJavaObject(PrometheusResVo.class);
|
||||
if (prometheusResVo != null && prometheusResVo.isSuccess()) {
|
||||
PrometheusResultVo prometheusResultVo = prometheusResVo.getData().getResult().get(0);
|
||||
if (prometheusResultVo.getValues() != null) {
|
||||
metricCommonDataList = MetricCommonData.prometheusResultVoToMetric(prometheusResultVo.getValues());
|
||||
}
|
||||
}
|
||||
}
|
||||
return metricCommonDataList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONArray getSentinelAppList() {
|
||||
JSONObject sentinelAppList = remoteGatewayService.getSentinelAppList(SecurityContextHolder.getUserKey());
|
||||
if (sentinelAppList != null && sentinelAppList.containsKey("success") && sentinelAppList.getBoolean("success")) {
|
||||
JSONArray sentinelAppListArray = sentinelAppList.getJSONArray("data");
|
||||
if (sentinelAppListArray != null && !sentinelAppList.getJSONArray("data").isEmpty()) {
|
||||
return sentinelAppListArray;
|
||||
}
|
||||
}
|
||||
return new JSONArray();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,980 @@
|
|||
package com.microservices.mon.k8s.service.impl;
|
||||
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
|
||||
import com.microservices.common.core.context.SecurityContextHolder;
|
||||
import com.microservices.common.core.exception.ServiceException;
|
||||
import com.microservices.common.core.utils.DateUtils;
|
||||
import com.microservices.common.core.utils.StringUtils;
|
||||
import com.microservices.common.core.web.page.GenericsTableDataInfo;
|
||||
import com.microservices.mon.k8s.domain.*;
|
||||
import com.microservices.mon.k8s.domain.vo.*;
|
||||
import com.microservices.mon.k8s.service.IK8sDashboardService;
|
||||
import com.microservices.mon.k8s.service.IMicroManagementService;
|
||||
import com.microservices.mon.k8s.service.IMonCommonAsyncService;
|
||||
import com.microservices.mon.k8s.utils.*;
|
||||
import com.microservices.system.api.RemoteGatewayService;
|
||||
import com.microservices.system.api.RemoteRancherService;
|
||||
import com.microservices.system.api.model.GraphqlQueryVo;
|
||||
import com.microservices.system.api.utils.FeignUtils;
|
||||
import feign.Response;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cloud.context.config.annotation.RefreshScope;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RefreshScope
|
||||
public class MicroManagementServiceImpl extends CommonService implements IMicroManagementService {
|
||||
@Autowired
|
||||
private IMonCommonAsyncService monCommonAsyncService;
|
||||
@Autowired
|
||||
@Lazy
|
||||
private IK8sDashboardService dashboardService;
|
||||
@Autowired
|
||||
private RemoteRancherService remoteRancherService;
|
||||
@Autowired
|
||||
private RemoteGatewayService remoteGatewayService;
|
||||
|
||||
|
||||
@Override
|
||||
public List<K8sApplicationPod> getPodList() {
|
||||
return monCommonAsyncService.getPodList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public K8sPodContainerMetricOverview getPodStatus(String podName, Long step) {
|
||||
return monCommonAsyncService.getPodStatus(podName, step);
|
||||
}
|
||||
|
||||
@Override
|
||||
public K8sApplication getApplicationDetail(String kind, String namespace, String applicationName) {
|
||||
ApplicationType applicationType = ApplicationType.getApplicationTypeByKey(kind);
|
||||
K8sApplication k8sApplication = new K8sApplication();
|
||||
JSONObject applicationJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sApplicationDetail(cluster_id, applicationType.getFullName(), namespace, applicationName, SecurityContextHolder.getUserKey()), "获取应用详情");
|
||||
if (applicationJson == null) {
|
||||
return k8sApplication;
|
||||
}
|
||||
RancherApplicationVo rancherApplicationVo = applicationJson.toJavaObject(RancherApplicationVo.class);
|
||||
k8sApplication = rancherApplicationVo.toK8sApplication();
|
||||
|
||||
// 获取应用下pod列表
|
||||
List<K8sApplicationPod> podList = getK8sApplicationPodList(k8sApplication);
|
||||
k8sApplication.setPodList(podList);
|
||||
k8sApplication.setRestartCount(podList.stream().filter(x -> x.getRestartCount() != null).mapToInt(K8sApplicationPod::getRestartCount).sum());
|
||||
return k8sApplication;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean deletePod(String namespace, String podName, Boolean isForce) {
|
||||
JSONObject deletePodBody = new JSONObject();
|
||||
if (isForce != null && isForce) {
|
||||
deletePodBody.put("force", true);
|
||||
deletePodBody.put("gracePeriod", 0);
|
||||
}
|
||||
try (Response response = remoteRancherService.deletePod(namespace, podName, deletePodBody, SecurityContextHolder.getUserKey())) {
|
||||
return RancherResponseHandler.handleBoolean(response, "删除容器");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<K8sApplicationPod> getK8sApplicationPodList(K8sApplication k8sApplication) {
|
||||
// 获取命名空间下pod列表
|
||||
JSONObject podListJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sPodListByNamespace(cluster_id, k8sApplication.getNamespace(), SecurityContextHolder.getUserKey()), "获取应用下容器列表");
|
||||
List<RancherPodVo> rancherPodVoList;
|
||||
if (podListJson != null && podListJson.containsKey("data")) {
|
||||
rancherPodVoList = podListJson.getJSONArray("data").toList(RancherPodVo.class);
|
||||
String podSelector = k8sApplication.getPodSelector();
|
||||
List<RancherPodVo> applicationToPodList = rancherPodVoList.stream()
|
||||
.filter(rancherPodVo -> {
|
||||
if (!StringUtils.isEmpty(podSelector)) {
|
||||
String[] podSelectorArr = podSelector.split("=");
|
||||
return rancherPodVo.getMetadata().getLabels().containsKey(podSelectorArr[0])
|
||||
&& rancherPodVo.getMetadata().getLabels().get(podSelectorArr[0]).equals(podSelectorArr[1]);
|
||||
}
|
||||
return false;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
return applicationToPodList.stream().map(RancherPodVo::toK8sApplicationPod).collect(Collectors.toList());
|
||||
}
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean operateApplication(String kind, String namespace, String applicationName, String operationKey) {
|
||||
ApplicationType applicationType = ApplicationType.getApplicationTypeByKey(kind);
|
||||
ApplicationStartAndStopType applicationStartAndStopType = ApplicationStartAndStopType.getByKey(operationKey);
|
||||
if (!ApplicationStartAndStopType.containsKey(operationKey) || applicationStartAndStopType == null) {
|
||||
throw new ServiceException("该应用操作类型不存在(操作类型[%s])", operationKey);
|
||||
}
|
||||
if ("DaemonSet".equals(kind) && !applicationStartAndStopType.getIsDaemonSetOperation()) {
|
||||
throw new ServiceException("该应用操作类型不支持(操作类型[%s])", operationKey);
|
||||
}
|
||||
JSONObject applicationDetailJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sApplicationDetail(cluster_id, applicationType.getFullName(), namespace, applicationName, SecurityContextHolder.getUserKey()), "获取应用详情");
|
||||
if (applicationDetailJson == null || !applicationDetailJson.containsKey("metadata") || !applicationDetailJson.containsKey("spec")) {
|
||||
throw new ServiceException("该应用不存在或应用数据异常(应用类型[%s],命名空间[%s],应用名称[%s],)", kind, namespace, applicationName);
|
||||
}
|
||||
RancherApplicationVo rancherApplicationVo = applicationDetailJson.toJavaObject(RancherApplicationVo.class);
|
||||
K8sApplication k8sApplication = rancherApplicationVo.toK8sApplication();
|
||||
// 移除无用字段
|
||||
applicationDetailJson.remove("type");
|
||||
applicationDetailJson.remove("links");
|
||||
applicationDetailJson.remove("status");
|
||||
JSONObject metadataJson = applicationDetailJson.getJSONObject("metadata");
|
||||
metadataJson.remove("creationTimestamp");
|
||||
metadataJson.remove("generation");
|
||||
metadataJson.remove("managedFields");
|
||||
metadataJson.remove("relationships");
|
||||
metadataJson.remove("state");
|
||||
metadataJson.remove("uid");
|
||||
applicationDetailJson.put("metadata", metadataJson);
|
||||
JSONObject applicationSpecJson = applicationDetailJson.getJSONObject("spec");
|
||||
|
||||
switch (applicationStartAndStopType) {
|
||||
case START: {
|
||||
if (k8sApplication.getReplicas() != null && k8sApplication.getReplicas() > 0) {
|
||||
return true;
|
||||
}
|
||||
applicationSpecJson.put("replicas", 1);
|
||||
try (Response response = remoteRancherService.updateK8sApplication(applicationType.getFullName(), namespace, applicationName, applicationDetailJson, SecurityContextHolder.getUserKey())) {
|
||||
return RancherResponseHandler.handleBoolean(response, "启动应用");
|
||||
}
|
||||
}
|
||||
case STOP: {
|
||||
applicationSpecJson.put("replicas", 0);
|
||||
try (Response response = remoteRancherService.updateK8sApplication(applicationType.getFullName(), namespace, applicationName, applicationDetailJson, SecurityContextHolder.getUserKey())) {
|
||||
return RancherResponseHandler.handleBoolean(response, "停止应用");
|
||||
}
|
||||
}
|
||||
case FORCE_STOP: {
|
||||
applicationSpecJson.put("replicas", 0);
|
||||
try (Response response = remoteRancherService.updateK8sApplication(applicationType.getFullName(), namespace, applicationName, applicationDetailJson, SecurityContextHolder.getUserKey())) {
|
||||
if (FeignUtils.isSuccess(response)) {
|
||||
boolean delPodSuccess = true;
|
||||
// 获取应用下pod列表
|
||||
List<K8sApplicationPod> podList = getK8sApplicationPodList(k8sApplication);
|
||||
if (podList != null) {
|
||||
for (K8sApplicationPod pod : podList) {
|
||||
// 强制删除Terminating状态pod
|
||||
if (pod.getState().getName().equals("Terminating")) {
|
||||
// 删除pod失败时返回错误信息
|
||||
delPodSuccess = delPodSuccess && deletePod(pod.getNamespace(), pod.getName(), true);
|
||||
}
|
||||
}
|
||||
}
|
||||
return delPodSuccess;
|
||||
}
|
||||
return RancherResponseHandler.handleBoolean(response, "强制停止应用");
|
||||
}
|
||||
}
|
||||
case RESTART: {
|
||||
if (metadataJson.containsKey("annotations")) {
|
||||
JSONObject annotations = metadataJson.getJSONObject("annotations");
|
||||
Integer oldRevision = annotations.getInteger("deployment.kubernetes.io/revision");
|
||||
if (oldRevision == null) {
|
||||
oldRevision = 1;
|
||||
}
|
||||
annotations.put("deployment.kubernetes.io/revision", String.valueOf(oldRevision + 1));
|
||||
metadataJson.put("annotations", annotations);
|
||||
|
||||
JSONObject templateJson = applicationSpecJson.getJSONObject("template");
|
||||
if (templateJson == null) {
|
||||
templateJson = new JSONObject();
|
||||
}
|
||||
JSONObject metadataTemplateJson = templateJson.getJSONObject("metadata");
|
||||
if (metadataTemplateJson == null) {
|
||||
metadataTemplateJson = new JSONObject();
|
||||
}
|
||||
JSONObject annotationsTemplateJson = metadataTemplateJson.getJSONObject("annotations");
|
||||
if (annotationsTemplateJson == null) {
|
||||
annotationsTemplateJson = new JSONObject();
|
||||
}
|
||||
|
||||
annotationsTemplateJson.put("kubectl.kubernetes.io/restartedAt", DateUtils.getNowDate());
|
||||
metadataTemplateJson.put("annotations", annotationsTemplateJson);
|
||||
templateJson.put("metadata", metadataTemplateJson);
|
||||
applicationSpecJson.put("template", templateJson);
|
||||
applicationDetailJson.put("spec", applicationSpecJson);
|
||||
applicationDetailJson.put("metadata", metadataJson);
|
||||
try (Response response = remoteRancherService.updateK8sApplication(applicationType.getFullName(), namespace, applicationName, applicationDetailJson, SecurityContextHolder.getUserKey())) {
|
||||
return RancherResponseHandler.handleBoolean(response, "重启应用");
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case PAUSED: {
|
||||
applicationSpecJson.put("paused", true);
|
||||
applicationDetailJson.put("spec", applicationSpecJson);
|
||||
try (Response response = remoteRancherService.updateK8sApplication(applicationType.getFullName(), namespace, applicationName, applicationDetailJson, SecurityContextHolder.getUserKey())) {
|
||||
return RancherResponseHandler.handleBoolean(response, "暂停应用");
|
||||
}
|
||||
}
|
||||
case RESUME: {
|
||||
applicationSpecJson.put("paused", false);
|
||||
applicationDetailJson.put("spec", applicationSpecJson);
|
||||
try (Response response = remoteRancherService.updateK8sApplication(applicationType.getFullName(), namespace, applicationName, applicationDetailJson, SecurityContextHolder.getUserKey())) {
|
||||
return RancherResponseHandler.handleBoolean(response, "恢复应用");
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ApplicationTypeVo> getApplicationTypeList() {
|
||||
List<ApplicationTypeVo> applicationTypeList = new ArrayList<>();
|
||||
for (ApplicationType applicationType : ApplicationType.values()) {
|
||||
ApplicationTypeVo applicationTypeVo = new ApplicationTypeVo();
|
||||
applicationTypeVo.setKey(applicationType.getKey());
|
||||
applicationTypeVo.setFullName(applicationType.getFullName());
|
||||
applicationTypeVo.setDescription(applicationType.getDescription());
|
||||
applicationTypeList.add(applicationTypeVo);
|
||||
}
|
||||
return applicationTypeList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String createApplication(String kind, String yamlContent) {
|
||||
ApplicationType applicationType = ApplicationType.getApplicationTypeByKey(kind);
|
||||
StringBuilder yamlBuilder = new StringBuilder();
|
||||
try {
|
||||
Yaml yaml = new Yaml();
|
||||
Iterable<Object> yamls = yaml.loadAll(yamlContent);
|
||||
boolean isContainApplicationKind = false;
|
||||
for (Object yamlObject : yamls) {
|
||||
JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(yamlObject));
|
||||
String currentKind = jsonObject.getString("kind");
|
||||
if (currentKind == null) {
|
||||
jsonObject.put("kind", applicationType.getKey());
|
||||
isContainApplicationKind = true;
|
||||
} else if (ApplicationType.isApplicationType(currentKind)) {
|
||||
jsonObject.put("kind", applicationType.getKey());
|
||||
isContainApplicationKind = true;
|
||||
}
|
||||
JsonNode jsonNode = new ObjectMapper().readTree(jsonObject.toJSONString());
|
||||
String resourceYamlStr = new YAMLMapper().writeValueAsString(jsonNode);
|
||||
yamlBuilder.append(resourceYamlStr);
|
||||
|
||||
}
|
||||
if (!isContainApplicationKind) {
|
||||
throw new ServiceException("编排文件格式错误,未包含需要创建的应用");
|
||||
}
|
||||
} catch (JsonProcessingException exception) {
|
||||
throw new ServiceException("编排文件格式错误");
|
||||
}
|
||||
|
||||
JSONObject applyK8sYamlJson = new JSONObject();
|
||||
applyK8sYamlJson.put("defaultNamespace", "default");
|
||||
applyK8sYamlJson.put("yaml", yamlBuilder.toString());
|
||||
|
||||
try (Response response = remoteRancherService.applyK8sYaml(cluster_id, applyK8sYamlJson, SecurityContextHolder.getUserKey())) {
|
||||
JSONObject resJson = RancherResponseHandler.handleJsonObject(response, "创建应用");
|
||||
StringBuilder applyMsg = new StringBuilder();
|
||||
if (resJson != null && resJson.getJSONArray("data") != null) {
|
||||
JSONArray dataArray = resJson.getJSONArray("data");
|
||||
for (int i = 0; i < dataArray.size(); i++) {
|
||||
JSONObject data = dataArray.getJSONObject(i);
|
||||
String createKind = data.getString("kind");
|
||||
String resourceName = "";
|
||||
String namespace = "";
|
||||
if (data.getJSONObject("metadata") != null) {
|
||||
if (data.getJSONObject("metadata").containsKey("name")) {
|
||||
resourceName = String.format("【%s】", data.getJSONObject("metadata").getString("name"));
|
||||
}
|
||||
if (data.getJSONObject("metadata").containsKey("namespace")) {
|
||||
namespace = String.format("在 %s 命名空间下", data.getJSONObject("metadata").getString("namespace"));
|
||||
}
|
||||
}
|
||||
applyMsg.append(String.format("成功%s创建 %s 类型资源%s;\n", namespace, createKind, resourceName));
|
||||
}
|
||||
}
|
||||
return String.valueOf(applyMsg);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject getApplicationYamlFile(String kind, String namespace, String applicationName) {
|
||||
ApplicationType applicationType = ApplicationType.getApplicationTypeByKey(kind);
|
||||
return RancherResponseHandler.handleJsonObject(remoteRancherService.getApplicationYamlFile(applicationType.getName(), namespace, applicationName, SecurityContextHolder.getUserKey()), "获取应用yaml文件");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean editApplication(String kind, String namespace, String applicationName, String yamlContent) {
|
||||
ApplicationType applicationType = ApplicationType.getApplicationTypeByKey(kind);
|
||||
try (Response response = remoteRancherService.editK8sApplication(applicationType.getFullName(), namespace, applicationName, yamlContent, SecurityContextHolder.getUserKey())) {
|
||||
return RancherResponseHandler.handleBoolean(response, "编辑应用");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean deleteApplication(String kind, String namespace, String applicationName) {
|
||||
ApplicationType applicationType = ApplicationType.getApplicationTypeByKey(kind);
|
||||
JSONObject applicationJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sApplicationDetail(cluster_id, applicationType.getFullName(), namespace, applicationName, SecurityContextHolder.getUserKey()), "获取应用详情");
|
||||
if (applicationJson == null) {
|
||||
throw new ServiceException("删除失败:【%s】命名空间下【%s】应用不存在", namespace, applicationName);
|
||||
}
|
||||
RancherApplicationVo rancherApplicationVo = applicationJson.toJavaObject(RancherApplicationVo.class);
|
||||
if (rancherApplicationVo.getSpec() != null && rancherApplicationVo.getSpec().getJSONObject("template") != null && rancherApplicationVo.getSpec().getJSONObject("template").getJSONObject("metadata") != null && rancherApplicationVo.getSpec().getJSONObject("template").getJSONObject("metadata").containsKey("labels")) {
|
||||
JSONObject applicationLabelJson = rancherApplicationVo.getSpec().getJSONObject("template").getJSONObject("metadata").getJSONObject("labels");
|
||||
JSONObject k8sSvcByNamespaceJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sServiceByNamespace(cluster_id, namespace, SecurityContextHolder.getUserKey()), "获取指定命名空间下的K8s服务列表");
|
||||
if (k8sSvcByNamespaceJson != null && k8sSvcByNamespaceJson.getJSONArray("data") != null) {
|
||||
List<RancherServiceVo> k8sSvcList = k8sSvcByNamespaceJson.getJSONArray("data").toJavaList(RancherServiceVo.class);
|
||||
for (RancherServiceVo rancherServiceVo : k8sSvcList) {
|
||||
if (rancherServiceVo.getSpec() != null && rancherServiceVo.getSpec().getSelector() != null) {
|
||||
JSONObject selectorJson = rancherServiceVo.getSpec().getSelector();
|
||||
for (String key : applicationLabelJson.keySet()) {
|
||||
if (selectorJson.containsKey(key) && selectorJson.getString(key).equals(applicationLabelJson.getString(key))) {
|
||||
try (Response response = remoteRancherService.deleteK8sService(rancherServiceVo.getId(), SecurityContextHolder.getUserKey())) {
|
||||
log.info("删除K8s服务【{}】成功:响应状态码:{},响应结果:{}", rancherServiceVo.getId(), response.status(), response.reason());
|
||||
} catch (Exception e) {
|
||||
log.error("删除K8s服务【{}】失败,失败原因:{}", rancherServiceVo, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
try (Response response = remoteRancherService.deleteApplication(applicationType.getFullName(), namespace, applicationName, SecurityContextHolder.getUserKey())) {
|
||||
return RancherResponseHandler.handleBoolean(response, "删除应用");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<K8sApplicationEnv> getApplicationEnv(String kind, String namespace, String applicationName) {
|
||||
List<K8sApplicationEnv> envList = new ArrayList<>();
|
||||
ApplicationType applicationType = ApplicationType.getApplicationTypeByKey(kind);
|
||||
JSONObject applicationJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sApplicationDetail(cluster_id, applicationType.getFullName(), namespace, applicationName, SecurityContextHolder.getUserKey()), "获取应用详情");
|
||||
if (applicationJson == null) {
|
||||
return envList;
|
||||
}
|
||||
RancherApplicationVo rancherApplicationVo = applicationJson.toJavaObject(RancherApplicationVo.class);
|
||||
if (rancherApplicationVo.getSpec() != null && rancherApplicationVo.getSpec().getJSONObject("template") != null && rancherApplicationVo.getSpec().getJSONObject("template").getJSONObject("spec") != null) {
|
||||
JSONArray containersJson = rancherApplicationVo.getSpec().getJSONObject("template").getJSONObject("spec").getJSONArray("containers");
|
||||
// TODO: 暂时只考虑第一个容器
|
||||
if (containersJson != null && !containersJson.isEmpty()) {
|
||||
JSONObject containerJson = containersJson.getJSONObject(0);
|
||||
if (containerJson != null) {
|
||||
JSONArray envJsonList = containerJson.getJSONArray("env");
|
||||
if (envJsonList != null && !envJsonList.isEmpty()) {
|
||||
for (int i = 0; i < envJsonList.size(); i++) {
|
||||
JSONObject envJson = envJsonList.getJSONObject(i);
|
||||
K8sApplicationEnv k8sApplicationEnv = K8sApplicationEnv.envJsonObjectToK8sApplicationEnv(envJson);
|
||||
if (k8sApplicationEnv != null) {
|
||||
envList.add(k8sApplicationEnv);
|
||||
}
|
||||
}
|
||||
}
|
||||
JSONArray envFromJsonList = containerJson.getJSONArray("envFrom");
|
||||
if (envFromJsonList != null && !envFromJsonList.isEmpty()) {
|
||||
for (int i = 0; i < envFromJsonList.size(); i++) {
|
||||
JSONObject envFromJson = envFromJsonList.getJSONObject(i);
|
||||
K8sApplicationEnv k8sApplicationEnv = K8sApplicationEnv.envFromJsonObjectToK8sApplicationEnv(envFromJson);
|
||||
if (k8sApplicationEnv != null) {
|
||||
envList.add(k8sApplicationEnv);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return envList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<K8sApplicationEnvOptionalParameter> getEnvOptionalParameters(String namespace) {
|
||||
List<K8sApplicationEnvOptionalParameter> envOptionalParametersList = new ArrayList<>();
|
||||
JSONObject configmapJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sConfigmapByNamespace(namespace, SecurityContextHolder.getUserKey()), "获取命名空间下所有ConfigMap");
|
||||
if (configmapJson != null && configmapJson.containsKey("data")) {
|
||||
JSONArray dataJsonArray = configmapJson.getJSONArray("data");
|
||||
for (int i = 0; i < dataJsonArray.size(); i++) {
|
||||
JSONObject dataJson = dataJsonArray.getJSONObject(i);
|
||||
if (dataJson != null && dataJson.containsKey("metadata") && dataJson.containsKey("data")) {
|
||||
JSONObject metadataJson = dataJson.getJSONObject("metadata");
|
||||
if (metadataJson != null && metadataJson.containsKey("name")) {
|
||||
K8sApplicationEnvOptionalParameter k8sApplicationEnvOptionalParameter = new K8sApplicationEnvOptionalParameter();
|
||||
String configmapName = metadataJson.getString("name");
|
||||
if (configmapName != null) {
|
||||
k8sApplicationEnvOptionalParameter.setType(ApplicationEnvType.CONFIGMAP.getKey());
|
||||
k8sApplicationEnvOptionalParameter.setName(configmapName);
|
||||
JSONObject configmapDataJson = dataJson.getJSONObject("data");
|
||||
List<String> keys = new ArrayList<>(configmapDataJson.keySet());
|
||||
k8sApplicationEnvOptionalParameter.setKeys(keys);
|
||||
envOptionalParametersList.add(k8sApplicationEnvOptionalParameter);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
JSONObject secretJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sSecretByNamespace(namespace, SecurityContextHolder.getUserKey()), "获取命名空间下所有Secret");
|
||||
if (secretJson != null && secretJson.containsKey("data")) {
|
||||
JSONArray dataJsonArray = secretJson.getJSONArray("data");
|
||||
for (int i = 0; i < dataJsonArray.size(); i++) {
|
||||
JSONObject dataJson = dataJsonArray.getJSONObject(i);
|
||||
if (dataJson != null && dataJson.containsKey("metadata") && dataJson.containsKey("data")) {
|
||||
JSONObject metadataJson = dataJson.getJSONObject("metadata");
|
||||
if (metadataJson != null && metadataJson.containsKey("name")) {
|
||||
K8sApplicationEnvOptionalParameter k8sApplicationEnvOptionalParameter = new K8sApplicationEnvOptionalParameter();
|
||||
String configmapName = metadataJson.getString("name");
|
||||
if (configmapName != null) {
|
||||
k8sApplicationEnvOptionalParameter.setType(ApplicationEnvType.SECRET.getKey());
|
||||
k8sApplicationEnvOptionalParameter.setName(configmapName);
|
||||
JSONObject configmapDataJson = dataJson.getJSONObject("data");
|
||||
List<String> keys = new ArrayList<>(configmapDataJson.keySet());
|
||||
k8sApplicationEnvOptionalParameter.setKeys(keys);
|
||||
envOptionalParametersList.add(k8sApplicationEnvOptionalParameter);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 设置资源可选参数
|
||||
K8sApplicationEnvOptionalParameter k8sApplicationEnvOptionalParameter = new K8sApplicationEnvOptionalParameter();
|
||||
k8sApplicationEnvOptionalParameter.setType(ApplicationEnvType.RESOURCE.getKey());
|
||||
k8sApplicationEnvOptionalParameter.setName("");
|
||||
List<String> resourceKeys = new ArrayList<>();
|
||||
resourceKeys.add("limits.cpu");
|
||||
resourceKeys.add("limits.ephemeral-storage");
|
||||
resourceKeys.add("limits.memory");
|
||||
resourceKeys.add("requests.cpu");
|
||||
resourceKeys.add("requests.ephemeral-storage");
|
||||
resourceKeys.add("requests.memory");
|
||||
k8sApplicationEnvOptionalParameter.setKeys(resourceKeys);
|
||||
envOptionalParametersList.add(k8sApplicationEnvOptionalParameter);
|
||||
return envOptionalParametersList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean updateApplicationEnv(String kind, String namespace, String applicationName, List<K8sApplicationEnv> k8sApplicationEnvList) {
|
||||
ApplicationType applicationType = ApplicationType.getApplicationTypeByKey(kind);
|
||||
JSONObject applicationDetailJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sApplicationDetail(cluster_id, applicationType.getFullName(), namespace, applicationName, SecurityContextHolder.getUserKey()), "获取应用详情");
|
||||
if (applicationDetailJson == null || !applicationDetailJson.containsKey("spec")) {
|
||||
throw new ServiceException("该应用不存在或应用数据异常(应用类型[%s],命名空间[%s],应用名称[%s],)", kind, namespace, applicationName);
|
||||
}
|
||||
|
||||
JSONObject specJson = applicationDetailJson.getJSONObject("spec");
|
||||
if (specJson.containsKey("template")) {
|
||||
JSONObject templateJson = specJson.getJSONObject("template");
|
||||
if (templateJson.containsKey("spec")) {
|
||||
JSONObject templateSpecJson = templateJson.getJSONObject("spec");
|
||||
if (templateSpecJson.containsKey("containers")) {
|
||||
JSONArray containersJson = templateSpecJson.getJSONArray("containers");
|
||||
// TODO: 暂时只考虑第一个容器
|
||||
if (containersJson != null && !containersJson.isEmpty()) {
|
||||
JSONObject containerJson = containersJson.getJSONObject(0);
|
||||
if (containerJson != null) {
|
||||
containersJson.set(0, updateApplicationContainerEnv(k8sApplicationEnvList, containerJson));
|
||||
}
|
||||
templateSpecJson.put("containers", containersJson);
|
||||
}
|
||||
templateJson.put("spec", templateSpecJson);
|
||||
}
|
||||
specJson.put("template", templateJson);
|
||||
}
|
||||
applicationDetailJson.put("spec", specJson);
|
||||
}
|
||||
|
||||
|
||||
try (Response response = remoteRancherService.updateK8sApplication(applicationType.getFullName(), namespace, applicationName, applicationDetailJson, SecurityContextHolder.getUserKey())) {
|
||||
return RancherResponseHandler.handleBoolean(response, "更新应用环境变量", "环境变量格式异常");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ApplicationEnvTypeVo> getEnvTypes() {
|
||||
List<ApplicationEnvTypeVo> applicationEnvTypeVoList = new ArrayList<>();
|
||||
for (ApplicationEnvType applicationEnvType : ApplicationEnvType.values()) {
|
||||
ApplicationEnvTypeVo applicationEnvTypeVo = new ApplicationEnvTypeVo();
|
||||
applicationEnvTypeVo.setKey(applicationEnvType.getKey());
|
||||
applicationEnvTypeVo.setAlias(applicationEnvType.getAlias());
|
||||
applicationEnvTypeVoList.add(applicationEnvTypeVo);
|
||||
}
|
||||
return applicationEnvTypeVoList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<GatewayRouteConfig> getGatewayRouteConfig() {
|
||||
List<GatewayRouteConfig> routeConfigList = new ArrayList<>();
|
||||
JSONObject nacosGatewayConfigJson = getNacosGatewayConfigJson();
|
||||
if (nacosGatewayConfigJson.containsKey("spring")) {
|
||||
JSONObject springJson = nacosGatewayConfigJson.getJSONObject("spring");
|
||||
if (springJson.containsKey("cloud")) {
|
||||
JSONObject cloudJson = springJson.getJSONObject("cloud");
|
||||
if (cloudJson.containsKey("gateway")) {
|
||||
JSONObject gatewayJson = cloudJson.getJSONObject("gateway");
|
||||
routeConfigList = gatewayJson.getJSONArray("routes").toJavaList(GatewayRouteConfig.class);
|
||||
}
|
||||
}
|
||||
}
|
||||
return routeConfigList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean updateGatewayRouteConfig(List<GatewayRouteConfig> gatewayRouteConfigList) {
|
||||
JSONObject nacosGatewayConfigJson = getNacosGatewayConfigJson();
|
||||
if (nacosGatewayConfigJson.containsKey("spring")) {
|
||||
JSONObject springJson = nacosGatewayConfigJson.getJSONObject("spring");
|
||||
if (springJson.containsKey("cloud")) {
|
||||
JSONObject cloudJson = springJson.getJSONObject("cloud");
|
||||
if (cloudJson.containsKey("gateway")) {
|
||||
JSONObject gatewayJson = cloudJson.getJSONObject("gateway");
|
||||
JSONArray routeConfigListJson = JSONArray.parseArray(JSON.toJSONString(gatewayRouteConfigList));
|
||||
gatewayJson.put("routes", routeConfigListJson);
|
||||
cloudJson.put("gateway", gatewayJson);
|
||||
}
|
||||
springJson.put("cloud", cloudJson);
|
||||
}
|
||||
nacosGatewayConfigJson.put("spring", springJson);
|
||||
}
|
||||
return updateNacosGatewayConfig(nacosGatewayConfigJson);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GatewaySafetyConfig getGatewaySafetyConfig() {
|
||||
GatewaySafetyConfig gatewaySafetyConfig = new GatewaySafetyConfig();
|
||||
JSONObject nacosGatewayConfigJson = getNacosGatewayConfigJson();
|
||||
if (nacosGatewayConfigJson.containsKey("spring")) {
|
||||
JSONObject springJson = nacosGatewayConfigJson.getJSONObject("spring");
|
||||
if (springJson.containsKey("cloud")) {
|
||||
JSONObject cloudJson = springJson.getJSONObject("cloud");
|
||||
if (cloudJson.containsKey("gateway")) {
|
||||
JSONObject gatewayJson = cloudJson.getJSONObject("gateway");
|
||||
if (gatewayJson.containsKey("globalcors")) {
|
||||
JSONObject globalcorsJson = gatewayJson.getJSONObject("globalcors");
|
||||
if (globalcorsJson.containsKey("cors-configurations")) {
|
||||
JSONObject corsConfigurationsJson = globalcorsJson.getJSONObject("cors-configurations");
|
||||
if (corsConfigurationsJson.containsKey("[/**]")) {
|
||||
gatewaySafetyConfig = corsConfigurationsJson.getJSONObject("[/**]").toJavaObject(GatewaySafetyConfig.class);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return gatewaySafetyConfig;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean updateGatewaySafetyConfig(GatewaySafetyConfig gatewaySafetyConfig) {
|
||||
JSONObject nacosGatewayConfigJson = getNacosGatewayConfigJson();
|
||||
if (nacosGatewayConfigJson.containsKey("spring")) {
|
||||
JSONObject springJson = nacosGatewayConfigJson.getJSONObject("spring");
|
||||
if (springJson.containsKey("cloud")) {
|
||||
JSONObject cloudJson = springJson.getJSONObject("cloud");
|
||||
if (cloudJson.containsKey("gateway")) {
|
||||
JSONObject gatewayJson = cloudJson.getJSONObject("gateway");
|
||||
if (gatewayJson.containsKey("globalcors")) {
|
||||
JSONObject globalcorsJson = gatewayJson.getJSONObject("globalcors");
|
||||
if (globalcorsJson.containsKey("cors-configurations")) {
|
||||
JSONObject corsConfigurationsJson = globalcorsJson.getJSONObject("cors-configurations");
|
||||
if (corsConfigurationsJson.containsKey("[/**]")) {
|
||||
JSONObject corsConfigurationsValueJson = JSONObject.from(gatewaySafetyConfig);
|
||||
corsConfigurationsJson.put("[/**]", corsConfigurationsValueJson);
|
||||
globalcorsJson.put("cors-configurations", corsConfigurationsJson);
|
||||
}
|
||||
gatewayJson.put("globalcors", globalcorsJson);
|
||||
}
|
||||
cloudJson.put("gateway", gatewayJson);
|
||||
}
|
||||
springJson.put("cloud", cloudJson);
|
||||
}
|
||||
nacosGatewayConfigJson.put("spring", springJson);
|
||||
}
|
||||
nacosGatewayConfigJson.put("spring", springJson);
|
||||
}
|
||||
return updateNacosGatewayConfig(nacosGatewayConfigJson);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GatewayWhitelistConfig getGatewayWhitelistConfig() {
|
||||
GatewayWhitelistConfig gatewayWhitelistConfig = new GatewayWhitelistConfig();
|
||||
JSONObject nacosGatewayConfigJson = getNacosGatewayConfigJson();
|
||||
if (nacosGatewayConfigJson.containsKey("security")) {
|
||||
JSONObject securityJson = nacosGatewayConfigJson.getJSONObject("security");
|
||||
if (securityJson.containsKey("ignore")) {
|
||||
gatewayWhitelistConfig = securityJson.getJSONObject("ignore").toJavaObject(GatewayWhitelistConfig.class);
|
||||
}
|
||||
}
|
||||
return gatewayWhitelistConfig;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean updateGatewayWhitelistConfig(GatewayWhitelistConfig gatewayWhitelistConfig) {
|
||||
JSONObject nacosGatewayConfigJson = getNacosGatewayConfigJson();
|
||||
if (nacosGatewayConfigJson.containsKey("security")) {
|
||||
JSONObject securityJson = nacosGatewayConfigJson.getJSONObject("security");
|
||||
if (securityJson.containsKey("ignore")) {
|
||||
JSONObject ignoreJson = JSONObject.from(gatewayWhitelistConfig);
|
||||
securityJson.put("ignore", ignoreJson);
|
||||
nacosGatewayConfigJson.put("security", securityJson);
|
||||
}
|
||||
nacosGatewayConfigJson.put("security", securityJson);
|
||||
}
|
||||
return updateNacosGatewayConfig(nacosGatewayConfigJson);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getExceptionHandingDateList() {
|
||||
List<String> dateList = new ArrayList<>();
|
||||
File gatewayLogPathDir = new File(gatewayLogPath);
|
||||
if (gatewayLogPathDir.exists() && gatewayLogPathDir.isDirectory()) {
|
||||
File[] listFiles = gatewayLogPathDir.listFiles();
|
||||
if (listFiles != null) {
|
||||
for (File file : listFiles) {
|
||||
if (!file.isDirectory()) {
|
||||
String fileName = file.getName();
|
||||
if (fileName.endsWith(".log") && fileName.contains("error")) {
|
||||
if (fileName.equalsIgnoreCase("error.log")) {
|
||||
dateList.add("今天");
|
||||
} else {
|
||||
dateList.add(file.getName().replace("error.", "").replace(".log", ""));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
dateList.sort(Comparator.reverseOrder());
|
||||
return dateList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getExceptionHandingRecordList(String date) {
|
||||
List<String> errLogList = new ArrayList<>();
|
||||
String dateLogFile;
|
||||
if (StringUtils.isEmpty(date) || date.equals("今天")) {
|
||||
dateLogFile = "error.log";
|
||||
} else {
|
||||
dateLogFile = "error." + date + ".log";
|
||||
}
|
||||
Path logPath = Paths.get(gatewayLogPath);
|
||||
Path dateLogFilePath = logPath.resolve(dateLogFile);
|
||||
if (!Files.exists(dateLogFilePath)) {
|
||||
throw new ServiceException("该日期网关异常处理记录不存在(日期[%s])", date);
|
||||
}
|
||||
try {
|
||||
try (Stream<String> lines = Files.lines(dateLogFilePath)) {
|
||||
lines.forEach(line -> {
|
||||
if (line.contains("异常处理")) {
|
||||
errLogList.add(line);
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("该日期网关异常处理记录读取失败:{}", e.getMessage());
|
||||
throw new ServiceException("该日期网关异常处理记录读取失败(日期[%s])", date);
|
||||
}
|
||||
errLogList.sort(Comparator.reverseOrder());
|
||||
return errLogList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<LinkTrackingApplication> getLinkTrackingList(String applicationName) {
|
||||
List<LinkTrackingApplication> linkTrackingApplicationList = new ArrayList<>();
|
||||
String search = skywalkingGroup + "::";
|
||||
// 查询服务列表
|
||||
GraphqlQueryVo gqlQueryVo = SkywalkingGQLConstant.searchServicesByKeyword(search);
|
||||
JSONObject skywalkingServices = remoteGatewayService.executeSkywalkingGql(gqlQueryVo);
|
||||
if (skywalkingServices != null
|
||||
&& skywalkingServices.getJSONObject("data") != null
|
||||
&& skywalkingServices.getJSONObject("data").getJSONArray(gqlQueryVo.getOperationName()) != null) {
|
||||
JSONArray skywalkingServicesArray = skywalkingServices.getJSONObject("data").getJSONArray(gqlQueryVo.getOperationName());
|
||||
int index = 1;
|
||||
for (int i = 0; i < skywalkingServicesArray.size(); i++) {
|
||||
JSONObject skywalkingService = skywalkingServicesArray.getJSONObject(i);
|
||||
String shortName = skywalkingService.getString("shortName");
|
||||
if (StringUtils.isEmpty(applicationName) || shortName.contains(applicationName)) {
|
||||
LinkTrackingApplication linkTrackingApplication = new LinkTrackingApplication();
|
||||
linkTrackingApplication.setIndex(index);
|
||||
linkTrackingApplication.setId(skywalkingService.getString("id"));
|
||||
linkTrackingApplication.setKey(skywalkingService.getString("name"));
|
||||
linkTrackingApplication.setApplicationName(shortName);
|
||||
linkTrackingApplicationList.add(linkTrackingApplication);
|
||||
index++;
|
||||
}
|
||||
}
|
||||
|
||||
// 查询服务状态列表
|
||||
gqlQueryVo = SkywalkingGQLConstant.queryMetricDataList(linkTrackingApplicationList);
|
||||
JSONObject skywalkingMetricDataList = remoteGatewayService.executeSkywalkingGql(gqlQueryVo);
|
||||
if (skywalkingMetricDataList != null
|
||||
&& skywalkingMetricDataList.getJSONObject("data") != null) {
|
||||
JSONObject data = skywalkingMetricDataList.getJSONObject("data");
|
||||
for (int i = 0; i < linkTrackingApplicationList.size(); i++) {
|
||||
LinkTrackingApplication linkTrackingApplication = linkTrackingApplicationList.get(i);
|
||||
for (SkywalkingMetricType metricType : SkywalkingMetricType.values()) {
|
||||
String functionName = metricType.getFunctionName(linkTrackingApplication.getIndex());
|
||||
JSONObject functionData = data.getJSONObject(functionName);
|
||||
if (functionData != null && functionData.getJSONObject("values") != null && functionData.getJSONObject("values").getJSONArray("values") != null) {
|
||||
JSONArray valuesArray = functionData.getJSONObject("values").getJSONArray("values");
|
||||
float metricValue = 0;
|
||||
for (int j = 0; j < valuesArray.size(); j++) {
|
||||
JSONObject value = valuesArray.getJSONObject(j);
|
||||
metricValue += value.getFloatValue("value");
|
||||
}
|
||||
metricValue = metricValue / valuesArray.size();
|
||||
String valueStr;
|
||||
switch (metricType) {
|
||||
case SERVICE_CPM:
|
||||
valueStr = String.format("%.2f", metricValue);
|
||||
linkTrackingApplication.setLoad(Float.parseFloat(valueStr));
|
||||
break;
|
||||
case SERVICE_SLA:
|
||||
valueStr = String.format("%.2f", metricValue / 100);
|
||||
linkTrackingApplication.setSuccessRate(Float.parseFloat(valueStr));
|
||||
break;
|
||||
case SERVICE_RESP_TIME:
|
||||
valueStr = String.format("%.2f", metricValue);
|
||||
linkTrackingApplication.setLatency(Float.parseFloat(valueStr));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
linkTrackingApplicationList.set(i, linkTrackingApplication);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return linkTrackingApplicationList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject getGatewayFlowLimitingPara() {
|
||||
JSONObject gatewayFlowLimitingPara = new JSONObject();
|
||||
JSONArray sentinelAppListArray = dashboardService.getSentinelAppList();
|
||||
for (int i = 0; i < sentinelAppListArray.size(); i++) {
|
||||
JSONObject sentinelApp = sentinelAppListArray.getJSONObject(i);
|
||||
if (sentinelApp.getLongValue("appType") == 11) {
|
||||
gatewayFlowLimitingPara.put("app", sentinelApp.getString("app"));
|
||||
gatewayFlowLimitingPara.put("appType", sentinelApp.getLongValue("appType"));
|
||||
return gatewayFlowLimitingPara;
|
||||
}
|
||||
}
|
||||
return gatewayFlowLimitingPara;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GenericsTableDataInfo<K8SEvent> getK8SEventList(String eventType, String reason, Date startTime, Date endTime, Boolean isAscOrderByOccurredTime, Integer pageNum, Integer pageSize) {
|
||||
JSONObject eventListQueryBody = ESQueryUtils.buildEventListQueryBody(eventType, reason, startTime, endTime, isAscOrderByOccurredTime, pageNum, pageSize);
|
||||
JSONObject esQueryRes = remoteGatewayService.executeElasticsearchQuery(esK8sEventIndex, eventListQueryBody);
|
||||
return K8SEvent.toK8SEventTable(esQueryRes);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<CommonTypeVo> getK8SEventReasonList(String eventType) {
|
||||
JSONObject eventReasonListQueryRes = remoteGatewayService.executeElasticsearchQuery(esK8sEventIndex, ESQueryUtils.buildEventReasonListQueryBody(eventType));
|
||||
return CommonTypeVo.eventReasonListToCommonTypeVoList(eventReasonListQueryRes);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<CommonTypeVo> getResourceObjectList() {
|
||||
JSONObject nodeInfoRes = remoteGatewayService.getPrometheusQueryRes(PromQLConstant.NODE_INFO(), SecurityContextHolder.getUserKey());
|
||||
if (nodeInfoRes != null) {
|
||||
PrometheusResVo prometheusResVo = nodeInfoRes.toJavaObject(PrometheusResVo.class);
|
||||
if (prometheusResVo != null && prometheusResVo.isSuccess()) {
|
||||
List<PrometheusResultVo> resultList = prometheusResVo.getData().getResult();
|
||||
return CommonTypeVo.resourceObjectToCommonTypeVoList(resultList);
|
||||
}
|
||||
}
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<K8SResourceUsage> getResourceUsageList(String searchResourceObject, Date startTime, Date endTime) {
|
||||
// 默认步长为六小时
|
||||
Long step = 60 * 60 * 6L;
|
||||
Date[] startAndEndDates = DateTimeNormalizer.normalize(startTime, endTime);
|
||||
List<K8SResourceUsage> resourceUsageList = new ArrayList<>();
|
||||
JSONObject nodeInfoRes = remoteGatewayService.getPrometheusQueryRes(PromQLConstant.NODE_INFO(), SecurityContextHolder.getUserKey());
|
||||
if (nodeInfoRes != null) {
|
||||
PrometheusResVo prometheusResVo = nodeInfoRes.toJavaObject(PrometheusResVo.class);
|
||||
if (prometheusResVo != null && prometheusResVo.isSuccess()) {
|
||||
List<PrometheusResultVo> resultList = prometheusResVo.getData().getResult();
|
||||
List<JSONObject> metricList = resultList.stream().map(PrometheusResultVo::getMetric).filter(metric -> {
|
||||
if (StringUtils.isEmpty(searchResourceObject)) {
|
||||
return true;
|
||||
} else if (StringUtils.isNotEmpty(searchResourceObject)) {
|
||||
return searchResourceObject.equals(metric.getString("ip"));
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
}).collect(Collectors.toList());
|
||||
resourceUsageList = monCommonAsyncService.getResourceUsageList(metricList, startAndEndDates, step);
|
||||
}
|
||||
}
|
||||
resourceUsageList.sort(Comparator.comparing(K8SResourceUsage::getOccurredTime).reversed());
|
||||
return resourceUsageList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据传入的环境变量列表,生成并更新容器对象的 env 与 envFrom 字段。
|
||||
*
|
||||
* <p>逻辑说明:</p>
|
||||
* <ul>
|
||||
* <li>遍历 {@code k8sApplicationEnvList},按 {@link ApplicationEnvType} 区分 7 种变量来源。</li>
|
||||
* <li>将每种来源转换成符合 Kubernetes 规范的 JSON 结构,分别归入:
|
||||
* <ul>
|
||||
* <li>{@code env} 数组:KEY_VALUE_PAIR、RESOURCE、CONFIG_MAP_KEY、SECRET_KEY、POD_FIELD</li>
|
||||
* <li>{@code envFrom} 数组:SECRET、CONFIGMAP</li>
|
||||
* </ul>
|
||||
* </li>
|
||||
* <li>给 RESOURCE、CONFIG_MAP_KEY、SECRET_KEY、SECRET、CONFIGMAP 统一补全必需字段(divisor / optional 等)。</li>
|
||||
* <li>最后将生成的 {@code env} 与 {@code envFrom} 数组写回 {@code containerJson} 并返回。</li>
|
||||
* </ul>
|
||||
*
|
||||
* @param k8sApplicationEnvList 待写入的环境变量列表
|
||||
* @param containerJson 待更新的容器 JSON 对象(K8s container spec)
|
||||
* @return 已更新 env & envFrom 的容器 JSON 对象(即入参 containerJson)
|
||||
*/
|
||||
private JSONObject updateApplicationContainerEnv(List<K8sApplicationEnv> k8sApplicationEnvList, JSONObject
|
||||
containerJson) {
|
||||
JSONArray envJsonArray = new JSONArray();
|
||||
JSONArray envFromJsonArray = new JSONArray();
|
||||
for (K8sApplicationEnv k8sApplicationEnv : k8sApplicationEnvList) {
|
||||
ApplicationEnvType applicationEnvType = ApplicationEnvType.getApplicationEnvTypeByKey(k8sApplicationEnv.getType());
|
||||
switch (applicationEnvType) {
|
||||
case KEY_VALUE_PAIR: {
|
||||
JSONObject envJson = new JSONObject();
|
||||
envJson.put("name", k8sApplicationEnv.getKey());
|
||||
if (k8sApplicationEnv.getValueObj() != null && k8sApplicationEnv.getValueObj().containsKey("value")) {
|
||||
envJson.put("value", k8sApplicationEnv.getValueObj().getString("value"));
|
||||
envJsonArray.add(envJson);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case RESOURCE: {
|
||||
JSONObject envJson = new JSONObject();
|
||||
envJson.put("name", k8sApplicationEnv.getKey());
|
||||
JSONObject valueFromJson = new JSONObject();
|
||||
JSONObject resourceFieldRef = new JSONObject();
|
||||
JSONObject valueObj = k8sApplicationEnv.getValueObj();
|
||||
resourceFieldRef.put("divisor", "1");
|
||||
resourceFieldRef.put("containerName", valueObj.getString("name"));
|
||||
resourceFieldRef.put("resource", valueObj.getString("key"));
|
||||
valueFromJson.put("resourceFieldRef", resourceFieldRef);
|
||||
envJson.put("valueFrom", valueFromJson);
|
||||
envJsonArray.add(envJson);
|
||||
break;
|
||||
}
|
||||
case CONFIG_MAP_KEY: {
|
||||
JSONObject envJson = new JSONObject();
|
||||
envJson.put("name", k8sApplicationEnv.getKey());
|
||||
JSONObject valueFromJson = new JSONObject();
|
||||
JSONObject configMapKeyRef = new JSONObject();
|
||||
JSONObject valueObj = k8sApplicationEnv.getValueObj();
|
||||
configMapKeyRef.put("optional", false);
|
||||
configMapKeyRef.put("name", valueObj.getString("name"));
|
||||
configMapKeyRef.put("key", valueObj.getString("key"));
|
||||
valueFromJson.put("configMapKeyRef", configMapKeyRef);
|
||||
envJson.put("valueFrom", valueFromJson);
|
||||
envJsonArray.add(envJson);
|
||||
break;
|
||||
}
|
||||
case SECRET_KEY: {
|
||||
JSONObject envJson = new JSONObject();
|
||||
envJson.put("name", k8sApplicationEnv.getKey());
|
||||
JSONObject valueFromJson = new JSONObject();
|
||||
JSONObject secretKeyRef = new JSONObject();
|
||||
JSONObject valueObj = k8sApplicationEnv.getValueObj();
|
||||
secretKeyRef.put("optional", false);
|
||||
secretKeyRef.put("name", valueObj.getString("name"));
|
||||
secretKeyRef.put("key", valueObj.getString("key"));
|
||||
valueFromJson.put("secretKeyRef", secretKeyRef);
|
||||
envJson.put("valueFrom", valueFromJson);
|
||||
envJsonArray.add(envJson);
|
||||
break;
|
||||
}
|
||||
case POD_FIELD: {
|
||||
JSONObject envJson = new JSONObject();
|
||||
envJson.put("name", k8sApplicationEnv.getKey());
|
||||
JSONObject valueFromJson = new JSONObject();
|
||||
JSONObject fieldRef = new JSONObject();
|
||||
JSONObject valueObj = k8sApplicationEnv.getValueObj();
|
||||
fieldRef.put("apiVersion", "v1");
|
||||
fieldRef.put("fieldPath", valueObj.getString("value"));
|
||||
valueFromJson.put("fieldRef", fieldRef);
|
||||
envJson.put("valueFrom", valueFromJson);
|
||||
envJsonArray.add(envJson);
|
||||
break;
|
||||
}
|
||||
case SECRET: {
|
||||
JSONObject envJson = new JSONObject();
|
||||
envJson.put("prefix", k8sApplicationEnv.getKey());
|
||||
JSONObject secretRef = new JSONObject();
|
||||
JSONObject valueObj = k8sApplicationEnv.getValueObj();
|
||||
secretRef.put("optional", false);
|
||||
secretRef.put("name", valueObj.getString("name"));
|
||||
envJson.put("secretRef", secretRef);
|
||||
envFromJsonArray.add(envJson);
|
||||
break;
|
||||
}
|
||||
case CONFIGMAP: {
|
||||
JSONObject envJson = new JSONObject();
|
||||
envJson.put("prefix", k8sApplicationEnv.getKey());
|
||||
JSONObject configMapRef = new JSONObject();
|
||||
JSONObject valueObj = k8sApplicationEnv.getValueObj();
|
||||
configMapRef.put("optional", false);
|
||||
configMapRef.put("name", valueObj.getString("name"));
|
||||
envJson.put("configMapRef", configMapRef);
|
||||
envFromJsonArray.add(envJson);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
containerJson.put("env", envJsonArray);
|
||||
containerJson.put("envFrom", envFromJsonArray);
|
||||
return containerJson;
|
||||
}
|
||||
|
||||
private JSONObject getNacosGatewayConfigJson() {
|
||||
String nacosGatewayConfigYaml = remoteGatewayService.getNacosConfigDetail(nacosGatewayConfigId, nacosDefaultGroup, SecurityContextHolder.getUserKey());
|
||||
Yaml yaml = new Yaml();
|
||||
LinkedHashMap<String, Object> yamlMap = yaml.load(nacosGatewayConfigYaml);
|
||||
return new JSONObject(yamlMap);
|
||||
}
|
||||
|
||||
private Boolean updateNacosGatewayConfig(JSONObject gatewayConfigJson) {
|
||||
String jsonString = gatewayConfigJson.toJSONString();
|
||||
JsonNode jsonNode;
|
||||
try {
|
||||
jsonNode = new ObjectMapper().readTree(jsonString);
|
||||
String string = new YAMLMapper().writeValueAsString(jsonNode);
|
||||
//因为writeValueAsString生成的yaml字符串会带有 ---\n 所以进行替换操作
|
||||
String yamlStr = string.replaceAll("---\n", "");
|
||||
|
||||
Map<String, String> nacosMap = new HashMap<>();
|
||||
nacosMap.put("dataId", nacosGatewayConfigId);
|
||||
nacosMap.put("group", nacosDefaultGroup);
|
||||
nacosMap.put("content", yamlStr);
|
||||
nacosMap.put("type", "yaml");
|
||||
nacosMap.put("modifyTime", String.valueOf(DateUtils.getNowDate().getTime()));
|
||||
try (Response response = remoteGatewayService.updateNacosConfig(nacosMap, SecurityContextHolder.getUserKey())) {
|
||||
return FeignUtils.isSuccess(response);
|
||||
}
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new ServiceException("更新网关配置文件失败:网关配置内容格式异常");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,180 @@
|
|||
package com.microservices.mon.k8s.service.impl;
|
||||
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.microservices.common.core.context.SecurityContextHolder;
|
||||
import com.microservices.common.core.utils.DateUtils;
|
||||
import com.microservices.mon.k8s.domain.*;
|
||||
import com.microservices.mon.k8s.domain.vo.*;
|
||||
import com.microservices.mon.k8s.service.IK8sDashboardService;
|
||||
import com.microservices.mon.k8s.service.IMicroStatusService;
|
||||
import com.microservices.mon.k8s.utils.PromQLConstant;
|
||||
import com.microservices.mon.k8s.utils.RancherResponseHandler;
|
||||
import com.microservices.system.api.RemoteGatewayService;
|
||||
import com.microservices.system.api.RemoteRancherService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cloud.context.config.annotation.RefreshScope;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RefreshScope
|
||||
public class MicroStatusServiceImpl extends CommonService implements IMicroStatusService {
|
||||
@Autowired
|
||||
private RemoteGatewayService remoteGatewayService;
|
||||
@Autowired
|
||||
private IK8sDashboardService k8sDashboardService;
|
||||
@Autowired
|
||||
private RemoteRancherService remoteRancherService;
|
||||
|
||||
@Override
|
||||
public K8sPodStartStopStatus getPodStartStopStatus() {
|
||||
List<K8sNamespace> k8sNamespaceList = k8sDashboardService.getK8sNamespaceList();
|
||||
List<String> namespaceNameList = k8sNamespaceList.stream().map(K8sNamespace::getName).collect(Collectors.toList());
|
||||
K8sPodStartStopStatus k8sPodStartStopStatus = new K8sPodStartStopStatus();
|
||||
JSONObject POD_START_COUNT = remoteGatewayService.getPrometheusQueryRes(PromQLConstant.POD_START_COUNT(cluster_id, namespaceNameList), SecurityContextHolder.getUserKey());
|
||||
PrometheusResVo prometheusResVo = POD_START_COUNT.toJavaObject(PrometheusResVo.class);
|
||||
k8sPodStartStopStatus.setStartCount(Integer.parseInt(PrometheusResVo.getPromStringValue(prometheusResVo)));
|
||||
|
||||
JSONObject POD_STOP_COUNT = remoteGatewayService.getPrometheusQueryRes(PromQLConstant.POD_COUNT(cluster_id, namespaceNameList), SecurityContextHolder.getUserKey());
|
||||
prometheusResVo = POD_STOP_COUNT.toJavaObject(PrometheusResVo.class);
|
||||
k8sPodStartStopStatus.setPodCount(Integer.parseInt(PrometheusResVo.getPromStringValue(prometheusResVo)));
|
||||
|
||||
JSONObject POD_START_DATE = remoteGatewayService.getPrometheusQueryRes(PromQLConstant.POD_START_DATE(cluster_id, namespaceNameList), SecurityContextHolder.getUserKey());
|
||||
prometheusResVo = POD_START_DATE.toJavaObject(PrometheusResVo.class);
|
||||
List<PrometheusResultVo> podStartDateList = PrometheusResVo.getPrometheusResultVoList(prometheusResVo);
|
||||
List<K8sPodStartStopDate> podStartStopDateList = new ArrayList<>();
|
||||
for (PrometheusResultVo result : podStartDateList) {
|
||||
K8sPodStartStopDate podStartStopDate = new K8sPodStartStopDate();
|
||||
String podName = result.getMetric().getString("pod");
|
||||
podStartStopDate.setPodName(podName);
|
||||
Long startTimeStamp = result.getValue().getLong(1);
|
||||
podStartStopDate.setStartDate(new Date(startTimeStamp * 1000));
|
||||
podStartStopDateList.add(podStartStopDate);
|
||||
}
|
||||
|
||||
JSONObject podListJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sPodList(cluster_id, SecurityContextHolder.getUserKey()), "获取所有容器列表");
|
||||
if (podListJson != null && podListJson.containsKey("data")) {
|
||||
List<RancherPodVo> rancherPodVoList = podListJson.getJSONArray("data").toList(RancherPodVo.class);
|
||||
for (RancherPodVo rancherPodVo : rancherPodVoList) {
|
||||
if (rancherPodVo.getMetadata() != null && rancherPodVo.getMetadata().getState() != null && rancherPodVo.getStatus() != null) {
|
||||
RancherMetadataState status = rancherPodVo.getMetadata().getState();
|
||||
if (!"running".equalsIgnoreCase(status.getName())) {
|
||||
JSONArray conditionList = rancherPodVo.getStatus().getConditions();
|
||||
for (int i = 0; i < conditionList.size(); i++) {
|
||||
JSONObject condition = conditionList.getJSONObject(i);
|
||||
if (condition != null && condition.containsKey("status") && !condition.getBoolean("status")) {
|
||||
Date stopDate = condition.getDate("lastTransitionTime");
|
||||
podStartStopDateList
|
||||
.stream()
|
||||
.filter(x -> x.getPodName().equalsIgnoreCase(rancherPodVo.getMetadata().getName()))
|
||||
.forEach(x -> {
|
||||
x.setStopDate(stopDate);
|
||||
x.setIsRunning(false);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
podStartStopDateList.sort(Comparator.comparing(K8sPodStartStopDate::getIsRunning));
|
||||
k8sPodStartStopStatus.setPodStartStopDateList(podStartStopDateList);
|
||||
return k8sPodStartStopStatus;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<K8sPodContainerMetric> getPodCpuUsage(Long step) {
|
||||
return getPodContainerMetric(PodMetricType.CPU_USAGE, step);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<K8sPodContainerMetric> getPodMemoryUsage(Long step) {
|
||||
return getPodContainerMetric(PodMetricType.MEMORY_USAGE, step);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<K8sPodContainerMetric> getPodDiskReads(Long step) {
|
||||
return getPodContainerMetric(PodMetricType.DISK_READ, step);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<K8sPodContainerMetric> getPodDiskWrites(Long step) {
|
||||
return getPodContainerMetric(PodMetricType.DISK_WRITE, step);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<K8sPodContainerMetric> getPodNetworkReception(Long step) {
|
||||
return getPodContainerMetric(PodMetricType.NETWORK_IN, step);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<K8sPodContainerMetric> getPodNetworkTransmission(Long step) {
|
||||
return getPodContainerMetric(PodMetricType.NETWORK_OUT, step);
|
||||
}
|
||||
|
||||
private List<K8sPodContainerMetric> getPodContainerMetric(PodMetricType type, Long step) {
|
||||
List<K8sPodContainerMetric> k8sPodContainerMetricList = new ArrayList<>();
|
||||
List<K8sNamespace> k8sNamespaceList = k8sDashboardService.getK8sNamespaceList();
|
||||
List<String> namespaceNameList = k8sNamespaceList.stream().map(K8sNamespace::getName).collect(Collectors.toList());
|
||||
// 设置默认统计频率
|
||||
if (step == null || step <= 0) {
|
||||
step = 10L;
|
||||
}
|
||||
// 设置查询时间范围为最近一小时
|
||||
Date now = DateUtils.getNowDate();
|
||||
final long endTime = now.getTime() / 1000;
|
||||
// 开始时间为当前时间减去1小时
|
||||
long startTime = now.getTime() / 1000 - 30 * 60;
|
||||
String query = null;
|
||||
switch (type) {
|
||||
case CPU_USAGE:
|
||||
query = PromQLConstant.ALL_POD_CPU_USAGE(namespaceNameList);
|
||||
break;
|
||||
case MEMORY_USAGE:
|
||||
query = PromQLConstant.ALL_POD_MEMORY_USAGE(namespaceNameList);
|
||||
break;
|
||||
case NETWORK_IN:
|
||||
query = PromQLConstant.ALL_POD_NETWORK_RECEPTION(namespaceNameList);
|
||||
break;
|
||||
case NETWORK_OUT:
|
||||
query = PromQLConstant.ALL_POD_NETWORK_TRANSMISSION(namespaceNameList);
|
||||
break;
|
||||
case DISK_READ:
|
||||
query = PromQLConstant.ALL_POD_DISK_READS(namespaceNameList);
|
||||
break;
|
||||
case DISK_WRITE:
|
||||
query = PromQLConstant.ALL_POD_DISK_WRITES(namespaceNameList);
|
||||
break;
|
||||
}
|
||||
JSONObject metricResJson = remoteGatewayService.getPrometheusQueryRangeRes(query, step, startTime, endTime, SecurityContextHolder.getUserKey());
|
||||
if (metricResJson != null && metricResJson.containsKey("data")) {
|
||||
PrometheusResVo prometheusResVo = metricResJson.toJavaObject(PrometheusResVo.class);
|
||||
if (prometheusResVo != null && prometheusResVo.isSuccess()) {
|
||||
List<PrometheusResultVo> prometheusResultVoList = prometheusResVo.getData().getResult();
|
||||
for (PrometheusResultVo prometheusResultVo : prometheusResultVoList) {
|
||||
K8sPodContainerMetric k8sPodContainerMetric = new K8sPodContainerMetric();
|
||||
k8sPodContainerMetric.setPodName(prometheusResultVo.getMetric().getString("container_label_io_kubernetes_pod_name"));
|
||||
k8sPodContainerMetric.setData(MetricCommonData.prometheusResultVoToMetric(prometheusResultVo.getValues()));
|
||||
k8sPodContainerMetricList.add(k8sPodContainerMetric);
|
||||
}
|
||||
}
|
||||
}
|
||||
return k8sPodContainerMetricList;
|
||||
}
|
||||
|
||||
enum PodMetricType {
|
||||
CPU_USAGE,
|
||||
MEMORY_USAGE,
|
||||
NETWORK_IN,
|
||||
NETWORK_OUT,
|
||||
DISK_READ,
|
||||
DISK_WRITE,
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,423 @@
|
|||
package com.microservices.mon.k8s.service.impl;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.microservices.common.core.context.SecurityContextHolder;
|
||||
import com.microservices.common.core.exception.ServiceException;
|
||||
import com.microservices.common.core.utils.DateUtils;
|
||||
import com.microservices.common.core.utils.StringUtils;
|
||||
import com.microservices.mon.k8s.domain.*;
|
||||
import com.microservices.mon.k8s.domain.vo.*;
|
||||
import com.microservices.mon.k8s.service.IK8sDashboardService;
|
||||
import com.microservices.mon.k8s.service.IMonCommonAsyncService;
|
||||
import com.microservices.mon.k8s.utils.CustomExecutorFactory;
|
||||
import com.microservices.mon.k8s.utils.PromQLConstant;
|
||||
import com.microservices.mon.k8s.utils.RancherResponseHandler;
|
||||
import com.microservices.system.api.RemoteGatewayService;
|
||||
import com.microservices.system.api.RemoteRancherService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cloud.context.config.annotation.RefreshScope;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RefreshScope
|
||||
public class MonCommonAsyncServiceImpl extends CommonService implements IMonCommonAsyncService {
|
||||
@Autowired
|
||||
private RemoteGatewayService remoteGatewayService;
|
||||
@Autowired
|
||||
@Lazy
|
||||
private IK8sDashboardService k8sDashboardService;
|
||||
@Autowired
|
||||
private RemoteRancherService remoteRancherService;
|
||||
|
||||
@Override
|
||||
public K8sClusterStatus getClusterStatus(String query) {
|
||||
K8sClusterStatus k8sClusterStatus = new K8sClusterStatus();
|
||||
CountDownLatch countDownLatch = new CountDownLatch(9);
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
JSONObject nodeCountJson = remoteGatewayService.getPrometheusQueryRes(PromQLConstant.CLUSTER_NODE_COUNT(cluster_id), SecurityContextHolder.getUserKey());
|
||||
k8sClusterStatus.setNodeCount(nodeCountJson.toJavaObject(PrometheusResVo.class));
|
||||
} finally {
|
||||
countDownLatch.countDown();
|
||||
}
|
||||
|
||||
});
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
JSONObject unavailableNodeCountJson = remoteGatewayService.getPrometheusQueryRes(PromQLConstant.CLUSTER_UNAVAILABLE_NODE_COUNT(cluster_id), SecurityContextHolder.getUserKey());
|
||||
k8sClusterStatus.setUnavailableNodeCount(unavailableNodeCountJson.toJavaObject(PrometheusResVo.class));
|
||||
} finally {
|
||||
countDownLatch.countDown();
|
||||
}
|
||||
});
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
JSONObject cpuUsageJson = remoteGatewayService.getPrometheusQueryRes(PromQLConstant.CLUSTER_CPU_USAGE(cluster_id), SecurityContextHolder.getUserKey());
|
||||
k8sClusterStatus.setCpuUsage(cpuUsageJson.toJavaObject(PrometheusResVo.class));
|
||||
} finally {
|
||||
countDownLatch.countDown();
|
||||
}
|
||||
});
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
JSONObject podUsageJson = remoteGatewayService.getPrometheusQueryRes(PromQLConstant.CLUSTER_POD_USAGE(cluster_id), SecurityContextHolder.getUserKey());
|
||||
k8sClusterStatus.setPodUsage(podUsageJson.toJavaObject(PrometheusResVo.class));
|
||||
} finally {
|
||||
countDownLatch.countDown();
|
||||
}
|
||||
});
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
JSONObject memoryUsageJson = remoteGatewayService.getPrometheusQueryRes(PromQLConstant.CLUSTER_MEMORY_USAGE(cluster_id), SecurityContextHolder.getUserKey());
|
||||
k8sClusterStatus.setMemoryUsage(memoryUsageJson.toJavaObject(PrometheusResVo.class));
|
||||
} finally {
|
||||
countDownLatch.countDown();
|
||||
}
|
||||
});
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
JSONObject totalRequestCountTodayJson = remoteGatewayService.getPrometheusQueryRes(PromQLConstant.TOTAL_REQUEST_COUNT_TODAY, SecurityContextHolder.getUserKey());
|
||||
k8sClusterStatus.setTotalRequestCountToday(totalRequestCountTodayJson.toJavaObject(PrometheusResVo.class));
|
||||
} finally {
|
||||
countDownLatch.countDown();
|
||||
}
|
||||
});
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
JSONObject averageRequestProcessingTimeTodayJson = remoteGatewayService.getPrometheusQueryRes(PromQLConstant.AVERAGE_REQUEST_PROCESSING_TIME_TODAY, SecurityContextHolder.getUserKey());
|
||||
k8sClusterStatus.setAverageRequestProcessingTimeToday(averageRequestProcessingTimeTodayJson.toJavaObject(PrometheusResVo.class));
|
||||
} finally {
|
||||
countDownLatch.countDown();
|
||||
}
|
||||
});
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
JSONObject requestSuccessRateTodayJson = remoteGatewayService.getPrometheusQueryRes(PromQLConstant.REQUEST_SUCCESS_RATE_TODAY, SecurityContextHolder.getUserKey());
|
||||
k8sClusterStatus.setRequestSuccessRateToday(requestSuccessRateTodayJson.toJavaObject(PrometheusResVo.class));
|
||||
} finally {
|
||||
countDownLatch.countDown();
|
||||
}
|
||||
});
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
List<K8sNamespace> k8sNamespaceList = k8sDashboardService.getNamespaceDetailList(false, null);
|
||||
k8sClusterStatus.setMicroserviceApplicationCount(k8sNamespaceList);
|
||||
List<String> namespaceNameList = k8sNamespaceList.stream().map(K8sNamespace::getName).collect(Collectors.toList());
|
||||
JSONObject microserviceRestartCountTodayJson = remoteGatewayService.getPrometheusQueryRes(PromQLConstant.MICROSERVICE_RESTART_COUNT_TODAY(cluster_id, namespaceNameList), SecurityContextHolder.getUserKey());
|
||||
k8sClusterStatus.setMicroserviceRestartCountToday(microserviceRestartCountTodayJson.toJavaObject(PrometheusResVo.class));
|
||||
|
||||
JSONObject podStatusJson = remoteGatewayService.getPrometheusQueryRes(PromQLConstant.POD_STATUS(cluster_id, namespaceNameList), SecurityContextHolder.getUserKey());
|
||||
k8sClusterStatus.setPodStatus(podStatusJson.toJavaObject(PrometheusResVo.class));
|
||||
} finally {
|
||||
countDownLatch.countDown();
|
||||
}
|
||||
});
|
||||
try {
|
||||
countDownLatch.await();
|
||||
} catch (InterruptedException e) {
|
||||
log.error("集群状态获取失败:{0}", e);
|
||||
throw new ServiceException("集群状态获取失败");
|
||||
}
|
||||
return k8sClusterStatus;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<K8sNamespace> getNamespaceDetailList(boolean needPod, String search) {
|
||||
List<RancherApplicationVo> rancherApplicationVoList = new ArrayList<>();
|
||||
List<K8sNamespace> k8sNamespaceList = new ArrayList<>();
|
||||
CountDownLatch applicationCountDownLatch = new CountDownLatch(4);
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
//调用rancher远程接口获取所有daemonsets列表
|
||||
JSONObject daemonsetsJsonObject = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sDaemonsetsList(cluster_id, SecurityContextHolder.getUserKey()), "获取DaemonSet类型应用");
|
||||
if (daemonsetsJsonObject != null && daemonsetsJsonObject.containsKey("data")) {
|
||||
rancherApplicationVoList.addAll(daemonsetsJsonObject.getJSONArray("data").toList(RancherApplicationVo.class));
|
||||
}
|
||||
} finally {
|
||||
applicationCountDownLatch.countDown();
|
||||
}
|
||||
});
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
//调用rancher远程接口获取所有deploy列表
|
||||
JSONObject deployJsonObject = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sDeployList(cluster_id, SecurityContextHolder.getUserKey()), "获取Deploy类型应用");
|
||||
if (deployJsonObject != null && deployJsonObject.containsKey("data")) {
|
||||
rancherApplicationVoList.addAll(deployJsonObject.getJSONArray("data").toList(RancherApplicationVo.class));
|
||||
}
|
||||
} finally {
|
||||
applicationCountDownLatch.countDown();
|
||||
}
|
||||
});
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
//调用rancher远程接口获取所有Stateful列表
|
||||
JSONObject statefulJsonObject = RancherResponseHandler.handleJsonObject(remoteRancherService
|
||||
.getK8sStatefulList(cluster_id, SecurityContextHolder.getUserKey()), "获取StatefulSet类型应用");
|
||||
if (statefulJsonObject != null && statefulJsonObject.containsKey("data")) {
|
||||
rancherApplicationVoList.addAll(statefulJsonObject.getJSONArray("data").toList(RancherApplicationVo.class));
|
||||
}
|
||||
} finally {
|
||||
applicationCountDownLatch.countDown();
|
||||
}
|
||||
});
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
k8sNamespaceList.addAll(k8sDashboardService.getK8sNamespaceList());
|
||||
} finally {
|
||||
applicationCountDownLatch.countDown();
|
||||
}
|
||||
});
|
||||
try {
|
||||
applicationCountDownLatch.await();
|
||||
} catch (InterruptedException e) {
|
||||
log.error("集群应用列表获取失败:{0}", e);
|
||||
throw new ServiceException("集群应用列表获取失败");
|
||||
}
|
||||
|
||||
|
||||
// 将rancher对象转换为k8s对象
|
||||
List<K8sApplication> k8sApplicationList = rancherApplicationVoList
|
||||
.stream()
|
||||
.map(RancherApplicationVo::toK8sApplication)
|
||||
.filter(x -> StringUtils.isEmpty(search) || x.getName().contains(search) || (StringUtils.isNotEmpty(x.getAlias()) && x.getAlias().contains(search)))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
CountDownLatch podCountDownLatch = new CountDownLatch(k8sNamespaceList.size());
|
||||
for (int i = 0; i < k8sNamespaceList.size(); i++) {
|
||||
int finalI = i;
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
K8sNamespace k8sNamespace = k8sNamespaceList.get(finalI);
|
||||
List<K8sApplication> namespaceApplicationList = k8sApplicationList
|
||||
.stream()
|
||||
.filter(k8sApplication -> k8sApplication.getNamespace().equals(k8sNamespace.getName()))
|
||||
.collect(Collectors.toList());
|
||||
if (needPod) {
|
||||
// 获取命名空间下pod列表
|
||||
JSONObject podListJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sPodListByNamespace(cluster_id, k8sNamespace.getName(), SecurityContextHolder.getUserKey()), "获取容器列表");
|
||||
List<RancherPodVo> rancherPodVoList;
|
||||
if (podListJson != null && podListJson.containsKey("data")) {
|
||||
rancherPodVoList = podListJson.getJSONArray("data").toList(RancherPodVo.class);
|
||||
for (int j = 0; j < namespaceApplicationList.size(); j++) {
|
||||
K8sApplication k8sApplication = namespaceApplicationList.get(j);
|
||||
List<RancherPodVo> applicationToPodList = rancherPodVoList.stream()
|
||||
.filter(rancherPodVo -> {
|
||||
if (!StringUtils.isEmpty(k8sApplication.getPodSelector())) {
|
||||
String[] podSelector = k8sApplication.getPodSelector().split("=");
|
||||
return rancherPodVo.getMetadata().getLabels().containsKey(podSelector[0])
|
||||
&& rancherPodVo.getMetadata().getLabels().get(podSelector[0]).equals(podSelector[1]);
|
||||
}
|
||||
return false;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
List<K8sApplicationPod> podList = applicationToPodList.stream().map(RancherPodVo::toK8sApplicationPod).sorted(Comparator.comparing(K8sApplicationPod::getName)).collect(Collectors.toList());
|
||||
k8sApplication.setPodList(podList);
|
||||
k8sApplication.setRestartCount(podList.stream().filter(x -> x.getRestartCount() != null).mapToInt(K8sApplicationPod::getRestartCount).sum());
|
||||
namespaceApplicationList.set(j, k8sApplication);
|
||||
}
|
||||
}
|
||||
}
|
||||
namespaceApplicationList.sort(Comparator.comparing(K8sApplication::getName));
|
||||
k8sNamespace.setApplicationList(namespaceApplicationList);
|
||||
k8sNamespaceList.set(finalI, k8sNamespace);
|
||||
} finally {
|
||||
podCountDownLatch.countDown();
|
||||
}
|
||||
});
|
||||
}
|
||||
try {
|
||||
podCountDownLatch.await();
|
||||
} catch (InterruptedException e) {
|
||||
log.error("K8S应用对象数据转换失败:{0}", e);
|
||||
throw new ServiceException("K8S应用对象数据转换失败");
|
||||
}
|
||||
k8sNamespaceList.sort(Comparator.comparing(K8sNamespace::getName));
|
||||
return k8sNamespaceList.stream().filter(x -> !x.getApplicationList().isEmpty()).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<K8sApplicationPod> getPodList() {
|
||||
List<K8sNamespace> k8sNamespaceList = k8sDashboardService.getK8sNamespaceList();
|
||||
CountDownLatch podCountDownLatch = new CountDownLatch(k8sNamespaceList.size());
|
||||
List<K8sApplicationPod> podList = new ArrayList<>();
|
||||
for (int i = 0; i < k8sNamespaceList.size(); i++) {
|
||||
int finalI = i;
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
K8sNamespace k8sNamespace = k8sNamespaceList.get(finalI);
|
||||
// 获取命名空间下pod列表
|
||||
JSONObject podListJson = RancherResponseHandler.handleJsonObject(remoteRancherService.getK8sPodListByNamespace(cluster_id, k8sNamespace.getName(), SecurityContextHolder.getUserKey()), "获取容器列表");
|
||||
|
||||
if (podListJson != null && podListJson.containsKey("data")) {
|
||||
List<RancherPodVo> rancherPodVoList = podListJson.getJSONArray("data").toList(RancherPodVo.class);
|
||||
podList.addAll(rancherPodVoList.stream().map(RancherPodVo::toK8sApplicationPod).collect(Collectors.toList()));
|
||||
}
|
||||
} finally {
|
||||
podCountDownLatch.countDown();
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
try {
|
||||
podCountDownLatch.await();
|
||||
} catch (InterruptedException e) {
|
||||
log.error("获取可视化面板容器列表失败:{0}", e);
|
||||
throw new ServiceException("获取可视化面板容器列表失败");
|
||||
}
|
||||
podList.sort(Comparator.comparing(K8sApplicationPod::getName));
|
||||
podList.sort(Comparator.comparing(K8sApplicationPod::getNamespace));
|
||||
return podList;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public K8sPodContainerMetricOverview getPodStatus(String podName, Long step) {
|
||||
K8sPodContainerMetricOverview k8SPodContainerMetricOverview = new K8sPodContainerMetricOverview();
|
||||
// 设置默认统计频率
|
||||
if (step == null || step <= 0) {
|
||||
step = 10L;
|
||||
}
|
||||
CountDownLatch countDownLatch = new CountDownLatch(6);
|
||||
// 设置查询时间范围为最近一小时
|
||||
Date now = DateUtils.getNowDate();
|
||||
final long endTime = now.getTime() / 1000;
|
||||
// 开始时间为当前时间减去1小时
|
||||
long startTime = now.getTime() / 1000 - 60 * 60;
|
||||
|
||||
|
||||
k8SPodContainerMetricOverview.setPodName(podName);
|
||||
|
||||
Long finalStep = step;
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
// 获取CPU使用率
|
||||
JSONObject metricResJson = remoteGatewayService.getPrometheusQueryRangeRes(PromQLConstant.POD_CPU_USAGE(podName), finalStep, startTime, endTime, SecurityContextHolder.getUserKey());
|
||||
List<MetricCommonData> metricCommonDataList = k8sDashboardService.getMetricCommonDataList(metricResJson);
|
||||
k8SPodContainerMetricOverview.setCpuUsage(metricCommonDataList);
|
||||
} finally {
|
||||
countDownLatch.countDown();
|
||||
}
|
||||
});
|
||||
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
// 获取内存使用情况
|
||||
JSONObject metricResJson = remoteGatewayService.getPrometheusQueryRangeRes(PromQLConstant.POD_MEMORY_USAGE(podName), finalStep, startTime, endTime, SecurityContextHolder.getUserKey());
|
||||
List<MetricCommonData> metricCommonDataList = k8sDashboardService.getMetricCommonDataList(metricResJson);
|
||||
k8SPodContainerMetricOverview.setMemoryUsage(metricCommonDataList);
|
||||
} finally {
|
||||
countDownLatch.countDown();
|
||||
}
|
||||
});
|
||||
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
// 获取磁盘写入情况
|
||||
JSONObject metricResJson = remoteGatewayService.getPrometheusQueryRangeRes(PromQLConstant.POD_DISK_WRITES(podName), finalStep, startTime, endTime, SecurityContextHolder.getUserKey());
|
||||
List<MetricCommonData> metricCommonDataList = k8sDashboardService.getMetricCommonDataList(metricResJson);
|
||||
k8SPodContainerMetricOverview.setDiskWrites(metricCommonDataList);
|
||||
} finally {
|
||||
countDownLatch.countDown();
|
||||
}
|
||||
});
|
||||
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
// 获取磁盘读取情况
|
||||
JSONObject metricResJson = remoteGatewayService.getPrometheusQueryRangeRes(PromQLConstant.POD_DISK_READS(podName), finalStep, startTime, endTime, SecurityContextHolder.getUserKey());
|
||||
List<MetricCommonData> metricCommonDataList = k8sDashboardService.getMetricCommonDataList(metricResJson);
|
||||
k8SPodContainerMetricOverview.setDiskReads(metricCommonDataList);
|
||||
} finally {
|
||||
countDownLatch.countDown();
|
||||
}
|
||||
});
|
||||
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
// 获取网络发送情况
|
||||
JSONObject metricResJson = remoteGatewayService.getPrometheusQueryRangeRes(PromQLConstant.POD_NETWORK_TRANSMISSION(podName), finalStep, startTime, endTime, SecurityContextHolder.getUserKey());
|
||||
List<MetricCommonData> metricCommonDataList = k8sDashboardService.getMetricCommonDataList(metricResJson);
|
||||
k8SPodContainerMetricOverview.setNetworkTransmission(metricCommonDataList);
|
||||
} finally {
|
||||
countDownLatch.countDown();
|
||||
}
|
||||
});
|
||||
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
// 获取网络接收情况
|
||||
JSONObject metricResJson = remoteGatewayService.getPrometheusQueryRangeRes(PromQLConstant.POD_NETWORK_RECEPTION(podName), finalStep, startTime, endTime, SecurityContextHolder.getUserKey());
|
||||
List<MetricCommonData> metricCommonDataList = k8sDashboardService.getMetricCommonDataList(metricResJson);
|
||||
k8SPodContainerMetricOverview.setNetworkReception(metricCommonDataList);
|
||||
} finally {
|
||||
countDownLatch.countDown();
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
countDownLatch.await();
|
||||
} catch (InterruptedException e) {
|
||||
log.error("获取微服务运行状态监控数据失败:{0}", e);
|
||||
throw new ServiceException("获取微服务运行状态监控数据失败");
|
||||
}
|
||||
return k8SPodContainerMetricOverview;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<K8SResourceUsage> getResourceUsageList(List<JSONObject> metricList, Date[] startAndEndDates, Long step) {
|
||||
List<K8SResourceUsage> resourceUsageList = Collections.synchronizedList(new ArrayList<>());
|
||||
CountDownLatch countDownLatch = new CountDownLatch(metricList.size() * 2);
|
||||
for (JSONObject metric : metricList) {
|
||||
String nodeInstance = metric.getString("instance");
|
||||
String nodeIp = metric.getString("ip");
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
JSONObject metricResJson = remoteGatewayService.getPrometheusQueryRangeRes(PromQLConstant.NODE_CPU_USAGE(nodeIp), step, startAndEndDates[0].getTime() / 1000, startAndEndDates[1].getTime() / 1000, SecurityContextHolder.getUserKey());
|
||||
List<MetricCommonData> metricCommonDataList = k8sDashboardService.getMetricCommonDataList(metricResJson);
|
||||
for (MetricCommonData metricCommonData : metricCommonDataList) {
|
||||
K8SResourceUsage k8SResourceUsage = new K8SResourceUsage();
|
||||
k8SResourceUsage.setOccurredTime(metricCommonData.getDate());
|
||||
k8SResourceUsage.setResourceType("K8S节点服务器");
|
||||
k8SResourceUsage.setResourceObject(String.format("%s(%s)", nodeInstance, nodeIp));
|
||||
k8SResourceUsage.setMessage(String.format("CPU使用率为:%s%%", metricCommonData.getValue()));
|
||||
resourceUsageList.add(k8SResourceUsage);
|
||||
}
|
||||
} finally {
|
||||
countDownLatch.countDown();
|
||||
}
|
||||
});
|
||||
CustomExecutorFactory.threadPoolExecutor.execute(() -> {
|
||||
try {
|
||||
JSONObject metricResJson = remoteGatewayService.getPrometheusQueryRangeRes(PromQLConstant.NODE_MEMORY_USAGE(nodeIp), step, startAndEndDates[0].getTime() / 1000, startAndEndDates[1].getTime() / 1000, SecurityContextHolder.getUserKey());
|
||||
List<MetricCommonData> metricCommonDataList = k8sDashboardService.getMetricCommonDataList(metricResJson);
|
||||
for (MetricCommonData metricCommonData : metricCommonDataList) {
|
||||
K8SResourceUsage k8SResourceUsage = new K8SResourceUsage();
|
||||
k8SResourceUsage.setOccurredTime(metricCommonData.getDate());
|
||||
k8SResourceUsage.setResourceType("K8S节点服务器");
|
||||
k8SResourceUsage.setResourceObject(String.format("%s(%s)", nodeInstance, nodeIp));
|
||||
k8SResourceUsage.setMessage(String.format("内存使用率为:%s%%", metricCommonData.getValue()));
|
||||
resourceUsageList.add(k8SResourceUsage);
|
||||
}
|
||||
} finally {
|
||||
countDownLatch.countDown();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
countDownLatch.await();
|
||||
} catch (InterruptedException e) {
|
||||
log.error("获取K8S资源占用数据失败:{0}", e);
|
||||
throw new ServiceException("获取K8S资源占用数据失败");
|
||||
}
|
||||
return resourceUsageList;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
package com.microservices.mon.k8s.utils;
|
||||
|
||||
import com.microservices.common.core.exception.ServiceException;
|
||||
import com.microservices.common.core.threadPool.ThreadPoolExecutorWrap;
|
||||
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 线程池工厂
|
||||
*
|
||||
* @author OTTO
|
||||
*/
|
||||
public class CustomExecutorFactory {
|
||||
/**
|
||||
* 创建线程池
|
||||
* 存在并发处理的情况,设置核心线程为2,设置有界队列长度为100,最大线程数为10
|
||||
* 当超出队列已满且达到最大线程数时抛出异常
|
||||
* Ncpu=CPU数量
|
||||
* Ucpu=目标CPU的使用率,0<=Ucpu<=1
|
||||
* W/C=任务等待时间与任务计算时间的比率
|
||||
* Nthreads =Ncpu*Ucpu*(1+W/C)
|
||||
*/
|
||||
public static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutorWrap(
|
||||
10
|
||||
, 20
|
||||
, 10
|
||||
, TimeUnit.SECONDS
|
||||
, new ArrayBlockingQueue<>(100)
|
||||
, Executors.defaultThreadFactory()
|
||||
, (r, executor) -> {
|
||||
throw new ServiceException("目前处理的人太多了,请稍后再试");
|
||||
}
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,114 @@
|
|||
package com.microservices.mon.k8s.utils;
|
||||
|
||||
import com.microservices.common.core.exception.ServiceException;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public class DateTimeNormalizer {
|
||||
|
||||
private static final int[] NORMAL_HOURS = {0, 6, 12, 18};
|
||||
|
||||
/**
|
||||
* 规范化
|
||||
*
|
||||
* @param start 开始时间(可为 null)
|
||||
* @param end 结束时间(可为 null)
|
||||
* @return 0-开始,1-结束
|
||||
*/
|
||||
public static Date[] normalize(Date start, Date end) {
|
||||
Date now = new Date();
|
||||
if (end == null) {
|
||||
end = now;
|
||||
}
|
||||
if (start == null) {
|
||||
// 如果开始时间为空则设置默认值为结束时间前十天
|
||||
Calendar c = Calendar.getInstance();
|
||||
c.setTime(end);
|
||||
c.add(Calendar.DAY_OF_MONTH, -10);
|
||||
start = c.getTime();
|
||||
}
|
||||
|
||||
if (start.after(end)) {
|
||||
throw new ServiceException("开始时间不能晚于结束时间");
|
||||
}
|
||||
start = normalizeDown(start);
|
||||
end = normalizeUp(end);
|
||||
return new Date[]{start, end};
|
||||
}
|
||||
|
||||
/* ---------- 核心工具 ---------- */
|
||||
|
||||
private static Date normalizeDown(Date d) {
|
||||
Calendar c = Calendar.getInstance();
|
||||
c.setTime(d);
|
||||
c.set(Calendar.MINUTE, 0);
|
||||
c.set(Calendar.SECOND, 0);
|
||||
c.set(Calendar.MILLISECOND, 0);
|
||||
|
||||
int hour = c.get(Calendar.HOUR_OF_DAY);
|
||||
int target = 0;
|
||||
for (int i = NORMAL_HOURS.length - 1; i >= 0; i--) {
|
||||
if (NORMAL_HOURS[i] <= hour) {
|
||||
target = NORMAL_HOURS[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (target > hour) { // 说明 hour < 0(不可能),或向前跨天
|
||||
c.add(Calendar.DATE, -1);
|
||||
target = 18;
|
||||
}
|
||||
c.set(Calendar.HOUR_OF_DAY, target);
|
||||
return c.getTime();
|
||||
}
|
||||
|
||||
private static Date normalizeUp(Date d) {
|
||||
Calendar c = Calendar.getInstance();
|
||||
c.setTime(d);
|
||||
c.set(Calendar.MINUTE, 0);
|
||||
c.set(Calendar.SECOND, 0);
|
||||
c.set(Calendar.MILLISECOND, 0);
|
||||
|
||||
int hour = c.get(Calendar.HOUR_OF_DAY);
|
||||
int target = 0;
|
||||
for (int nh : NORMAL_HOURS) {
|
||||
if (nh >= hour) {
|
||||
target = nh;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (target < hour) { // 说明需要次日 00:00
|
||||
c.add(Calendar.DATE, 1);
|
||||
}
|
||||
c.set(Calendar.HOUR_OF_DAY, target);
|
||||
return c.getTime();
|
||||
}
|
||||
|
||||
/* ---------- 简单测试 ---------- */
|
||||
public static void main(String[] args) {
|
||||
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
Date start = parse("2025-10-01 04:59:21");
|
||||
Date end = parse("2025-10-11 11:02:03");
|
||||
|
||||
Date[] r1 = normalize(start, end);
|
||||
System.out.println("开始: " + sdf.format(r1[0]));
|
||||
System.out.println("结束: " + sdf.format(r1[1]));
|
||||
|
||||
Date[] r2 = normalize(null, end);
|
||||
System.out.println("开始: " + sdf.format(r2[0]));
|
||||
System.out.println("结束: " + sdf.format(r2[1]));
|
||||
|
||||
Date[] r3 = normalize(start, null);
|
||||
System.out.println("开始: " + sdf.format(r3[0]));
|
||||
System.out.println("结束: " + sdf.format(r3[1]));
|
||||
}
|
||||
|
||||
private static Date parse(String s) {
|
||||
try {
|
||||
return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(s);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue