Merge "Add debugging of REST call"
[policy/drools-applications.git] / controlloop / common / model-impl / vfc / src / main / java / org / onap / policy / vfc / VfcManager.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2017-2018 Intel Corp, AT&T. All rights reserved.
4  * Modifications Copyright (C) 2018-2019 AT&T Corporation. All rights reserved.
5  * Modifications Copyright (C) 2019 Samsung Electronics Co., Ltd.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.vfc;
22
23 import com.google.gson.JsonSyntaxException;
24
25 import java.util.HashMap;
26 import java.util.Map;
27
28 import org.drools.core.WorkingMemory;
29 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
30 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
31 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
32 import org.onap.policy.drools.system.PolicyEngine;
33 import org.onap.policy.rest.RestManager;
34 import org.onap.policy.rest.RestManager.Pair;
35 import org.onap.policy.vfc.util.Serialization;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 public final class VfcManager implements Runnable {
40
41     private String vfcUrlBase;
42     private String username;
43     private String password;
44     private VfcRequest vfcRequest;
45     private WorkingMemory workingMem;
46     private static final Logger logger = LoggerFactory.getLogger(VfcManager.class);
47
48     // The REST manager used for processing REST calls for this VFC manager
49     private RestManager restManager;
50
51     /**
52      * Constructor.
53      *
54      * @param wm Drools working memory
55      * @param request request
56      */
57     public VfcManager(WorkingMemory wm, VfcRequest request) {
58         if (wm == null || request == null) {
59             throw new IllegalArgumentException(
60                     "the parameters \"wm\" and \"request\" on the VfcManager constructor may not be null");
61         }
62         workingMem = wm;
63         vfcRequest = request;
64
65         restManager = new RestManager();
66
67         // use getPEManagerEnvProperty() for required properties; others are optional
68         setVfcParams(getPeManagerEnvProperty("vfc.url"), PolicyEngine.manager.getEnvironmentProperty("vfc.username"),
69                 PolicyEngine.manager.getEnvironmentProperty("vfc.password"));
70     }
71
72     /**
73      * Set the parameters.
74      *
75      * @param baseUrl base URL
76      * @param name username
77      * @param pwd password
78      */
79     public void setVfcParams(String baseUrl, String name, String pwd) {
80         vfcUrlBase = baseUrl + "/api/nslcm/v1";
81         username = name;
82         password = pwd;
83     }
84
85     @Override
86     public void run() {
87         Map<String, String> headers = new HashMap<>();
88         Pair<Integer, String> httpDetails;
89
90         VfcResponse responseError = new VfcResponse();
91         responseError.setResponseDescriptor(new VfcResponseDescriptor());
92         responseError.getResponseDescriptor().setStatus("error");
93
94         headers.put("Accept", "application/json");
95         String vfcUrl = vfcUrlBase + "/ns/" + vfcRequest.getNsInstanceId() + "/heal";
96         try {
97             String vfcRequestJson = Serialization.gsonPretty.toJson(vfcRequest);
98             NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, vfcUrl, vfcRequestJson);
99
100             httpDetails = restManager.post(vfcUrl, username, password, headers, "application/json", vfcRequestJson);
101         } catch (Exception e) {
102             logger.error(e.getMessage(), e);
103             workingMem.insert(responseError);
104             return;
105         }
106
107         if (httpDetails == null) {
108             workingMem.insert(responseError);
109             return;
110         }
111
112         if (httpDetails.first != 202) {
113             logger.warn("VFC Heal Restcall failed");
114             return;
115         }
116
117         try {
118             VfcResponse response = Serialization.gsonPretty.fromJson(httpDetails.second, VfcResponse.class);
119             NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, vfcUrl, httpDetails.second);
120             String body = Serialization.gsonPretty.toJson(response);
121             logger.debug("Response to VFC Heal post:");
122             logger.debug(body);
123
124             String jobId = response.getJobId();
125             int attemptsLeft = 20;
126
127             String urlGet = vfcUrlBase + "/jobs/" + jobId;
128             VfcResponse responseGet = null;
129
130             while (attemptsLeft-- > 0) {
131                 NetLoggerUtil.getNetworkLogger().info("[OUT|{}|{}|]", "VFC", urlGet);
132                 Pair<Integer, String> httpDetailsGet = restManager.get(urlGet, username, password, headers);
133                 responseGet = Serialization.gsonPretty.fromJson(httpDetailsGet.second, VfcResponse.class);
134                 NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, vfcUrl, httpDetailsGet.second);
135                 responseGet.setRequestId(vfcRequest.getRequestId().toString());
136                 body = Serialization.gsonPretty.toJson(responseGet);
137                 logger.debug("Response to VFC Heal get:");
138                 logger.debug(body);
139
140                 String responseStatus = responseGet.getResponseDescriptor().getStatus();
141                 if (httpDetailsGet.first == 200
142                         && ("finished".equalsIgnoreCase(responseStatus) || "error".equalsIgnoreCase(responseStatus))) {
143                     logger.debug("VFC Heal Status {}", responseGet.getResponseDescriptor().getStatus());
144                     workingMem.insert(responseGet);
145                     break;
146                 }
147                 Thread.sleep(20000);
148             }
149             if ((attemptsLeft <= 0) && (responseGet != null) && (responseGet.getResponseDescriptor() != null)
150                     && (responseGet.getResponseDescriptor().getStatus() != null)
151                     && (!responseGet.getResponseDescriptor().getStatus().isEmpty())) {
152                 logger.debug("VFC timeout. Status: ({})", responseGet.getResponseDescriptor().getStatus());
153                 workingMem.insert(responseGet);
154             }
155         } catch (JsonSyntaxException e) {
156             logger.error("Failed to deserialize into VfcResponse {}", e.getLocalizedMessage(), e);
157         } catch (InterruptedException e) {
158             logger.error("Interrupted exception: {}", e.getLocalizedMessage(), e);
159             Thread.currentThread().interrupt();
160         } catch (Exception e) {
161             logger.error("Unknown error deserializing into VfcResponse {}", e.getLocalizedMessage(), e);
162         }
163     }
164
165     /**
166      * Protected setter for rest manager to allow mocked rest manager to be used for testing.
167      *
168      * @param restManager the test REST manager
169      */
170     protected void setRestManager(final RestManager restManager) {
171         this.restManager = restManager;
172     }
173
174     /**
175      * This method reads and validates environmental properties coming from the policy engine. Null
176      * properties cause an {@link IllegalArgumentException} runtime exception to be thrown
177      *
178      * @param string the name of the parameter to retrieve
179      * @return the property value
180      */
181
182     private String getPeManagerEnvProperty(String enginePropertyName) {
183         String enginePropertyValue = PolicyEngine.manager.getEnvironmentProperty(enginePropertyName);
184         if (enginePropertyValue == null) {
185             throw new IllegalArgumentException("The value of policy engine manager environment property \""
186                     + enginePropertyName + "\" may not be null");
187         }
188         return enginePropertyValue;
189     }
190 }