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