Remove SDC query
[clamp.git] / src / main / java / org / onap / clamp / clds / service / CldsService.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017-2018 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  * Modifications copyright (c) 2018 Nokia
21  * ===================================================================
22  *
23  */
24
25 package org.onap.clamp.clds.service;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29
30 import com.google.gson.JsonElement;
31 import com.google.gson.JsonObject;
32 import com.google.gson.reflect.TypeToken;
33 import java.io.IOException;
34 import java.lang.reflect.Type;
35 import java.security.GeneralSecurityException;
36 import java.util.Date;
37 import java.util.List;
38 import java.util.UUID;
39
40 import javax.servlet.http.HttpServletRequest;
41 import javax.ws.rs.BadRequestException;
42 import javax.ws.rs.NotAuthorizedException;
43 import javax.xml.transform.TransformerException;
44
45 import org.apache.camel.Produce;
46 import org.apache.commons.codec.DecoderException;
47 import org.json.simple.parser.ParseException;
48 import org.onap.clamp.clds.camel.CamelProxy;
49 import org.onap.clamp.clds.client.DcaeDispatcherServices;
50 import org.onap.clamp.clds.client.DcaeInventoryServices;
51 import org.onap.clamp.clds.config.ClampProperties;
52 import org.onap.clamp.clds.dao.CldsDao;
53 import org.onap.clamp.clds.exception.policy.PolicyClientException;
54 import org.onap.clamp.clds.exception.sdc.SdcCommunicationException;
55 import org.onap.clamp.clds.model.CldsEvent;
56 import org.onap.clamp.clds.model.CldsInfo;
57 import org.onap.clamp.clds.model.CldsModel;
58 import org.onap.clamp.clds.model.CldsModelProp;
59 import org.onap.clamp.clds.model.CldsMonitoringDetails;
60 import org.onap.clamp.clds.model.CldsTemplate;
61 import org.onap.clamp.clds.model.DcaeEvent;
62 import org.onap.clamp.clds.model.ValueItem;
63 import org.onap.clamp.clds.model.properties.ModelProperties;
64 import org.onap.clamp.clds.model.sdc.SdcServiceInfo;
65 import org.onap.clamp.clds.sdc.controller.installer.CsarInstallerImpl;
66 import org.onap.clamp.clds.transform.XslTransformer;
67 import org.onap.clamp.clds.util.JsonUtils;
68 import org.onap.clamp.clds.util.LoggingUtils;
69 import org.onap.clamp.clds.util.ONAPLogConstants;
70 import org.slf4j.event.Level;
71 import org.springframework.beans.factory.annotation.Autowired;
72 import org.springframework.beans.factory.annotation.Value;
73 import org.springframework.http.HttpStatus;
74 import org.springframework.http.ResponseEntity;
75 import org.springframework.stereotype.Component;
76 import org.springframework.web.client.HttpClientErrorException;
77
78 /**
79  * Service to save and retrieve the CLDS model attributes.
80  */
81 @Component
82 public class CldsService extends SecureServiceBase {
83
84     public static final Type LIST_OF_SDC_SERVICE_INFO_TYPE = new TypeToken<List<SdcServiceInfo>>() {
85     }.getType();
86     @Produce(uri = "direct:processSubmit")
87     private CamelProxy camelProxy;
88     protected static final EELFLogger securityLogger = EELFManager.getInstance().getSecurityLogger();
89     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsService.class);
90
91     public static final String GLOBAL_PROPERTIES_KEY = "files.globalProperties";
92     private final String cldsPermissionTypeClManage;
93     private final String cldsPermissionTypeClEvent;
94     private final String cldsPermissionTypeFilterVf;
95     private final String cldsPermissionInstance;
96     final SecureServicePermission permissionReadCl;
97     final SecureServicePermission permissionUpdateCl;
98     final SecureServicePermission permissionReadTemplate;
99     final SecureServicePermission permissionUpdateTemplate;
100     final SecureServicePermission permissionReadTosca;
101     final SecureServicePermission permissionUpdateTosca;
102
103     private final CldsDao cldsDao;
104     private final XslTransformer cldsBpmnTransformer;
105     private final ClampProperties refProp;
106     private final DcaeDispatcherServices dcaeDispatcherServices;
107     private final DcaeInventoryServices dcaeInventoryServices;
108     private LoggingUtils util = new LoggingUtils(logger);
109
110     @Autowired
111     private HttpServletRequest request;
112
113     @Autowired
114     public CldsService(CldsDao cldsDao, XslTransformer cldsBpmnTransformer, ClampProperties refProp,
115         DcaeDispatcherServices dcaeDispatcherServices,
116         DcaeInventoryServices dcaeInventoryServices,
117         @Value("${clamp.config.security.permission.type.cl:permission-type-cl}") String cldsPersmissionTypeCl,
118         @Value("${clamp.config.security.permission.type.cl.manage:permission-type-cl-manage}") String cldsPermissionTypeClManage,
119         @Value("${clamp.config.security.permission.type.cl.event:permission-type-cl-event}") String cldsPermissionTypeClEvent,
120         @Value("${clamp.config.security.permission.type.filter.vf:permission-type-filter-vf}") String cldsPermissionTypeFilterVf,
121         @Value("${clamp.config.security.permission.type.template:permission-type-template}") String cldsPermissionTypeTemplate,
122         @Value("${clamp.config.security.permission.type.tosca:permission-type-tosca}") String cldsPermissionTypeTosca,
123         @Value("${clamp.config.security.permission.instance:dev}") String cldsPermissionInstance) {
124         this.cldsDao = cldsDao;
125         this.cldsBpmnTransformer = cldsBpmnTransformer;
126         this.refProp = refProp;
127         this.dcaeDispatcherServices = dcaeDispatcherServices;
128         this.dcaeInventoryServices = dcaeInventoryServices;
129         this.cldsPermissionTypeClManage = cldsPermissionTypeClManage;
130         this.cldsPermissionTypeClEvent = cldsPermissionTypeClEvent;
131         this.cldsPermissionTypeFilterVf = cldsPermissionTypeFilterVf;
132         this.cldsPermissionInstance = cldsPermissionInstance;
133         permissionReadCl = SecureServicePermission.create(cldsPersmissionTypeCl, cldsPermissionInstance, "read");
134         permissionUpdateCl = SecureServicePermission.create(cldsPersmissionTypeCl, cldsPermissionInstance, "update");
135         permissionReadTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance,
136             "read");
137         permissionUpdateTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance,
138             "update");
139         permissionReadTosca = SecureServicePermission.create(cldsPermissionTypeTosca, cldsPermissionInstance, "read");
140         permissionUpdateTosca = SecureServicePermission.create(cldsPermissionTypeTosca, cldsPermissionInstance,
141             "update");
142     }
143
144     /*
145      * @return list of CLDS-Monitoring-Details: CLOSELOOP_NAME | Close loop name
146      * used in the CLDS application (prefix: ClosedLoop- + unique ClosedLoop ID)
147      * MODEL_NAME | Model Name in CLDS application SERVICE_TYPE_ID | TypeId returned
148      * from the DCAE application when the ClosedLoop is submitted
149      * (DCAEServiceTypeRequest generated in DCAE application). DEPLOYMENT_ID | Id
150      * generated when the ClosedLoop is deployed in DCAE. TEMPLATE_NAME | Template
151      * used to generate the ClosedLoop model. ACTION_CD | Current state of the
152      * ClosedLoop in CLDS application.
153      */
154     public List<CldsMonitoringDetails> getCldsDetails() {
155         util.entering(request, "CldsService: GET model details");
156         Date startTime = new Date();
157         List<CldsMonitoringDetails> cldsMonitoringDetailsList = cldsDao.getCLDSMonitoringDetails();
158         // audit log
159         LoggingUtils.setTimeContext(startTime, new Date());
160         auditLogger.info("GET cldsDetails completed");
161         util.exiting("200", "Get cldsDetails success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
162         return cldsMonitoringDetailsList;
163     }
164
165     /*
166      * CLDS IFO service will return 3 things 1. User Name 2. CLDS code version that
167      * is currently installed from pom.xml file 3. User permissions
168      */
169     public CldsInfo getCldsInfo() {
170         util.entering(request, "CldsService: GET cldsInfo");
171         Date startTime = new Date();
172         LoggingUtils.setTimeContext(startTime, new Date());
173
174         CldsInfoProvider cldsInfoProvider = new CldsInfoProvider(this);
175         CldsInfo cldsInfo = cldsInfoProvider.getCldsInfo();
176
177         // audit log
178         LoggingUtils.setTimeContext(startTime, new Date());
179         securityLogger.info("GET cldsInfo completed");
180         util.exiting("200", "Get cldsInfo success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
181         return cldsInfo;
182     }
183
184     /**
185      * REST service that retrieves BPMN for a CLDS model name from the database.
186      * This is subset of the json getModel. This is only expected to be used for
187      * testing purposes, not by the UI.
188      *
189      * @param modelName
190      * @return bpmn xml text - content of bpmn given name
191      */
192     public String getBpmnXml(String modelName) {
193         util.entering(request, "CldsService: GET model bpmn");
194         Date startTime = new Date();
195         isAuthorized(permissionReadCl);
196         logger.info("GET bpmnText for modelName={}", modelName);
197         CldsModel model = CldsModel.retrieve(cldsDao, modelName, false);
198         // audit log
199         LoggingUtils.setTimeContext(startTime, new Date());
200         auditLogger.info("GET model bpmn completed");
201         util.exiting("200", "Get model bpmn success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
202         return model.getBpmnText();
203     }
204
205     /**
206      * REST service that retrieves image for a CLDS model name from the database.
207      * This is subset of the json getModel. This is only expected to be used for
208      * testing purposes, not by the UI.
209      *
210      * @param modelName
211      * @return image xml text - content of image given name
212      */
213     public String getImageXml(String modelName) {
214         util.entering(request, "CldsService: GET model image");
215         Date startTime = new Date();
216         isAuthorized(permissionReadCl);
217         logger.info("GET imageText for modelName={}", modelName);
218         CldsModel model = CldsModel.retrieve(cldsDao, modelName, false);
219         // audit log
220         LoggingUtils.setTimeContext(startTime, new Date());
221         auditLogger.info("GET model image completed");
222         util.exiting("200", "Get model image success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
223         return model.getImageText();
224     }
225
226     /**
227      * REST service that retrieves a CLDS model by name from the database.
228      *
229      * @param modelName
230      * @return clds model - clds model for the given model name
231      */
232     public CldsModel getModel(String modelName) {
233         util.entering(request, "CldsService: GET model");
234         Date startTime = new Date();
235         isAuthorized(permissionReadCl);
236         logger.debug("GET model for  modelName={}", modelName);
237         CldsModel cldsModel = CldsModel.retrieve(cldsDao, modelName, false);
238         isAuthorizedForVf(cldsModel);
239         // Try an update for DCAE status
240         // Checking condition whether our CLDS model can call Inventory Method
241         try {
242             // Method to call dcae inventory and invoke insert event method
243             if (cldsModel.canDcaeInventoryCall()
244                 && !cldsModel.getTemplateName().startsWith(CsarInstallerImpl.TEMPLATE_NAME_PREFIX)) {
245                 dcaeInventoryServices.setEventInventory(cldsModel, getUserId());
246             }
247             // This is a blocking call
248             if (cldsModel.getEvent().isActionCd(CldsEvent.ACTION_DEPLOY)
249                 && !CldsModel.STATUS_ACTIVE.equals(cldsModel.getStatus()) && cldsModel.getDeploymentId() != null
250                 && cldsModel.getDeploymentStatusUrl() != null) {
251                 checkDcaeDeploymentStatus(cldsModel, CldsEvent.ACTION_DEPLOY, false);
252                 // Refresh the model object in any cases for new event
253                 cldsModel = CldsModel.retrieve(cldsDao, cldsModel.getName(), false);
254             }
255         } catch (Exception e) {
256             LoggingUtils.setErrorContext("900", "Set event inventory error");
257             logger.error("getModel set event Inventory error:" + e);
258         }
259         // audit log
260         LoggingUtils.setTimeContext(startTime, new Date());
261         auditLogger.info("GET model completed");
262         util.exiting("200", "Get model success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
263         return cldsModel;
264     }
265
266     /**
267      * REST service that saves a CLDS model by name in the database.
268      *
269      * @param modelName
270      */
271     public CldsModel putModel(String modelName, CldsModel cldsModel) {
272         util.entering(request, "CldsService: PUT model");
273         Date startTime = new Date();
274         isAuthorized(permissionUpdateCl);
275         isAuthorizedForVf(cldsModel);
276         logger.info("PUT model for  modelName={}", modelName);
277         logger.info("PUT bpmnText={}", cldsModel.getBpmnText());
278         logger.info("PUT propText={}", cldsModel.getPropText());
279         logger.info("PUT imageText={}", cldsModel.getImageText());
280         fillInCldsModel(cldsModel);
281         cldsModel.save(cldsDao, getUserId());
282
283         // audit log
284         LoggingUtils.setTimeContext(startTime, new Date());
285         auditLogger.info("PUT model completed");
286         util.exiting("200", "Put model success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
287         return cldsModel;
288     }
289
290     /**
291      * REST service that retrieves a list of CLDS model names.
292      *
293      * @return model names in JSON
294      */
295     public List<ValueItem> getModelNames() {
296         util.entering(request, "CldsService: GET model names");
297         Date startTime = new Date();
298         isAuthorized(permissionReadCl);
299         logger.info("GET list of model names");
300         List<ValueItem> names = cldsDao.getModelNames();
301         // audit log
302         LoggingUtils.setTimeContext(startTime, new Date());
303         auditLogger.info("GET model names completed");
304         util.exiting("200", "Get model names success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
305         return names;
306     }
307
308     private void fillInCldsModel(CldsModel model) {
309         if (model.getTemplateName() != null) {
310             CldsTemplate template = cldsDao.getTemplate(model.getTemplateName());
311             if (template != null) {
312                 model.setTemplateId(template.getId());
313                 model.setDocText(template.getPropText());
314                 // This is to provide the Bpmn XML when Template part in UI
315                 // is
316                 // disabled
317                 model.setBpmnText(template.getBpmnText());
318             }
319         }
320     }
321
322     /**
323      * REST service that saves and processes an action for a CLDS model by name.
324      *
325      * @param action
326      * @param modelName
327      * @param test
328      * @param model
329      * @return
330      * @throws TransformerException
331      *         In case of issues when doing the XSLT of the BPMN flow
332      * @throws ParseException
333      *         In case of issues when parsing the JSON
334      * @throws GeneralSecurityException
335      *         In case of issues when decrypting the password
336      * @throws DecoderException
337      *         In case of issues with the Hex String decoding
338      */
339     public ResponseEntity<?> putModelAndProcessAction(String action, String modelName, String test, CldsModel model)
340         throws TransformerException, ParseException {
341         util.entering(request, "CldsService: Process model action");
342         Date startTime = new Date();
343         String errorMessage = "";
344         String actionCd = "";
345         try {
346             actionCd = action.toUpperCase();
347             SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage,
348                 cldsPermissionInstance, actionCd);
349             isAuthorized(permisionManage);
350             isAuthorizedForVf(model);
351             String userId = getUserId();
352             logger.info("PUT actionCd={}", actionCd);
353             logger.info("PUT modelName={}", modelName);
354             logger.info("PUT test={}", test);
355             logger.info("PUT bpmnText={}", model.getBpmnText());
356             logger.info("PUT propText={}", model.getPropText());
357             logger.info("PUT userId={}", userId);
358             logger.info("PUT getTypeId={}", model.getTypeId());
359             logger.info("PUT deploymentId={}", model.getDeploymentId());
360             this.fillInCldsModel(model);
361             // save model to db just in case
362             model.save(cldsDao, getUserId());
363
364             // get vars and format if necessary
365             String prop = model.getPropText();
366             String bpmn = model.getBpmnText();
367             String docText = model.getDocText();
368             String controlName = model.getControlName();
369             String bpmnJson = cldsBpmnTransformer.doXslTransformToString(bpmn);
370             logger.info("PUT bpmnJson={}", bpmnJson);
371             // Test flag coming from UI or from Clamp config
372             boolean isTest = Boolean.parseBoolean(test)
373                 || Boolean.parseBoolean(refProp.getStringValue("action.test.override"));
374             logger.info("PUT isTest={}", isTest);
375             boolean isInsertTestEvent = Boolean.parseBoolean(refProp.getStringValue("action.insert.test.event"));
376             logger.info("PUT isInsertTestEvent={}", isInsertTestEvent);
377             // determine if requested action is permitted
378             model.validateAction(actionCd);
379             logger.info("modelProp - " + prop);
380             logger.info("docText - " + docText);
381             try {
382                 String result = camelProxy.executeAction(actionCd, prop, bpmnJson, modelName, controlName, docText,
383                     isTest, userId, isInsertTestEvent, model.getEvent().getActionCd());
384                 logger.info("Starting Camel flow on request, result is: ", result);
385             } catch (SdcCommunicationException | PolicyClientException | BadRequestException e) {
386                 logger.error("Exception occured during invoking Camel process", e);
387                 errorMessage = e.getMessage();
388             }
389             // audit log
390             LoggingUtils.setTimeContext(startTime, new Date());
391             auditLogger.info("Process model action completed");
392         } catch (Exception e) {
393             logger.error("Exception occured during putModelAndProcessAction", e);
394             errorMessage = e.getMessage();
395         }
396
397         if (!errorMessage.isEmpty()) {
398             CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), actionCd, CldsEvent.ACTION_STATE_ERROR,
399                 null);
400             // Need a refresh as new events have been inserted
401             model = CldsModel.retrieve(cldsDao, modelName, false);
402             model.setErrorMessageForUi(errorMessage);
403             util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "putModelAndProcessAction failed", Level.INFO,
404                 ONAPLogConstants.ResponseStatus.ERROR);
405             return new ResponseEntity<>(model, HttpStatus.INTERNAL_SERVER_ERROR);
406         } else {
407             // Need a refresh as new events have been inserted, could have been deleted so
408             // not blocking call
409             model = CldsModel.retrieve(cldsDao, modelName, true);
410             util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
411             return new ResponseEntity<>(model, HttpStatus.OK);
412         }
413     }
414
415     /**
416      * REST service that accepts events for a model.
417      *
418      * @param test
419      * @param dcaeEvent
420      */
421     public String postDcaeEvent(String test, DcaeEvent dcaeEvent) {
422         util.entering(request, "CldsService: Post dcae event");
423         Date startTime = new Date();
424         String userid = null;
425         // TODO: allow auth checking to be turned off by removing the permission
426         // type property
427         if (cldsPermissionTypeClEvent != null && cldsPermissionTypeClEvent.length() > 0) {
428             SecureServicePermission permissionEvent = SecureServicePermission.create(cldsPermissionTypeClEvent,
429                 cldsPermissionInstance, dcaeEvent.getEvent());
430             isAuthorized(permissionEvent);
431             userid = getUserId();
432         }
433         // Flag indicates whether it is triggered by Validation Test button from
434         // UI
435         boolean isTest = Boolean.parseBoolean(test);
436         int instanceCount = 0;
437         if (dcaeEvent.getInstances() != null) {
438             instanceCount = dcaeEvent.getInstances().size();
439         }
440         String msgInfo = "event=" + dcaeEvent.getEvent() + " serviceUUID=" + dcaeEvent.getServiceUUID()
441             + " resourceUUID=" + dcaeEvent.getResourceUUID() + " artifactName=" + dcaeEvent.getArtifactName()
442             + " instance count=" + instanceCount + " isTest=" + isTest;
443         logger.info("POST dcae event {}", msgInfo);
444         if (isTest) {
445             logger.warn("Ignorning test event from DCAE");
446         } else {
447             if (DcaeEvent.EVENT_DEPLOYMENT.equalsIgnoreCase(dcaeEvent.getEvent())) {
448                 CldsModel.insertModelInstance(cldsDao, dcaeEvent, userid);
449             } else {
450                 CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userid, dcaeEvent.getCldsActionCd(),
451                     CldsEvent.ACTION_STATE_RECEIVED, null);
452             }
453         }
454         // audit log
455         LoggingUtils.setTimeContext(startTime, new Date());
456         auditLogger.info("Post dcae event completed");
457         util.exiting("200", "Post dcae event success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
458         return msgInfo;
459     }
460
461     /**
462      * REST service that retrieves total properties required by UI
463      *
464      * @throws IOException
465      *         In case of issues
466      */
467     public String getSdcProperties() throws IOException {
468         return refProp.getJsonTemplate(GLOBAL_PROPERTIES_KEY).toString();
469     }
470
471
472     /**
473      * Determine if the user is authorized for a particular VF by its invariant
474      * UUID.
475      *
476      * @param vfInvariantUuid
477      * @throws NotAuthorizedException
478      * @return
479      */
480     public boolean isAuthorizedForVf(String vfInvariantUuid) {
481         if (cldsPermissionTypeFilterVf != null && !cldsPermissionTypeFilterVf.isEmpty()) {
482             SecureServicePermission permission = SecureServicePermission.create(cldsPermissionTypeFilterVf,
483                 cldsPermissionInstance, vfInvariantUuid);
484             return isAuthorized(permission);
485         } else {
486             // if CLDS_PERMISSION_TYPE_FILTER_VF property is not provided, then
487             // VF filtering is turned off
488             logger.warn("VF filtering turned off");
489             return true;
490         }
491     }
492
493     /**
494      * Determine if the user is authorized for a particular VF by its invariant
495      * UUID. If not authorized, then NotAuthorizedException is thrown.
496      *
497      * @param model
498      * @return
499      */
500     private boolean isAuthorizedForVf(CldsModel model) {
501         String vf = ModelProperties.getVf(model);
502         if (vf == null || vf.length() == 0) {
503             logger.info("VF not found in model");
504             return true;
505         } else {
506             return isAuthorizedForVf(vf);
507         }
508     }
509
510     public ResponseEntity<CldsModel> deployModel(String modelName, CldsModel model) {
511         util.entering(request, "CldsService: Deploy model");
512         Date startTime = new Date();
513         String errorMessage = "";
514         try {
515             fillInCldsModel(model);
516             String bpmnJson = cldsBpmnTransformer.doXslTransformToString(model.getBpmnText());
517             logger.info("PUT bpmnJson={}", bpmnJson);
518             SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage,
519                 cldsPermissionInstance, CldsEvent.ACTION_DEPLOY);
520             isAuthorized(permisionManage);
521             isAuthorizedForVf(model);
522             ModelProperties modelProp = new ModelProperties(modelName, model.getControlName(), CldsEvent.ACTION_DEPLOY,
523                 false, bpmnJson, model.getPropText());
524             checkForDuplicateServiceVf(modelName, model.getPropText());
525             String deploymentId = "";
526             // If model is already deployed then pass same deployment id
527             if (model.getDeploymentId() != null && !model.getDeploymentId().isEmpty()) {
528                 deploymentId = model.getDeploymentId();
529             } else {
530                 model.setDeploymentId(deploymentId = "closedLoop_" + UUID.randomUUID() + "_deploymentId");
531             }
532             model.setDeploymentStatusUrl(dcaeDispatcherServices.createNewDeployment(deploymentId, model.getTypeId(),
533                 modelProp.getGlobal().getDeployParameters()));
534             CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), CldsEvent.ACTION_DEPLOY,
535                 CldsEvent.ACTION_STATE_INITIATED, null);
536             model.save(cldsDao, getUserId());
537             // This is a blocking call
538             checkDcaeDeploymentStatus(model, CldsEvent.ACTION_DEPLOY, true);
539             // Refresh the model object in any cases for new event
540             model = CldsModel.retrieve(cldsDao, model.getName(), false);
541             // audit log
542             LoggingUtils.setTimeContext(startTime, new Date());
543             auditLogger.info("Deploy model completed");
544         } catch (Exception e) {
545             errorMessage = e.getMessage();
546             logger.error("Exception occured during deployModel", e);
547         }
548         if (!errorMessage.isEmpty()) {
549             model.setErrorMessageForUi(errorMessage);
550             util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "DeployModel failed", Level.INFO,
551                 ONAPLogConstants.ResponseStatus.ERROR);
552             return new ResponseEntity<>(model, HttpStatus.INTERNAL_SERVER_ERROR);
553         } else {
554             util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
555             return new ResponseEntity<>(model, HttpStatus.OK);
556         }
557     }
558
559     public ResponseEntity<CldsModel> unDeployModel(String modelName, CldsModel model) {
560         util.entering(request, "CldsService: Undeploy model");
561         Date startTime = new Date();
562         String errorMessage = "";
563         try {
564             SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage,
565                 cldsPermissionInstance, CldsEvent.ACTION_UNDEPLOY);
566             isAuthorized(permisionManage);
567             isAuthorizedForVf(model);
568             model.setDeploymentStatusUrl(
569                 dcaeDispatcherServices.deleteExistingDeployment(model.getDeploymentId(), model.getTypeId()));
570             CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), CldsEvent.ACTION_UNDEPLOY,
571                 CldsEvent.ACTION_STATE_INITIATED, null);
572             // clean the deployment ID
573             model.setDeploymentId(null);
574             model.save(cldsDao, getUserId());
575             // This is a blocking call
576             checkDcaeDeploymentStatus(model, CldsEvent.ACTION_UNDEPLOY, true);
577             // Refresh the model object in any cases for new event
578             model = CldsModel.retrieve(cldsDao, model.getName(), false);
579             // audit log
580             LoggingUtils.setTimeContext(startTime, new Date());
581             auditLogger.info("Undeploy model completed");
582         } catch (Exception e) {
583             errorMessage = e.getMessage();
584             logger.error("Exception occured during unDeployModel", e);
585         }
586         if (!errorMessage.isEmpty()) {
587             model.setErrorMessageForUi(errorMessage);
588             util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "UndeployModel failed", Level.INFO,
589                 ONAPLogConstants.ResponseStatus.ERROR);
590             return new ResponseEntity<>(model, HttpStatus.INTERNAL_SERVER_ERROR);
591         } else {
592             util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
593             return new ResponseEntity<>(model, HttpStatus.OK);
594         }
595     }
596
597     private void checkDcaeDeploymentStatus(CldsModel model, String cldsEvent, boolean withRetry)
598         throws InterruptedException {
599         String operationStatus = withRetry
600             ? dcaeDispatcherServices.getOperationStatusWithRetry(model.getDeploymentStatusUrl())
601             : dcaeDispatcherServices.getOperationStatus(model.getDeploymentStatusUrl());
602         if ("succeeded".equalsIgnoreCase(operationStatus)) {
603             logger.info(cldsEvent + " model (" + model.getName() + ") succeeded...Deployment Id is - "
604                 + model.getDeploymentId());
605             CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), cldsEvent,
606                 CldsEvent.ACTION_STATE_COMPLETED, null);
607         } else {
608             String info = "DCAE " + cldsEvent + " (" + model.getName() + ") failed...Operation Status is - "
609                 + operationStatus;
610             logger.info(info);
611             CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), cldsEvent, CldsEvent.ACTION_STATE_ERROR,
612                 null);
613             util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "DCAE operation(" + cldsEvent + ") failed",
614                 Level.INFO, ONAPLogConstants.ResponseStatus.ERROR);
615             throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, info);
616         }
617     }
618
619     private void checkForDuplicateServiceVf(String modelName, String modelPropText) throws IOException {
620         JsonElement globalNode = JsonUtils.GSON.fromJson(modelPropText, JsonObject.class).get("global");
621         String service = JsonUtils.getStringValueByName(globalNode, "service");
622         List<String> resourceVf = JsonUtils.getStringValuesByName(globalNode, "vf");
623         if (service != null && resourceVf != null && !resourceVf.isEmpty()) {
624             List<CldsModelProp> cldsModelPropList = cldsDao.getDeployedModelProperties();
625             for (CldsModelProp cldsModelProp : cldsModelPropList) {
626                 JsonElement currentNode = JsonUtils.GSON
627                     .fromJson(cldsModelProp.getPropText(), JsonObject.class)
628                     .get("global");
629                 String currentService = JsonUtils.getStringValueByName(currentNode, "service");
630                 List<String> currentVf = JsonUtils.getStringValuesByName(currentNode, "vf");
631                 if (currentVf != null && !currentVf.isEmpty()) {
632                     if (!modelName.equalsIgnoreCase(cldsModelProp.getName()) && service.equalsIgnoreCase(currentService)
633                         && resourceVf.get(0).equalsIgnoreCase(currentVf.get(0))) {
634                         throw new BadRequestException("Same Service/VF already exists in " + cldsModelProp.getName()
635                             + " model, please select different Service/VF.");
636                     }
637                 }
638             }
639         }
640     }
641
642     // Created for the integration test
643     public void setLoggingUtil(LoggingUtils utilP) {
644         util = utilP;
645     }
646 }