| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270 |
- package cn.edu.nju.plagdemo.api.impl;
- import cn.edu.nju.plagdemo.api.IOssApi;
- import cn.edu.nju.plagdemo.api.IPlagDetectApi;
- import cn.edu.nju.plagdemo.exception.DefinitionException;
- import cn.edu.nju.plagdemo.model.dto.plag.AlgorithmRemoteParams;
- import cn.edu.nju.plagdemo.model.dto.plag.EndpointDTO;
- import cn.edu.nju.plagdemo.model.po.plag.AlgorithmPO;
- import cn.edu.nju.plagdemo.model.po.plag.BaseFilePO;
- import cn.edu.nju.plagdemo.model.po.plag.DetectionFilePO;
- import cn.edu.nju.plagdemo.model.po.plag.RecordPO;
- import cn.edu.nju.plagdemo.model.vo.AliyunTokenVO;
- import cn.edu.nju.plagdemo.model.vo.OssInfoVO;
- import cn.edu.nju.plagdemo.service.IAlgorithmService;
- import cn.edu.nju.plagdemo.service.IBaseFileService;
- import cn.edu.nju.plagdemo.service.IDetectionFileService;
- import cn.edu.nju.plagdemo.service.IRecordService;
- import cn.edu.nju.plagdemo.utils.RestResult;
- import cn.edu.nju.plagdemo.utils.SimpleCache;
- import com.aliyun.fc_open20210406.Client;
- import com.aliyun.fc_open20210406.models.InvokeFunctionHeaders;
- import com.aliyun.fc_open20210406.models.InvokeFunctionRequest;
- import com.aliyun.teaopenapi.models.Config;
- import com.aliyun.teautil.models.RuntimeOptions;
- import com.aliyuncs.DefaultAcsClient;
- import com.aliyuncs.exceptions.ClientException;
- import com.aliyuncs.fc.client.FunctionComputeClient;
- import com.aliyuncs.fc.model.HttpAuthType;
- import com.aliyuncs.fc.model.HttpMethod;
- import com.aliyuncs.fc.request.HttpInvokeFunctionRequest;
- import com.aliyuncs.fc.response.InvokeFunctionResponse;
- import com.aliyuncs.http.MethodType;
- import com.aliyuncs.profile.DefaultProfile;
- import com.aliyuncs.profile.IClientProfile;
- import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
- import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
- import com.fasterxml.jackson.core.JsonProcessingException;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import lombok.extern.slf4j.Slf4j;
- import okhttp3.Headers;
- import okhttp3.Response;
- import okhttp3.ResponseBody;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.http.HttpStatus;
- import org.springframework.http.ResponseEntity;
- import org.springframework.stereotype.Service;
- import org.springframework.web.client.RestTemplate;
- import java.nio.charset.StandardCharsets;
- import java.util.Arrays;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Objects;
- @Slf4j
- @Service
- public class PlagDetectApiImpl implements IPlagDetectApi {
- @Autowired
- private IAlgorithmService algorithmService;
- @Autowired
- private IDetectionFileService detectionFileService;
- @Autowired
- private IBaseFileService baseFileService;
- @Autowired
- private IRecordService recordService;
- @Autowired
- private RestTemplate restTemplate;
- @Autowired
- private IOssApi ossApi;
- // aliyun-fc配置
- // STS接入地址,例如sts.cn-hangzhou.aliyuncs.com。
- @Value("${aliyunfc.endpoint}")
- String endpoint = "";
- // 填写步骤1生成的RAM用户访问密钥AccessKey ID和AccessKey Secret。
- @Value("${aliyunfc.accesskey.id}")
- String accessKeyId = "";
- @Value("${aliyunfc.accesskey.secret}")
- String accessKeySecret = "";
- // 填写步骤3获取的角色ARN。
- @Value("${aliyunfc.role.arn}")
- String roleArn = "";
- // 自定义角色会话名称,用来区分不同的令牌,例如可填写为SessionTest。
- @Value("${aliyunfc.role.sessionname}")
- String roleSessionName = "";
- // regionId表示RAM的地域ID。以华东1(杭州)地域为例,regionID填写为cn-hangzhou。也可以保留默认值,默认值为空字符串("")。
- @Value("${aliyunfc.region}")
- String regionId = "";
- @Value("${aliyunfc.uid}")
- String uid = "";
- // 设置临时访问凭证的有效时间为15 * 60秒。 The Min/Max value of DurationSeconds is 15min/1hr.
- Long durationSeconds = 60L * 15;
- /**
- * 远程调用查重检测的函数服务
- * */
- @Override
- public RestResult<?> plagDetect(Integer file, Integer baseFile, Integer fileType, Integer algorithm, Map<String, Object> params) {
- // TODO 需要向数据库中记录record
- RecordPO recordPO = new RecordPO();
- recordPO.setFileId(file);
- recordPO.setBaseFileId(baseFile);
- recordPO.setAlgorithm(algorithm);
- recordService.save(recordPO);
- AlgorithmPO algorithmPO = algorithmService.getById(algorithm);
- String defaultOptions = algorithmPO.getDefaultOptions();
- ObjectMapper objectMapper = new ObjectMapper();
- Map<String, Object> option = null;
- try {
- option = objectMapper.readValue(defaultOptions, Map.class);
- } catch (JsonProcessingException e) {
- throw new DefinitionException(HttpStatus.INTERNAL_SERVER_ERROR, "option default value parse失败!");
- }
- if(option != null && params != null) {
- Map<String, Object> finalOption = option;
- params.forEach((k, v)-> {
- if (v!=null && finalOption.containsKey(k)) {
- finalOption.put(k, v);
- }
- });
- }
- DetectionFilePO detectionFilePO = detectionFileService.getById(file);
- String fileOssLink = detectionFilePO.getOssLink();
- BaseFilePO baseFilePO = baseFileService.getById(baseFile);
- String baseFileOssLink = baseFilePO.getOssLink();
- AlgorithmRemoteParams remoteParams = new AlgorithmRemoteParams();
- remoteParams.setRecordId(recordPO.getId());
- remoteParams.setOptions(option);
- remoteParams.setFileOssLink(fileOssLink);
- remoteParams.setBaseFileOssLink(baseFileOssLink);
- OssInfoVO ossClientInfo = ossApi.getOssClientInfo();
- remoteParams.setOssClient(ossClientInfo);
- RestResult<?> restResult = null;
- recordPO.setOptions(option.toString());
- try {
- EndpointDTO endpointDTO = new EndpointDTO(algorithmPO.getEndpoint());
- restResult = callFC(endpointDTO, remoteParams);
- } catch (Exception e) {
- recordPO.setState("查重失败");
- recordService.updateById(recordPO);
- throw new DefinitionException(HttpStatus.INTERNAL_SERVER_ERROR, "serverless 远程调用失败!");
- }
- recordPO.setState("正在查重");
- recordService.updateById(recordPO);
- return restResult;
- }
- public AliyunTokenVO getSTSToken() {
- AliyunTokenVO stsToken = (AliyunTokenVO) SimpleCache.get("fc_sts_token");
- if(stsToken != null) return stsToken;
- try {
- DefaultProfile.addEndpoint(regionId, "Sts", endpoint);
- IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
- DefaultAcsClient client = new DefaultAcsClient(profile);
- final AssumeRoleRequest request = new AssumeRoleRequest();
- request.setSysMethod(MethodType.POST);
- // 适用于Java SDK 3.12.0以下版本。
- // request.setMethod(MethodType.POST);
- request.setRoleArn(roleArn);
- request.setRoleSessionName(roleSessionName);
- request.setPolicy(null);
- request.setDurationSeconds(durationSeconds);
- System.out.println(roleArn);
- final AssumeRoleResponse response = client.getAcsResponse(request);
- stsToken = new AliyunTokenVO();
- stsToken.setSecurityToken(response.getCredentials().getSecurityToken());
- stsToken.setAccessKeyId(response.getCredentials().getAccessKeyId());
- stsToken.setAccessKeySecret(response.getCredentials().getAccessKeySecret());
- SimpleCache.put("fc_sts_token", stsToken, (durationSeconds - 5) * 1000);
- return stsToken;
- } catch (ClientException e) {
- log.error("Failed:" +
- "\nError code: " + e.getErrCode() +
- "\nError message: " + e.getErrMsg() +
- "\nRequestId: " + e.getRequestId(), e);
- throw new DefinitionException(HttpStatus.INTERNAL_SERVER_ERROR, "获取sts token失败");
- }
- }
- /**
- * 新旧sdk调用方式(url的方式会有bug,仅作为本地调用使用)
- */
- @Override
- public RestResult<?> callFC(EndpointDTO endpointDTO, AlgorithmRemoteParams remoteParams) throws Exception{
- RestResult restResult = null;
- if(endpointDTO.isURL()) {
- restResult = this.callFC(endpointDTO.getEndpoint(), remoteParams);
- } else {
- restResult = this.callFC(endpointDTO.getServiceName(), endpointDTO.getFunctionName(), endpointDTO.getPath(), remoteParams);
- }
- return restResult;
- }
- /**
- * 千万不要用这个方法来远程调用,使用新sdk中url的方式调用aliyun fc会有bug
- * 但是可以用这个函数来进行本地测试, 比方说 AlgorithmPO的endpoint可以填 http://localhost:8080/invoke,这样会通过url的方式访问本地服务
- * 如果 AlgorithmPO的endpoint填类似 serviceName/functionName/invoke这种,则会使用老的sdk访问阿里云服务,能成功调用远程服务
- */
- public RestResult<?> callFC(String url, AlgorithmRemoteParams remoteParams) throws Exception {
- AliyunTokenVO stsToken = this.getSTSToken();
- // AliyunTokenVO stsToken = new AliyunTokenVO(); // 本地调试用。可注释上一行,不去访问云端。
- Config config = new Config().setAccessKeyId(stsToken.getAccessKeyId())
- .setAccessKeySecret(stsToken.getAccessKeySecret())
- .setSecurityToken(stsToken.getSecurityToken())
- .setRegionId(regionId);
- Client client = new Client(config);
- ObjectMapper mapper = new ObjectMapper();
- String paramsInString = mapper.writeValueAsString(remoteParams);
- Response response = client.InvokeHTTPTrigger(
- url,
- "POST",
- paramsInString.getBytes(StandardCharsets.UTF_8),
- new Headers.Builder().build());
- RestResult restResult = null;
- byte[] bytes = Objects.requireNonNull(response.body()).bytes();
- try {
- restResult = mapper.readValue(bytes, RestResult.class);
- } catch (Exception ignore) {
- System.out.println(ignore);
- restResult = RestResult.fail(new String(bytes));
- }
- return restResult;
- }
- public RestResult<?> callFC(String serviceName, String functionName, String path, AlgorithmRemoteParams remoteParams) throws Exception { // TODO 不知道能不能跑,但是先提交一手
- AliyunTokenVO stsToken = this.getSTSToken();
- System.out.println(stsToken);
- FunctionComputeClient fcClient = new FunctionComputeClient(new com.aliyuncs.fc.config.Config(
- regionId, uid, stsToken.getAccessKeyId(), stsToken.getAccessKeySecret(), stsToken.getSecurityToken(), true
- ));
- HttpInvokeFunctionRequest request = new HttpInvokeFunctionRequest(serviceName, functionName, HttpAuthType.FUNCTION, HttpMethod.POST, path);
- ObjectMapper mapper = new ObjectMapper();
- String payload = mapper.writeValueAsString(remoteParams);
- request.setPayload(payload.getBytes());
- request.setHeader("Content-Type", "application/json");
- InvokeFunctionResponse response = fcClient.invokeFunction(request);
- RestResult restResult = null;
- byte[] bytes = response.getContent();
- try {
- restResult = mapper.readValue(bytes, RestResult.class);
- } catch (Exception ignore) {
- System.out.println(ignore);
- restResult = RestResult.fail(new String(bytes));
- }
- return restResult;
- }
- }
|