Commit babfff41 authored by chenchao.deng's avatar chenchao.deng

对腾讯云api

parent f41957ad
......@@ -195,10 +195,16 @@
<version>5.0.13</version>
</dependency>
<!--腾讯云 云服务器ECS api -->
<!-- <dependency>-->
<!-- <groupId>com.tencentcloudapi</groupId>-->
<!-- <artifactId>tencentcloud-sdk-java</artifactId>-->
<!-- <version>3.1.830</version>-->
<!-- </dependency>-->
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<version>3.1.830</version>
<version>3.1.1091</version>
</dependency>
</dependencies>
......
......@@ -7,42 +7,31 @@ public class CloudamAlipayConfig extends AlipayConfig{
@Override
public String getAPPID() {
return "2019071765790965";
return "2021004169642053";
}
@Override
public String getAPP_PRIVATE_KEY() {
return "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDDU+npZLO6AoKN" +
"lQBO/3gOMTJEeOBDV5zRdvkrMUBq8R5r5phzkq2T2lxg5gMnZx6Lk/NZ0evSntMG" +
"PzKXFEmVdBKRuqQvQ7gaZNeWA494sCP76dEDPREcvs7qcP7xTuK9/FTqPQH3iUEA" +
"058N03/edQGdv1HLi3BmTYdp2ywZQsb0hqGu6/pPYCLnwSprBdWv1nG3zstcBEmK" +
"PYNKipzy0LpHiGB445XO0EJWV/XK6t1knDKrC6FFiFfxuLy3fHy37jjFW2TxZLSc" +
"ROGs0Py+w9saxIJ1n7jGJqHCQmyuNgPKtelYy1jpbdXIX/2bhW1ck4dOCF8j37Gc" +
"cGZR+c3nAgMBAAECggEASFW1FDe0zzfKvT/mw1qcTTUu1milNIsnifKzR6mPn4r3" +
"pyHYZ0R0f4KoH0JO/LKVfz8lKagx2ufyYifZRlW/Alff4JPr5Y0AitW5eNaMtTcV" +
"vF7UhoyA39JRskRyRU7fbVga4jwBlHgB2JqGFoqymeFe3dpSIjzbPSeM9Ei0Rg3s" +
"hIv+An/U2optO29ggsC0hXyHWXLupaMwbIpBTOHDiFzxW7z4ZxU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fLzy5xk6bFW2Jwkr9jD5TqkpjgI3ZYykz1VkgFxASHUo8+6tHjoOfhtul0MyDbtU8"
+ "/XrXr6spGRGRsHbxTiRj4wflKJHXFwZHM3Bq+5jV8m5SOlHXx62PkTCk8BJsrwYT06CZz3VH8M72JYiZu05Zm8AMKYjKmsmLdzCozL4PB7ztPWmGvLe+5Nc0As2urLBgfX7XGWHju"
+ "k8VsZaxQaVSn4z7cr4eP9iijmqJJXBFhtQLqzMjtlBRqqFn0kvUHiPg/ndEXq8TEVqN0uaSDdIZ+LPrIVvMnmcyaHKBn1fHQHNNaho9B/5PwHMYumQIDAQAB";
}
@Override
......
......@@ -7,43 +7,31 @@ public class VpsAlipayConfig extends AlipayConfig{
@Override
public String getAPPID() {
return "2019091967616095";
return "2021004169642053";
}
@Override
public String getAPP_PRIVATE_KEY() {
return "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDQi9PVnyGA+r1Q"+
"Fu08beA/oGX1FBBWMl6A1e7LydbpFutHY2gtLszQquM2CnfR6cS+p2lhNLRO1al9" +
"LO26NR7F+UEbj0ieo1HLss8jS8qpmIcMjWdYYvEbiK19lEW0aYO2tgDKj+JGtvru" +
"L9mBZnr4quuQPa8gBb07DbJ+GsXBNWfRyz3YjVKfzwbU85azu72Gh/cRvqX6Zcbk" +
"1nlbfvHkhGTv/JkTQBT3ilo2bhPffFyArI20gwA0a9zAGr4h31QOl6Sw6mv3q8ed" +
"u4vBl0vVAAKiQJW1e52thLuJ5tflZToqnk5A7QdwqfCe8mksA3V/97+T04bUzINn" +
"QhFK4Q/JAgMBAAECggEAbN0BONt33t+FIaDGOKxWyoANmTDfEk/62yBSJpl3kXfA" +
"XCS9RhDPJAKA1z4BrFdut+Omc/LSSPDqKAjjFDgUl131KdDTJNS2pzHxRUiUQ5H2" +
"tYu/LfmASVJA1nQnKvWFp0Q9B4Cyqx1rwhjCXvVDLjny+/nnSD0WuhP9YCzTnHY1" +
"U7djStrlHmVm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BIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlryO1G3TVb9mRVS08U19s1ydhyfLzy5xk6bFW2Jwkr9jD5TqkpjgI3ZYykz1VkgFxASHUo8+6tHjoOfhtul0MyDbtU8"
+ "/XrXr6spGRGRsHbxTiRj4wflKJHXFwZHM3Bq+5jV8m5SOlHXx62PkTCk8BJsrwYT06CZz3VH8M72JYiZu05Zm8AMKYjKmsmLdzCozL4PB7ztPWmGvLe+5Nc0As2urLBgfX7XGWHju"
+ "k8VsZaxQaVSn4z7cr4eP9iijmqJJXBFhtQLqzMjtlBRqqFn0kvUHiPg/ndEXq8TEVqN0uaSDdIZ+LPrIVvMnmcyaHKBn1fHQHNNaho9B/5PwHMYumQIDAQAB";
}
@Override
......
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form name="punchout_form" method="post" action="https://openapi.alipay.com/gateway.do?charset=utf-8&method=alipay.trade.page.pay&sign=QSc3QsyyBSvtRWHrvD0eoUxRxMb080CUde5BowfoPaUZyVmwXtAGFiKN8DCspxOB7D1I1cbhWZkUcP%2FRAJ8xmnxg7Cqnp84tyO3%2FbmigYWoqD2frlPzdIDOt6%2Fg5NU%2FltVa%2F2LOoTnMVdhVeBgzlJ9vfFTQXvjaNofufN0Y3b%2F7Lxu7AqOk%2BhJtV%2BzWtSLO5C1zf5%2BhIyV%2Fmx86gBBFFdZ4Lv1iTSdxuRNOC6U15GoOq0BZGYlr9kIaE%2BbztC9y%2F72c%2FUP98hXGWRYG0p5iiNpNe2Dq3StuDgzFrlkpYPG4uu7l5%2B%2Fth3%2Bem0ivPDgWj4iu2DO92tnAFXhMVufQtzA%3D%3D&return_url=https%3A%2F%2Fwww.fangguanlian.cn%2Fweb%2FpaySuccess.html%3Falipayreturn%3D202409112024253737&notify_url=https%3A%2F%2Fwww.cloudam.cn%2Faccounts%2F0xalipaycallback%2F202409112024253737&version=1.0&app_id=2021004169642053&sign_type=RSA2&timestamp=2024-09-11+20%3A24%3A28&alipay_sdk=alipay-sdk-java-3.7.110.ALL&format=json">
<input type="hidden" name="biz_content" value="{&quot;out_trade_no&quot;:&quot;202409112024253737&quot;,&quot;product_code&quot;:&quot;FAST_INSTANT_TRADE_PAY&quot;,&quot;total_amount&quot;:&quot;100.00&quot;,&quot;subject&quot;:&quot;订单202409112024253737&quot;,&quot;body&quot;:&quot;&quot;}">
<input type="submit" value="立即支付" style="display:none" >
</form>
<script>document.forms[0].submit();</script>
</body>
</html>
\ No newline at end of file
......@@ -31,4 +31,8 @@ public class CloudPlatformConfig {
private String usableArea;//可用区
private String imageId; //镜像id
private String keyId; //镜像id
}
......@@ -18,9 +18,17 @@ public class ReceptionPlatformOptions {
private String platform;//平台
private String platformDesc;//平台描述
private String url;//网址
private int platformType;//平台类型: 1:全球开店 2:亚马逊站点
private String url1;//网址
private String url2;//网址
private String url3;//网址
private int platformType;//平台类型: 1:全球开店 2:亚马逊站点 3.网址导航
private int childType;//子类型
......
......@@ -5,14 +5,12 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
public interface LoginHistoryRepository extends MongoRepository<LoginHistory, String> {
LoginHistory findFirstByUsername(String username);
Page<LoginHistory> findByAdministratorAndLoginTimeGreaterThanOrderByLoginTime(String administrator, long time, Pageable pageable);
Page<LoginHistory> findByAdministratorAndLoginTimeGreaterThanOrderByLoginTimeDesc(String administrator, long time, Pageable pageable);
Page<LoginHistory> findByUsernameAndLoginTimeGreaterThanOrderByLoginTime(String username, long time, Pageable pageable);
Page<LoginHistory> findByUsernameAndLoginTimeGreaterThanOrderByLoginTimeDesc(String username, long time, Pageable pageable);
int countByUsername(String username);
}
......@@ -96,9 +96,9 @@ public class HistoryServiceImpl implements HistoryService {
Page<LoginHistory> loginHistoryPage;
long time = Instant.now().atZone(ZoneOffset.UTC).minusDays(historyListRequestDto.getDay()).toInstant().toEpochMilli();
if (account.getParent() == null) {
loginHistoryPage = loginHistoryRepository.findByAdministratorAndLoginTimeGreaterThanOrderByLoginTime(username, time, pageable);
loginHistoryPage = loginHistoryRepository.findByAdministratorAndLoginTimeGreaterThanOrderByLoginTimeDesc(username, time, pageable);
} else {
loginHistoryPage = loginHistoryRepository.findByUsernameAndLoginTimeGreaterThanOrderByLoginTime(username, time, pageable);
loginHistoryPage = loginHistoryRepository.findByUsernameAndLoginTimeGreaterThanOrderByLoginTimeDesc(username, time, pageable);
}
List<LoginHistoryDto> loginHistoryDtoList = new ArrayList<>();
......
......@@ -2,6 +2,7 @@ package com.edgec.browserbackend.browser.service.Impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.sdk.service.ecs20140526.models.DeleteInstanceResponse;
import com.aliyun.sdk.service.ecs20140526.models.DescribeInstancesResponse;
import com.aliyun.sdk.service.ecs20140526.models.DescribeInstancesResponseBody.Instance;
import com.aliyun.sdk.service.ecs20140526.models.RenewInstanceResponse;
......@@ -20,9 +21,12 @@ import com.edgec.browserbackend.browser.repository.*;
import com.edgec.browserbackend.browser.service.IpAndShopService;
import com.edgec.browserbackend.browser.service.IpResourceService;
import com.edgec.browserbackend.common.client.AliEcsClient;
import com.edgec.browserbackend.common.client.TenCentEcsClient;
import com.edgec.browserbackend.common.commons.error.ClientRequestException;
import com.edgec.browserbackend.common.commons.utils.NotifyUtils;
import com.edgec.browserbackend.common.utils.FileUtil;
import com.tencentcloudapi.cvm.v20170312.models.RenewInstancesResponse;
import com.tencentcloudapi.cvm.v20170312.models.TerminateInstancesResponse;
import java.time.format.DateTimeFormatter;
import javax.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
......@@ -153,6 +157,9 @@ public class IpResourceServiceImpl implements IpResourceService {
@Resource
private CloudPlatformOrderRepository cloudPlatformOrderRepository;
@Resource
private CloudPlatformConfigRepository cloudPlatformConfigRepository;
public HttpHeaders buildPostHeader() {
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_JSON);
......@@ -194,6 +201,9 @@ public class IpResourceServiceImpl implements IpResourceService {
.map(x -> x.substring(x.lastIndexOf("-") + 1))
.collect(Collectors.joining());
newprice = "week".equals(ipResourceRequestDto.getUnit()) ? (Integer.valueOf(price) / 3) : Integer.valueOf(price);
}else {
//自有ip设置成1元
newprice = 1;
}
// 3. 计算总共需要花费多少钱 并 校验账户余额 够不够扣费
......@@ -542,7 +552,6 @@ public class IpResourceServiceImpl implements IpResourceService {
Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
String URL = (profiles.equals("dev") || profiles.equals("staging")) ? TESTURL : CLOUDAMURL;
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = buildGetHeader();
Map<String, String> params = new HashMap<String, String>();
......@@ -574,36 +583,54 @@ public class IpResourceServiceImpl implements IpResourceService {
}
try {
// 调用 uri删除远程的 IP资源
ResponseEntity<String> result = restTemplate.exchange(URL + "/intelligroup/ipresources?accountId=browser&ip={ip}", HttpMethod.DELETE, httpEntity, String.class, ipAddr);
DeleteIpResultDto deleteIpResultDto = JSON.parseObject(result.getBody(), DeleteIpResultDto.class);
if (deleteIpResultDto.getResult().equals("failed") || StringUtils.isNotBlank(deleteIpResultDto.getErrorCode())) {
NotifyUtils.sendMessage("防关联浏览器 ip " + ipResource.getAddr() + " 删除失败", NotifyUtils.MsgType.WEBHOOK);
logger.error("ip " + ipResource.getAddr() + " 删除失败");
logger.error("ErrorCode: " + deleteIpResultDto.getErrorCode() + " " + deleteIpResultDto.getResult());
}
} catch (Exception e) {
logger.error("fail to delete ip", e);
ipOperationResultDto.getFailList().add(ipAddr);
}
try {
// ip资源为未绑定,则直接删除
if (ipResource.getStatus() == 6) {
ipResourceRepository.delete(ipResource);
// 其他情况(主要是 ip资源还未创建成功的状态),则将 ip资源的状态改为删除
} else {
ipResource.setShopIds(null);
ipResource.setDeleted(true);
ipResourceRepository.save(ipResource);
}else {
List<CloudPlatformOrder> list = cloudPlatformOrderRepository.findByOwnerAndIpResourceId(
ipResource.getOwner(), ipResource.getId());
if (CollectionUtils.isNotEmpty(list)) {
CloudPlatformOrder cloudPlatformOrder = list.get(0);
Boolean isDelet = false;
if ("aliyun".equals(cloudPlatformOrder.getPlatformType())) {
DeleteInstanceResponse response = AliEcsClient.deleteInstance(
ipResource.getOwner(),
cloudPlatformOrder.getPlatformOrderId(),
cloudPlatformOrder.getRegionId());
if (null != response && response.getStatusCode()
.equals(200)) {
isDelet = true;
}
} else if ("tenCent".equals(
cloudPlatformOrder.getPlatformType())) {
CloudPlatformConfig config = cloudPlatformConfigRepository.findByPlatformAndRegionId(
"tenCent",
cloudPlatformOrder.getRegionId());
TerminateInstancesResponse response = null;
if (StringUtils.isNotEmpty(config.getTemplateId())) {
response = TenCentEcsClient.deleteInstance(
ipResource.getOwner(),
cloudPlatformOrder.getPlatformOrderId(),
cloudPlatformOrder.getRegionId());
}
if (null != response) {
isDelet = true;
}
}
if (!isDelet) {
ipResource.setShopIds(null);
ipResource.setDeleted(true);
ipResourceRepository.save(ipResource);
} else {
logger.error("ip " + ipResource.getAddr() + " 删除失败");
logger.error("Scheduled {}, {} delete failed",
ipResource.getAddr());
}
}
}
ipOperationResultDto.getSuccessList().add(ipAddr);
} catch (Exception e) {
logger.error("fail to delete ip", e);
ipOperationResultDto.getFailList().add(ipAddr);
return;
}
}
);
......@@ -620,12 +647,29 @@ public class IpResourceServiceImpl implements IpResourceService {
ipResourceRepository.delete(ipResource);
} else if (StringUtils.isNotBlank(ipResource.getAddr()) && ipResource.getIpType() == IpType.VENDOR) {
try {
ResponseEntity<String> result = restTemplate.exchange(URL + "/intelligroup/ipresources?accountId=browser&ip={ip}",
HttpMethod.DELETE, httpEntity, String.class, ipResource.getAddr());
DeleteIpResultDto deleteIpResultDto = JSON.parseObject(result.getBody(), DeleteIpResultDto.class);
if (deleteIpResultDto.getResult().equals("failed") || StringUtils.isNotBlank(deleteIpResultDto.getErrorCode())) {
NotifyUtils.sendMessage("防关联浏览器 ip " + ipResource.getAddr() + " 删除失败", NotifyUtils.MsgType.WEBHOOK);
logger.error("ip " + ipResource.getAddr() + " 删除失败");
List<CloudPlatformOrder> list = cloudPlatformOrderRepository.findByOwnerAndIpResourceId(
ipResource.getOwner(), ipResource.getId());
if (CollectionUtils.isNotEmpty(list)) {
CloudPlatformOrder cloudPlatformOrder = list.get(0);
if ("aliyun".equals(cloudPlatformOrder.getPlatformType())) {
DeleteInstanceResponse response = AliEcsClient.deleteInstance(
ipResource.getOwner(),
cloudPlatformOrder.getPlatformOrderId(),
cloudPlatformOrder.getRegionId());
} else if ("tenCent".equals(
cloudPlatformOrder.getPlatformType())) {
CloudPlatformConfig config = cloudPlatformConfigRepository.findByPlatformAndRegionId(
"tenCent",
cloudPlatformOrder.getRegionId());
TerminateInstancesResponse response = null;
if (StringUtils.isNotEmpty(config.getTemplateId())) {
response = TenCentEcsClient.deleteInstance(
ipResource.getOwner(),
cloudPlatformOrder.getPlatformOrderId(),
cloudPlatformOrder.getRegionId());
}
}
}
} catch (Exception t) {
logger.error("ip " + ipResource.getAddr() + " 删除失败", t);
......@@ -1136,6 +1180,18 @@ public class IpResourceServiceImpl implements IpResourceService {
ipData.setIp(ipResource.getAddr());
ipDataList.add(ipData);
}
}else if("tenCent".equals(cloudPlatformOrder.getPlatformType())){
RenewInstancesResponse response = TenCentEcsClient.renewInstance(
ipResource.getOwner(), cloudPlatformOrder.getRegionId(),
cloudPlatformOrder.getPlatformOrderId(), period);
if (null ==response) {
logger.error("fail to renew ip : {}", JSON.toJSON(response));
}else if(Objects.nonNull(response.getRequestId())){
IPData ipData = new IPData();
ipData.setIp(ipResource.getAddr());
ipDataList.add(ipData);
}
}
}
......
......@@ -38,6 +38,7 @@ import com.edgec.browserbackend.common.utils.ThreadPoolUtils;
import com.edgec.browserbackend.common.utils.Trans;
import com.tencentcloudapi.cvm.v20170312.models.ModifyInstancesChargeTypeResponse;
import com.tencentcloudapi.cvm.v20170312.models.TerminateInstancesResponse;
import com.tencentcloudapi.lighthouse.v20200324.models.CreateInstancesResponse;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
......@@ -105,24 +106,31 @@ public class BrowserTask {
public Map<String, String> buildGetHeader() {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
if (profiles.equals("dev") || profiles.equals("staging"))
headers.put("Authorization", "Bearer oq5tg3gMsflHcK5iZ2741G5R30XYd9blyOqH9qeBItKtrzfTsGIoy8AsxqqNXdcm");
else if (profiles.equals("prod"))
headers.put("Authorization", "Bearer tKWsuHzcngf0RQPMss70f9jgymDIwgQ9zbLfESJdcou3pZSNWl7lNTzto8VQgwaO");
if (profiles.equals("dev") || profiles.equals("staging")) {
headers.put("Authorization",
"Bearer oq5tg3gMsflHcK5iZ2741G5R30XYd9blyOqH9qeBItKtrzfTsGIoy8AsxqqNXdcm");
} else if (profiles.equals("prod")) {
headers.put("Authorization",
"Bearer tKWsuHzcngf0RQPMss70f9jgymDIwgQ9zbLfESJdcou3pZSNWl7lNTzto8VQgwaO");
}
return headers;
}
public Map<String, String> buildPostHeader() {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
if (profiles.equals("dev") || profiles.equals("staging"))
headers.put("Authorization", "Bearer oq5tg3gMsflHcK5iZ2741G5R30XYd9blyOqH9qeBItKtrzfTsGIoy8AsxqqNXdcm");
else if (profiles.equals("prod"))
headers.put("Authorization", "Bearer tKWsuHzcngf0RQPMss70f9jgymDIwgQ9zbLfESJdcou3pZSNWl7lNTzto8VQgwaO");
if (profiles.equals("dev") || profiles.equals("staging")) {
headers.put("Authorization",
"Bearer oq5tg3gMsflHcK5iZ2741G5R30XYd9blyOqH9qeBItKtrzfTsGIoy8AsxqqNXdcm");
} else if (profiles.equals("prod")) {
headers.put("Authorization",
"Bearer tKWsuHzcngf0RQPMss70f9jgymDIwgQ9zbLfESJdcou3pZSNWl7lNTzto8VQgwaO");
}
return headers;
}
private IpChargeRequestDto buildIpChargeRequestDto(IpResource request, int chargeType, int payMethod) {
private IpChargeRequestDto buildIpChargeRequestDto(IpResource request, int chargeType,
int payMethod) {
IpChargeRequestDto ipChargeRequestDto = new IpChargeRequestDto();
ipChargeRequestDto.setAmount(1);
ipChargeRequestDto.setChargeType(chargeType);
......@@ -152,9 +160,11 @@ public class BrowserTask {
log.info("{}, ip resource purchase : {}", logs, ipResource.getId());
try {
RegionMappingEnum byRegion = RegionMappingEnum.getByRegion(ipResource.getRegion());
if(Objects.isNull(byRegion)){
log.error("buyIpNewTasks-购买ip error:查询不到地区映射-region:{}",ipResource.getRegion());
RegionMappingEnum byRegion = RegionMappingEnum.getByRegion(
ipResource.getRegion());
if (Objects.isNull(byRegion)) {
log.error("buyIpNewTasks-购买ip error:查询不到地区映射-region:{}",
ipResource.getRegion());
return;
}
......@@ -163,26 +173,34 @@ public class BrowserTask {
cloudPlatformOrder.setOwner(ipResource.getOwner());
cloudPlatformOrder.setIpResourceId(ipResource.getId());
boolean result = false;
if(ipResource.getVendorCn().equals("阿里云")){
if (ipResource.getVendorCn().equals("阿里云")) {
//获取阿里云服务器region映射
String aliRegion = RegionMappingEnum.getAliRegion(ipResource.getRegion());
if(StringUtils.isEmpty(aliRegion)){
log.error("buyIpNewTasks-购买ip error:查询不到阿里云映射api-region:{}",ipResource.getRegion());
String aliRegion = RegionMappingEnum.getAliRegion(
ipResource.getRegion());
if (StringUtils.isEmpty(aliRegion)) {
log.error(
"buyIpNewTasks-购买ip error:查询不到阿里云映射api-region:{}",
ipResource.getRegion());
return;
}
CloudPlatformConfig config = cloudPlatformConfigRepository.findByPlatformAndRegionId("ali",
CloudPlatformConfig config = cloudPlatformConfigRepository.findByPlatformAndRegionId(
"ali",
aliRegion);
if(Objects.isNull(config)){
log.error("buyIpNewTasks-购买ip error:查询不到阿里云模板配置-region:{}", aliRegion);
if (Objects.isNull(config)) {
log.error(
"buyIpNewTasks-购买ip error:查询不到阿里云模板配置-region:{}",
aliRegion);
return;
}
RunInstancesResponse response = AliEcsClient.runInstances(
ipResource.getOwner(), ipResource.getUsername(),ipResource.getPassword(), config);
if (null ==response || !response.getStatusCode().equals(200)) {
ipResource.getOwner(), ipResource.getUsername(),
ipResource.getPassword(), config);
if (null == response || !response.getStatusCode().equals(200)) {
log.error("{}, fail to buy ip : {}", logs, JSON.toJSON(response));
}else if(Objects.nonNull(response.getBody())){
String instanceId = response.getBody().getInstanceIdSets().getInstanceIdSet().get(0);
} else if (Objects.nonNull(response.getBody())) {
String instanceId = response.getBody().getInstanceIdSets()
.getInstanceIdSet().get(0);
cloudPlatformOrder.setPlatformOrderId(instanceId);
cloudPlatformOrder.setPlatformType("aliyun");
cloudPlatformOrder.setRegionId(aliRegion);
......@@ -192,24 +210,44 @@ public class BrowserTask {
cloudPlatformOrderRepository.save(cloudPlatformOrder);
result = true;
}
}else if(ipResource.getVendorCn().equals("腾讯云")){
} else if (ipResource.getVendorCn().equals("腾讯云")) {
//获取腾讯云服务器region映射
String tenCentRegion = RegionMappingEnum.getTenCentRegion(ipResource.getRegion());
if(StringUtils.isEmpty(tenCentRegion)){
log.error("buyIpNewTasks-购买ip error:查询不到腾讯云映射api-region:{}",ipResource.getRegion());
String tenCentRegion = RegionMappingEnum.getTenCentRegion(
ipResource.getRegion());
if (StringUtils.isEmpty(tenCentRegion)) {
log.error(
"buyIpNewTasks-购买ip error:查询不到腾讯云映射api-region:{}",
ipResource.getRegion());
return;
}
CloudPlatformConfig config = cloudPlatformConfigRepository.findByPlatformAndRegionId("tenCent",
CloudPlatformConfig config = cloudPlatformConfigRepository.findByPlatformAndRegionId(
"tenCent",
tenCentRegion);
if(Objects.isNull(config)){
log.error("buyIpNewTasks-购买ip error:查询不到腾讯云模板配置-region:{}", tenCentRegion);
if (Objects.isNull(config)) {
log.error(
"buyIpNewTasks-购买ip error:查询不到腾讯云模板配置-region:{}",
tenCentRegion);
return;
}
com.tencentcloudapi.cvm.v20170312.models.RunInstancesResponse response =
TenCentEcsClient.runInstances(ipResource.getOwner(), ipResource.getUsername(), ipResource.getPassword(), config);
if(Objects.nonNull(response.getInstanceIdSet())){
String instanceId = response.getInstanceIdSet()[0];
String instanceId = null;
if (StringUtils.isNotEmpty(config.getTemplateId())) {
com.tencentcloudapi.cvm.v20170312.models.RunInstancesResponse response =
TenCentEcsClient.runInstances(ipResource.getOwner(),
ipResource.getUsername(), ipResource.getPassword(),
config);
if (Objects.nonNull(response) && Objects.nonNull(response.getInstanceIdSet())) {
instanceId = response.getInstanceIdSet()[0];
}
} else {
CreateInstancesResponse response1 = TenCentEcsClient.createInstances(
ipResource.getOwner(), ipResource.getUsername(),
ipResource.getPassword(), config);
if (null != response1 && null == response1.getInstanceIdSet()) {
instanceId = response1.getInstanceIdSet()[0];
}
}
if (StringUtils.isNotEmpty(instanceId)) {
cloudPlatformOrder.setPlatformOrderId(instanceId);
cloudPlatformOrder.setPlatformType("tenCent");
cloudPlatformOrder.setRegionId(tenCentRegion);
......@@ -228,24 +266,31 @@ public class BrowserTask {
* 购买malaysia实例失败后不进行重新购买
* 购买时长超过20分钟的ip资源释放,并将购买花销退回账户余额。
*/
boolean overtime = ipResource.getPurchasedTime() < Instant.now().minusSeconds(7200).toEpochMilli();
boolean overtime =
ipResource.getPurchasedTime() < Instant.now().minusSeconds(7200)
.toEpochMilli();
/*boolean problemRegion = "malaysia".equals(ipResource.getRegion());
boolean deal = overtime || problemRegion;*/
if (!result && overtime) {
log.info("{}, ip resource purchase failure, {}", logs, ipResource);
IpChargeRequestDto ipChargeRequestDto = buildIpChargeRequestDto(ipResource, 3, 0);
accountService.chargeByMoney(ipResource.getOwner(), -ipResource.getPrice(), ipChargeRequestDto);
if (ipResource.getShopIds() != null && ipResource.getShopIds().size() > 0) {
IpChargeRequestDto ipChargeRequestDto = buildIpChargeRequestDto(
ipResource, 3, 0);
accountService.chargeByMoney(ipResource.getOwner(),
-ipResource.getPrice(), ipChargeRequestDto);
if (ipResource.getShopIds() != null
&& ipResource.getShopIds().size() > 0) {
ShopRequestDto shopRequestDto = new ShopRequestDto();
shopRequestDto.setIpId(ipResource.getId());
shopRequestDto.setShopIds(ipResource.getShopIds());
ipAndShopService.unBindShops(ipResource.getUsername(), shopRequestDto);
ipAndShopService.unBindShops(ipResource.getUsername(),
shopRequestDto);
}
ipResourceRepository.deleteById(ipResource.getId());
}
} finally {
long end = System.currentTimeMillis();
log.info("{}, buy ip task {} execution time is: {}s", logs, ipResource.getId(), (end - start) / 1000);
log.info("{}, buy ip task {} execution time is: {}s", logs,
ipResource.getId(), (end - start) / 1000);
try {
ipResourceRepository.unLockTask(ipResource.getId());
} catch (Throwable th) {
......@@ -300,8 +345,10 @@ public class BrowserTask {
ipResource.setAddr(
instance.getPublicIpAddress().getIpAddress().get(0));
ipResource.setStatus(0);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mmX");
Instant instant = Instant.from(formatter.parse(instance.getExpiredTime()));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"yyyy-MM-dd'T'HH:mmX");
Instant instant = Instant.from(
formatter.parse(instance.getExpiredTime()));
ipResource.setValidTime(instant.toEpochMilli());
if (StringUtils.isNotBlank(ipResource.getRegion())
&& region.contains(ipResource.getRegion())) {
......@@ -321,14 +368,16 @@ public class BrowserTask {
//查询是否为重复ip
String ipNo = instance.getPublicIpAddress().getIpAddress()
.get(0);
LocalDateTime localDateTime = LocalDateTime.now().minus(3, ChronoUnit.MONTHS);
Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
LocalDateTime localDateTime = LocalDateTime.now()
.minus(3, ChronoUnit.MONTHS);
Instant instant = localDateTime.atZone(ZoneId.systemDefault())
.toInstant();
List<IpHistory> ipHistoryList = ipHistoryRepository.findByIpNoAndPurchasedTimeAfter(
ipNo,
instant.toEpochMilli());
if (CollectionUtils.isNotEmpty(ipHistoryList) &&
(Objects.isNull(cloudPlatformOrder.getRetryCount()) ||
cloudPlatformOrder.getRetryCount() < 5)) {
cloudPlatformOrder.getRetryCount() < 5)) {
//重新分配ip(删除旧的 购买新的)
AliEcsClient.deleteInstance(
ipResource.getOwner(),
......@@ -378,20 +427,63 @@ public class BrowserTask {
}
}
} else if("tenCent".equals(cloudPlatformOrder.getPlatformType())){
com.tencentcloudapi.cvm.v20170312.models.DescribeInstancesResponse response =
TenCentEcsClient.getDescribeInstances(ipResource.getOwner(), cloudPlatformOrder.getPlatformOrderId(),
} else if ("tenCent".equals(cloudPlatformOrder.getPlatformType())) {
CloudPlatformConfig config = cloudPlatformConfigRepository.findByPlatformAndRegionId(
"tenCent",
cloudPlatformOrder.getRegionId());
if (Objects.isNull(response) || Objects.isNull(response.getInstanceSet())) {
if (StringUtils.isEmpty(config.getPlatform())) {
//轻量级服务器
com.tencentcloudapi.lighthouse.v20200324.models.DescribeInstancesResponse describeInstancesLight = TenCentEcsClient.getDescribeInstancesLight(
ipResource.getOwner(),
cloudPlatformOrder.getPlatformOrderId(),
cloudPlatformOrder.getRegionId());
if (Objects.isNull(describeInstancesLight) || Objects.isNull(
describeInstancesLight.getInstanceSet())) {
log.error("fail to query ip");
return;
}
com.tencentcloudapi.lighthouse.v20200324.models.Instance instance = describeInstancesLight.getInstanceSet()[0];
if (instance.getInstanceState().equals("RUNNING")) {
ipResource.setAddr(instance.getPublicAddresses()[0]);
ipResource.setStatus(0);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"yyyy-MM-dd'T'HH:mmX");
Instant instant = Instant.from(
formatter.parse(instance.getExpiredTime()));
ipResource.setValidTime(instant.toEpochMilli());
if (StringUtils.isNotBlank(ipResource.getRegion())
&& region.contains(ipResource.getRegion())) {
ipResource.setProxyUsername(ipResource.getAddr());
ipResource.setProxyPassword(genRandom(3, 12));
ipResource.setSpecialLine(true);
}
ipResourceRepository.save(ipResource);
IpHistory ipHistory = new IpHistory();
ipHistory.setIpNo(ipResource.getAddr());
ipHistory.setPlatformType(
cloudPlatformOrder.getPlatformType());
ipHistory.setPurchasedTime(Instant.now().toEpochMilli());
ipHistoryRepository.save(ipHistory);
}
return;
}
com.tencentcloudapi.cvm.v20170312.models.DescribeInstancesResponse response =
TenCentEcsClient.getDescribeInstances(ipResource.getOwner(),
cloudPlatformOrder.getPlatformOrderId(),
cloudPlatformOrder.getRegionId());
if (Objects.isNull(response) || Objects.isNull(
response.getInstanceSet())) {
log.error("fail to query ip");
return;
}
com.tencentcloudapi.cvm.v20170312.models.Instance instance = response.getInstanceSet()[0];
if (instance.getInstanceChargeType().equals("PREPAID")) {
//包年包月 更新ip状态
ipResource.setAddr(instance.getPublicIpAddresses()[0]);
ipResource.setStatus(0);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mmX");
Instant instant = Instant.from(formatter.parse(instance.getExpiredTime()));
DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
Instant instant = Instant.from(
formatter.parse(instance.getExpiredTime()));
ipResource.setValidTime(instant.toEpochMilli());
if (StringUtils.isNotBlank(ipResource.getRegion())
&& region.contains(ipResource.getRegion())) {
......@@ -411,8 +503,10 @@ public class BrowserTask {
//查询是否为重复ip
String ipNo = instance.getPublicIpAddresses()[0];
LocalDateTime localDateTime = LocalDateTime.now().minus(3, ChronoUnit.MONTHS);
Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
LocalDateTime localDateTime = LocalDateTime.now()
.minus(3, ChronoUnit.MONTHS);
Instant instant = localDateTime.atZone(ZoneId.systemDefault())
.toInstant();
List<IpHistory> ipHistoryList = ipHistoryRepository.findByIpNoAndPurchasedTimeAfter(
ipNo,
instant.toEpochMilli());
......@@ -424,16 +518,13 @@ public class BrowserTask {
ipResource.getOwner(),
cloudPlatformOrder.getPlatformOrderId(),
cloudPlatformOrder.getRegionId());
CloudPlatformConfig config = cloudPlatformConfigRepository.findByPlatformAndRegionId(
"tenCent",
cloudPlatformOrder.getRegionId());
com.tencentcloudapi.cvm.v20170312.models.RunInstancesResponse response1 = TenCentEcsClient.runInstances(
ipResource.getOwner(), ipResource.getUsername(),
ipResource.getPassword(), config);
if (null == response1 || null == response1.getInstanceIdSet()) {
log.error("queryIpNewTasks, fail to buy ip again : {}",
JSON.toJSON(response));
} else{
} else {
int oldRetryCount =
Objects.isNull(cloudPlatformOrder.getRetryCount())
? 0 : cloudPlatformOrder.getRetryCount();
......@@ -519,14 +610,16 @@ public class BrowserTask {
if (instance.getInstanceChargeType().equals("PrePaid")) {
//包年包夜 更新ip状态
ipResource.setStatus(0);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mmX");
Instant instant = Instant.from(formatter.parse(instance.getExpiredTime()));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"yyyy-MM-dd'T'HH:mmX");
Instant instant = Instant.from(
formatter.parse(instance.getExpiredTime()));
ipResource.setValidTime(instant.toEpochMilli());
ipResourceRepository.save(ipResource);
}
}
}else if("tenCent".equals(cloudPlatformOrder.getPlatformType())){
} else if ("tenCent".equals(cloudPlatformOrder.getPlatformType())) {
com.tencentcloudapi.cvm.v20170312.models.DescribeInstancesResponse describeInstances = TenCentEcsClient.getDescribeInstances(
ipResource.getOwner(), cloudPlatformOrder.getPlatformOrderId(),
cloudPlatformOrder.getRegionId());
......@@ -540,8 +633,9 @@ public class BrowserTask {
if (instance.getInstanceChargeType().equals("PREPAID")) {
//包年包夜 更新ip状态
ipResource.setStatus(0);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mmX");
Instant instant = Instant.from(formatter.parse(instance.getExpiredTime()));
DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
Instant instant = Instant.from(
formatter.parse(instance.getExpiredTime()));
ipResource.setValidTime(instant.toEpochMilli());
ipResourceRepository.save(ipResource);
}
......@@ -570,6 +664,7 @@ public class BrowserTask {
);
}
}
/**
* 购买ip的定时任务,每分钟一次
*/
......@@ -586,101 +681,118 @@ public class BrowserTask {
for (IpResource ipResource : ipResources) {
long start = System.currentTimeMillis();
CompletableFuture future = CompletableFuture.runAsync(() -> {
if (ipResourceRepository.lockTask(ipResource)) {
log.info("{}, ip resource purchase : {}", logs, ipResource.getId());
if (ipResourceRepository.lockTask(ipResource)) {
log.info("{}, ip resource purchase : {}", logs, ipResource.getId());
try {
boolean result = false;
Map<String, String> header = buildPostHeader();
HashMap<String, Object> map = new HashMap<>();
map.put("name", ipResource.getUsername());
if ("uk".equals(ipResource.getRegion())) {
map.put("region", "london");
} else {
map.put("region", ipResource.getRegion());
}
map.put("period", String.valueOf(ipResource.getPeriod()));
map.put("provider", ipResource.getVendor());
map.put("unit", ipResource.getUnit());
map.put("amount", 1);
map.put("loginPassword", ipResource.getPassword());
map.put("startscript", "");
map.put("ipkeptperiod", 7);
map.put("persistSystemDiskOnTermination", false);
// HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(map, header);
IpBuyResultDto ipBuyResultDto = null;
try {
boolean result = false;
Map<String, String> header = buildPostHeader();
HashMap<String, Object> map = new HashMap<>();
map.put("name", ipResource.getUsername());
if ("uk".equals(ipResource.getRegion())) {
map.put("region", "london");
} else {
map.put("region", ipResource.getRegion());
log.info("{}, ip resource purchase params : {}", logs,
JSONObject.toJSONString(map));
String requestResult = HttpClientutils.doPost(
URL + "/intelligroup/ipresources?accountId=browser", header,
JSONObject.toJSONString(map));
log.info("{}, ip resource purchase result : {}", logs, requestResult);
ipBuyResultDto = JSONObject.parseObject(requestResult,
IpBuyResultDto.class);
if (StringUtils.isNotBlank(ipBuyResultDto.getErrorCode())) {
log.error("{}, fail to buy ip : {}", logs,
ipBuyResultDto.getErrorCode());
}
map.put("period", String.valueOf(ipResource.getPeriod()));
map.put("provider", ipResource.getVendor());
map.put("unit", ipResource.getUnit());
map.put("amount", 1);
map.put("loginPassword", ipResource.getPassword());
map.put("startscript", "");
map.put("ipkeptperiod", 7);
map.put("persistSystemDiskOnTermination", false);
// HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(map, header);
IpBuyResultDto ipBuyResultDto = null;
try {
log.info("{}, ip resource purchase params : {}", logs, JSONObject.toJSONString(map));
String requestResult = HttpClientutils.doPost(URL + "/intelligroup/ipresources?accountId=browser", header, JSONObject.toJSONString(map));
log.info("{}, ip resource purchase result : {}", logs, requestResult);
ipBuyResultDto = JSONObject.parseObject(requestResult, IpBuyResultDto.class);
if (StringUtils.isNotBlank(ipBuyResultDto.getErrorCode())) {
log.error("{}, fail to buy ip : {}", logs, ipBuyResultDto.getErrorCode());
}
if (ipBuyResultDto != null && ipBuyResultDto.getIplist() != null
&& ipBuyResultDto.getIplist().size() >= 1) {
log.info("{}, ip resource purchase successful : {}", logs,
ipResource);
AtomicInteger index = new AtomicInteger();
ipBuyResultDto.getIplist().forEach(
x -> {
ipResource.setAddr(x.getIp());
ipResource.setStatus(3);
ipResource.setValidTime(
Instant.parse(x.getValidTill()).toEpochMilli());
if (StringUtils.isNotBlank(ipResource.getRegion())
&& region.contains(ipResource.getRegion())) {
ipResource.setProxyUsername(ipResource.getAddr());
ipResource.setProxyPassword(genRandom(3, 12));
ipResource.setSpecialLine(true);
}
ipResourceRepository.save(ipResource);
if (ipBuyResultDto != null && ipBuyResultDto.getIplist() != null && ipBuyResultDto.getIplist().size() >= 1) {
log.info("{}, ip resource purchase successful : {}", logs, ipResource);
AtomicInteger index = new AtomicInteger();
ipBuyResultDto.getIplist().forEach(
x -> {
ipResource.setAddr(x.getIp());
ipResource.setStatus(3);
ipResource.setValidTime(Instant.parse(x.getValidTill()).toEpochMilli());
if (StringUtils.isNotBlank(ipResource.getRegion()) && region.contains(ipResource.getRegion())) {
ipResource.setProxyUsername(ipResource.getAddr());
ipResource.setProxyPassword(genRandom(3, 12));
ipResource.setSpecialLine(true);
}
ipResourceRepository.save(ipResource);
index.getAndIncrement();
}
);
result = true;
}
} catch (Exception e) {
log.error("{}, ip resource purchase Exception {}", logs, e.getMessage(), e);
result = false;
index.getAndIncrement();
}
);
result = true;
}
} catch (Exception e) {
log.error("{}, ip resource purchase Exception {}", logs, e.getMessage(),
e);
result = false;
}
/**
* 购买失败处理
*
* 购买后,长时间未能成功的ip资源视为购买失败。
* 购买malaysia实例失败后不进行重新购买
* 购买时长超过20分钟的ip资源释放,并将购买花销退回账户余额。
*/
boolean overtime = ipResource.getPurchasedTime() < Instant.now().minusSeconds(7200).toEpochMilli();
/**
* 购买失败处理
*
* 购买后,长时间未能成功的ip资源视为购买失败。
* 购买malaysia实例失败后不进行重新购买
* 购买时长超过20分钟的ip资源释放,并将购买花销退回账户余额。
*/
boolean overtime =
ipResource.getPurchasedTime() < Instant.now().minusSeconds(7200)
.toEpochMilli();
/*boolean problemRegion = "malaysia".equals(ipResource.getRegion());
boolean deal = overtime || problemRegion;*/
if (!result && overtime) {
log.info("{}, ip resource purchase failure, {}", logs, ipResource);
IpChargeRequestDto ipChargeRequestDto = buildIpChargeRequestDto(ipResource, 3, 0);
accountService.chargeByMoney(ipResource.getOwner(), -ipResource.getPrice(), ipChargeRequestDto);
if (ipResource.getShopIds() != null && ipResource.getShopIds().size() > 0) {
ShopRequestDto shopRequestDto = new ShopRequestDto();
shopRequestDto.setIpId(ipResource.getId());
shopRequestDto.setShopIds(ipResource.getShopIds());
ipAndShopService.unBindShops(ipResource.getUsername(), shopRequestDto);
}
ipResourceRepository.deleteById(ipResource.getId());
}
} finally {
long end = System.currentTimeMillis();
log.info("{}, buy ip task {} execution time is: {}s", logs, ipResource.getId(), (end - start) / 1000);
try {
ipResourceRepository.unLockTask(ipResource.getId());
} catch (Throwable th) {
log.error("{}, unlock failed : {}", logs, th.getMessage(), th);
//try again
ipResourceRepository.unLockTask(ipResource.getId());
if (!result && overtime) {
log.info("{}, ip resource purchase failure, {}", logs, ipResource);
IpChargeRequestDto ipChargeRequestDto = buildIpChargeRequestDto(
ipResource, 3, 0);
accountService.chargeByMoney(ipResource.getOwner(),
-ipResource.getPrice(), ipChargeRequestDto);
if (ipResource.getShopIds() != null
&& ipResource.getShopIds().size() > 0) {
ShopRequestDto shopRequestDto = new ShopRequestDto();
shopRequestDto.setIpId(ipResource.getId());
shopRequestDto.setShopIds(ipResource.getShopIds());
ipAndShopService.unBindShops(ipResource.getUsername(),
shopRequestDto);
}
ipResourceRepository.deleteById(ipResource.getId());
}
} finally {
long end = System.currentTimeMillis();
log.info("{}, buy ip task {} execution time is: {}s", logs,
ipResource.getId(), (end - start) / 1000);
try {
ipResourceRepository.unLockTask(ipResource.getId());
} catch (Throwable th) {
log.error("{}, unlock failed : {}", logs, th.getMessage(), th);
//try again
ipResourceRepository.unLockTask(ipResource.getId());
}
}
},
ThreadPoolUtils.buyIpTasksPool
}
},
ThreadPoolUtils.buyIpTasksPool
);
futureList.add(future);
}
......@@ -695,40 +807,45 @@ public class BrowserTask {
for (IpResource ipResource : ipResources) {
long start = System.currentTimeMillis();
CompletableFuture.runAsync(
() -> {
if (ipResourceRepository.lockTask(ipResource)) {
() -> {
if (ipResourceRepository.lockTask(ipResource)) {
try {
String url =
URL + "/ecc/ipinfo?accountId=browser&ip=" + ipResource.getAddr();
Map<String, String> header = buildGetHeader();
String rs = HttpClientutils.doGet(url, header);
IpInfoResultDto ipInfoResultDto = null;
try {
String url = URL + "/ecc/ipinfo?accountId=browser&ip=" + ipResource.getAddr();
Map<String, String> header = buildGetHeader();
String rs = HttpClientutils.doGet(url, header);
IpInfoResultDto ipInfoResultDto = null;
try {
ipInfoResultDto = JSONObject.parseObject(rs, IpInfoResultDto.class);
} catch (Exception e) {
log.error("fail to pars json {}", rs, e);
}
if (ipInfoResultDto != null && StringUtils.isBlank(ipInfoResultDto.getErrorCode())) {
if (StringUtils.isNotEmpty(ipInfoResultDto.getStatus())) {
ipResourceRepository.updateStatus(ipResource.getId(), 0);
}
}
ipInfoResultDto = JSONObject.parseObject(rs, IpInfoResultDto.class);
} catch (Exception e) {
log.error(e.getMessage(), e);
NotifyUtils.sendMessage("浏览器后端 queryIpTasks() 又炸了,赶紧看啊", e, NotifyUtils.MsgType.WEBHOOK);
} finally {
long end = System.currentTimeMillis();
log.debug("queryIpTask {} execution time is: " + (end - start) / 1000 + "s", ipResource.getId());
try {
ipResourceRepository.unLockTask(ipResource.getId());
} catch (Throwable th) {
log.error("unlock failed", th);
//try again
ipResourceRepository.unLockTask(ipResource.getId());
log.error("fail to pars json {}", rs, e);
}
if (ipInfoResultDto != null && StringUtils.isBlank(
ipInfoResultDto.getErrorCode())) {
if (StringUtils.isNotEmpty(ipInfoResultDto.getStatus())) {
ipResourceRepository.updateStatus(ipResource.getId(), 0);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
NotifyUtils.sendMessage("浏览器后端 queryIpTasks() 又炸了,赶紧看啊", e,
NotifyUtils.MsgType.WEBHOOK);
} finally {
long end = System.currentTimeMillis();
log.debug(
"queryIpTask {} execution time is: " + (end - start) / 1000 + "s",
ipResource.getId());
try {
ipResourceRepository.unLockTask(ipResource.getId());
} catch (Throwable th) {
log.error("unlock failed", th);
//try again
ipResourceRepository.unLockTask(ipResource.getId());
}
}
},
ThreadPoolUtils.queryIpTasksPool
}
},
ThreadPoolUtils.queryIpTasksPool
);
}
}
......@@ -748,19 +865,26 @@ public class BrowserTask {
final int maxRetry = Math.max(queryIpUrlLists.size(), 5);
// 如果 ip 已经失效,且 ip 的状态不是 3:正在分配 和 6:未分配,则将 ip 的状态设置为 1 已过期
if (ipResource.getValidTime() <= Instant.now().toEpochMilli() && ipResource.getStatus() != 3 && ipResource.getStatus() != 6) {
if (ipResource.getValidTime() <= Instant.now().toEpochMilli()
&& ipResource.getStatus() != 3 && ipResource.getStatus() != 6) {
ipResource.setStatus(1);
ipResourceRepository.save(ipResource);
// 如果 ip 为专线 ip,或者 ip 为用户自己的,但是使用了系统的专线功能
} else if (ipResource.isSpecialLine() || (ipResource.getIpType() == IpType.OWN && ipResource.isUsingSpecialLine())) {
} else if (ipResource.isSpecialLine() || (ipResource.getIpType() == IpType.OWN
&& ipResource.isUsingSpecialLine())) {
Trans trans = new Trans(ipResource.getProxyUsername(), ipResource.getProxyPassword());
String sp_result = trans.get(getNextUrl(queryIpUrlLists, failTime).getUrl());
Trans trans = new Trans(ipResource.getProxyUsername(),
ipResource.getProxyPassword());
String sp_result = trans.get(
getNextUrl(queryIpUrlLists, failTime).getUrl());
while (!sp_result.contains(ipResource.getAddr())) {
if (failTime > maxRetry) {
NotifyUtils.sendMessage("防关联浏览器 ip " + ipResource.getAddr() + " 专线代理异常:" + ipResource.getIpType(), NotifyUtils.MsgType.WEBHOOK);
log.error("防关联浏览器 ip " + ipResource.getAddr() + " 专线代理异常 " + sp_result);
NotifyUtils.sendMessage(
"防关联浏览器 ip " + ipResource.getAddr() + " 专线代理异常:"
+ ipResource.getIpType(), NotifyUtils.MsgType.WEBHOOK);
log.error("防关联浏览器 ip " + ipResource.getAddr() + " 专线代理异常 "
+ sp_result);
break;
}
failTime++;
......@@ -770,13 +894,19 @@ public class BrowserTask {
// 如果 ip 类型为 vendor
} else if (ipResource.getIpType() == IpType.VENDOR) {
Trans trans = new Trans(ipResource.getAddr(), Integer.valueOf(ipResource.getPort().size() > 1 ? ipResource.getPort().get(1) : ipResource.getPort().get(0)), ipResource.getUsername(), ipResource.getPassword());
Trans trans = new Trans(ipResource.getAddr(), Integer.valueOf(
ipResource.getPort().size() > 1 ? ipResource.getPort().get(1)
: ipResource.getPort().get(0)), ipResource.getUsername(),
ipResource.getPassword());
String result = trans.get(getNextUrl(queryIpUrlLists, failTime).getUrl());
if (!result.contains(ipResource.getAddr())) {
while (!result.contains(ipResource.getAddr())) {
if (failTime > maxRetry) {
NotifyUtils.sendMessage("防关联浏览器 ip " + ipResource.getAddr() + " 代理异常:" + ipResource.getIpType(), NotifyUtils.MsgType.WEBHOOK);
log.error("防关联浏览器 ip " + ipResource.getAddr() + " 代理异常 " + result);
NotifyUtils.sendMessage(
"防关联浏览器 ip " + ipResource.getAddr() + " 代理异常:"
+ ipResource.getIpType(), NotifyUtils.MsgType.WEBHOOK);
log.error("防关联浏览器 ip " + ipResource.getAddr() + " 代理异常 "
+ result);
break;
}
failTime++;
......@@ -787,11 +917,14 @@ public class BrowserTask {
}
} catch (Exception e) {
// todo 将代理异常改为 健康检查异常
NotifyUtils.sendMessage("防关联浏览器 ip " + ipResource.getAddr() + " 健康检查异常", e, NotifyUtils.MsgType.WEBHOOK);
NotifyUtils.sendMessage(
"防关联浏览器 ip " + ipResource.getAddr() + " 健康检查异常", e,
NotifyUtils.MsgType.WEBHOOK);
log.error(e.getMessage(), e);
} finally {
long end = System.currentTimeMillis();
log.debug("queryIpTask {} execution time is: " + (end - start) / 1000 + "s", ipResource.getId());
log.debug("queryIpTask {} execution time is: " + (end - start) / 1000 + "s",
ipResource.getId());
try {
ipResourceRepository.unLockHealth(ipResource.getId());
} catch (Throwable th) {
......@@ -808,15 +941,15 @@ public class BrowserTask {
/**
* 删除逾期IP
*
* 每小时查询 {@code validTime}早于3天前,并且未被删除的ip。
* 调用{@code deleteOverdueIp}删除IP资源
* <p>
* 每小时查询 {@code validTime}早于3天前,并且未被删除的ip。 调用{@code deleteOverdueIp}删除IP资源
*/
@Scheduled(cron = "0 0 * * * ?")
public void deleteOverdueIps() {
String logs = "【deleteOverdueIps】 ";
List<IpResource> list = ipResourceRepository
.findByValidTimeLessThanAndIsDeleted(Instant.now().minusSeconds(60 * 60 * 24 * 7).toEpochMilli(), false);
.findByValidTimeLessThanAndIsDeleted(
Instant.now().minusSeconds(60 * 60 * 24 * 7).toEpochMilli(), false);
log.error("Scheduled {}, list size : {}", logs, list.size());
list.forEach(this::deleteOverdueIp);
......@@ -824,39 +957,43 @@ public class BrowserTask {
/**
* 删除逾期IP
*
* 调用uri查看是否还存在指定资源
* 如果不存在,则{@code deleted}置为true
* <p>
* 调用uri查看是否还存在指定资源 如果不存在,则{@code deleted}置为true
*
* @param ipResource ipResource
*/
private void deleteOverdueIp(IpResource ipResource){
private void deleteOverdueIp(IpResource ipResource) {
String logs = "【deleteOverdueIp】 ";
List<CloudPlatformOrder> list = cloudPlatformOrderRepository.findByOwnerAndIpResourceId(
ipResource.getOwner(), ipResource.getId());
if(CollectionUtils.isNotEmpty(list)){
if (CollectionUtils.isNotEmpty(list)) {
CloudPlatformOrder cloudPlatformOrder = list.get(0);
Boolean isDelet = false;
if("aliyun".equals(cloudPlatformOrder.getPlatformType())){
String aliRegion = RegionMappingEnum.getAliRegion(ipResource.getRegion());
if ("aliyun".equals(cloudPlatformOrder.getPlatformType())) {
DeleteInstanceResponse response = AliEcsClient.deleteInstance(
ipResource.getOwner(), cloudPlatformOrder.getPlatformOrderId(), aliRegion);
if(null != response && response.getStatusCode().equals(200)) {
ipResource.getOwner(), cloudPlatformOrder.getPlatformOrderId(), cloudPlatformOrder.getRegionId());
if (null != response && response.getStatusCode().equals(200)) {
isDelet = true;
}
}else if("tenCent".equals(cloudPlatformOrder.getPlatformType())){
String aliRegion = RegionMappingEnum.getAliRegion(ipResource.getRegion());
TerminateInstancesResponse response = TenCentEcsClient.deleteInstance(
ipResource.getOwner(), cloudPlatformOrder.getPlatformOrderId(), aliRegion);
if(null != response) {
} else if ("tenCent".equals(cloudPlatformOrder.getPlatformType())) {
CloudPlatformConfig config = cloudPlatformConfigRepository.findByPlatformAndRegionId(
"tenCent",
cloudPlatformOrder.getRegionId());
TerminateInstancesResponse response = null;
if(StringUtils.isNotEmpty(config.getTemplateId())) {
response = TenCentEcsClient.deleteInstance(
ipResource.getOwner(), cloudPlatformOrder.getPlatformOrderId(),
cloudPlatformOrder.getRegionId());
}
if (null != response) {
isDelet = true;
}
}
if(isDelet){
if (isDelet) {
ipResource.setShopIds(null);
ipResource.setDeleted(true);
ipResourceRepository.save(ipResource);
}else {
} else {
log.error("Scheduled {}, {} delete failed", logs, ipResource.getAddr());
}
}
......@@ -881,14 +1018,14 @@ public class BrowserTask {
/**
* 封装HttpClientUtils.doDelete方法
*
* @param path path
* @param path path
* @param params params
* @return String
* @throws IOException IOException
*/
private boolean doDelete(String path, String params){
private boolean doDelete(String path, String params) {
String logs = "【doDelete】 ";
try{
try {
String uri = (PROD.equals(profiles) ? CLOUDAMURL : TESTURL) + path + params;
log.info("Scheduled {}, {} delete , params : {}", logs, params, params);
String result = HttpClientutils.doDelete(uri, buildGetHeader());
......@@ -897,9 +1034,11 @@ public class BrowserTask {
if (SUCCESS.equals(deleteIpResultDto.getResult())) {
return true;
}
NotifyUtils.sendMessage("防关联浏览器 ip " + params + " 删除失败", NotifyUtils.MsgType.WEBHOOK);
log.error("Scheduled {}, {} delete failed, ErrorCode : {}, result : {}", logs, params, deleteIpResultDto.getErrorCode(), deleteIpResultDto.getResult());
}catch (Exception e){
NotifyUtils.sendMessage("防关联浏览器 ip " + params + " 删除失败",
NotifyUtils.MsgType.WEBHOOK);
log.error("Scheduled {}, {} delete failed, ErrorCode : {}, result : {}", logs, params,
deleteIpResultDto.getErrorCode(), deleteIpResultDto.getResult());
} catch (Exception e) {
log.error("Scheduled {}, Exception : {}", logs, e.getMessage(), e);
}
return false;
......@@ -920,21 +1059,23 @@ public class BrowserTask {
List<Account> accounts = accountRepository.findAll();
try {
accounts.forEach(
x -> {
IpCountRecord ipCountRecord = new IpCountRecord();
ipCountRecord.setUsername(x.getName());
ipCountRecord.setTimestamp(Instant.now().toEpochMilli());
long ipcount_using = ipResourceRepository.countAllByOwnerAndIsDeletedAndValidTimeGreaterThan(x.getName(), false, Instant.now().toEpochMilli());
long ipcount_all = ipResourceRepository.countAllByOwner(x.getName());
ipCountRecord.setIp_all(ipcount_all);
ipCountRecord.setIp_using(ipcount_using);
ipCountRecordRepository.save(ipCountRecord);
}
x -> {
IpCountRecord ipCountRecord = new IpCountRecord();
ipCountRecord.setUsername(x.getName());
ipCountRecord.setTimestamp(Instant.now().toEpochMilli());
long ipcount_using = ipResourceRepository.countAllByOwnerAndIsDeletedAndValidTimeGreaterThan(
x.getName(), false, Instant.now().toEpochMilli());
long ipcount_all = ipResourceRepository.countAllByOwner(x.getName());
ipCountRecord.setIp_all(ipcount_all);
ipCountRecord.setIp_using(ipcount_using);
ipCountRecordRepository.save(ipCountRecord);
}
);
IpCountRecord ipCountRecord = new IpCountRecord();
ipCountRecord.setUsername("all");
ipCountRecord.setTimestamp(Instant.now().toEpochMilli());
long ipcount_using = ipResourceRepository.countAllByIsDeletedAndValidTimeGreaterThan(false, Instant.now().toEpochMilli());
long ipcount_using = ipResourceRepository.countAllByIsDeletedAndValidTimeGreaterThan(
false, Instant.now().toEpochMilli());
long ipcount_all = ipResourceRepository.count();
ipCountRecord.setIp_using(ipcount_using);
ipCountRecord.setIp_all(ipcount_all);
......@@ -946,6 +1087,7 @@ public class BrowserTask {
}
public static class HttpClientutils {
static OkHttpClient.Builder builder = new OkHttpClient.Builder();
static {
......@@ -958,10 +1100,10 @@ public class BrowserTask {
public static String doDelete(String url, Map<String, String> headers) throws IOException {
Headers httpHeaders = Headers.of(headers);
Request request = new Request.Builder()
.delete()
.url(url)
.headers(httpHeaders)
.build();
.delete()
.url(url)
.headers(httpHeaders)
.build();
Call call = client.newCall(request);
Response response = call.execute();
ResponseBody responseBody = response.body();
......@@ -972,23 +1114,24 @@ public class BrowserTask {
public static String doGet(String url, Map<String, String> headers) throws IOException {
Headers httpHeaders = Headers.of(headers);
Request request = new Request.Builder()
.get()
.url(url)
.headers(httpHeaders)
.build();
.get()
.url(url)
.headers(httpHeaders)
.build();
Call call = client.newCall(request);
Response response = call.execute();
ResponseBody responseBody = response.body();
return responseBody.string();
}
public static String doPost(String url, Map<String, String> headers, String body) throws IOException {
public static String doPost(String url, Map<String, String> headers, String body)
throws IOException {
Headers httpHeaders = Headers.of(headers);
Request request = new Request.Builder()
.post(RequestBody.create(body, okhttp3.MediaType.get("application/json")))
.url(url)
.headers(httpHeaders)
.build();
.post(RequestBody.create(body, okhttp3.MediaType.get("application/json")))
.url(url)
.headers(httpHeaders)
.build();
Call call = client.newCall(request);
Response response = call.execute();
ResponseBody responseBody = response.body();
......
package com.edgec.browserbackend.common.client;
import com.alibaba.fastjson.JSON;
import com.edgec.browserbackend.browser.ErrorCode.BrowserErrorCode;
import com.edgec.browserbackend.browser.domain.CloudPlatformConfig;
import com.edgec.browserbackend.common.commons.error.ClientRequestException;
import com.edgec.browserbackend.common.utils.Aes;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.cvm.v20170312.CvmClient;
import com.tencentcloudapi.cvm.v20170312.models.DescribeInstancesRequest;
import com.tencentcloudapi.cvm.v20170312.models.DescribeInstancesResponse;
import com.tencentcloudapi.cvm.v20170312.models.DescribeZonesRequest;
import com.tencentcloudapi.cvm.v20170312.models.DescribeZonesResponse;
import com.tencentcloudapi.cvm.v20170312.models.InstanceChargePrepaid;
import com.tencentcloudapi.cvm.v20170312.models.LaunchTemplate;
import com.tencentcloudapi.cvm.v20170312.models.LoginSettings;
import com.tencentcloudapi.cvm.v20170312.models.ModifyInstancesChargeTypeRequest;
import com.tencentcloudapi.cvm.v20170312.models.ModifyInstancesChargeTypeResponse;
import com.tencentcloudapi.cvm.v20170312.models.Placement;
import com.tencentcloudapi.cvm.v20170312.models.RenewInstancesRequest;
import com.tencentcloudapi.cvm.v20170312.models.RenewInstancesResponse;
import com.tencentcloudapi.cvm.v20170312.models.RunInstancesRequest;
import com.tencentcloudapi.cvm.v20170312.models.RunInstancesResponse;
import com.tencentcloudapi.cvm.v20170312.models.TerminateInstancesRequest;
import com.tencentcloudapi.cvm.v20170312.models.TerminateInstancesResponse;
import com.tencentcloudapi.cvm.v20170312.models.ZoneInfo;
import com.tencentcloudapi.lighthouse.v20200324.LighthouseClient;
import com.tencentcloudapi.lighthouse.v20200324.models.Command;
import com.tencentcloudapi.lighthouse.v20200324.models.CreateInstancesRequest;
import com.tencentcloudapi.lighthouse.v20200324.models.CreateInstancesResponse;
import com.tencentcloudapi.lighthouse.v20200324.models.DockerContainerConfiguration;
import com.tencentcloudapi.lighthouse.v20200324.models.LoginConfiguration;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
/**
......@@ -71,6 +91,18 @@ public class TenCentEcsClient {
return new CvmClient(cred, regionId, clientProfile);
}
private static LighthouseClient createLightHouseClient(String regionId) {
Credential cred = new Credential(getSecretId(), getSecretKey());
// 实例化一个http选项,可选的,没有特殊需求可以跳过
HttpProfile httpProfile = new HttpProfile();
httpProfile.setEndpoint("lighthouse.tencentcloudapi.com");
// 实例化一个client选项,可选的,没有特殊需求可以跳过
ClientProfile clientProfile = new ClientProfile();
clientProfile.setHttpProfile(httpProfile);
// 实例化要请求产品的client对象,clientProfile是可选的
return new LighthouseClient(cred, regionId, clientProfile);
}
/**
* 创建并运行实例
*/
......@@ -88,7 +120,7 @@ public class TenCentEcsClient {
LoginSettings loginSettings = new LoginSettings();
loginSettings.setKeyIds(Collections.singletonList("skey-j9n2x0pl").toArray(new String[0]));
runInstancesRequest.setLoginSettings(loginSettings);
log.info("调用TenCentEcs创建并运行实例,入参:owner:{},regionId:{}", owner, config.getRegionId());
log.info("调用TenCentEcs创建并运行实例,入参:owner:{},regionId:{}, request{}", owner, config.getRegionId(), JSON.toJSON(runInstancesRequest));
runInstancesResponse = cvmClient.RunInstances(runInstancesRequest);
log.info("调用TenCentEcs创建并运行实例,响应参数:owner:{},response:{}", owner,
JSON.toJSON(runInstancesResponse));
......@@ -188,9 +220,75 @@ public class TenCentEcsClient {
response = cvmClient.RenewInstances(req);
log.info("调用TenCentEcs续费实例,响应参数:owner:{},response:{}", owner, JSON.toJSON(response));
} catch (Exception e) {
log.error("fail to TenCentEcs runInstances {}", e.getMessage());
log.error("fail to TenCentEcs renewInstance {}", e.getMessage());
}
return response;
}
/**
* 创建轻量级应用服务器
*/
public static CreateInstancesResponse createInstances(String owner, String username,
String password, CloudPlatformConfig config) {
LighthouseClient cvmClient = createLightHouseClient(config.getRegionId());
CreateInstancesResponse createInstancesResponse = null;
String userData = String.format(getUserData(), username, password, username);
try {
// 实例化一个请求对象,每个接口都会对应一个request对象
CreateInstancesRequest req = new CreateInstancesRequest();
//TODO 暂时写死
req.setBundleId("bundle_starter_nmc_lin_med2_01");
req.setBlueprintId(config.getImageId());
com.tencentcloudapi.lighthouse.v20200324.models.InstanceChargePrepaid instanceChargePrepaid =
new com.tencentcloudapi.lighthouse.v20200324.models.InstanceChargePrepaid();
instanceChargePrepaid.setPeriod(1L);
req.setInstanceChargePrepaid(instanceChargePrepaid);
LoginConfiguration loginSettings = new LoginConfiguration();
loginSettings.setKeyIds(
Collections.singletonList(config.getKeyId()).toArray(new String[0]));
req.setLoginConfiguration(loginSettings);
Command command = new Command();
command.setContent(Aes.base64Encode(userData.getBytes()));
req.setInitCommand(command);
//TODO 暂时写死
req.setFirewallTemplateId("lhft-46ceryhz");
// 返回的resp是一个CreateInstancesResponse的实例,与请求对象对应
log.info("调用TenCentEcs创建并运行轻量级实例,入参:owner:{},regionId:{}, request{}",
owner, config.getRegionId(), JSON.toJSON(req));
createInstancesResponse = cvmClient.CreateInstances(req);
log.info("调用TenCentEcs创建并运行轻量级实例,响应参数:owner:{},response:{}", owner,
JSON.toJSON(createInstancesResponse));
} catch (Exception e) {
log.error("fail to tenCentEcs createInstances {}", e.getMessage());
}
return createInstancesResponse;
}
/**
* 查询轻量级应用服务器
*/
public static com.tencentcloudapi.lighthouse.v20200324.models.DescribeInstancesResponse getDescribeInstancesLight(
String owner,
String instanceId, String regionId) {
LighthouseClient cvmClient = createLightHouseClient(regionId);
// 返回的resp是一个DescribeInstancesResponse的实例,与请求对象对应
com.tencentcloudapi.lighthouse.v20200324.models.DescribeInstancesResponse describeInstancesResponse = null;
try {
com.tencentcloudapi.lighthouse.v20200324.models.DescribeInstancesRequest req =
new com.tencentcloudapi.lighthouse.v20200324.models.DescribeInstancesRequest();
String[] instanceIds = {"" + instanceId + ""};
req.setInstanceIds(instanceIds);
log.info("调用TenCentEcs查询单个轻量级实例,入参:owner:{},regionId:{},instanceId:{}",
owner, regionId, instanceId);
describeInstancesResponse = cvmClient.DescribeInstances(req);
log.info("调用TenCentEcs查询单个轻量级实例,响应参数:owner:{},response:{}", owner,
JSON.toJSON(describeInstancesResponse));
} catch (Exception e) {
log.error("fail to TenCentEcs getDescribeInstancesLight {}", e.getMessage());
}
return describeInstancesResponse;
}
}
......@@ -28,7 +28,7 @@ public class FGLWxConfig extends WXPayConfig {
@Override
public InputStream getCertStream() {
return getClass().getResourceAsStream("/certs/fangguanlian_cert.p12");
return getClass().getResourceAsStream("/certs/apiclient_cert.p12");
}
@Override
......
......@@ -5,7 +5,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>1</title>
<script src="https://www.kuaitux.com/web/js/plugin/jq.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
......
......@@ -15,11 +15,24 @@ import com.edgec.browserbackend.common.client.AliEcsClient;
import com.edgec.browserbackend.common.client.TenCentEcsClient;
import com.edgec.browserbackend.common.commons.utils.SmsUtils;
import com.edgec.browserbackend.common.utils.Aes;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.lighthouse.v20200324.LighthouseClient;
import com.tencentcloudapi.lighthouse.v20200324.models.CreateInstancesRequest;
import com.tencentcloudapi.tat.v20201028.models.Command;
import java.time.Instant;
import javax.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.lighthouse.v20200324.LighthouseClient;
import com.tencentcloudapi.lighthouse.v20200324.models.*;
@SpringBootTest
class BrowserBackendApplicationTests {
......@@ -40,21 +53,22 @@ class BrowserBackendApplicationTests {
receptionPlatformOptions.setUrl("https:www.dhgate.com");
receptionPlatformOptions.setPictureUrl("https://ip-image.oss-rg-china-mainland.aliyuncs.com/app_image/app_image/dhgate.png");
receptionPlatformOptions.setWeight(100);
repository.save(receptionPlatformOptions);
//repository.save(receptionPlatformOptions);
}
@Test
void buyEcsTest() throws Exception {
CloudPlatformConfig config = cloudPlatformConfigRepository.findByPlatformAndRegionId("tenCent",
"ap-guangzhou");
"ap-tokyo");
//browserTask.queryIpNewTasks();
//AliEcsClient.runInstances("111","ceshi11","2222",config);
//AliEcsClient.getDescribeInstances("测试","i-wz9hf0i13xj6h904k14p","cn-shenzhen");
//DeleteInstanceResponse response = AliEcsClient.deleteInstance("测试", "i-j6cd9fujd6we3dzk8z9e","cn-hongkong");
//AliEcsClient.modifyInstanceChargeType("18711016574","Week",1,"cn-hongkong", "i-j6cd9fujd6we3dzk8z9e");
//TenCentEcsClient.runInstances("111","ceshi11","2222",config);
TenCentEcsClient.deleteInstance("111","ins-nws56gg8","ap-guangzhou");
//TenCentEcsClient.createInstances("111","ceshi11","2222",config);
//TenCentEcsClient.getDescribeInstancesLight("测试","lhins-psgtwyeb","ap-tokyo");
//TenCentEcsClient.deleteInstance("111","ins-nws56gg8","ap-guangzhou");
}
@Resource
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment