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