2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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 * ===================================================================
25 package org.onap.clamp.clds.service;
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
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;
40 import javax.servlet.http.HttpServletRequest;
41 import javax.ws.rs.BadRequestException;
42 import javax.ws.rs.NotAuthorizedException;
43 import javax.xml.transform.TransformerException;
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;
79 * Service to save and retrieve the CLDS model attributes.
82 public class CldsService extends SecureServiceBase {
84 public static final Type LIST_OF_SDC_SERVICE_INFO_TYPE = new TypeToken<List<SdcServiceInfo>>() {
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);
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;
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);
111 private HttpServletRequest request;
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,
137 permissionUpdateTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance,
139 permissionReadTosca = SecureServicePermission.create(cldsPermissionTypeTosca, cldsPermissionInstance, "read");
140 permissionUpdateTosca = SecureServicePermission.create(cldsPermissionTypeTosca, cldsPermissionInstance,
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.
154 public List<CldsMonitoringDetails> getCldsDetails() {
155 util.entering(request, "CldsService: GET model details");
156 Date startTime = new Date();
157 List<CldsMonitoringDetails> cldsMonitoringDetailsList = cldsDao.getCLDSMonitoringDetails();
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;
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
169 public CldsInfo getCldsInfo() {
170 util.entering(request, "CldsService: GET cldsInfo");
171 Date startTime = new Date();
172 LoggingUtils.setTimeContext(startTime, new Date());
174 CldsInfoProvider cldsInfoProvider = new CldsInfoProvider(this);
175 CldsInfo cldsInfo = cldsInfoProvider.getCldsInfo();
178 LoggingUtils.setTimeContext(startTime, new Date());
179 securityLogger.info("GET cldsInfo completed");
180 util.exiting("200", "Get cldsInfo success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
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.
190 * @return bpmn xml text - content of bpmn given name
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);
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();
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.
211 * @return image xml text - content of image given name
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);
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();
227 * REST service that retrieves a CLDS model by name from the database.
230 * @return clds model - clds model for the given model name
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
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());
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);
255 } catch (Exception e) {
256 LoggingUtils.setErrorContext("900", "Set event inventory error");
257 logger.error("getModel set event Inventory error:" + e);
260 LoggingUtils.setTimeContext(startTime, new Date());
261 auditLogger.info("GET model completed");
262 util.exiting("200", "Get model success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
267 * REST service that saves a CLDS model by name in the database.
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());
284 LoggingUtils.setTimeContext(startTime, new Date());
285 auditLogger.info("PUT model completed");
286 util.exiting("200", "Put model success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
291 * REST service that retrieves a list of CLDS model names.
293 * @return model names in JSON
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();
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);
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
317 model.setBpmnText(template.getBpmnText());
323 * REST service that saves and processes an action for a CLDS model by name.
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
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 = "";
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());
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);
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();
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();
397 if (null == errorMessage || (null != errorMessage && !errorMessage.isEmpty())) {
398 CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), actionCd, CldsEvent.ACTION_STATE_ERROR,
400 // Need a refresh as new events have been inserted
401 model = CldsModel.retrieve(cldsDao, modelName, false);
402 if (null == errorMessage) {
403 errorMessage = "No response from Policy";
405 model.setErrorMessageForUi(errorMessage);
406 util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "putModelAndProcessAction failed", Level.INFO,
407 ONAPLogConstants.ResponseStatus.ERROR);
408 return new ResponseEntity<>(model, HttpStatus.INTERNAL_SERVER_ERROR);
410 // Need a refresh as new events have been inserted, could have been deleted so
412 model = CldsModel.retrieve(cldsDao, modelName, true);
413 util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
414 return new ResponseEntity<>(model, HttpStatus.OK);
419 * REST service that accepts events for a model.
424 public String postDcaeEvent(String test, DcaeEvent dcaeEvent) {
425 util.entering(request, "CldsService: Post dcae event");
426 Date startTime = new Date();
427 String userid = null;
428 // TODO: allow auth checking to be turned off by removing the permission
430 if (cldsPermissionTypeClEvent != null && cldsPermissionTypeClEvent.length() > 0) {
431 SecureServicePermission permissionEvent = SecureServicePermission.create(cldsPermissionTypeClEvent,
432 cldsPermissionInstance, dcaeEvent.getEvent());
433 isAuthorized(permissionEvent);
434 userid = getUserId();
436 // Flag indicates whether it is triggered by Validation Test button from
438 boolean isTest = Boolean.parseBoolean(test);
439 int instanceCount = 0;
440 if (dcaeEvent.getInstances() != null) {
441 instanceCount = dcaeEvent.getInstances().size();
443 String msgInfo = "event=" + dcaeEvent.getEvent() + " serviceUUID=" + dcaeEvent.getServiceUUID()
444 + " resourceUUID=" + dcaeEvent.getResourceUUID() + " artifactName=" + dcaeEvent.getArtifactName()
445 + " instance count=" + instanceCount + " isTest=" + isTest;
446 logger.info("POST dcae event {}", msgInfo);
448 logger.warn("Ignorning test event from DCAE");
450 if (DcaeEvent.EVENT_DEPLOYMENT.equalsIgnoreCase(dcaeEvent.getEvent())) {
451 CldsModel.insertModelInstance(cldsDao, dcaeEvent, userid);
453 CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userid, dcaeEvent.getCldsActionCd(),
454 CldsEvent.ACTION_STATE_RECEIVED, null);
458 LoggingUtils.setTimeContext(startTime, new Date());
459 auditLogger.info("Post dcae event completed");
460 util.exiting("200", "Post dcae event success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
465 * REST service that retrieves total properties required by UI
467 * @throws IOException
470 public String getSdcProperties() throws IOException {
471 return refProp.getJsonTemplate(GLOBAL_PROPERTIES_KEY).toString();
476 * Determine if the user is authorized for a particular VF by its invariant
479 * @param vfInvariantUuid
480 * @throws NotAuthorizedException
483 public boolean isAuthorizedForVf(String vfInvariantUuid) {
484 if (cldsPermissionTypeFilterVf != null && !cldsPermissionTypeFilterVf.isEmpty()) {
485 SecureServicePermission permission = SecureServicePermission.create(cldsPermissionTypeFilterVf,
486 cldsPermissionInstance, vfInvariantUuid);
487 return isAuthorized(permission);
489 // if CLDS_PERMISSION_TYPE_FILTER_VF property is not provided, then
490 // VF filtering is turned off
491 logger.warn("VF filtering turned off");
497 * Determine if the user is authorized for a particular VF by its invariant
498 * UUID. If not authorized, then NotAuthorizedException is thrown.
503 private boolean isAuthorizedForVf(CldsModel model) {
504 String vf = ModelProperties.getVf(model);
505 if (vf == null || vf.length() == 0) {
506 logger.info("VF not found in model");
509 return isAuthorizedForVf(vf);
513 public ResponseEntity<CldsModel> deployModel(String modelName, CldsModel model) {
514 util.entering(request, "CldsService: Deploy model");
515 Date startTime = new Date();
516 String errorMessage = "";
518 fillInCldsModel(model);
519 String bpmnJson = cldsBpmnTransformer.doXslTransformToString(model.getBpmnText());
520 logger.info("PUT bpmnJson={}", bpmnJson);
521 SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage,
522 cldsPermissionInstance, CldsEvent.ACTION_DEPLOY);
523 isAuthorized(permisionManage);
524 isAuthorizedForVf(model);
525 ModelProperties modelProp = new ModelProperties(modelName, model.getControlName(), CldsEvent.ACTION_DEPLOY,
526 false, bpmnJson, model.getPropText());
527 checkForDuplicateServiceVf(modelName, model.getPropText());
528 String deploymentId = "";
529 // If model is already deployed then pass same deployment id
530 if (model.getDeploymentId() != null && !model.getDeploymentId().isEmpty()) {
531 deploymentId = model.getDeploymentId();
533 model.setDeploymentId(deploymentId = "closedLoop_" + UUID.randomUUID() + "_deploymentId");
535 model.setDeploymentStatusUrl(dcaeDispatcherServices.createNewDeployment(deploymentId, model.getTypeId(),
536 modelProp.getGlobal().getDeployParameters()));
537 CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), CldsEvent.ACTION_DEPLOY,
538 CldsEvent.ACTION_STATE_INITIATED, null);
539 model.save(cldsDao, getUserId());
540 // This is a blocking call
541 checkDcaeDeploymentStatus(model, CldsEvent.ACTION_DEPLOY, true);
542 // Refresh the model object in any cases for new event
543 model = CldsModel.retrieve(cldsDao, model.getName(), false);
545 LoggingUtils.setTimeContext(startTime, new Date());
546 auditLogger.info("Deploy model completed");
547 } catch (Exception e) {
548 errorMessage = e.getMessage();
549 logger.error("Exception occured during deployModel", e);
551 if (!errorMessage.isEmpty()) {
552 model.setErrorMessageForUi(errorMessage);
553 util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "DeployModel failed", Level.INFO,
554 ONAPLogConstants.ResponseStatus.ERROR);
555 return new ResponseEntity<>(model, HttpStatus.INTERNAL_SERVER_ERROR);
557 util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
558 return new ResponseEntity<>(model, HttpStatus.OK);
562 public ResponseEntity<CldsModel> unDeployModel(String modelName, CldsModel model) {
563 util.entering(request, "CldsService: Undeploy model");
564 Date startTime = new Date();
565 String errorMessage = "";
567 SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage,
568 cldsPermissionInstance, CldsEvent.ACTION_UNDEPLOY);
569 isAuthorized(permisionManage);
570 isAuthorizedForVf(model);
571 model.setDeploymentStatusUrl(
572 dcaeDispatcherServices.deleteExistingDeployment(model.getDeploymentId(), model.getTypeId()));
573 CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), CldsEvent.ACTION_UNDEPLOY,
574 CldsEvent.ACTION_STATE_INITIATED, null);
575 // clean the deployment ID
576 model.setDeploymentId(null);
577 model.save(cldsDao, getUserId());
578 // This is a blocking call
579 checkDcaeDeploymentStatus(model, CldsEvent.ACTION_UNDEPLOY, true);
580 // Refresh the model object in any cases for new event
581 model = CldsModel.retrieve(cldsDao, model.getName(), false);
583 LoggingUtils.setTimeContext(startTime, new Date());
584 auditLogger.info("Undeploy model completed");
585 } catch (Exception e) {
586 errorMessage = e.getMessage();
587 logger.error("Exception occured during unDeployModel", e);
589 if (!errorMessage.isEmpty()) {
590 model.setErrorMessageForUi(errorMessage);
591 util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "UndeployModel failed", Level.INFO,
592 ONAPLogConstants.ResponseStatus.ERROR);
593 return new ResponseEntity<>(model, HttpStatus.INTERNAL_SERVER_ERROR);
595 util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
596 return new ResponseEntity<>(model, HttpStatus.OK);
600 private void checkDcaeDeploymentStatus(CldsModel model, String cldsEvent, boolean withRetry)
601 throws InterruptedException {
602 String operationStatus = withRetry
603 ? dcaeDispatcherServices.getOperationStatusWithRetry(model.getDeploymentStatusUrl())
604 : dcaeDispatcherServices.getOperationStatus(model.getDeploymentStatusUrl());
605 if ("succeeded".equalsIgnoreCase(operationStatus)) {
606 logger.info(cldsEvent + " model (" + model.getName() + ") succeeded...Deployment Id is - "
607 + model.getDeploymentId());
608 CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), cldsEvent,
609 CldsEvent.ACTION_STATE_COMPLETED, null);
611 String info = "DCAE " + cldsEvent + " (" + model.getName() + ") failed...Operation Status is - "
614 CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), cldsEvent, CldsEvent.ACTION_STATE_ERROR,
616 util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "DCAE operation(" + cldsEvent + ") failed",
617 Level.INFO, ONAPLogConstants.ResponseStatus.ERROR);
618 throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, info);
622 private void checkForDuplicateServiceVf(String modelName, String modelPropText) throws IOException {
623 JsonElement globalNode = JsonUtils.GSON.fromJson(modelPropText, JsonObject.class).get("global");
624 String service = JsonUtils.getStringValueByName(globalNode, "service");
625 List<String> resourceVf = JsonUtils.getStringValuesByName(globalNode, "vf");
626 if (service != null && resourceVf != null && !resourceVf.isEmpty()) {
627 List<CldsModelProp> cldsModelPropList = cldsDao.getDeployedModelProperties();
628 for (CldsModelProp cldsModelProp : cldsModelPropList) {
629 JsonElement currentNode = JsonUtils.GSON
630 .fromJson(cldsModelProp.getPropText(), JsonObject.class)
632 String currentService = JsonUtils.getStringValueByName(currentNode, "service");
633 List<String> currentVf = JsonUtils.getStringValuesByName(currentNode, "vf");
634 if (currentVf != null && !currentVf.isEmpty()) {
635 if (!modelName.equalsIgnoreCase(cldsModelProp.getName()) && service.equalsIgnoreCase(currentService)
636 && resourceVf.get(0).equalsIgnoreCase(currentVf.get(0))) {
637 throw new BadRequestException("Same Service/VF already exists in " + cldsModelProp.getName()
638 + " model, please select different Service/VF.");
645 // Created for the integration test
646 public void setLoggingUtil(LoggingUtils utilP) {