PlagDetectApiImpl.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. package cn.edu.nju.plagdemo.api.impl;
  2. import cn.edu.nju.plagdemo.api.IOssApi;
  3. import cn.edu.nju.plagdemo.api.IPlagDetectApi;
  4. import cn.edu.nju.plagdemo.exception.DefinitionException;
  5. import cn.edu.nju.plagdemo.model.dto.plag.AlgorithmRemoteParams;
  6. import cn.edu.nju.plagdemo.model.dto.plag.EndpointDTO;
  7. import cn.edu.nju.plagdemo.model.po.plag.AlgorithmPO;
  8. import cn.edu.nju.plagdemo.model.po.plag.BaseFilePO;
  9. import cn.edu.nju.plagdemo.model.po.plag.DetectionFilePO;
  10. import cn.edu.nju.plagdemo.model.po.plag.RecordPO;
  11. import cn.edu.nju.plagdemo.model.vo.AliyunTokenVO;
  12. import cn.edu.nju.plagdemo.model.vo.OssInfoVO;
  13. import cn.edu.nju.plagdemo.service.IAlgorithmService;
  14. import cn.edu.nju.plagdemo.service.IBaseFileService;
  15. import cn.edu.nju.plagdemo.service.IDetectionFileService;
  16. import cn.edu.nju.plagdemo.service.IRecordService;
  17. import cn.edu.nju.plagdemo.utils.RestResult;
  18. import cn.edu.nju.plagdemo.utils.SimpleCache;
  19. import com.aliyun.fc_open20210406.Client;
  20. import com.aliyun.fc_open20210406.models.InvokeFunctionHeaders;
  21. import com.aliyun.fc_open20210406.models.InvokeFunctionRequest;
  22. import com.aliyun.teaopenapi.models.Config;
  23. import com.aliyun.teautil.models.RuntimeOptions;
  24. import com.aliyuncs.DefaultAcsClient;
  25. import com.aliyuncs.exceptions.ClientException;
  26. import com.aliyuncs.fc.client.FunctionComputeClient;
  27. import com.aliyuncs.fc.model.HttpAuthType;
  28. import com.aliyuncs.fc.model.HttpMethod;
  29. import com.aliyuncs.fc.request.HttpInvokeFunctionRequest;
  30. import com.aliyuncs.fc.response.InvokeFunctionResponse;
  31. import com.aliyuncs.http.MethodType;
  32. import com.aliyuncs.profile.DefaultProfile;
  33. import com.aliyuncs.profile.IClientProfile;
  34. import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
  35. import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
  36. import com.fasterxml.jackson.core.JsonProcessingException;
  37. import com.fasterxml.jackson.databind.ObjectMapper;
  38. import lombok.extern.slf4j.Slf4j;
  39. import okhttp3.Headers;
  40. import okhttp3.Response;
  41. import okhttp3.ResponseBody;
  42. import org.springframework.beans.factory.annotation.Autowired;
  43. import org.springframework.beans.factory.annotation.Value;
  44. import org.springframework.http.HttpStatus;
  45. import org.springframework.http.ResponseEntity;
  46. import org.springframework.stereotype.Service;
  47. import org.springframework.web.client.RestTemplate;
  48. import java.nio.charset.StandardCharsets;
  49. import java.util.Arrays;
  50. import java.util.HashMap;
  51. import java.util.Map;
  52. import java.util.Objects;
  53. @Slf4j
  54. @Service
  55. public class PlagDetectApiImpl implements IPlagDetectApi {
  56. @Autowired
  57. private IAlgorithmService algorithmService;
  58. @Autowired
  59. private IDetectionFileService detectionFileService;
  60. @Autowired
  61. private IBaseFileService baseFileService;
  62. @Autowired
  63. private IRecordService recordService;
  64. @Autowired
  65. private RestTemplate restTemplate;
  66. @Autowired
  67. private IOssApi ossApi;
  68. // aliyun-fc配置
  69. // STS接入地址,例如sts.cn-hangzhou.aliyuncs.com。
  70. @Value("${aliyunfc.endpoint}")
  71. String endpoint = "";
  72. // 填写步骤1生成的RAM用户访问密钥AccessKey ID和AccessKey Secret。
  73. @Value("${aliyunfc.accesskey.id}")
  74. String accessKeyId = "";
  75. @Value("${aliyunfc.accesskey.secret}")
  76. String accessKeySecret = "";
  77. // 填写步骤3获取的角色ARN。
  78. @Value("${aliyunfc.role.arn}")
  79. String roleArn = "";
  80. // 自定义角色会话名称,用来区分不同的令牌,例如可填写为SessionTest。
  81. @Value("${aliyunfc.role.sessionname}")
  82. String roleSessionName = "";
  83. // regionId表示RAM的地域ID。以华东1(杭州)地域为例,regionID填写为cn-hangzhou。也可以保留默认值,默认值为空字符串("")。
  84. @Value("${aliyunfc.region}")
  85. String regionId = "";
  86. @Value("${aliyunfc.uid}")
  87. String uid = "";
  88. // 设置临时访问凭证的有效时间为15 * 60秒。 The Min/Max value of DurationSeconds is 15min/1hr.
  89. Long durationSeconds = 60L * 15;
  90. /**
  91. * 远程调用查重检测的函数服务
  92. * */
  93. @Override
  94. public RestResult<?> plagDetect(Integer file, Integer baseFile, Integer fileType, Integer algorithm, Map<String, Object> params) {
  95. // TODO 需要向数据库中记录record
  96. RecordPO recordPO = new RecordPO();
  97. recordPO.setFileId(file);
  98. recordPO.setBaseFileId(baseFile);
  99. recordPO.setAlgorithm(algorithm);
  100. recordService.save(recordPO);
  101. AlgorithmPO algorithmPO = algorithmService.getById(algorithm);
  102. String defaultOptions = algorithmPO.getDefaultOptions();
  103. ObjectMapper objectMapper = new ObjectMapper();
  104. Map<String, Object> option = null;
  105. try {
  106. option = objectMapper.readValue(defaultOptions, Map.class);
  107. } catch (JsonProcessingException e) {
  108. throw new DefinitionException(HttpStatus.INTERNAL_SERVER_ERROR, "option default value parse失败!");
  109. }
  110. if(option != null && params != null) {
  111. Map<String, Object> finalOption = option;
  112. params.forEach((k, v)-> {
  113. if (v!=null && finalOption.containsKey(k)) {
  114. finalOption.put(k, v);
  115. }
  116. });
  117. }
  118. DetectionFilePO detectionFilePO = detectionFileService.getById(file);
  119. String fileOssLink = detectionFilePO.getOssLink();
  120. BaseFilePO baseFilePO = baseFileService.getById(baseFile);
  121. String baseFileOssLink = baseFilePO.getOssLink();
  122. AlgorithmRemoteParams remoteParams = new AlgorithmRemoteParams();
  123. remoteParams.setRecordId(recordPO.getId());
  124. remoteParams.setOptions(option);
  125. remoteParams.setFileOssLink(fileOssLink);
  126. remoteParams.setBaseFileOssLink(baseFileOssLink);
  127. OssInfoVO ossClientInfo = ossApi.getOssClientInfo();
  128. remoteParams.setOssClient(ossClientInfo);
  129. RestResult<?> restResult = null;
  130. recordPO.setOptions(option.toString());
  131. try {
  132. EndpointDTO endpointDTO = new EndpointDTO(algorithmPO.getEndpoint());
  133. restResult = callFC(endpointDTO, remoteParams);
  134. } catch (Exception e) {
  135. recordPO.setState("查重失败");
  136. recordService.updateById(recordPO);
  137. throw new DefinitionException(HttpStatus.INTERNAL_SERVER_ERROR, "serverless 远程调用失败!");
  138. }
  139. recordPO.setState("正在查重");
  140. recordService.updateById(recordPO);
  141. return restResult;
  142. }
  143. public AliyunTokenVO getSTSToken() {
  144. AliyunTokenVO stsToken = (AliyunTokenVO) SimpleCache.get("fc_sts_token");
  145. if(stsToken != null) return stsToken;
  146. try {
  147. DefaultProfile.addEndpoint(regionId, "Sts", endpoint);
  148. IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
  149. DefaultAcsClient client = new DefaultAcsClient(profile);
  150. final AssumeRoleRequest request = new AssumeRoleRequest();
  151. request.setSysMethod(MethodType.POST);
  152. // 适用于Java SDK 3.12.0以下版本。
  153. // request.setMethod(MethodType.POST);
  154. request.setRoleArn(roleArn);
  155. request.setRoleSessionName(roleSessionName);
  156. request.setPolicy(null);
  157. request.setDurationSeconds(durationSeconds);
  158. System.out.println(roleArn);
  159. final AssumeRoleResponse response = client.getAcsResponse(request);
  160. stsToken = new AliyunTokenVO();
  161. stsToken.setSecurityToken(response.getCredentials().getSecurityToken());
  162. stsToken.setAccessKeyId(response.getCredentials().getAccessKeyId());
  163. stsToken.setAccessKeySecret(response.getCredentials().getAccessKeySecret());
  164. SimpleCache.put("fc_sts_token", stsToken, (durationSeconds - 5) * 1000);
  165. return stsToken;
  166. } catch (ClientException e) {
  167. log.error("Failed:" +
  168. "\nError code: " + e.getErrCode() +
  169. "\nError message: " + e.getErrMsg() +
  170. "\nRequestId: " + e.getRequestId(), e);
  171. throw new DefinitionException(HttpStatus.INTERNAL_SERVER_ERROR, "获取sts token失败");
  172. }
  173. }
  174. /**
  175. * 新旧sdk调用方式(url的方式会有bug,仅作为本地调用使用)
  176. */
  177. @Override
  178. public RestResult<?> callFC(EndpointDTO endpointDTO, AlgorithmRemoteParams remoteParams) throws Exception{
  179. RestResult restResult = null;
  180. if(endpointDTO.isURL()) {
  181. restResult = this.callFC(endpointDTO.getEndpoint(), remoteParams);
  182. } else {
  183. restResult = this.callFC(endpointDTO.getServiceName(), endpointDTO.getFunctionName(), endpointDTO.getPath(), remoteParams);
  184. }
  185. return restResult;
  186. }
  187. /**
  188. * 千万不要用这个方法来远程调用,使用新sdk中url的方式调用aliyun fc会有bug
  189. * 但是可以用这个函数来进行本地测试, 比方说 AlgorithmPO的endpoint可以填 http://localhost:8080/invoke,这样会通过url的方式访问本地服务
  190. * 如果 AlgorithmPO的endpoint填类似 serviceName/functionName/invoke这种,则会使用老的sdk访问阿里云服务,能成功调用远程服务
  191. */
  192. public RestResult<?> callFC(String url, AlgorithmRemoteParams remoteParams) throws Exception {
  193. AliyunTokenVO stsToken = this.getSTSToken();
  194. // AliyunTokenVO stsToken = new AliyunTokenVO(); // 本地调试用。可注释上一行,不去访问云端。
  195. Config config = new Config().setAccessKeyId(stsToken.getAccessKeyId())
  196. .setAccessKeySecret(stsToken.getAccessKeySecret())
  197. .setSecurityToken(stsToken.getSecurityToken())
  198. .setRegionId(regionId);
  199. Client client = new Client(config);
  200. ObjectMapper mapper = new ObjectMapper();
  201. String paramsInString = mapper.writeValueAsString(remoteParams);
  202. Response response = client.InvokeHTTPTrigger(
  203. url,
  204. "POST",
  205. paramsInString.getBytes(StandardCharsets.UTF_8),
  206. new Headers.Builder().build());
  207. RestResult restResult = null;
  208. byte[] bytes = Objects.requireNonNull(response.body()).bytes();
  209. try {
  210. restResult = mapper.readValue(bytes, RestResult.class);
  211. } catch (Exception ignore) {
  212. System.out.println(ignore);
  213. restResult = RestResult.fail(new String(bytes));
  214. }
  215. return restResult;
  216. }
  217. public RestResult<?> callFC(String serviceName, String functionName, String path, AlgorithmRemoteParams remoteParams) throws Exception { // TODO 不知道能不能跑,但是先提交一手
  218. AliyunTokenVO stsToken = this.getSTSToken();
  219. System.out.println(stsToken);
  220. FunctionComputeClient fcClient = new FunctionComputeClient(new com.aliyuncs.fc.config.Config(
  221. regionId, uid, stsToken.getAccessKeyId(), stsToken.getAccessKeySecret(), stsToken.getSecurityToken(), true
  222. ));
  223. HttpInvokeFunctionRequest request = new HttpInvokeFunctionRequest(serviceName, functionName, HttpAuthType.FUNCTION, HttpMethod.POST, path);
  224. ObjectMapper mapper = new ObjectMapper();
  225. String payload = mapper.writeValueAsString(remoteParams);
  226. request.setPayload(payload.getBytes());
  227. request.setHeader("Content-Type", "application/json");
  228. InvokeFunctionResponse response = fcClient.invokeFunction(request);
  229. RestResult restResult = null;
  230. byte[] bytes = response.getContent();
  231. try {
  232. restResult = mapper.readValue(bytes, RestResult.class);
  233. } catch (Exception ignore) {
  234. System.out.println(ignore);
  235. restResult = RestResult.fail(new String(bytes));
  236. }
  237. return restResult;
  238. }
  239. }