Add dist mode
[vnfsdk/refrepo.git] / vnfmarket-be / vnf-sdk-marketplace / src / main / java / org / onap / vtp / VTPResource.java
1 /**
2  * Copyright 2018 Huawei Technologies Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.onap.vtp;
18
19 import java.io.IOException;
20 import java.text.SimpleDateFormat;
21 import java.util.*;
22
23 import com.google.gson.*;
24 import org.apache.http.HttpStatus;
25 import org.onap.vtp.error.VTPError;
26 import org.onap.vtp.error.VTPError.VTPException;
27 import org.onap.vtp.manager.DistManager;
28 import org.onap.vtp.manager.model.Tester;
29 import org.open.infc.grpc.Output;
30 import org.open.infc.grpc.Result;
31 import org.open.infc.grpc.client.OpenInterfaceGrpcClient;
32 import org.open.infc.grpc.client.OpenRemoteCli;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 import com.google.gson.reflect.TypeToken;
37 import org.yaml.snakeyaml.DumperOptions;
38 import org.yaml.snakeyaml.Yaml;
39
40 import javax.ws.rs.client.Client;
41 import javax.ws.rs.client.ClientBuilder;
42 import javax.ws.rs.client.WebTarget;
43 import javax.ws.rs.core.MediaType;
44
45 public class VTPResource {
46
47     protected static final Logger LOG = LoggerFactory.getLogger(VTPResource.class);
48     private static Gson gson = new Gson();
49
50     protected static String VTP_TEST_CENTER_IP;  // NOSONAR
51     protected static int VTP_TEST_CENTER_PORT;  // NOSONAR
52     protected static String VTP_ARTIFACT_STORE;  // NOSONAR
53     protected static String VTP_EXECUTION_TEMP_STORE;  // NOSONAR
54     protected static int VTP_EXECUTION_GRPC_TIMEOUT;  // NOSONAR
55     protected static String VTP_YAML_STORE;  // NOSONAR
56     protected static String VTP_SCRIPT_STORE;  // NOSONAR
57     public static boolean mode=false;
58     protected static final SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);  // NOSONAR
59     DistManager distManager = null;
60     Tester tester = null;
61     static {
62         dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
63
64         Properties prp = new Properties();
65         try {
66             prp.load(VTPResource.class.getClassLoader().getResourceAsStream("vtp.properties"));
67             VTP_TEST_CENTER_IP = prp.getProperty("vtp.grpc.server");
68             VTP_TEST_CENTER_PORT = Integer.parseInt(prp.getProperty("vtp.grpc.port"));
69             VTP_ARTIFACT_STORE = prp.getProperty("vtp.artifact.store");
70             VTP_EXECUTION_TEMP_STORE = prp.getProperty("vtp.file.store");
71             VTP_EXECUTION_GRPC_TIMEOUT = Integer.parseInt(prp.getProperty("vtp.grpc.timeout")) * 1000 ;
72             VTP_YAML_STORE = prp.getProperty("vtp.yaml.store");
73             VTP_SCRIPT_STORE = prp.getProperty("vtp.script.store");
74             if (prp.getProperty("vtp.execution.mode").equals("dist"))
75                 mode=true;
76         } catch (Exception e) {  // NOSONAR
77             LOG.error(e.getMessage());
78         }
79     }
80
81     protected Result makeRpc(List <String> args) throws VTPException {
82         return this.makeRpc(args, VTP_EXECUTION_GRPC_TIMEOUT);
83     }
84
85     protected Result makeRpc(List <String> args, int timeout) throws VTPException {
86         String executionId=args.get(4);
87         if(isDistMode() && (executionId.contains("-") || args.contains("schema-show"))) {
88             distManager =new DistManager();
89
90             if (executionId.contains("-")){
91                 tester = distManager.httpRequestExecutions(executionId);
92             }
93             else {
94                 String scenario=args.get(4);
95                 String testSuiteName=args.get(6);
96                 String testCaseName=args.get(8);
97                 tester = distManager.httpRequestTestcase(testSuiteName,scenario,testCaseName);
98             }
99
100             VTP_TEST_CENTER_IP = tester.getIp();
101             VTP_TEST_CENTER_PORT = tester.getPort();
102
103         }
104         Result result = null;
105         String requestId = UUID.randomUUID().toString();
106         try {
107             result = new OpenRemoteCli(
108                     VTP_TEST_CENTER_IP,
109                     VTP_TEST_CENTER_PORT,
110                     timeout,
111                     requestId).run(args);
112         } catch(OpenInterfaceGrpcClient.OpenInterfaceGrpcTimeoutExecption e) {
113             LOG.info("Timed out.", e);
114             throw new VTPException(
115                   new VTPError().setHttpStatus(HttpStatus.SC_GATEWAY_TIMEOUT).setMessage("Timed out. Please use request-id to track the progress.").setCode(VTPError.TIMEOUT));
116         } catch (Exception e) {
117             LOG.info("Exception occurs.", e);
118             throw new VTPException(new VTPError().setMessage(e.getMessage()));
119         }
120
121         if (result.getExitCode() != 0) {
122             throw new VTPException(
123                     new VTPError().setMessage(result.getOutput()));
124         }
125
126         return result;
127     }
128
129     public static String getStorePath() {
130         return VTP_ARTIFACT_STORE;
131     }
132
133     protected JsonElement makeRpcAndGetJson(List<String> args) throws VTPException, IOException {
134         return this.makeRpcAndGetJson(args, VTP_EXECUTION_GRPC_TIMEOUT);
135     }
136
137     protected JsonElement makeRpcAndGetJson(List<String> args, int timeout) throws VTPException {
138         Result result = this.makeRpc(args, timeout);
139         JsonParser jsonParser = new JsonParser();
140         return jsonParser.parse(result.getOutput());
141     }
142
143     protected Output makeRpc(String testSuite,String scenario, String requestId, String profile, String testCase, JsonElement argsJsonNode) throws VTPException {
144         return this.makeRpc(testSuite,scenario, requestId, profile, testCase, argsJsonNode, VTP_EXECUTION_GRPC_TIMEOUT);
145     }
146
147     protected Output makeRpc(String testSuite,String scenario, String requestId, String profile, String testCase, JsonElement argsJsonNode, int timeout) throws VTPException {
148         if (isDistMode()){
149             distManager =new DistManager();
150             tester = distManager.httpRequestTestcase(testSuite,scenario,testCase);
151             VTP_TEST_CENTER_IP =tester.getIp();
152             VTP_TEST_CENTER_PORT = tester.getPort();
153         }
154         Output output = null;
155         Map <String, String> args = gson.fromJson(argsJsonNode, new TypeToken<Map<String,String>>(){}.getType());
156         try {
157             output = new OpenRemoteCli(
158                     VTP_TEST_CENTER_IP,
159                     VTP_TEST_CENTER_PORT,
160                     timeout,
161                     requestId).invoke(scenario, profile, testCase, args);
162          } catch(OpenInterfaceGrpcClient.OpenInterfaceGrpcTimeoutExecption e) {
163             LOG.info("Timed out.", e);
164              throw new VTPException(
165                   new VTPError().setHttpStatus(HttpStatus.SC_GATEWAY_TIMEOUT).setMessage("Timed out. Please use request-id to track the progress.").setCode(VTPError.TIMEOUT));
166         } catch (Exception e) {
167             LOG.info("Exception occurs", e);
168             throw new VTPException(
169                     new VTPError().setMessage(e.getMessage()));
170         }
171         if (isDistMode())
172         {
173             String executionId= output.getAddonsMap().get("execution-id");
174             assert distManager != null;
175             distManager.postDataToManager(executionId,tester.getId(),tester.getTesterId());
176         }
177         return output;
178     }
179
180     /**
181      * Build SnakeYaml instance
182      * @return
183      */
184     protected Yaml snakeYaml() {
185         DumperOptions dumperOptions = new DumperOptions();
186         dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
187         dumperOptions.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);
188         dumperOptions.setPrettyFlow(false);
189         return new Yaml(dumperOptions);
190     }
191     public boolean isDistMode() {
192         return mode;
193     }
194     protected JsonElement makeRpcAndGetJson(List<String> args,int count,int index) throws VTPException, IOException {
195         return this.makeRpcAndGetJson(args,count,index, VTP_EXECUTION_GRPC_TIMEOUT);
196     }
197
198     protected JsonElement makeRpcAndGetJson(List<String> args,int count,int index, int timeout) throws VTPException {
199         List<String> result = this.makeRpc(args,count,index, timeout);
200         JsonArray jsonArray = new JsonArray();
201         for (String jsonString : result) {
202             JsonElement obj = new JsonParser().parse(jsonString);
203             jsonArray.add(obj);
204         }
205         return jsonArray;
206     }
207
208     protected List<String> makeRpc(List<String> args, int count, int index, int timeout) {
209         distManager = new DistManager();
210         JsonElement jsonElement = distManager.getExecutionJson(count, index);
211         List<String> resultList = new ArrayList<>();
212         if (jsonElement != null && jsonElement.isJsonArray() && jsonElement.getAsJsonArray().size() > 0) {
213             JsonArray resultsArray = jsonElement.getAsJsonArray();
214             Client client = ClientBuilder.newClient();
215             for (JsonElement jElement : resultsArray) {
216                 JsonObject jsonObject = jElement.getAsJsonObject();
217                 String testerId = null;
218                 String executionId = null;
219                 if (jsonObject.has("tester_id"))
220                     testerId = jsonObject.get("tester_id").getAsString();
221                 if (jsonObject.has("execution_id"))
222                     executionId = jsonObject.get("execution_id").getAsString();
223                 if (testerId == null || executionId == null)
224                     throw new IllegalArgumentException("testerId: " + testerId + " and " + " executionId: " + executionId + " should not be null");
225
226                 String testerPath = "/manager/tester/" + testerId;
227                 JsonObject jObject = distManager.getResponseFromTester(client, distManager.getManagerURL(), testerPath).getAsJsonObject();
228                 String vtpTestCenterIp = jObject.get("iP").getAsString();
229                 int vtpTestCenterPort = Integer.parseInt(jObject.get("port").getAsString());
230                 args.set(4, executionId);
231                 try {
232                     resultList.add(distManager.getExecutionDetails(vtpTestCenterIp, vtpTestCenterPort, args, timeout).getOutput());
233                 } catch (Exception e) {
234                     LOG.error("executionId : " + executionId + " not valid::: " + e.getMessage());
235                 }
236             }
237         }
238         return resultList;
239     }
240 }