Fix dcae url status
[clamp.git] / src / main / java / org / onap / clamp / loop / LoopOperation.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights
6  *                             reserved.
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  */
23
24 package org.onap.clamp.loop;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.google.gson.JsonObject;
29
30 import java.io.IOException;
31 import java.util.Iterator;
32 import java.util.Set;
33 import java.util.UUID;
34
35 import org.apache.camel.Exchange;
36 import org.apache.camel.Message;
37 import org.json.simple.JSONObject;
38 import org.json.simple.parser.JSONParser;
39 import org.json.simple.parser.ParseException;
40 import org.onap.clamp.policy.operational.OperationalPolicy;
41 import org.springframework.beans.factory.annotation.Autowired;
42 import org.springframework.stereotype.Component;
43
44 /**
45  * Closed loop operations.
46  */
47 @Component
48 public class LoopOperation {
49
50     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(LoopOperation.class);
51     protected static final EELFLogger auditLogger = EELFManager.getInstance().getMetricsLogger();
52     private static final String DCAE_LINK_FIELD = "links";
53     private static final String DCAE_STATUS_FIELD = "status";
54     private static final String DCAE_SERVICETYPE_ID = "serviceTypeId";
55     private static final String DCAE_INPUTS = "inputs";
56     private static final String DCAE_DEPLOYMENT_PREFIX = "CLAMP_";
57     private static final String DEPLOYMENT_PARA = "dcaeDeployParameters";
58     private final LoopService loopService;
59
60     public enum TempLoopState {
61         NOT_SUBMITTED, SUBMITTED, DEPLOYED, NOT_DEPLOYED, PROCESSING, IN_ERROR;
62     }
63
64     /**
65      * The constructor.
66      *
67      * @param loopService
68      *        The loop service
69      * @param refProp
70      *        The clamp properties
71      */
72     @Autowired
73     public LoopOperation(LoopService loopService) {
74         this.loopService = loopService;
75     }
76
77     /**
78      * Get the payload used to send the deploy closed loop request.
79      *
80      * @param loop
81      *        The loop
82      * @return The payload used to send deploy closed loop request
83      * @throws IOException
84      *         IOException
85      */
86     public String getDeployPayload(Loop loop) throws IOException {
87         JsonObject globalProp = loop.getGlobalPropertiesJson();
88         JsonObject deploymentProp = globalProp.getAsJsonObject(DEPLOYMENT_PARA);
89
90         String serviceTypeId = loop.getDcaeBlueprintId();
91
92         JsonObject rootObject = new JsonObject();
93         rootObject.addProperty(DCAE_SERVICETYPE_ID, serviceTypeId);
94         if (deploymentProp != null) {
95             rootObject.add(DCAE_INPUTS, deploymentProp);
96         }
97         String apiBodyString = rootObject.toString();
98         logger.info("Dcae api Body String - " + apiBodyString);
99
100         return apiBodyString;
101     }
102
103     /**
104      * Get the deployment id.
105      *
106      * @param loop
107      *        The loop
108      * @return The deployment id
109      * @throws IOException
110      *         IOException
111      */
112     public String getDeploymentId(Loop loop) {
113         // Set the deploymentId if not present yet
114         String deploymentId = "";
115         // If model is already deployed then pass same deployment id
116         if (loop.getDcaeDeploymentId() != null && !loop.getDcaeDeploymentId().isEmpty()) {
117             deploymentId = loop.getDcaeDeploymentId();
118         } else {
119             deploymentId = DCAE_DEPLOYMENT_PREFIX + UUID.randomUUID();
120         }
121         return deploymentId;
122     }
123
124     /**
125      * Update the loop info.
126      *
127      * @param camelExchange
128      *        The camel exchange
129      * @param loop
130      *        The loop
131      * @param deploymentId
132      *        The deployment id
133      * @throws ParseException
134      *         The parse exception
135      */
136     public void updateLoopInfo(Exchange camelExchange, Loop loop, String deploymentId) throws ParseException {
137         Message in = camelExchange.getIn();
138         String msg = in.getBody(String.class);
139
140         JSONParser parser = new JSONParser();
141         Object obj0 = parser.parse(msg);
142         JSONObject jsonObj = (JSONObject) obj0;
143
144         JSONObject linksObj = (JSONObject) jsonObj.get(DCAE_LINK_FIELD);
145         String statusUrl = (String) linksObj.get(DCAE_STATUS_FIELD);
146
147         if (deploymentId == null) {
148             loop.setDcaeDeploymentId(null);
149             loop.setDcaeDeploymentStatusUrl(null);
150         } else {
151             loop.setDcaeDeploymentId(deploymentId);
152             loop.setDcaeDeploymentStatusUrl(statusUrl.replaceAll("http:", "http4:").replaceAll("https:", "https4:"));
153         }
154         loopService.saveOrUpdateLoop(loop);
155     }
156
157     /**
158      * Get the Closed Loop status based on the reply from Policy.
159      *
160      * @param statusCode
161      *        The status code
162      * @return The state based on policy response
163      * @throws ParseException
164      *         The parse exception
165      */
166     public String analysePolicyResponse(int statusCode) {
167         if (statusCode == 200) {
168             return TempLoopState.SUBMITTED.toString();
169         } else if (statusCode == 404) {
170             return TempLoopState.NOT_SUBMITTED.toString();
171         }
172         return TempLoopState.IN_ERROR.toString();
173     }
174
175     /**
176      * Get the name of the first Operational policy.
177      *
178      * @param loop
179      *        The closed loop
180      * @return The name of the first operational policy
181      */
182     public String getOperationalPolicyName(Loop loop) {
183         Set<OperationalPolicy> opSet = loop.getOperationalPolicies();
184         Iterator<OperationalPolicy> iterator = opSet.iterator();
185         while (iterator.hasNext()) {
186             OperationalPolicy policy = iterator.next();
187             return policy.getName();
188         }
189         return null;
190     }
191
192     /**
193      * Get the Closed Loop status based on the reply from DCAE.
194      *
195      * @param camelExchange
196      *        The camel exchange
197      * @return The state based on DCAE response
198      * @throws ParseException
199      *         The parse exception
200      */
201     public String analyseDcaeResponse(Exchange camelExchange, Integer statusCode) throws ParseException {
202         if (statusCode == null) {
203             return TempLoopState.NOT_DEPLOYED.toString();
204         }
205         if (statusCode == 200) {
206             Message in = camelExchange.getIn();
207             String msg = in.getBody(String.class);
208
209             JSONParser parser = new JSONParser();
210             Object obj0 = parser.parse(msg);
211             JSONObject jsonObj = (JSONObject) obj0;
212
213             String opType = (String) jsonObj.get("operationType");
214             String status = (String) jsonObj.get("status");
215
216             // status = processing/successded/failed
217             if (status.equals("succeeded")) {
218                 if (opType.equals("install")) {
219                     return TempLoopState.DEPLOYED.toString();
220                 } else if (opType.equals("uninstall")) {
221                     return TempLoopState.NOT_DEPLOYED.toString();
222                 }
223             } else if (status.equals("processing")) {
224                 return TempLoopState.PROCESSING.toString();
225             }
226         } else if (statusCode == 404) {
227             return TempLoopState.NOT_DEPLOYED.toString();
228         }
229         return TempLoopState.IN_ERROR.toString();
230     }
231
232     /**
233      * Update the status of the closed loop based on the response from Policy and
234      * DCAE.
235      *
236      * @param loop
237      *        The closed loop
238      * @param policyState
239      *        The state get from Policy
240      * @param dcaeState
241      *        The state get from DCAE
242      * @throws ParseException
243      *         The parse exception
244      */
245     public LoopState updateLoopStatus(Loop loop, TempLoopState policyState, TempLoopState dcaeState) {
246         LoopState clState = LoopState.IN_ERROR;
247         if (policyState == TempLoopState.SUBMITTED) {
248             if (dcaeState == TempLoopState.DEPLOYED) {
249                 clState = LoopState.DEPLOYED;
250             } else if (dcaeState == TempLoopState.PROCESSING) {
251                 clState = LoopState.WAITING;
252             } else if (dcaeState == TempLoopState.NOT_DEPLOYED) {
253                 clState = LoopState.SUBMITTED;
254             }
255         } else if (policyState == TempLoopState.NOT_SUBMITTED) {
256             if (dcaeState == TempLoopState.NOT_DEPLOYED) {
257                 clState = LoopState.DESIGN;
258             }
259         }
260         loop.setLastComputedState(clState);
261         loopService.saveOrUpdateLoop(loop);
262         return clState;
263     }
264
265 }