af615af113ccc2de79d280fd46d4b737239f66dc
[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.lang.reflect.Array;
35 import java.util.Collection;
36 import java.util.Date;
37 import java.util.Map;
38
39 import javax.servlet.http.HttpServletRequest;
40
41 import org.apache.camel.Exchange;
42 import org.onap.clamp.clds.client.DcaeDispatcherServices;
43 import org.onap.clamp.clds.util.LoggingUtils;
44 import org.onap.clamp.clds.util.ONAPLogConstants;
45 import org.onap.clamp.exception.OperationException;
46 import org.onap.clamp.loop.Loop;
47 import org.onap.clamp.loop.LoopService;
48 import org.onap.clamp.loop.LoopState;
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         this.loopService = loopService;
73         this.dcaeDispatcherServices = dcaeDispatcherServices;
74     }
75
76     /**
77      * Deploy the closed loop.
78      *
79      * @param loopName the loop name
80      * @return the updated loop
81      * @throws Exceptions during the operation
82      */
83     public Loop deployLoop(Exchange camelExchange, String loopName) throws OperationException {
84         util.entering(request, "CldsService: Deploy model");
85         Date startTime = new Date();
86         Loop loop = loopService.getLoop(loopName);
87
88         if (loop == null) {
89             String msg = "Deploy loop exception: Not able to find closed loop:" + loopName;
90             util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO,
91                 ONAPLogConstants.ResponseStatus.ERROR);
92             throw new OperationException(msg);
93         }
94
95         // verify the current closed loop state
96         if (loop.getLastComputedState() != LoopState.SUBMITTED) {
97             String msg = "Deploy loop exception: This closed loop is in state:" + loop.getLastComputedState() 
98                 + ". It could be deployed only when it is in SUBMITTED state.";
99             util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO,
100                 ONAPLogConstants.ResponseStatus.ERROR);
101             throw new OperationException(msg);
102         }
103
104         // Set the deploymentId if not present yet
105         String deploymentId = "";
106         // If model is already deployed then pass same deployment id
107         if (loop.getDcaeDeploymentId() != null && !loop.getDcaeDeploymentId().isEmpty()) {
108             deploymentId = loop.getDcaeDeploymentId();
109         } else {
110             loop.setDcaeDeploymentId(deploymentId = "closedLoop_" + loopName + "_deploymentId");
111         }
112
113         Yaml yaml = new Yaml();
114         Map<String, Object> yamlMap = yaml.load(loop.getBlueprint());
115         JsonObject bluePrint = wrapSnakeObject(yamlMap).getAsJsonObject();
116
117         loop.setDcaeDeploymentStatusUrl(dcaeDispatcherServices.createNewDeployment(deploymentId, loop.getDcaeBlueprintId(), bluePrint));
118         loop.setLastComputedState(LoopState.DEPLOYED);
119         // save the updated loop
120         loopService.saveOrUpdateLoop (loop);
121
122         // audit log
123         LoggingUtils.setTimeContext(startTime, new Date());
124         auditLogger.info("Deploy model completed");
125         util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
126         return  loop;
127     }
128
129     /**
130      * Un deploy closed loop.
131      *
132      * @param loopName the loop name
133      * @return the updated loop
134      */
135     public Loop unDeployLoop(String loopName)  throws OperationException {
136         util.entering(request, "LoopOperation: Undeploy the closed loop");
137         Date startTime = new Date();
138         Loop loop = loopService.getLoop(loopName);
139
140         if (loop == null) {
141             String msg = "Undeploy loop exception: Not able to find closed loop:" + loopName;
142             util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO,
143                 ONAPLogConstants.ResponseStatus.ERROR);
144             throw new OperationException(msg);
145         } 
146
147         // verify the current closed loop state
148         if (loop.getLastComputedState() != LoopState.DEPLOYED) {
149             String msg = "Unploy loop exception: This closed loop is in state:" + loop.getLastComputedState() 
150                 + ". It could be undeployed only when it is in DEPLOYED state.";
151             util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO,
152                 ONAPLogConstants.ResponseStatus.ERROR);
153             throw new OperationException(msg);
154         }
155
156         loop.setDcaeDeploymentStatusUrl(
157             dcaeDispatcherServices.deleteExistingDeployment(loop.getDcaeDeploymentId(), loop.getDcaeBlueprintId()));
158
159         // clean the deployment ID
160         loop.setDcaeDeploymentId(null);
161         loop.setLastComputedState(LoopState.SUBMITTED);
162
163         // save the updated loop
164         loopService.saveOrUpdateLoop (loop);
165
166         // audit log
167         LoggingUtils.setTimeContext(startTime, new Date());
168         auditLogger.info("Undeploy model completed");
169         util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
170         return loop;
171     }
172
173     private JsonElement wrapSnakeObject(Object o) {
174         //NULL => JsonNull
175         if (o == null)
176             return JsonNull.INSTANCE;
177
178         // Collection => JsonArray
179         if (o instanceof Collection) {
180             JsonArray array = new JsonArray();
181             for (Object childObj : (Collection<?>)o)
182                 array.add(wrapSnakeObject(childObj));
183             return array;
184         }
185
186         // Array => JsonArray
187         if (o.getClass().isArray()) {
188             JsonArray array = new JsonArray();
189
190             int length = Array.getLength(array);
191             for (int i=0; i<length; i++)
192                 array.add(wrapSnakeObject(Array.get(array, i)));
193             return array;
194         }
195
196         // Map => JsonObject
197         if (o instanceof Map) {
198             Map<?, ?> map = (Map<?, ?>)o;
199
200             JsonObject jsonObject = new JsonObject();
201             for (final Map.Entry<?, ?> entry : map.entrySet()) {
202                 final String name = String.valueOf(entry.getKey());
203                 final Object value = entry.getValue();
204                 jsonObject.add(name, wrapSnakeObject(value));
205             }
206             return jsonObject;
207         }
208
209         // otherwise take it as a string
210         return new JsonPrimitive(String.valueOf(o));
211     }
212 }