Merge "Update cadi to 2.1.10 and updated keystore"
[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.JsonArray;
29 import com.google.gson.JsonElement;
30 import com.google.gson.JsonNull;
31 import com.google.gson.JsonObject;
32 import com.google.gson.JsonPrimitive;
33
34 import java.io.IOException;
35 import java.lang.reflect.Array;
36 import java.util.Collection;
37 import java.util.Date;
38 import java.util.Map;
39
40 import javax.servlet.http.HttpServletRequest;
41
42 import org.apache.camel.Exchange;
43 import org.onap.clamp.clds.client.DcaeDispatcherServices;
44 import org.onap.clamp.clds.config.ClampProperties;
45 import org.onap.clamp.clds.util.LoggingUtils;
46 import org.onap.clamp.clds.util.ONAPLogConstants;
47 import org.onap.clamp.exception.OperationException;
48 import org.onap.clamp.util.HttpConnectionManager;
49 import org.slf4j.event.Level;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.http.HttpStatus;
52 import org.springframework.stereotype.Component;
53 import org.yaml.snakeyaml.Yaml;
54
55 /**
56  * Closed loop operations
57  */
58 @Component
59 public class LoopOperation {
60
61     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(LoopOperation.class);
62     protected static final EELFLogger auditLogger = EELFManager.getInstance().getMetricsLogger();
63     private final DcaeDispatcherServices dcaeDispatcherServices;
64     private final LoopService loopService;
65     private LoggingUtils util = new LoggingUtils(logger);
66
67     @Autowired
68     private HttpServletRequest request;
69
70     @Autowired
71     public LoopOperation(LoopService loopService, DcaeDispatcherServices dcaeDispatcherServices,
72         ClampProperties refProp, HttpConnectionManager httpConnectionManager) {
73         this.loopService = loopService;
74         this.dcaeDispatcherServices = dcaeDispatcherServices;
75     }
76
77     /**
78      * Deploy the closed loop.
79      *
80      * @param loopName
81      *        the loop name
82      * @return the updated loop
83      * @throws Exceptions
84      *         during the operation
85      */
86     public Loop deployLoop(Exchange camelExchange, String loopName) throws OperationException {
87         util.entering(request, "CldsService: Deploy model");
88         Date startTime = new Date();
89         Loop loop = loopService.getLoop(loopName);
90
91         if (loop == null) {
92             String msg = "Deploy loop exception: Not able to find closed loop:" + loopName;
93             util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO,
94                 ONAPLogConstants.ResponseStatus.ERROR);
95             throw new OperationException(msg);
96         }
97
98         // verify the current closed loop state
99         if (loop.getLastComputedState() != LoopState.SUBMITTED) {
100             String msg = "Deploy loop exception: This closed loop is in state:" + loop.getLastComputedState()
101                 + ". It could be deployed only when it is in SUBMITTED state.";
102             util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, ONAPLogConstants.ResponseStatus.ERROR);
103             throw new OperationException(msg);
104         }
105
106         // Set the deploymentId if not present yet
107         String deploymentId = "";
108         // If model is already deployed then pass same deployment id
109         if (loop.getDcaeDeploymentId() != null && !loop.getDcaeDeploymentId().isEmpty()) {
110             deploymentId = loop.getDcaeDeploymentId();
111         } else {
112             loop.setDcaeDeploymentId(deploymentId = "closedLoop_" + loopName + "_deploymentId");
113         }
114
115         Yaml yaml = new Yaml();
116         Map<String, Object> yamlMap = yaml.load(loop.getBlueprint());
117         JsonObject bluePrint = wrapSnakeObject(yamlMap).getAsJsonObject();
118
119         loop.setDcaeDeploymentStatusUrl(
120             dcaeDispatcherServices.createNewDeployment(deploymentId, loop.getDcaeBlueprintId(), bluePrint));
121         loop.setLastComputedState(LoopState.DEPLOYED);
122         // save the updated loop
123         loopService.saveOrUpdateLoop(loop);
124
125         // audit log
126         LoggingUtils.setTimeContext(startTime, new Date());
127         auditLogger.info("Deploy model completed");
128         util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
129         return loop;
130     }
131
132     /**
133      * Un deploy closed loop.
134      *
135      * @param loopName
136      *        the loop name
137      * @return the updated loop
138      */
139     public Loop unDeployLoop(String loopName) throws OperationException {
140         util.entering(request, "LoopOperation: Undeploy the closed loop");
141         Date startTime = new Date();
142         Loop loop = loopService.getLoop(loopName);
143
144         if (loop == null) {
145             String msg = "Undeploy loop exception: Not able to find closed loop:" + loopName;
146             util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO,
147                 ONAPLogConstants.ResponseStatus.ERROR);
148             throw new OperationException(msg);
149         }
150
151         // verify the current closed loop state
152         if (loop.getLastComputedState() != LoopState.DEPLOYED) {
153             String msg = "Unploy loop exception: This closed loop is in state:" + loop.getLastComputedState()
154                 + ". It could be undeployed only when it is in DEPLOYED state.";
155             util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, ONAPLogConstants.ResponseStatus.ERROR);
156             throw new OperationException(msg);
157         }
158
159         loop.setDcaeDeploymentStatusUrl(
160             dcaeDispatcherServices.deleteExistingDeployment(loop.getDcaeDeploymentId(), loop.getDcaeBlueprintId()));
161
162         // clean the deployment ID
163         loop.setDcaeDeploymentId(null);
164         loop.setLastComputedState(LoopState.SUBMITTED);
165
166         // save the updated loop
167         loopService.saveOrUpdateLoop(loop);
168
169         // audit log
170         LoggingUtils.setTimeContext(startTime, new Date());
171         auditLogger.info("Undeploy model completed");
172         util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
173         return loop;
174     }
175
176     private JsonElement wrapSnakeObject(Object o) {
177         // NULL => JsonNull
178         if (o == null)
179             return JsonNull.INSTANCE;
180
181         // Collection => JsonArray
182         if (o instanceof Collection) {
183             JsonArray array = new JsonArray();
184             for (Object childObj : (Collection<?>) o)
185                 array.add(wrapSnakeObject(childObj));
186             return array;
187         }
188
189         // Array => JsonArray
190         if (o.getClass().isArray()) {
191             JsonArray array = new JsonArray();
192
193             int length = Array.getLength(array);
194             for (int i = 0; i < length; i++)
195                 array.add(wrapSnakeObject(Array.get(array, i)));
196             return array;
197         }
198
199         // Map => JsonObject
200         if (o instanceof Map) {
201             Map<?, ?> map = (Map<?, ?>) o;
202
203             JsonObject jsonObject = new JsonObject();
204             for (final Map.Entry<?, ?> entry : map.entrySet()) {
205                 final String name = String.valueOf(entry.getKey());
206                 final Object value = entry.getValue();
207                 jsonObject.add(name, wrapSnakeObject(value));
208             }
209             return jsonObject;
210         }
211
212         // otherwise take it as a string
213         return new JsonPrimitive(String.valueOf(o));
214     }
215
216     /**
217      * Submit the Ms policies.
218      *
219      * @param loopName
220      *        the loop name
221      * @return the updated loop
222      * @throws IOException
223      *         IO exception
224      * @throws Exceptions
225      *         during the operation
226      */
227     public Loop submitMsPolicies(String loopName) throws OperationException, IOException {
228         util.entering(request, "LoopOperation: delete microservice policies");
229         Date startTime = new Date();
230         Loop loop = loopService.getLoop(loopName);
231
232         if (loop == null) {
233             String msg = "Submit MS policies exception: Not able to find closed loop:" + loopName;
234             util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO,
235                 ONAPLogConstants.ResponseStatus.ERROR);
236             throw new OperationException(msg);
237         }
238
239         // verify the current closed loop state
240         if (loop.getLastComputedState() != LoopState.SUBMITTED && loop.getLastComputedState() != LoopState.DESIGN) {
241             String msg = "Submit MS policies exception: This closed loop is in state:" + loop.getLastComputedState()
242                 + ". It could be deleted only when it is in SUBMITTED state.";
243             util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, ONAPLogConstants.ResponseStatus.ERROR);
244             throw new OperationException(msg);
245         }
246
247         // Establish the api call to Policy to create the ms services
248         // policyOp.createMsPolicy(loop.getMicroServicePolicies());
249
250         // audit log
251         LoggingUtils.setTimeContext(startTime, new Date());
252         auditLogger.info("Deletion of MS policies completed");
253         util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
254         return loop;
255     }
256
257     /**
258      * Delete the Ms policies.
259      *
260      * @param loopName
261      *        the loop name
262      * @return the updated loop
263      * @throws IOException
264      *         IO exception
265      * @throws Exceptions
266      *         during the operation
267      */
268     public Loop deleteMsPolicies(Exchange camelExchange, String loopName) throws OperationException, IOException {
269         util.entering(request, "LoopOperation: delete microservice policies");
270         Date startTime = new Date();
271         Loop loop = loopService.getLoop(loopName);
272
273         if (loop == null) {
274             String msg = "Delete MS policies exception: Not able to find closed loop:" + loopName;
275             util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO,
276                 ONAPLogConstants.ResponseStatus.ERROR);
277             throw new OperationException(msg);
278         }
279
280         // verify the current closed loop state
281         if (loop.getLastComputedState() != LoopState.SUBMITTED) {
282             String msg = "Delete MS policies exception: This closed loop is in state:" + loop.getLastComputedState()
283                 + ". It could be deleted only when it is in SUBMITTED state.";
284             util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, ONAPLogConstants.ResponseStatus.ERROR);
285             throw new OperationException(msg);
286         }
287
288         // Establish the api call to Policy to create the ms services
289         // policyOp.deleteMsPolicy(loop.getMicroServicePolicies());
290
291         // audit log
292         LoggingUtils.setTimeContext(startTime, new Date());
293         auditLogger.info("Deletion of MS policies completed");
294         util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
295         return loop;
296     }
297
298     /**
299      * Delete the operational policy.
300      *
301      * @param loopName
302      *        the loop name
303      * @return the updated loop
304      * @throws Exceptions
305      *         during the operation
306      */
307     public Loop deleteOpPolicy(Exchange camelExchange, String loopName) throws OperationException {
308         util.entering(request, "LoopOperation: delete guard policy");
309         Date startTime = new Date();
310         Loop loop = loopService.getLoop(loopName);
311
312         if (loop == null) {
313             String msg = "Delete guard policy exception: Not able to find closed loop:" + loopName;
314             util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO,
315                 ONAPLogConstants.ResponseStatus.ERROR);
316             throw new OperationException(msg);
317         }
318
319         // verify the current closed loop state
320         if (loop.getLastComputedState() != LoopState.SUBMITTED) {
321             String msg = "Delete MS policies exception: This closed loop is in state:" + loop.getLastComputedState()
322                 + ". It could be deleted only when it is in SUBMITTED state.";
323             util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, ONAPLogConstants.ResponseStatus.ERROR);
324             throw new OperationException(msg);
325         }
326
327         // Establish the api call to Policy to delete operational policy
328         // client.deleteOpPolicy();
329
330         // audit log
331         LoggingUtils.setTimeContext(startTime, new Date());
332         auditLogger.info("Deletion of Guard policy completed");
333         util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
334         return loop;
335     }
336
337     /**
338      * Delete the Guard policy.
339      *
340      * @param loopName
341      *        the loop name
342      * @return the updated loop
343      * @throws Exceptions
344      *         during the operation
345      */
346     public Loop deleteGuardPolicy(Exchange camelExchange, String loopName) throws OperationException {
347         util.entering(request, "LoopOperation: delete operational policy");
348         Date startTime = new Date();
349         Loop loop = loopService.getLoop(loopName);
350
351         if (loop == null) {
352             String msg = "Delete operational policy exception: Not able to find closed loop:" + loopName;
353             util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO,
354                 ONAPLogConstants.ResponseStatus.ERROR);
355             throw new OperationException(msg);
356         }
357
358         // verify the current closed loop state
359         if (loop.getLastComputedState() != LoopState.SUBMITTED) {
360             String msg = "Delete MS policies exception: This closed loop is in state:" + loop.getLastComputedState()
361                 + ". It could be deleted only when it is in SUBMITTED state.";
362             util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, ONAPLogConstants.ResponseStatus.ERROR);
363             throw new OperationException(msg);
364         }
365
366         // Establish the api call to Policy to delete Guard policy
367         // client.deleteOpPolicy();
368
369         // audit log
370         LoggingUtils.setTimeContext(startTime, new Date());
371         auditLogger.info("Deletion of operational policy completed");
372         util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
373         return loop;
374     }
375 }