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