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

对腾讯云api

parent f41957ad
...@@ -195,10 +195,16 @@ ...@@ -195,10 +195,16 @@
<version>5.0.13</version> <version>5.0.13</version>
</dependency> </dependency>
<!--腾讯云 云服务器ECS api --> <!--腾讯云 云服务器ECS api -->
<!-- <dependency>-->
<!-- <groupId>com.tencentcloudapi</groupId>-->
<!-- <artifactId>tencentcloud-sdk-java</artifactId>-->
<!-- <version>3.1.830</version>-->
<!-- </dependency>-->
<dependency> <dependency>
<groupId>com.tencentcloudapi</groupId> <groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId> <artifactId>tencentcloud-sdk-java</artifactId>
<version>3.1.830</version> <version>3.1.1091</version>
</dependency> </dependency>
</dependencies> </dependencies>
......
...@@ -7,42 +7,31 @@ public class CloudamAlipayConfig extends AlipayConfig{ ...@@ -7,42 +7,31 @@ public class CloudamAlipayConfig extends AlipayConfig{
@Override @Override
public String getAPPID() { public String getAPPID() {
return "2019071765790965"; return "2021004169642053";
} }
@Override @Override
public String getAPP_PRIVATE_KEY() { public String getAPP_PRIVATE_KEY() {
return "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDDU+npZLO6AoKN" + return "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCTiRoS+HcBGhxMKGmkJlktf+HRRErZYDw0KV8T6ub5HczH/YQ3LkTKyEhZxvcTngavL/"
"lQBO/3gOMTJEeOBDV5zRdvkrMUBq8R5r5phzkq2T2lxg5gMnZx6Lk/NZ0evSntMG" + + "iNZQoFAtQbXBHDVH8L7qlS09+ouBmezZ9ijrX6XahNpoZwWPm+7Ua6rQB/8g+ZS/GQJUzez8RngPP2A00803oYLap+iA+tV+lAr1OKmvRBpKSRb7oUfY7tvHf/"
"PzKXFEmVdBKRuqQvQ7gaZNeWA494sCP76dEDPREcvs7qcP7xTuK9/FTqPQH3iUEA" + + "nRgM9KH1mlWbxEavtrZm+8VBSMcx33v+ePWTn1Pp9sqFV/yMPxY9rOBcWIrdb0kuynILS371Do3jT9IgtYe8p0ShLtbWbJkt4gTBC/nVmE8kzH+I0uWmAHJw8QUj"
"058N03/edQGdv1HLi3BmTYdp2ywZQsb0hqGu6/pPYCLnwSprBdWv1nG3zstcBEmK" + + "ysalSwFMsyvybvcK4rvq2x2Pi0t9AgMBAAECggEAZc9Bn/+315nWFzP4Gp+gAIb0JP30jOcdBH3cL5l1REmtLAElQRL7w9fMHa/whqgRQslewuwLqwOVrT+uvlVLy"
"PYNKipzy0LpHiGB445XO0EJWV/XK6t1knDKrC6FFiFfxuLy3fHy37jjFW2TxZLSc" + + "scqL48oE3zfqTeKGnAS4i/JWbRlp5eu2HNS0LVb1+8JlqbSjr8+ua80gJx7PbRvk174LUEuG1z3PI6i1tFmXAmf6yloYvhdrf4CqCuZJ/mP3hDs4qnRmbhw/Rb7z9p"
"ROGs0Py+w9saxIJ1n7jGJqHCQmyuNgPKtelYy1jpbdXIX/2bhW1ck4dOCF8j37Gc" + + "ImLVGxKUxZkaDUvchGKcKrsyl76GA/y8DEIj3j/2GWSzZLh0LuDN3ZJQS4DZ0ZxOGw15TB2Us0XiC1TBlu8si1td0WGI1k4q716bucE9Bp/ODkln1D0EoF7JkShZyWzg"
"cGZR+c3nAgMBAAECggEASFW1FDe0zzfKvT/mw1qcTTUu1milNIsnifKzR6mPn4r3" + + "TXQKBgQDFvy0PjjlAuFHgcK1ihygL60gIxZ5vGu+KG8K5gf8jDqk5Rqj507YvXmWbqax5CyRUOL6KhVD/fk3ddsuzb74JSRO8GS1o7WvcCiyDBteGP8syObYBBDTf0Jz6N"
"pyHYZ0R0f4KoH0JO/LKVfz8lKagx2ufyYifZRlW/Alff4JPr5Y0AitW5eNaMtTcV" + + "Nq1ANkamZSxgt6MUGdQrx1X4FpzSXYA17RbFtrf/JaLRdFNQwKBgQC+/0869jkgDQsFodh64eGuOu1g32JzpZuLMSXQGmqk//HbScMMmvco2iwg2ULd9nGxgY3eA/kTvdmK"
"vF7UhoyA39JRskRyRU7fbVga4jwBlHgB2JqGFoqymeFe3dpSIjzbPSeM9Ei0Rg3s" + + "/ByoRPieJ7pS0ryP83Qq9M699J240/bzrNbQMAgEguq71ewt8yS+ATk4+ntj/9aGMjOGyTZi7M8HLOu8RqlD35SDbNkYPwKBgGW+j7jJPLwIGliYoR1o3ToEvPOGepZADa"
"hIv+An/U2optO29ggsC0hXyHWXLupaMwbIpBTOHDiFzxW7z4ZxUH1jAL0jvQxuNN" + + "/JyM8aC+RFztwhdx/TxpFoyG7nRk6hZPfQmnk7TwmmOvoP/Y89l1G/v9+wNKUgQ7bbpTtlcc8pU6tr9jFfsLTX6WzzdPRck1gUXWVYKJmZZQ8mirqEPQXEbmrQkYOspsFIfUz"
"YEY8vAcvJAlz4iab5x2vlEn00crfhE+kwO6f+0Am7spDKjkjsVX8mioD+J/VozZk" + + "7h01xAoGBALdugcxRvuk+PZCqMDtMBq+LHoGD6IzCxxC2IeesBzHyMXh2beIETk0ow2rE3chIsEZW80X/MM657Vzi5i7hFpjl9LcodzoVCUNcG9YpQPTKdYjvPNty1bBnf0Lo"
"517zz5EF66DdtD5i9LdLIGBsWjagbINtVrH7KWqlgQKBgQDzWxlOMpjsP/WFk0L5" + + "n8w9kNL+X9OOFMUkZwY43m2bfyUg42+zv67xegyahIp4FkOHAoGACv7HiBADC9SUJ4J4D2+sQhuNRWzCyvT0b7MZyiC7G0t3ch3pjL8asWtk8ZR1bSQurMPuUqGdeix5xD4Nx"
"ic7HJvflbz+hCJAyQlDAy43Ls8nVYIkeTk2Umae+uSbkMga2N83LN4e1FRNGDjGB" + + "b4ZbhA8gxr2K9TvmVan2Not/L0GgvFULj4l1mli5wjzmli9WJIfcD23FjJ0Dz1w7pcXPzSw4pK3bTsandp0LDf3rrs=";
"JNDHtzAF3aAwPXS+PDwLGDrgQ44KN8aw/1dt0W9TiBVLHOhAjqPO4UqW0wkgSwNh" +
"HqeuR1GwLyp5IueFZxX/YhNT4QKBgQDNef0W6fDhhcsxyLm5dDL+LuenE1omas74" +
"zNKPaR7yQpZOxqdJYXEI6nrJ1vTUOLa1nqT1/n8kgLNDASRQH5NFQfSizRG07tij" +
"3NLto8DD89h82y7IbY1Rz38FH3Mf+W7soKMKo6tQb7oHOZm2uDTlSpe25neDSJeI" +
"kL+JsEbaxwKBgQCkAOYJ/DFxLh2CGt+NGqF/N7TjK9k+5m1/YY/YjpYODSldowRl" +
"pzHDjtYsw80BBvHdBbisVs0fbYeis9gLB8uofL1hhp35RMGTnzZ756VuFDj6i+Jc" +
"0IiUWwviyJhJGb8wGrEssEo7YRgKamNppWYuHqRfzzmZj7tl/TYm+Wq7IQKBgBFo" +
"NDisuOtiGkStbI55eZhvAND2orx+b+pD79KWZTjAy1sBGUruJlVLB/vxaexQoanh" +
"NrhgRwUgog8bGahwBFnprH/eP5HEajX3jybyqHHxRnXNW7k/DqnPmkMk1uvuhacm" +
"NKnCE9FMpcXW616/XDvQhenIvHcyvyOin5dah6YhAoGASANVYkA4JX3cTXzDvlzh" +
"5l/afal++mv6Ld2TH/3aeg2CBh2HzNIUBCr/SQFpqOjQf6L2lpftDPIbtDB7ogVv" +
"roAgSIXPlz+TK9rgMRI/uzWTP4J164r2UBs5aT5N5Y6hArL7ce1+1QemCsevFRTP" +
"tHwdG2+8KyXqSWp4eyFmBFs=";
} }
@Override @Override
public String getALIPAY_PUBLIC_KEY() { public String getALIPAY_PUBLIC_KEY() {
return "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkXY3UcHC2Eu4X0Ggf36Kz94aag+nGoBhIjcyXADTCsqYpKLenWC/RzgzbipFKOur+Z8AyxK9pk4Z/B5NlMuSsNM+D4cHdRl21qZszXlygTNIxOnl+tGdlbxjEmlIqwuhSFZRAz7/zhAQ0Rto/1mz+DNmHvhXpXY91xVMLetWXkIKQR+D5IXtAXVkssHevRMiMhMrlazw9Gn1vS+8iKy+Op9G7o9M2LvNiKv0HNOIhvoMqntdPCFWgGNuXMPoobsfkD8dFQs2GzuERgWs+maBQuHWXkghk4RoMYCjS0wKvm8zxJVfHmQ6yApcM676R1pRpJrMzX+LTQINm3UQCaCxKwIDAQAB"; return "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlryO1G3TVb9mRVS08U19s1ydhyfLzy5xk6bFW2Jwkr9jD5TqkpjgI3ZYykz1VkgFxASHUo8+6tHjoOfhtul0MyDbtU8"
+ "/XrXr6spGRGRsHbxTiRj4wflKJHXFwZHM3Bq+5jV8m5SOlHXx62PkTCk8BJsrwYT06CZz3VH8M72JYiZu05Zm8AMKYjKmsmLdzCozL4PB7ztPWmGvLe+5Nc0As2urLBgfX7XGWHju"
+ "k8VsZaxQaVSn4z7cr4eP9iijmqJJXBFhtQLqzMjtlBRqqFn0kvUHiPg/ndEXq8TEVqN0uaSDdIZ+LPrIVvMnmcyaHKBn1fHQHNNaho9B/5PwHMYumQIDAQAB";
} }
@Override @Override
......
...@@ -7,43 +7,31 @@ public class VpsAlipayConfig extends AlipayConfig{ ...@@ -7,43 +7,31 @@ public class VpsAlipayConfig extends AlipayConfig{
@Override @Override
public String getAPPID() { public String getAPPID() {
return "2019091967616095"; return "2021004169642053";
} }
@Override @Override
public String getAPP_PRIVATE_KEY() { public String getAPP_PRIVATE_KEY() {
return "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDQi9PVnyGA+r1Q"+ return "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";
"AN8h3aMo2lryEB8Cv/6uMjMYRFkuuMCVc1XaAsjTxJhO1qwsW4/IkWIoM7uGMD74" +
"5zGvWg12QQuMPV7sVXT0XCrxFwKBgQDTvdjdu3QdIWYUaiRIkF/8e+6+finFZ0Dt" +
"aaTnZ6mDSGaBwGqOSt+woOB61Vkl/EoaLpPGW0mKmhSlAnrD04LmB1LNt16W39RN" +
"5mjVxBdHIkyWUcQAq46kNYvPJ6BGJkZiRW1eOrXfw0fTBQPb3X1Na2cWBzvT4+tw" +
"Am1Sjv/SHwKBgQDkCKLnvZ194CTwEYMncaun+9OXwIz8wqnotMU6KeZH6Ib+mDjb" +
"TqIr36LCE5sKU6mczvka0PRaYCXhLKJVkEQ91L4jzJhEJOBnFE26LhyX7fjakK1c" +
"fRtAORR4sm0toGnHFGhN9W7Y/TC0hB3v7ui4trFGKj3PcBHRnNhRyKntsQKBgGR2" +
"xEnYYixcJ2nyPorrbY+HYeyiQcF2zziWEnb1GVm/5VsU57nhzqaofjnptmWugZ5Q" +
"kS7hK1CG8NqmBYeaeJYZzXDr2wZs5vebJgyfAIhwvrPn0b6bp49EFLTSUVpXWLfR" +
"xyWZZ6fmqNJ3o7ATNBuipQOvpPRRROkdTa+JR9nzAoGBAJV4ejLCkgllaGr7IISK" +
"YgYNicZKqzNtJ7JTxYsH7pylNHC8eo63S+xNv5xCUp85vjHGQXbp+HY3HeEqzkRn" +
"PS7gkR0Q9tpdX03xREkWodj0GchdjwRgSlHK9W30x00pccv0iDlxSrGJUVLTqFlu" +
"fCu0gOJ91NfpFLX9bP1YN29V";
} }
@Override @Override
public String getALIPAY_PUBLIC_KEY() { public String getALIPAY_PUBLIC_KEY() {
return "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhwIiSpdHHs7XgZyNiSA++/usN6Sg2IKLlEUhfy89yig9GSGyb2p/VW7Ei4/5IuG9hM0yQx9bM28VDMj/KO0Y5VCcOgrVB11UhfdwpLx8JQXB9u9x0gf/q/wovdxBgqtStLuQ98vveID2O/nf+PluWfq/90EgiQs16fi91b7H150fHr3ra8HHTuvCMKGBck3QUURrRp9OdQaa/vPQjuEyVUNUyX9B9HRdn4PkigI/5rrxjVt4r/jvSOR2MhgBo0QKIm4lCxNibumAHN/w+mewjmoTu77X14bn80V1xPjTRfRohyuW1t0pOcPIpiV7FmlQB0T6uzKZ8I3vVg4l0SxfdQIDAQAB"; return "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlryO1G3TVb9mRVS08U19s1ydhyfLzy5xk6bFW2Jwkr9jD5TqkpjgI3ZYykz1VkgFxASHUo8+6tHjoOfhtul0MyDbtU8"
+ "/XrXr6spGRGRsHbxTiRj4wflKJHXFwZHM3Bq+5jV8m5SOlHXx62PkTCk8BJsrwYT06CZz3VH8M72JYiZu05Zm8AMKYjKmsmLdzCozL4PB7ztPWmGvLe+5Nc0As2urLBgfX7XGWHju"
+ "k8VsZaxQaVSn4z7cr4eP9iijmqJJXBFhtQLqzMjtlBRqqFn0kvUHiPg/ndEXq8TEVqN0uaSDdIZ+LPrIVvMnmcyaHKBn1fHQHNNaho9B/5PwHMYumQIDAQAB";
} }
@Override @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 { ...@@ -31,4 +31,8 @@ public class CloudPlatformConfig {
private String usableArea;//可用区 private String usableArea;//可用区
private String imageId; //镜像id
private String keyId; //镜像id
} }
...@@ -18,9 +18,17 @@ public class ReceptionPlatformOptions { ...@@ -18,9 +18,17 @@ public class ReceptionPlatformOptions {
private String platform;//平台 private String platform;//平台
private String platformDesc;//平台描述
private String url;//网址 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;//子类型 private int childType;//子类型
......
...@@ -5,14 +5,12 @@ import org.springframework.data.domain.Page; ...@@ -5,14 +5,12 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
public interface LoginHistoryRepository extends MongoRepository<LoginHistory, String> { public interface LoginHistoryRepository extends MongoRepository<LoginHistory, String> {
LoginHistory findFirstByUsername(String username); 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); int countByUsername(String username);
} }
...@@ -96,9 +96,9 @@ public class HistoryServiceImpl implements HistoryService { ...@@ -96,9 +96,9 @@ public class HistoryServiceImpl implements HistoryService {
Page<LoginHistory> loginHistoryPage; Page<LoginHistory> loginHistoryPage;
long time = Instant.now().atZone(ZoneOffset.UTC).minusDays(historyListRequestDto.getDay()).toInstant().toEpochMilli(); long time = Instant.now().atZone(ZoneOffset.UTC).minusDays(historyListRequestDto.getDay()).toInstant().toEpochMilli();
if (account.getParent() == null) { if (account.getParent() == null) {
loginHistoryPage = loginHistoryRepository.findByAdministratorAndLoginTimeGreaterThanOrderByLoginTime(username, time, pageable); loginHistoryPage = loginHistoryRepository.findByAdministratorAndLoginTimeGreaterThanOrderByLoginTimeDesc(username, time, pageable);
} else { } else {
loginHistoryPage = loginHistoryRepository.findByUsernameAndLoginTimeGreaterThanOrderByLoginTime(username, time, pageable); loginHistoryPage = loginHistoryRepository.findByUsernameAndLoginTimeGreaterThanOrderByLoginTimeDesc(username, time, pageable);
} }
List<LoginHistoryDto> loginHistoryDtoList = new ArrayList<>(); List<LoginHistoryDto> loginHistoryDtoList = new ArrayList<>();
......
...@@ -2,6 +2,7 @@ package com.edgec.browserbackend.browser.service.Impl; ...@@ -2,6 +2,7 @@ package com.edgec.browserbackend.browser.service.Impl;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; 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.DescribeInstancesResponse;
import com.aliyun.sdk.service.ecs20140526.models.DescribeInstancesResponseBody.Instance; import com.aliyun.sdk.service.ecs20140526.models.DescribeInstancesResponseBody.Instance;
import com.aliyun.sdk.service.ecs20140526.models.RenewInstanceResponse; import com.aliyun.sdk.service.ecs20140526.models.RenewInstanceResponse;
...@@ -20,9 +21,12 @@ import com.edgec.browserbackend.browser.repository.*; ...@@ -20,9 +21,12 @@ import com.edgec.browserbackend.browser.repository.*;
import com.edgec.browserbackend.browser.service.IpAndShopService; import com.edgec.browserbackend.browser.service.IpAndShopService;
import com.edgec.browserbackend.browser.service.IpResourceService; import com.edgec.browserbackend.browser.service.IpResourceService;
import com.edgec.browserbackend.common.client.AliEcsClient; 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.error.ClientRequestException;
import com.edgec.browserbackend.common.commons.utils.NotifyUtils; import com.edgec.browserbackend.common.commons.utils.NotifyUtils;
import com.edgec.browserbackend.common.utils.FileUtil; 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 java.time.format.DateTimeFormatter;
import javax.annotation.Resource; import javax.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
...@@ -153,6 +157,9 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -153,6 +157,9 @@ public class IpResourceServiceImpl implements IpResourceService {
@Resource @Resource
private CloudPlatformOrderRepository cloudPlatformOrderRepository; private CloudPlatformOrderRepository cloudPlatformOrderRepository;
@Resource
private CloudPlatformConfigRepository cloudPlatformConfigRepository;
public HttpHeaders buildPostHeader() { public HttpHeaders buildPostHeader() {
HttpHeaders header = new HttpHeaders(); HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_JSON); header.setContentType(MediaType.APPLICATION_JSON);
...@@ -194,6 +201,9 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -194,6 +201,9 @@ public class IpResourceServiceImpl implements IpResourceService {
.map(x -> x.substring(x.lastIndexOf("-") + 1)) .map(x -> x.substring(x.lastIndexOf("-") + 1))
.collect(Collectors.joining()); .collect(Collectors.joining());
newprice = "week".equals(ipResourceRequestDto.getUnit()) ? (Integer.valueOf(price) / 3) : Integer.valueOf(price); newprice = "week".equals(ipResourceRequestDto.getUnit()) ? (Integer.valueOf(price) / 3) : Integer.valueOf(price);
}else {
//自有ip设置成1元
newprice = 1;
} }
// 3. 计算总共需要花费多少钱 并 校验账户余额 够不够扣费 // 3. 计算总共需要花费多少钱 并 校验账户余额 够不够扣费
...@@ -542,7 +552,6 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -542,7 +552,6 @@ public class IpResourceServiceImpl implements IpResourceService {
Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST)); Account account = accountRepository.findByName(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
String URL = (profiles.equals("dev") || profiles.equals("staging")) ? TESTURL : CLOUDAMURL;
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = buildGetHeader(); HttpHeaders headers = buildGetHeader();
Map<String, String> params = new HashMap<String, String>(); Map<String, String> params = new HashMap<String, String>();
...@@ -574,36 +583,54 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -574,36 +583,54 @@ public class IpResourceServiceImpl implements IpResourceService {
} }
try { 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) { if (ipResource.getStatus() == 6) {
ipResourceRepository.delete(ipResource); ipResourceRepository.delete(ipResource);
}else {
// 其他情况(主要是 ip资源还未创建成功的状态),则将 ip资源的状态改为删除 List<CloudPlatformOrder> list = cloudPlatformOrderRepository.findByOwnerAndIpResourceId(
} else { ipResource.getOwner(), ipResource.getId());
ipResource.setShopIds(null); if (CollectionUtils.isNotEmpty(list)) {
ipResource.setDeleted(true); CloudPlatformOrder cloudPlatformOrder = list.get(0);
ipResourceRepository.save(ipResource); 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); ipOperationResultDto.getSuccessList().add(ipAddr);
} catch (Exception e) { } catch (Exception e) {
logger.error("fail to delete ip", e); logger.error("fail to delete ip", e);
ipOperationResultDto.getFailList().add(ipAddr); ipOperationResultDto.getFailList().add(ipAddr);
return;
} }
} }
); );
...@@ -620,12 +647,29 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -620,12 +647,29 @@ public class IpResourceServiceImpl implements IpResourceService {
ipResourceRepository.delete(ipResource); ipResourceRepository.delete(ipResource);
} else if (StringUtils.isNotBlank(ipResource.getAddr()) && ipResource.getIpType() == IpType.VENDOR) { } else if (StringUtils.isNotBlank(ipResource.getAddr()) && ipResource.getIpType() == IpType.VENDOR) {
try { try {
ResponseEntity<String> result = restTemplate.exchange(URL + "/intelligroup/ipresources?accountId=browser&ip={ip}", List<CloudPlatformOrder> list = cloudPlatformOrderRepository.findByOwnerAndIpResourceId(
HttpMethod.DELETE, httpEntity, String.class, ipResource.getAddr()); ipResource.getOwner(), ipResource.getId());
DeleteIpResultDto deleteIpResultDto = JSON.parseObject(result.getBody(), DeleteIpResultDto.class); if (CollectionUtils.isNotEmpty(list)) {
if (deleteIpResultDto.getResult().equals("failed") || StringUtils.isNotBlank(deleteIpResultDto.getErrorCode())) { CloudPlatformOrder cloudPlatformOrder = list.get(0);
NotifyUtils.sendMessage("防关联浏览器 ip " + ipResource.getAddr() + " 删除失败", NotifyUtils.MsgType.WEBHOOK); if ("aliyun".equals(cloudPlatformOrder.getPlatformType())) {
logger.error("ip " + ipResource.getAddr() + " 删除失败"); 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) { } catch (Exception t) {
logger.error("ip " + ipResource.getAddr() + " 删除失败", t); logger.error("ip " + ipResource.getAddr() + " 删除失败", t);
...@@ -1136,6 +1180,18 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -1136,6 +1180,18 @@ public class IpResourceServiceImpl implements IpResourceService {
ipData.setIp(ipResource.getAddr()); ipData.setIp(ipResource.getAddr());
ipDataList.add(ipData); 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; ...@@ -38,6 +38,7 @@ import com.edgec.browserbackend.common.utils.ThreadPoolUtils;
import com.edgec.browserbackend.common.utils.Trans; import com.edgec.browserbackend.common.utils.Trans;
import com.tencentcloudapi.cvm.v20170312.models.ModifyInstancesChargeTypeResponse; import com.tencentcloudapi.cvm.v20170312.models.ModifyInstancesChargeTypeResponse;
import com.tencentcloudapi.cvm.v20170312.models.TerminateInstancesResponse; import com.tencentcloudapi.cvm.v20170312.models.TerminateInstancesResponse;
import com.tencentcloudapi.lighthouse.v20200324.models.CreateInstancesResponse;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.ZoneId; import java.time.ZoneId;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
...@@ -105,24 +106,31 @@ public class BrowserTask { ...@@ -105,24 +106,31 @@ public class BrowserTask {
public Map<String, String> buildGetHeader() { public Map<String, String> buildGetHeader() {
Map<String, String> headers = new HashMap<>(); Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json"); headers.put("Content-Type", "application/json");
if (profiles.equals("dev") || profiles.equals("staging")) if (profiles.equals("dev") || profiles.equals("staging")) {
headers.put("Authorization", "Bearer oq5tg3gMsflHcK5iZ2741G5R30XYd9blyOqH9qeBItKtrzfTsGIoy8AsxqqNXdcm"); headers.put("Authorization",
else if (profiles.equals("prod")) "Bearer oq5tg3gMsflHcK5iZ2741G5R30XYd9blyOqH9qeBItKtrzfTsGIoy8AsxqqNXdcm");
headers.put("Authorization", "Bearer tKWsuHzcngf0RQPMss70f9jgymDIwgQ9zbLfESJdcou3pZSNWl7lNTzto8VQgwaO"); } else if (profiles.equals("prod")) {
headers.put("Authorization",
"Bearer tKWsuHzcngf0RQPMss70f9jgymDIwgQ9zbLfESJdcou3pZSNWl7lNTzto8VQgwaO");
}
return headers; return headers;
} }
public Map<String, String> buildPostHeader() { public Map<String, String> buildPostHeader() {
Map<String, String> headers = new HashMap<>(); Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json"); headers.put("Content-Type", "application/json");
if (profiles.equals("dev") || profiles.equals("staging")) if (profiles.equals("dev") || profiles.equals("staging")) {
headers.put("Authorization", "Bearer oq5tg3gMsflHcK5iZ2741G5R30XYd9blyOqH9qeBItKtrzfTsGIoy8AsxqqNXdcm"); headers.put("Authorization",
else if (profiles.equals("prod")) "Bearer oq5tg3gMsflHcK5iZ2741G5R30XYd9blyOqH9qeBItKtrzfTsGIoy8AsxqqNXdcm");
headers.put("Authorization", "Bearer tKWsuHzcngf0RQPMss70f9jgymDIwgQ9zbLfESJdcou3pZSNWl7lNTzto8VQgwaO"); } else if (profiles.equals("prod")) {
headers.put("Authorization",
"Bearer tKWsuHzcngf0RQPMss70f9jgymDIwgQ9zbLfESJdcou3pZSNWl7lNTzto8VQgwaO");
}
return headers; 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 ipChargeRequestDto = new IpChargeRequestDto();
ipChargeRequestDto.setAmount(1); ipChargeRequestDto.setAmount(1);
ipChargeRequestDto.setChargeType(chargeType); ipChargeRequestDto.setChargeType(chargeType);
...@@ -152,9 +160,11 @@ public class BrowserTask { ...@@ -152,9 +160,11 @@ public class BrowserTask {
log.info("{}, ip resource purchase : {}", logs, ipResource.getId()); log.info("{}, ip resource purchase : {}", logs, ipResource.getId());
try { try {
RegionMappingEnum byRegion = RegionMappingEnum.getByRegion(ipResource.getRegion()); RegionMappingEnum byRegion = RegionMappingEnum.getByRegion(
if(Objects.isNull(byRegion)){ ipResource.getRegion());
log.error("buyIpNewTasks-购买ip error:查询不到地区映射-region:{}",ipResource.getRegion()); if (Objects.isNull(byRegion)) {
log.error("buyIpNewTasks-购买ip error:查询不到地区映射-region:{}",
ipResource.getRegion());
return; return;
} }
...@@ -163,26 +173,34 @@ public class BrowserTask { ...@@ -163,26 +173,34 @@ public class BrowserTask {
cloudPlatformOrder.setOwner(ipResource.getOwner()); cloudPlatformOrder.setOwner(ipResource.getOwner());
cloudPlatformOrder.setIpResourceId(ipResource.getId()); cloudPlatformOrder.setIpResourceId(ipResource.getId());
boolean result = false; boolean result = false;
if(ipResource.getVendorCn().equals("阿里云")){ if (ipResource.getVendorCn().equals("阿里云")) {
//获取阿里云服务器region映射 //获取阿里云服务器region映射
String aliRegion = RegionMappingEnum.getAliRegion(ipResource.getRegion()); String aliRegion = RegionMappingEnum.getAliRegion(
ipResource.getRegion());
if(StringUtils.isEmpty(aliRegion)){
log.error("buyIpNewTasks-购买ip error:查询不到阿里云映射api-region:{}",ipResource.getRegion()); if (StringUtils.isEmpty(aliRegion)) {
log.error(
"buyIpNewTasks-购买ip error:查询不到阿里云映射api-region:{}",
ipResource.getRegion());
return; return;
} }
CloudPlatformConfig config = cloudPlatformConfigRepository.findByPlatformAndRegionId("ali", CloudPlatformConfig config = cloudPlatformConfigRepository.findByPlatformAndRegionId(
"ali",
aliRegion); aliRegion);
if(Objects.isNull(config)){ if (Objects.isNull(config)) {
log.error("buyIpNewTasks-购买ip error:查询不到阿里云模板配置-region:{}", aliRegion); log.error(
"buyIpNewTasks-购买ip error:查询不到阿里云模板配置-region:{}",
aliRegion);
return; return;
} }
RunInstancesResponse response = AliEcsClient.runInstances( RunInstancesResponse response = AliEcsClient.runInstances(
ipResource.getOwner(), ipResource.getUsername(),ipResource.getPassword(), config); ipResource.getOwner(), ipResource.getUsername(),
if (null ==response || !response.getStatusCode().equals(200)) { ipResource.getPassword(), config);
if (null == response || !response.getStatusCode().equals(200)) {
log.error("{}, fail to buy ip : {}", logs, JSON.toJSON(response)); log.error("{}, fail to buy ip : {}", logs, JSON.toJSON(response));
}else if(Objects.nonNull(response.getBody())){ } else if (Objects.nonNull(response.getBody())) {
String instanceId = response.getBody().getInstanceIdSets().getInstanceIdSet().get(0); String instanceId = response.getBody().getInstanceIdSets()
.getInstanceIdSet().get(0);
cloudPlatformOrder.setPlatformOrderId(instanceId); cloudPlatformOrder.setPlatformOrderId(instanceId);
cloudPlatformOrder.setPlatformType("aliyun"); cloudPlatformOrder.setPlatformType("aliyun");
cloudPlatformOrder.setRegionId(aliRegion); cloudPlatformOrder.setRegionId(aliRegion);
...@@ -192,24 +210,44 @@ public class BrowserTask { ...@@ -192,24 +210,44 @@ public class BrowserTask {
cloudPlatformOrderRepository.save(cloudPlatformOrder); cloudPlatformOrderRepository.save(cloudPlatformOrder);
result = true; result = true;
} }
}else if(ipResource.getVendorCn().equals("腾讯云")){ } else if (ipResource.getVendorCn().equals("腾讯云")) {
//获取腾讯云服务器region映射 //获取腾讯云服务器region映射
String tenCentRegion = RegionMappingEnum.getTenCentRegion(ipResource.getRegion()); String tenCentRegion = RegionMappingEnum.getTenCentRegion(
if(StringUtils.isEmpty(tenCentRegion)){ ipResource.getRegion());
log.error("buyIpNewTasks-购买ip error:查询不到腾讯云映射api-region:{}",ipResource.getRegion()); if (StringUtils.isEmpty(tenCentRegion)) {
log.error(
"buyIpNewTasks-购买ip error:查询不到腾讯云映射api-region:{}",
ipResource.getRegion());
return; return;
} }
CloudPlatformConfig config = cloudPlatformConfigRepository.findByPlatformAndRegionId("tenCent", CloudPlatformConfig config = cloudPlatformConfigRepository.findByPlatformAndRegionId(
"tenCent",
tenCentRegion); tenCentRegion);
if(Objects.isNull(config)){ if (Objects.isNull(config)) {
log.error("buyIpNewTasks-购买ip error:查询不到腾讯云模板配置-region:{}", tenCentRegion); log.error(
"buyIpNewTasks-购买ip error:查询不到腾讯云模板配置-region:{}",
tenCentRegion);
return; return;
} }
com.tencentcloudapi.cvm.v20170312.models.RunInstancesResponse response = String instanceId = null;
TenCentEcsClient.runInstances(ipResource.getOwner(), ipResource.getUsername(), ipResource.getPassword(), config); if (StringUtils.isNotEmpty(config.getTemplateId())) {
if(Objects.nonNull(response.getInstanceIdSet())){ com.tencentcloudapi.cvm.v20170312.models.RunInstancesResponse response =
String instanceId = response.getInstanceIdSet()[0]; 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.setPlatformOrderId(instanceId);
cloudPlatformOrder.setPlatformType("tenCent"); cloudPlatformOrder.setPlatformType("tenCent");
cloudPlatformOrder.setRegionId(tenCentRegion); cloudPlatformOrder.setRegionId(tenCentRegion);
...@@ -228,24 +266,31 @@ public class BrowserTask { ...@@ -228,24 +266,31 @@ public class BrowserTask {
* 购买malaysia实例失败后不进行重新购买 * 购买malaysia实例失败后不进行重新购买
* 购买时长超过20分钟的ip资源释放,并将购买花销退回账户余额。 * 购买时长超过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 problemRegion = "malaysia".equals(ipResource.getRegion());
boolean deal = overtime || problemRegion;*/ boolean deal = overtime || problemRegion;*/
if (!result && overtime) { if (!result && overtime) {
log.info("{}, ip resource purchase failure, {}", logs, ipResource); log.info("{}, ip resource purchase failure, {}", logs, ipResource);
IpChargeRequestDto ipChargeRequestDto = buildIpChargeRequestDto(ipResource, 3, 0); IpChargeRequestDto ipChargeRequestDto = buildIpChargeRequestDto(
accountService.chargeByMoney(ipResource.getOwner(), -ipResource.getPrice(), ipChargeRequestDto); ipResource, 3, 0);
if (ipResource.getShopIds() != null && ipResource.getShopIds().size() > 0) { accountService.chargeByMoney(ipResource.getOwner(),
-ipResource.getPrice(), ipChargeRequestDto);
if (ipResource.getShopIds() != null
&& ipResource.getShopIds().size() > 0) {
ShopRequestDto shopRequestDto = new ShopRequestDto(); ShopRequestDto shopRequestDto = new ShopRequestDto();
shopRequestDto.setIpId(ipResource.getId()); shopRequestDto.setIpId(ipResource.getId());
shopRequestDto.setShopIds(ipResource.getShopIds()); shopRequestDto.setShopIds(ipResource.getShopIds());
ipAndShopService.unBindShops(ipResource.getUsername(), shopRequestDto); ipAndShopService.unBindShops(ipResource.getUsername(),
shopRequestDto);
} }
ipResourceRepository.deleteById(ipResource.getId()); ipResourceRepository.deleteById(ipResource.getId());
} }
} finally { } finally {
long end = System.currentTimeMillis(); 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 { try {
ipResourceRepository.unLockTask(ipResource.getId()); ipResourceRepository.unLockTask(ipResource.getId());
} catch (Throwable th) { } catch (Throwable th) {
...@@ -300,8 +345,10 @@ public class BrowserTask { ...@@ -300,8 +345,10 @@ public class BrowserTask {
ipResource.setAddr( ipResource.setAddr(
instance.getPublicIpAddress().getIpAddress().get(0)); instance.getPublicIpAddress().getIpAddress().get(0));
ipResource.setStatus(0); ipResource.setStatus(0);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mmX"); DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
Instant instant = Instant.from(formatter.parse(instance.getExpiredTime())); "yyyy-MM-dd'T'HH:mmX");
Instant instant = Instant.from(
formatter.parse(instance.getExpiredTime()));
ipResource.setValidTime(instant.toEpochMilli()); ipResource.setValidTime(instant.toEpochMilli());
if (StringUtils.isNotBlank(ipResource.getRegion()) if (StringUtils.isNotBlank(ipResource.getRegion())
&& region.contains(ipResource.getRegion())) { && region.contains(ipResource.getRegion())) {
...@@ -321,14 +368,16 @@ public class BrowserTask { ...@@ -321,14 +368,16 @@ public class BrowserTask {
//查询是否为重复ip //查询是否为重复ip
String ipNo = instance.getPublicIpAddress().getIpAddress() String ipNo = instance.getPublicIpAddress().getIpAddress()
.get(0); .get(0);
LocalDateTime localDateTime = LocalDateTime.now().minus(3, ChronoUnit.MONTHS); LocalDateTime localDateTime = LocalDateTime.now()
Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant(); .minus(3, ChronoUnit.MONTHS);
Instant instant = localDateTime.atZone(ZoneId.systemDefault())
.toInstant();
List<IpHistory> ipHistoryList = ipHistoryRepository.findByIpNoAndPurchasedTimeAfter( List<IpHistory> ipHistoryList = ipHistoryRepository.findByIpNoAndPurchasedTimeAfter(
ipNo, ipNo,
instant.toEpochMilli()); instant.toEpochMilli());
if (CollectionUtils.isNotEmpty(ipHistoryList) && if (CollectionUtils.isNotEmpty(ipHistoryList) &&
(Objects.isNull(cloudPlatformOrder.getRetryCount()) || (Objects.isNull(cloudPlatformOrder.getRetryCount()) ||
cloudPlatformOrder.getRetryCount() < 5)) { cloudPlatformOrder.getRetryCount() < 5)) {
//重新分配ip(删除旧的 购买新的) //重新分配ip(删除旧的 购买新的)
AliEcsClient.deleteInstance( AliEcsClient.deleteInstance(
ipResource.getOwner(), ipResource.getOwner(),
...@@ -378,20 +427,63 @@ public class BrowserTask { ...@@ -378,20 +427,63 @@ public class BrowserTask {
} }
} }
} else if("tenCent".equals(cloudPlatformOrder.getPlatformType())){ } else if ("tenCent".equals(cloudPlatformOrder.getPlatformType())) {
com.tencentcloudapi.cvm.v20170312.models.DescribeInstancesResponse response = CloudPlatformConfig config = cloudPlatformConfigRepository.findByPlatformAndRegionId(
TenCentEcsClient.getDescribeInstances(ipResource.getOwner(), cloudPlatformOrder.getPlatformOrderId(), "tenCent",
cloudPlatformOrder.getRegionId()); 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"); log.error("fail to query ip");
return;
} }
com.tencentcloudapi.cvm.v20170312.models.Instance instance = response.getInstanceSet()[0]; com.tencentcloudapi.cvm.v20170312.models.Instance instance = response.getInstanceSet()[0];
if (instance.getInstanceChargeType().equals("PREPAID")) { if (instance.getInstanceChargeType().equals("PREPAID")) {
//包年包月 更新ip状态 //包年包月 更新ip状态
ipResource.setAddr(instance.getPublicIpAddresses()[0]); ipResource.setAddr(instance.getPublicIpAddresses()[0]);
ipResource.setStatus(0); ipResource.setStatus(0);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mmX"); DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
Instant instant = Instant.from(formatter.parse(instance.getExpiredTime())); Instant instant = Instant.from(
formatter.parse(instance.getExpiredTime()));
ipResource.setValidTime(instant.toEpochMilli()); ipResource.setValidTime(instant.toEpochMilli());
if (StringUtils.isNotBlank(ipResource.getRegion()) if (StringUtils.isNotBlank(ipResource.getRegion())
&& region.contains(ipResource.getRegion())) { && region.contains(ipResource.getRegion())) {
...@@ -411,8 +503,10 @@ public class BrowserTask { ...@@ -411,8 +503,10 @@ public class BrowserTask {
//查询是否为重复ip //查询是否为重复ip
String ipNo = instance.getPublicIpAddresses()[0]; String ipNo = instance.getPublicIpAddresses()[0];
LocalDateTime localDateTime = LocalDateTime.now().minus(3, ChronoUnit.MONTHS); LocalDateTime localDateTime = LocalDateTime.now()
Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant(); .minus(3, ChronoUnit.MONTHS);
Instant instant = localDateTime.atZone(ZoneId.systemDefault())
.toInstant();
List<IpHistory> ipHistoryList = ipHistoryRepository.findByIpNoAndPurchasedTimeAfter( List<IpHistory> ipHistoryList = ipHistoryRepository.findByIpNoAndPurchasedTimeAfter(
ipNo, ipNo,
instant.toEpochMilli()); instant.toEpochMilli());
...@@ -424,16 +518,13 @@ public class BrowserTask { ...@@ -424,16 +518,13 @@ public class BrowserTask {
ipResource.getOwner(), ipResource.getOwner(),
cloudPlatformOrder.getPlatformOrderId(), cloudPlatformOrder.getPlatformOrderId(),
cloudPlatformOrder.getRegionId()); cloudPlatformOrder.getRegionId());
CloudPlatformConfig config = cloudPlatformConfigRepository.findByPlatformAndRegionId(
"tenCent",
cloudPlatformOrder.getRegionId());
com.tencentcloudapi.cvm.v20170312.models.RunInstancesResponse response1 = TenCentEcsClient.runInstances( com.tencentcloudapi.cvm.v20170312.models.RunInstancesResponse response1 = TenCentEcsClient.runInstances(
ipResource.getOwner(), ipResource.getUsername(), ipResource.getOwner(), ipResource.getUsername(),
ipResource.getPassword(), config); ipResource.getPassword(), config);
if (null == response1 || null == response1.getInstanceIdSet()) { if (null == response1 || null == response1.getInstanceIdSet()) {
log.error("queryIpNewTasks, fail to buy ip again : {}", log.error("queryIpNewTasks, fail to buy ip again : {}",
JSON.toJSON(response)); JSON.toJSON(response));
} else{ } else {
int oldRetryCount = int oldRetryCount =
Objects.isNull(cloudPlatformOrder.getRetryCount()) Objects.isNull(cloudPlatformOrder.getRetryCount())
? 0 : cloudPlatformOrder.getRetryCount(); ? 0 : cloudPlatformOrder.getRetryCount();
...@@ -519,14 +610,16 @@ public class BrowserTask { ...@@ -519,14 +610,16 @@ public class BrowserTask {
if (instance.getInstanceChargeType().equals("PrePaid")) { if (instance.getInstanceChargeType().equals("PrePaid")) {
//包年包夜 更新ip状态 //包年包夜 更新ip状态
ipResource.setStatus(0); ipResource.setStatus(0);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mmX"); DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
Instant instant = Instant.from(formatter.parse(instance.getExpiredTime())); "yyyy-MM-dd'T'HH:mmX");
Instant instant = Instant.from(
formatter.parse(instance.getExpiredTime()));
ipResource.setValidTime(instant.toEpochMilli()); ipResource.setValidTime(instant.toEpochMilli());
ipResourceRepository.save(ipResource); ipResourceRepository.save(ipResource);
} }
} }
}else if("tenCent".equals(cloudPlatformOrder.getPlatformType())){ } else if ("tenCent".equals(cloudPlatformOrder.getPlatformType())) {
com.tencentcloudapi.cvm.v20170312.models.DescribeInstancesResponse describeInstances = TenCentEcsClient.getDescribeInstances( com.tencentcloudapi.cvm.v20170312.models.DescribeInstancesResponse describeInstances = TenCentEcsClient.getDescribeInstances(
ipResource.getOwner(), cloudPlatformOrder.getPlatformOrderId(), ipResource.getOwner(), cloudPlatformOrder.getPlatformOrderId(),
cloudPlatformOrder.getRegionId()); cloudPlatformOrder.getRegionId());
...@@ -540,8 +633,9 @@ public class BrowserTask { ...@@ -540,8 +633,9 @@ public class BrowserTask {
if (instance.getInstanceChargeType().equals("PREPAID")) { if (instance.getInstanceChargeType().equals("PREPAID")) {
//包年包夜 更新ip状态 //包年包夜 更新ip状态
ipResource.setStatus(0); ipResource.setStatus(0);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mmX"); DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
Instant instant = Instant.from(formatter.parse(instance.getExpiredTime())); Instant instant = Instant.from(
formatter.parse(instance.getExpiredTime()));
ipResource.setValidTime(instant.toEpochMilli()); ipResource.setValidTime(instant.toEpochMilli());
ipResourceRepository.save(ipResource); ipResourceRepository.save(ipResource);
} }
...@@ -570,6 +664,7 @@ public class BrowserTask { ...@@ -570,6 +664,7 @@ public class BrowserTask {
); );
} }
} }
/** /**
* 购买ip的定时任务,每分钟一次 * 购买ip的定时任务,每分钟一次
*/ */
...@@ -586,101 +681,118 @@ public class BrowserTask { ...@@ -586,101 +681,118 @@ public class BrowserTask {
for (IpResource ipResource : ipResources) { for (IpResource ipResource : ipResources) {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
CompletableFuture future = CompletableFuture.runAsync(() -> { CompletableFuture future = CompletableFuture.runAsync(() -> {
if (ipResourceRepository.lockTask(ipResource)) { if (ipResourceRepository.lockTask(ipResource)) {
log.info("{}, ip resource purchase : {}", logs, ipResource.getId()); 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 { try {
boolean result = false; log.info("{}, ip resource purchase params : {}", logs,
Map<String, String> header = buildPostHeader(); JSONObject.toJSONString(map));
HashMap<String, Object> map = new HashMap<>(); String requestResult = HttpClientutils.doPost(
map.put("name", ipResource.getUsername()); URL + "/intelligroup/ipresources?accountId=browser", header,
if ("uk".equals(ipResource.getRegion())) { JSONObject.toJSONString(map));
map.put("region", "london"); log.info("{}, ip resource purchase result : {}", logs, requestResult);
} else {
map.put("region", ipResource.getRegion()); 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 (ipBuyResultDto != null && ipBuyResultDto.getIplist() != null
&& ipBuyResultDto.getIplist().size() >= 1) {
if (StringUtils.isNotBlank(ipBuyResultDto.getErrorCode())) { log.info("{}, ip resource purchase successful : {}", logs,
log.error("{}, fail to buy ip : {}", logs, ipBuyResultDto.getErrorCode()); 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) { index.getAndIncrement();
log.info("{}, ip resource purchase successful : {}", logs, ipResource); }
AtomicInteger index = new AtomicInteger(); );
ipBuyResultDto.getIplist().forEach( result = true;
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;
} }
} catch (Exception e) {
log.error("{}, ip resource purchase Exception {}", logs, e.getMessage(),
e);
result = false;
}
/** /**
* 购买失败处理 * 购买失败处理
* *
* 购买后,长时间未能成功的ip资源视为购买失败。 * 购买后,长时间未能成功的ip资源视为购买失败。
* 购买malaysia实例失败后不进行重新购买 * 购买malaysia实例失败后不进行重新购买
* 购买时长超过20分钟的ip资源释放,并将购买花销退回账户余额。 * 购买时长超过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 problemRegion = "malaysia".equals(ipResource.getRegion());
boolean deal = overtime || problemRegion;*/ boolean deal = overtime || problemRegion;*/
if (!result && overtime) { if (!result && overtime) {
log.info("{}, ip resource purchase failure, {}", logs, ipResource); log.info("{}, ip resource purchase failure, {}", logs, ipResource);
IpChargeRequestDto ipChargeRequestDto = buildIpChargeRequestDto(ipResource, 3, 0); IpChargeRequestDto ipChargeRequestDto = buildIpChargeRequestDto(
accountService.chargeByMoney(ipResource.getOwner(), -ipResource.getPrice(), ipChargeRequestDto); ipResource, 3, 0);
if (ipResource.getShopIds() != null && ipResource.getShopIds().size() > 0) { accountService.chargeByMoney(ipResource.getOwner(),
ShopRequestDto shopRequestDto = new ShopRequestDto(); -ipResource.getPrice(), ipChargeRequestDto);
shopRequestDto.setIpId(ipResource.getId()); if (ipResource.getShopIds() != null
shopRequestDto.setShopIds(ipResource.getShopIds()); && ipResource.getShopIds().size() > 0) {
ipAndShopService.unBindShops(ipResource.getUsername(), shopRequestDto); ShopRequestDto shopRequestDto = new ShopRequestDto();
} shopRequestDto.setIpId(ipResource.getId());
ipResourceRepository.deleteById(ipResource.getId()); shopRequestDto.setShopIds(ipResource.getShopIds());
} ipAndShopService.unBindShops(ipResource.getUsername(),
} finally { shopRequestDto);
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());
} }
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); futureList.add(future);
} }
...@@ -695,40 +807,45 @@ public class BrowserTask { ...@@ -695,40 +807,45 @@ public class BrowserTask {
for (IpResource ipResource : ipResources) { for (IpResource ipResource : ipResources) {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
CompletableFuture.runAsync( 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 { try {
String url = URL + "/ecc/ipinfo?accountId=browser&ip=" + ipResource.getAddr(); ipInfoResultDto = JSONObject.parseObject(rs, IpInfoResultDto.class);
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);
}
}
} catch (Exception e) { } catch (Exception e) {
log.error(e.getMessage(), e); log.error("fail to pars json {}", rs, e);
NotifyUtils.sendMessage("浏览器后端 queryIpTasks() 又炸了,赶紧看啊", e, NotifyUtils.MsgType.WEBHOOK); }
} finally { if (ipInfoResultDto != null && StringUtils.isBlank(
long end = System.currentTimeMillis(); ipInfoResultDto.getErrorCode())) {
log.debug("queryIpTask {} execution time is: " + (end - start) / 1000 + "s", ipResource.getId()); if (StringUtils.isNotEmpty(ipInfoResultDto.getStatus())) {
try { ipResourceRepository.updateStatus(ipResource.getId(), 0);
ipResourceRepository.unLockTask(ipResource.getId());
} catch (Throwable th) {
log.error("unlock failed", th);
//try again
ipResourceRepository.unLockTask(ipResource.getId());
} }
} }
} 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 { ...@@ -748,19 +865,26 @@ public class BrowserTask {
final int maxRetry = Math.max(queryIpUrlLists.size(), 5); final int maxRetry = Math.max(queryIpUrlLists.size(), 5);
// 如果 ip 已经失效,且 ip 的状态不是 3:正在分配 和 6:未分配,则将 ip 的状态设置为 1 已过期 // 如果 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); ipResource.setStatus(1);
ipResourceRepository.save(ipResource); ipResourceRepository.save(ipResource);
// 如果 ip 为专线 ip,或者 ip 为用户自己的,但是使用了系统的专线功能 // 如果 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()); Trans trans = new Trans(ipResource.getProxyUsername(),
String sp_result = trans.get(getNextUrl(queryIpUrlLists, failTime).getUrl()); ipResource.getProxyPassword());
String sp_result = trans.get(
getNextUrl(queryIpUrlLists, failTime).getUrl());
while (!sp_result.contains(ipResource.getAddr())) { while (!sp_result.contains(ipResource.getAddr())) {
if (failTime > maxRetry) { if (failTime > maxRetry) {
NotifyUtils.sendMessage("防关联浏览器 ip " + ipResource.getAddr() + " 专线代理异常:" + ipResource.getIpType(), NotifyUtils.MsgType.WEBHOOK); NotifyUtils.sendMessage(
log.error("防关联浏览器 ip " + ipResource.getAddr() + " 专线代理异常 " + sp_result); "防关联浏览器 ip " + ipResource.getAddr() + " 专线代理异常:"
+ ipResource.getIpType(), NotifyUtils.MsgType.WEBHOOK);
log.error("防关联浏览器 ip " + ipResource.getAddr() + " 专线代理异常 "
+ sp_result);
break; break;
} }
failTime++; failTime++;
...@@ -770,13 +894,19 @@ public class BrowserTask { ...@@ -770,13 +894,19 @@ public class BrowserTask {
// 如果 ip 类型为 vendor // 如果 ip 类型为 vendor
} else if (ipResource.getIpType() == IpType.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()); String result = trans.get(getNextUrl(queryIpUrlLists, failTime).getUrl());
if (!result.contains(ipResource.getAddr())) { if (!result.contains(ipResource.getAddr())) {
while (!result.contains(ipResource.getAddr())) { while (!result.contains(ipResource.getAddr())) {
if (failTime > maxRetry) { if (failTime > maxRetry) {
NotifyUtils.sendMessage("防关联浏览器 ip " + ipResource.getAddr() + " 代理异常:" + ipResource.getIpType(), NotifyUtils.MsgType.WEBHOOK); NotifyUtils.sendMessage(
log.error("防关联浏览器 ip " + ipResource.getAddr() + " 代理异常 " + result); "防关联浏览器 ip " + ipResource.getAddr() + " 代理异常:"
+ ipResource.getIpType(), NotifyUtils.MsgType.WEBHOOK);
log.error("防关联浏览器 ip " + ipResource.getAddr() + " 代理异常 "
+ result);
break; break;
} }
failTime++; failTime++;
...@@ -787,11 +917,14 @@ public class BrowserTask { ...@@ -787,11 +917,14 @@ public class BrowserTask {
} }
} catch (Exception e) { } catch (Exception e) {
// todo 将代理异常改为 健康检查异常 // todo 将代理异常改为 健康检查异常
NotifyUtils.sendMessage("防关联浏览器 ip " + ipResource.getAddr() + " 健康检查异常", e, NotifyUtils.MsgType.WEBHOOK); NotifyUtils.sendMessage(
"防关联浏览器 ip " + ipResource.getAddr() + " 健康检查异常", e,
NotifyUtils.MsgType.WEBHOOK);
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
} finally { } finally {
long end = System.currentTimeMillis(); 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 { try {
ipResourceRepository.unLockHealth(ipResource.getId()); ipResourceRepository.unLockHealth(ipResource.getId());
} catch (Throwable th) { } catch (Throwable th) {
...@@ -808,15 +941,15 @@ public class BrowserTask { ...@@ -808,15 +941,15 @@ public class BrowserTask {
/** /**
* 删除逾期IP * 删除逾期IP
* * <p>
* 每小时查询 {@code validTime}早于3天前,并且未被删除的ip。 * 每小时查询 {@code validTime}早于3天前,并且未被删除的ip。 调用{@code deleteOverdueIp}删除IP资源
* 调用{@code deleteOverdueIp}删除IP资源
*/ */
@Scheduled(cron = "0 0 * * * ?") @Scheduled(cron = "0 0 * * * ?")
public void deleteOverdueIps() { public void deleteOverdueIps() {
String logs = "【deleteOverdueIps】 "; String logs = "【deleteOverdueIps】 ";
List<IpResource> list = ipResourceRepository 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()); log.error("Scheduled {}, list size : {}", logs, list.size());
list.forEach(this::deleteOverdueIp); list.forEach(this::deleteOverdueIp);
...@@ -824,39 +957,43 @@ public class BrowserTask { ...@@ -824,39 +957,43 @@ public class BrowserTask {
/** /**
* 删除逾期IP * 删除逾期IP
* * <p>
* 调用uri查看是否还存在指定资源 * 调用uri查看是否还存在指定资源 如果不存在,则{@code deleted}置为true
* 如果不存在,则{@code deleted}置为true
* *
* @param ipResource ipResource * @param ipResource ipResource
*/ */
private void deleteOverdueIp(IpResource ipResource){ private void deleteOverdueIp(IpResource ipResource) {
String logs = "【deleteOverdueIp】 "; String logs = "【deleteOverdueIp】 ";
List<CloudPlatformOrder> list = cloudPlatformOrderRepository.findByOwnerAndIpResourceId( List<CloudPlatformOrder> list = cloudPlatformOrderRepository.findByOwnerAndIpResourceId(
ipResource.getOwner(), ipResource.getId()); ipResource.getOwner(), ipResource.getId());
if(CollectionUtils.isNotEmpty(list)){ if (CollectionUtils.isNotEmpty(list)) {
CloudPlatformOrder cloudPlatformOrder = list.get(0); CloudPlatformOrder cloudPlatformOrder = list.get(0);
Boolean isDelet = false; Boolean isDelet = false;
if("aliyun".equals(cloudPlatformOrder.getPlatformType())){ if ("aliyun".equals(cloudPlatformOrder.getPlatformType())) {
String aliRegion = RegionMappingEnum.getAliRegion(ipResource.getRegion());
DeleteInstanceResponse response = AliEcsClient.deleteInstance( DeleteInstanceResponse response = AliEcsClient.deleteInstance(
ipResource.getOwner(), cloudPlatformOrder.getPlatformOrderId(), aliRegion); ipResource.getOwner(), cloudPlatformOrder.getPlatformOrderId(), cloudPlatformOrder.getRegionId());
if(null != response && response.getStatusCode().equals(200)) { if (null != response && response.getStatusCode().equals(200)) {
isDelet = true; isDelet = true;
} }
}else if("tenCent".equals(cloudPlatformOrder.getPlatformType())){ } else if ("tenCent".equals(cloudPlatformOrder.getPlatformType())) {
String aliRegion = RegionMappingEnum.getAliRegion(ipResource.getRegion()); CloudPlatformConfig config = cloudPlatformConfigRepository.findByPlatformAndRegionId(
TerminateInstancesResponse response = TenCentEcsClient.deleteInstance( "tenCent",
ipResource.getOwner(), cloudPlatformOrder.getPlatformOrderId(), aliRegion); cloudPlatformOrder.getRegionId());
if(null != response) { TerminateInstancesResponse response = null;
if(StringUtils.isNotEmpty(config.getTemplateId())) {
response = TenCentEcsClient.deleteInstance(
ipResource.getOwner(), cloudPlatformOrder.getPlatformOrderId(),
cloudPlatformOrder.getRegionId());
}
if (null != response) {
isDelet = true; isDelet = true;
} }
} }
if(isDelet){ if (isDelet) {
ipResource.setShopIds(null); ipResource.setShopIds(null);
ipResource.setDeleted(true); ipResource.setDeleted(true);
ipResourceRepository.save(ipResource); ipResourceRepository.save(ipResource);
}else { } else {
log.error("Scheduled {}, {} delete failed", logs, ipResource.getAddr()); log.error("Scheduled {}, {} delete failed", logs, ipResource.getAddr());
} }
} }
...@@ -881,14 +1018,14 @@ public class BrowserTask { ...@@ -881,14 +1018,14 @@ public class BrowserTask {
/** /**
* 封装HttpClientUtils.doDelete方法 * 封装HttpClientUtils.doDelete方法
* *
* @param path path * @param path path
* @param params params * @param params params
* @return String * @return String
* @throws IOException IOException * @throws IOException IOException
*/ */
private boolean doDelete(String path, String params){ private boolean doDelete(String path, String params) {
String logs = "【doDelete】 "; String logs = "【doDelete】 ";
try{ try {
String uri = (PROD.equals(profiles) ? CLOUDAMURL : TESTURL) + path + params; String uri = (PROD.equals(profiles) ? CLOUDAMURL : TESTURL) + path + params;
log.info("Scheduled {}, {} delete , params : {}", logs, params, params); log.info("Scheduled {}, {} delete , params : {}", logs, params, params);
String result = HttpClientutils.doDelete(uri, buildGetHeader()); String result = HttpClientutils.doDelete(uri, buildGetHeader());
...@@ -897,9 +1034,11 @@ public class BrowserTask { ...@@ -897,9 +1034,11 @@ public class BrowserTask {
if (SUCCESS.equals(deleteIpResultDto.getResult())) { if (SUCCESS.equals(deleteIpResultDto.getResult())) {
return true; return true;
} }
NotifyUtils.sendMessage("防关联浏览器 ip " + params + " 删除失败", NotifyUtils.MsgType.WEBHOOK); NotifyUtils.sendMessage("防关联浏览器 ip " + params + " 删除失败",
log.error("Scheduled {}, {} delete failed, ErrorCode : {}, result : {}", logs, params, deleteIpResultDto.getErrorCode(), deleteIpResultDto.getResult()); NotifyUtils.MsgType.WEBHOOK);
}catch (Exception e){ log.error("Scheduled {}, {} delete failed, ErrorCode : {}, result : {}", logs, params,
deleteIpResultDto.getErrorCode(), deleteIpResultDto.getResult());
} catch (Exception e) {
log.error("Scheduled {}, Exception : {}", logs, e.getMessage(), e); log.error("Scheduled {}, Exception : {}", logs, e.getMessage(), e);
} }
return false; return false;
...@@ -920,21 +1059,23 @@ public class BrowserTask { ...@@ -920,21 +1059,23 @@ public class BrowserTask {
List<Account> accounts = accountRepository.findAll(); List<Account> accounts = accountRepository.findAll();
try { try {
accounts.forEach( accounts.forEach(
x -> { x -> {
IpCountRecord ipCountRecord = new IpCountRecord(); IpCountRecord ipCountRecord = new IpCountRecord();
ipCountRecord.setUsername(x.getName()); ipCountRecord.setUsername(x.getName());
ipCountRecord.setTimestamp(Instant.now().toEpochMilli()); ipCountRecord.setTimestamp(Instant.now().toEpochMilli());
long ipcount_using = ipResourceRepository.countAllByOwnerAndIsDeletedAndValidTimeGreaterThan(x.getName(), false, Instant.now().toEpochMilli()); long ipcount_using = ipResourceRepository.countAllByOwnerAndIsDeletedAndValidTimeGreaterThan(
long ipcount_all = ipResourceRepository.countAllByOwner(x.getName()); x.getName(), false, Instant.now().toEpochMilli());
ipCountRecord.setIp_all(ipcount_all); long ipcount_all = ipResourceRepository.countAllByOwner(x.getName());
ipCountRecord.setIp_using(ipcount_using); ipCountRecord.setIp_all(ipcount_all);
ipCountRecordRepository.save(ipCountRecord); ipCountRecord.setIp_using(ipcount_using);
} ipCountRecordRepository.save(ipCountRecord);
}
); );
IpCountRecord ipCountRecord = new IpCountRecord(); IpCountRecord ipCountRecord = new IpCountRecord();
ipCountRecord.setUsername("all"); ipCountRecord.setUsername("all");
ipCountRecord.setTimestamp(Instant.now().toEpochMilli()); 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(); long ipcount_all = ipResourceRepository.count();
ipCountRecord.setIp_using(ipcount_using); ipCountRecord.setIp_using(ipcount_using);
ipCountRecord.setIp_all(ipcount_all); ipCountRecord.setIp_all(ipcount_all);
...@@ -946,6 +1087,7 @@ public class BrowserTask { ...@@ -946,6 +1087,7 @@ public class BrowserTask {
} }
public static class HttpClientutils { public static class HttpClientutils {
static OkHttpClient.Builder builder = new OkHttpClient.Builder(); static OkHttpClient.Builder builder = new OkHttpClient.Builder();
static { static {
...@@ -958,10 +1100,10 @@ public class BrowserTask { ...@@ -958,10 +1100,10 @@ public class BrowserTask {
public static String doDelete(String url, Map<String, String> headers) throws IOException { public static String doDelete(String url, Map<String, String> headers) throws IOException {
Headers httpHeaders = Headers.of(headers); Headers httpHeaders = Headers.of(headers);
Request request = new Request.Builder() Request request = new Request.Builder()
.delete() .delete()
.url(url) .url(url)
.headers(httpHeaders) .headers(httpHeaders)
.build(); .build();
Call call = client.newCall(request); Call call = client.newCall(request);
Response response = call.execute(); Response response = call.execute();
ResponseBody responseBody = response.body(); ResponseBody responseBody = response.body();
...@@ -972,23 +1114,24 @@ public class BrowserTask { ...@@ -972,23 +1114,24 @@ public class BrowserTask {
public static String doGet(String url, Map<String, String> headers) throws IOException { public static String doGet(String url, Map<String, String> headers) throws IOException {
Headers httpHeaders = Headers.of(headers); Headers httpHeaders = Headers.of(headers);
Request request = new Request.Builder() Request request = new Request.Builder()
.get() .get()
.url(url) .url(url)
.headers(httpHeaders) .headers(httpHeaders)
.build(); .build();
Call call = client.newCall(request); Call call = client.newCall(request);
Response response = call.execute(); Response response = call.execute();
ResponseBody responseBody = response.body(); ResponseBody responseBody = response.body();
return responseBody.string(); 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); Headers httpHeaders = Headers.of(headers);
Request request = new Request.Builder() Request request = new Request.Builder()
.post(RequestBody.create(body, okhttp3.MediaType.get("application/json"))) .post(RequestBody.create(body, okhttp3.MediaType.get("application/json")))
.url(url) .url(url)
.headers(httpHeaders) .headers(httpHeaders)
.build(); .build();
Call call = client.newCall(request); Call call = client.newCall(request);
Response response = call.execute(); Response response = call.execute();
ResponseBody responseBody = response.body(); ResponseBody responseBody = response.body();
......
package com.edgec.browserbackend.common.client; package com.edgec.browserbackend.common.client;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.edgec.browserbackend.browser.ErrorCode.BrowserErrorCode;
import com.edgec.browserbackend.browser.domain.CloudPlatformConfig; import com.edgec.browserbackend.browser.domain.CloudPlatformConfig;
import com.edgec.browserbackend.common.commons.error.ClientRequestException;
import com.edgec.browserbackend.common.utils.Aes; import com.edgec.browserbackend.common.utils.Aes;
import com.tencentcloudapi.common.Credential; import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile; import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile; import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.cvm.v20170312.CvmClient; import com.tencentcloudapi.cvm.v20170312.CvmClient;
import com.tencentcloudapi.cvm.v20170312.models.DescribeInstancesRequest; import com.tencentcloudapi.cvm.v20170312.models.DescribeInstancesRequest;
import com.tencentcloudapi.cvm.v20170312.models.DescribeInstancesResponse; 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.InstanceChargePrepaid;
import com.tencentcloudapi.cvm.v20170312.models.LaunchTemplate; import com.tencentcloudapi.cvm.v20170312.models.LaunchTemplate;
import com.tencentcloudapi.cvm.v20170312.models.LoginSettings; import com.tencentcloudapi.cvm.v20170312.models.LoginSettings;
import com.tencentcloudapi.cvm.v20170312.models.ModifyInstancesChargeTypeRequest; import com.tencentcloudapi.cvm.v20170312.models.ModifyInstancesChargeTypeRequest;
import com.tencentcloudapi.cvm.v20170312.models.ModifyInstancesChargeTypeResponse; 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.RenewInstancesRequest;
import com.tencentcloudapi.cvm.v20170312.models.RenewInstancesResponse; import com.tencentcloudapi.cvm.v20170312.models.RenewInstancesResponse;
import com.tencentcloudapi.cvm.v20170312.models.RunInstancesRequest; import com.tencentcloudapi.cvm.v20170312.models.RunInstancesRequest;
import com.tencentcloudapi.cvm.v20170312.models.RunInstancesResponse; import com.tencentcloudapi.cvm.v20170312.models.RunInstancesResponse;
import com.tencentcloudapi.cvm.v20170312.models.TerminateInstancesRequest; import com.tencentcloudapi.cvm.v20170312.models.TerminateInstancesRequest;
import com.tencentcloudapi.cvm.v20170312.models.TerminateInstancesResponse; 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.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
/** /**
...@@ -71,6 +91,18 @@ public class TenCentEcsClient { ...@@ -71,6 +91,18 @@ public class TenCentEcsClient {
return new CvmClient(cred, regionId, clientProfile); 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 { ...@@ -88,7 +120,7 @@ public class TenCentEcsClient {
LoginSettings loginSettings = new LoginSettings(); LoginSettings loginSettings = new LoginSettings();
loginSettings.setKeyIds(Collections.singletonList("skey-j9n2x0pl").toArray(new String[0])); loginSettings.setKeyIds(Collections.singletonList("skey-j9n2x0pl").toArray(new String[0]));
runInstancesRequest.setLoginSettings(loginSettings); 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); runInstancesResponse = cvmClient.RunInstances(runInstancesRequest);
log.info("调用TenCentEcs创建并运行实例,响应参数:owner:{},response:{}", owner, log.info("调用TenCentEcs创建并运行实例,响应参数:owner:{},response:{}", owner,
JSON.toJSON(runInstancesResponse)); JSON.toJSON(runInstancesResponse));
...@@ -188,9 +220,75 @@ public class TenCentEcsClient { ...@@ -188,9 +220,75 @@ public class TenCentEcsClient {
response = cvmClient.RenewInstances(req); response = cvmClient.RenewInstances(req);
log.info("调用TenCentEcs续费实例,响应参数:owner:{},response:{}", owner, JSON.toJSON(response)); log.info("调用TenCentEcs续费实例,响应参数:owner:{},response:{}", owner, JSON.toJSON(response));
} catch (Exception e) { } catch (Exception e) {
log.error("fail to TenCentEcs runInstances {}", e.getMessage()); log.error("fail to TenCentEcs renewInstance {}", e.getMessage());
} }
return response; 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 { ...@@ -28,7 +28,7 @@ public class FGLWxConfig extends WXPayConfig {
@Override @Override
public InputStream getCertStream() { public InputStream getCertStream() {
return getClass().getResourceAsStream("/certs/fangguanlian_cert.p12"); return getClass().getResourceAsStream("/certs/apiclient_cert.p12");
} }
@Override @Override
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>1</title> <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> </head>
<body> <body>
......
...@@ -15,11 +15,24 @@ import com.edgec.browserbackend.common.client.AliEcsClient; ...@@ -15,11 +15,24 @@ import com.edgec.browserbackend.common.client.AliEcsClient;
import com.edgec.browserbackend.common.client.TenCentEcsClient; import com.edgec.browserbackend.common.client.TenCentEcsClient;
import com.edgec.browserbackend.common.commons.utils.SmsUtils; import com.edgec.browserbackend.common.commons.utils.SmsUtils;
import com.edgec.browserbackend.common.utils.Aes; 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 java.time.Instant;
import javax.annotation.Resource; import javax.annotation.Resource;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest; 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 @SpringBootTest
class BrowserBackendApplicationTests { class BrowserBackendApplicationTests {
...@@ -40,21 +53,22 @@ class BrowserBackendApplicationTests { ...@@ -40,21 +53,22 @@ class BrowserBackendApplicationTests {
receptionPlatformOptions.setUrl("https:www.dhgate.com"); receptionPlatformOptions.setUrl("https:www.dhgate.com");
receptionPlatformOptions.setPictureUrl("https://ip-image.oss-rg-china-mainland.aliyuncs.com/app_image/app_image/dhgate.png"); receptionPlatformOptions.setPictureUrl("https://ip-image.oss-rg-china-mainland.aliyuncs.com/app_image/app_image/dhgate.png");
receptionPlatformOptions.setWeight(100); receptionPlatformOptions.setWeight(100);
repository.save(receptionPlatformOptions); //repository.save(receptionPlatformOptions);
} }
@Test @Test
void buyEcsTest() throws Exception { void buyEcsTest() throws Exception {
CloudPlatformConfig config = cloudPlatformConfigRepository.findByPlatformAndRegionId("tenCent", CloudPlatformConfig config = cloudPlatformConfigRepository.findByPlatformAndRegionId("tenCent",
"ap-guangzhou"); "ap-tokyo");
//browserTask.queryIpNewTasks(); //browserTask.queryIpNewTasks();
//AliEcsClient.runInstances("111","ceshi11","2222",config); //AliEcsClient.runInstances("111","ceshi11","2222",config);
//AliEcsClient.getDescribeInstances("测试","i-wz9hf0i13xj6h904k14p","cn-shenzhen"); //AliEcsClient.getDescribeInstances("测试","i-wz9hf0i13xj6h904k14p","cn-shenzhen");
//DeleteInstanceResponse response = AliEcsClient.deleteInstance("测试", "i-j6cd9fujd6we3dzk8z9e","cn-hongkong"); //DeleteInstanceResponse response = AliEcsClient.deleteInstance("测试", "i-j6cd9fujd6we3dzk8z9e","cn-hongkong");
//AliEcsClient.modifyInstanceChargeType("18711016574","Week",1,"cn-hongkong", "i-j6cd9fujd6we3dzk8z9e"); //AliEcsClient.modifyInstanceChargeType("18711016574","Week",1,"cn-hongkong", "i-j6cd9fujd6we3dzk8z9e");
//TenCentEcsClient.runInstances("111","ceshi11","2222",config); //TenCentEcsClient.createInstances("111","ceshi11","2222",config);
//TenCentEcsClient.getDescribeInstancesLight("测试","lhins-psgtwyeb","ap-tokyo");
TenCentEcsClient.deleteInstance("111","ins-nws56gg8","ap-guangzhou"); //TenCentEcsClient.deleteInstance("111","ins-nws56gg8","ap-guangzhou");
} }
@Resource @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