Fix logging issues
[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.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.config.ClampProperties;
44 import org.onap.clamp.clds.util.LoggingUtils;
45 import org.onap.clamp.clds.util.ONAPLogConstants;
46 import org.onap.clamp.exception.OperationException;
47 import org.onap.clamp.util.HttpConnectionManager;
48 import org.slf4j.event.Level;
49 import org.springframework.beans.factory.annotation.Autowired;
50 import org.springframework.http.HttpStatus;
51 import org.springframework.stereotype.Component;
52 import org.yaml.snakeyaml.Yaml;
53
54 /**
55  * Closed loop operations.
56  */
57 @Component
58 public class LoopOperation {
59
60     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(LoopOperation.class);
61     protected static final EELFLogger auditLogger = EELFManager.getInstance().getMetricsLogger();
62     private final DcaeDispatcherServices dcaeDispatcherServices;
63     private final LoopService loopService;
64     private LoggingUtils util = new LoggingUtils(logger);
65
66     @Autowired
67     private HttpServletRequest request;
68
69     @Autowired
70     public LoopOperation(LoopService loopService, DcaeDispatcherServices dcaeDispatcherServices,
71         ClampProperties refProp, HttpConnectionManager httpConnectionManager) {
72         this.loopService = loopService;
73         this.dcaeDispatcherServices = dcaeDispatcherServices;
74     }
75     
76     /**
77      * Deploy the closed loop.
78      *
79      * @param loopName
80      *        the loop name
81      * @return the updated loop
82      * @throws OperationException
83      *         Exception during the operation
84      */
85     public Loop deployLoop(Exchange camelExchange, String loopName) throws OperationException {
86         util.entering(request, "CldsService: Deploy model");
87         Date startTime = new Date();
88         Loop loop = loopService.getLoop(loopName);
89
90         if (loop == null) {
91             String msg = "Deploy loop exception: Not able to find closed loop:" + loopName;
92             util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO,
93                 ONAPLogConstants.ResponseStatus.ERROR);
94             throw new OperationException(msg);
95         }
96
97         // verify the current closed loop state
98         if (loop.getLastComputedState() != LoopState.SUBMITTED) {
99             String msg = "Deploy loop exception: This closed loop is in state:" + loop.getLastComputedState()
100                 + ". It could be deployed only when it is in SUBMITTED state.";
101             util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, ONAPLogConstants.ResponseStatus.ERROR);
102             throw new OperationException(msg);
103         }
104
105         // Set the deploymentId if not present yet
106         String deploymentId = "";
107         // If model is already deployed then pass same deployment id
108         if (loop.getDcaeDeploymentId() != null && !loop.getDcaeDeploymentId().isEmpty()) {
109             deploymentId = loop.getDcaeDeploymentId();
110         } else {
111             loop.setDcaeDeploymentId(deploymentId = "closedLoop_" + loopName + "_deploymentId");
112         }
113
114         Yaml yaml = new Yaml();
115         Map<String, Object> yamlMap = yaml.load(loop.getBlueprint());
116         JsonObject bluePrint = wrapSnakeObject(yamlMap).getAsJsonObject();
117
118         loop.setDcaeDeploymentStatusUrl(
119             dcaeDispatcherServices.createNewDeployment(deploymentId, loop.getDcaeBlueprintId(), bluePrint));
120         loop.setLastComputedState(LoopState.DEPLOYED);
121         // save the updated loop
122         loopService.saveOrUpdateLoop(loop);
123
124         // audit log
125         LoggingUtils.setTimeContext(startTime, new Date());
126         auditLogger.info("Deploy model completed");
127         util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
128         return loop;
129     }
130
131     /**
132      * Un deploy closed loop.
133      *
134      * @param loopName
135      *        the loop name
136      * @return the updated loop
137      */
138     public Loop unDeployLoop(String loopName) throws OperationException {
139         util.entering(request, "LoopOperation: Undeploy the closed loop");
140         Date startTime = new Date();
141         Loop loop = loopService.getLoop(loopName);
142
143         if (loop == null) {
144             String msg = "Undeploy loop exception: Not able to find closed loop:" + loopName;
145             util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO,
146                 ONAPLogConstants.ResponseStatus.ERROR);
147             throw new OperationException(msg);
148         }
149
150         // verify the current closed loop state
151         if (loop.getLastComputedState() != LoopState.DEPLOYED) {
152             String msg = "Unploy loop exception: This closed loop is in state:" + loop.getLastComputedState()
153                 + ". It could be undeployed only when it is in DEPLOYED state.";
154             util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, ONAPLogConstants.ResponseStatus.ERROR);
155             throw new OperationException(msg);
156         }
157
158         loop.setDcaeDeploymentStatusUrl(
159             dcaeDispatcherServices.deleteExistingDeployment(loop.getDcaeDeploymentId(), loop.getDcaeBlueprintId()));
160
161         // clean the deployment ID
162         loop.setDcaeDeploymentId(null);
163         loop.setLastComputedState(LoopState.SUBMITTED);
164
165         // save the updated loop
166         loopService.saveOrUpdateLoop(loop);
167
168         // audit log
169         LoggingUtils.setTimeContext(startTime, new Date());
170         auditLogger.info("Undeploy model completed");
171         util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
172         return loop;
173     }
174
175     private JsonElement wrapSnakeObject(Object obj) {
176         // NULL => JsonNull
177         if (obj == null) {
178             return JsonNull.INSTANCE;
179         }
180
181         // Collection => JsonArray
182         if (obj instanceof Collection) {
183             JsonArray array = new JsonArray();
184             for (Object childObj : (Collection<?>) obj) {
185                 array.add(wrapSnakeObject(childObj));
186             }
187             return array;
188         }
189
190         // Array => JsonArray
191         if (obj.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             }
198             return array;
199         }
200
201         // Map => JsonObject
202         if (obj instanceof Map) {
203             Map<?, ?> map = (Map<?, ?>) obj;
204
205             JsonObject jsonObject = new JsonObject();
206             for (final Map.Entry<?, ?> entry : map.entrySet()) {
207                 final String name = String.valueOf(entry.getKey());
208                 final Object value = entry.getValue();
209                 jsonObject.add(name, wrapSnakeObject(value));
210             }
211             return jsonObject;
212         }
213
214         // otherwise take it as a string
215         return new JsonPrimitive(String.valueOf(obj));
216     }
217
218 }