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