Generate Random UUID for DCAE
[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         // use http4 instead of http, because camel http4 component is used to do the
148         // http call
149         String newStatusUrl = statusUrl.replaceAll("http:", "http4:").replaceAll("https:", "https4:");
150
151         loop.setDcaeDeploymentId(deploymentId);
152         loop.setDcaeDeploymentStatusUrl(newStatusUrl);
153         loopService.saveOrUpdateLoop(loop);
154     }
155
156     /**
157      * Get the Closed Loop status based on the reply from Policy.
158      *
159      * @param statusCode
160      *        The status code
161      * @return The state based on policy response
162      * @throws ParseException
163      *         The parse exception
164      */
165     public String analysePolicyResponse(int statusCode) {
166         if (statusCode == 200) {
167             return TempLoopState.SUBMITTED.toString();
168         } else if (statusCode == 404) {
169             return TempLoopState.NOT_SUBMITTED.toString();
170         }
171         return TempLoopState.IN_ERROR.toString();
172     }
173
174     /**
175      * Get the name of the first Operational policy.
176      *
177      * @param loop
178      *        The closed loop
179      * @return The name of the first operational policy
180      */
181     public String getOperationalPolicyName(Loop loop) {
182         Set<OperationalPolicy> opSet = loop.getOperationalPolicies();
183         Iterator<OperationalPolicy> iterator = opSet.iterator();
184         while (iterator.hasNext()) {
185             OperationalPolicy policy = iterator.next();
186             return policy.getName();
187         }
188         return null;
189     }
190
191     /**
192      * Get the Closed Loop status based on the reply from DCAE.
193      *
194      * @param camelExchange
195      *        The camel exchange
196      * @return The state based on DCAE response
197      * @throws ParseException
198      *         The parse exception
199      */
200     public String analyseDcaeResponse(Exchange camelExchange, Integer statusCode) throws ParseException {
201         if (statusCode == null) {
202             return TempLoopState.NOT_DEPLOYED.toString();
203         }
204         if (statusCode == 200) {
205             Message in = camelExchange.getIn();
206             String msg = in.getBody(String.class);
207
208             JSONParser parser = new JSONParser();
209             Object obj0 = parser.parse(msg);
210             JSONObject jsonObj = (JSONObject) obj0;
211
212             String opType = (String) jsonObj.get("operationType");
213             String status = (String) jsonObj.get("status");
214
215             // status = processing/successded/failed
216             if (status.equals("succeeded")) {
217                 if (opType.equals("install")) {
218                     return TempLoopState.DEPLOYED.toString();
219                 } else if (opType.equals("uninstall")) {
220                     return TempLoopState.NOT_DEPLOYED.toString();
221                 }
222             } else if (status.equals("processing")) {
223                 return TempLoopState.PROCESSING.toString();
224             }
225         } else if (statusCode == 404) {
226             return TempLoopState.NOT_DEPLOYED.toString();
227         }
228         return TempLoopState.IN_ERROR.toString();
229     }
230
231     /**
232      * Update the status of the closed loop based on the response from Policy and
233      * DCAE.
234      *
235      * @param loop
236      *        The closed loop
237      * @param policyState
238      *        The state get from Policy
239      * @param dcaeState
240      *        The state get from DCAE
241      * @throws ParseException
242      *         The parse exception
243      */
244     public LoopState updateLoopStatus(Loop loop, TempLoopState policyState, TempLoopState dcaeState) {
245         LoopState clState = LoopState.IN_ERROR;
246         if (policyState == TempLoopState.SUBMITTED) {
247             if (dcaeState == TempLoopState.DEPLOYED) {
248                 clState = LoopState.DEPLOYED;
249             } else if (dcaeState == TempLoopState.PROCESSING) {
250                 clState = LoopState.WAITING;
251             } else if (dcaeState == TempLoopState.NOT_DEPLOYED) {
252                 clState = LoopState.SUBMITTED;
253             }
254         } else if (policyState == TempLoopState.NOT_SUBMITTED) {
255             if (dcaeState == TempLoopState.NOT_DEPLOYED) {
256                 clState = LoopState.DESIGN;
257             }
258         }
259         loop.setLastComputedState(clState);
260         loopService.saveOrUpdateLoop(loop);
261         return clState;
262     }
263
264 }