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 * ===================================================================
21 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
24 package org.onap.clamp.clds.service;
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.fasterxml.jackson.databind.JsonNode;
29 import com.fasterxml.jackson.databind.ObjectMapper;
30 import com.fasterxml.jackson.databind.node.ObjectNode;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.security.GeneralSecurityException;
35 import java.util.ArrayList;
36 import java.util.Date;
37 import java.util.HashMap;
38 import java.util.List;
40 import java.util.Properties;
41 import java.util.UUID;
42 import java.util.concurrent.TimeUnit;
44 import javax.annotation.PostConstruct;
45 import javax.ws.rs.BadRequestException;
46 import javax.ws.rs.Consumes;
47 import javax.ws.rs.DefaultValue;
48 import javax.ws.rs.GET;
49 import javax.ws.rs.NotAuthorizedException;
50 import javax.ws.rs.POST;
51 import javax.ws.rs.PUT;
52 import javax.ws.rs.Path;
53 import javax.ws.rs.PathParam;
54 import javax.ws.rs.Produces;
55 import javax.ws.rs.QueryParam;
56 import javax.ws.rs.core.MediaType;
57 import javax.xml.transform.TransformerException;
59 import org.apache.camel.Produce;
60 import org.apache.commons.codec.DecoderException;
61 import org.apache.commons.lang3.StringUtils;
62 import org.json.simple.parser.ParseException;
63 import org.onap.clamp.clds.camel.CamelProxy;
64 import org.onap.clamp.clds.client.DcaeDispatcherServices;
65 import org.onap.clamp.clds.client.DcaeInventoryServices;
66 import org.onap.clamp.clds.client.req.sdc.SdcCatalogServices;
67 import org.onap.clamp.clds.dao.CldsDao;
68 import org.onap.clamp.clds.exception.CldsConfigException;
69 import org.onap.clamp.clds.exception.SdcCommunicationException;
70 import org.onap.clamp.clds.exception.policy.PolicyClientException;
71 import org.onap.clamp.clds.model.CLDSMonitoringDetails;
72 import org.onap.clamp.clds.model.CldsDBServiceCache;
73 import org.onap.clamp.clds.model.CldsEvent;
74 import org.onap.clamp.clds.model.CldsHealthCheck;
75 import org.onap.clamp.clds.model.CldsInfo;
76 import org.onap.clamp.clds.model.CldsModel;
77 import org.onap.clamp.clds.model.CldsModelProp;
78 import org.onap.clamp.clds.model.CldsSdcResource;
79 import org.onap.clamp.clds.model.CldsSdcServiceDetail;
80 import org.onap.clamp.clds.model.CldsSdcServiceInfo;
81 import org.onap.clamp.clds.model.CldsServiceData;
82 import org.onap.clamp.clds.model.CldsTemplate;
83 import org.onap.clamp.clds.model.DcaeEvent;
84 import org.onap.clamp.clds.model.ValueItem;
85 import org.onap.clamp.clds.model.prop.AbstractModelElement;
86 import org.onap.clamp.clds.model.prop.ModelProperties;
87 import org.onap.clamp.clds.model.refprop.RefProp;
88 import org.onap.clamp.clds.transform.XslTransformer;
89 import org.onap.clamp.clds.util.LoggingUtils;
90 import org.springframework.beans.factory.annotation.Autowired;
91 import org.springframework.beans.factory.annotation.Value;
92 import org.springframework.context.ApplicationContext;
93 import org.springframework.http.HttpStatus;
94 import org.springframework.stereotype.Component;
95 import org.springframework.web.client.HttpClientErrorException;
98 * Service to save and retrieve the CLDS model attributes.
102 public class CldsService extends SecureServiceBase {
104 @Produce(uri = "direct:processSubmit")
105 private CamelProxy camelProxy;
106 protected static final EELFLogger securityLogger = EELFManager.getInstance().getSecurityLogger();
108 private ApplicationContext appContext;
109 private static final String RESOURCE_NAME = "clds-version.properties";
110 @Value("${CLDS_PERMISSION_TYPE_CL:permission-type-cl}")
111 private String cldsPersmissionTypeCl;
112 @Value("${CLDS_PERMISSION_TYPE_CL_MANAGE:permission-type-cl-manage}")
113 private String cldsPermissionTypeClManage;
114 @Value("${CLDS_PERMISSION_TYPE_CL_EVENT:permission-type-cl-event}")
115 private String cldsPermissionTypeClEvent;
116 @Value("${CLDS_PERMISSION_TYPE_FILTER_VF:permission-type-filter-vf}")
117 private String cldsPermissionTypeFilterVf;
118 @Value("${CLDS_PERMISSION_TYPE_TEMPLATE:permission-type-template}")
119 private String cldsPermissionTypeTemplate;
120 @Value("${CLDS_PERMISSION_INSTANCE:dev}")
121 private String cldsPermissionInstance;
122 private SecureServicePermission permissionReadCl;
123 private SecureServicePermission permissionUpdateCl;
124 private SecureServicePermission permissionReadTemplate;
125 private SecureServicePermission permissionUpdateTemplate;
128 private final void afterConstruction() {
129 permissionReadCl = SecureServicePermission.create(cldsPersmissionTypeCl, cldsPermissionInstance, "read");
130 permissionUpdateCl = SecureServicePermission.create(cldsPersmissionTypeCl, cldsPermissionInstance, "update");
131 permissionReadTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance,
133 permissionUpdateTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance,
137 @Value("${org.onap.clamp.config.files.globalClds:'classpath:/clds/globalClds.properties'}")
138 private String globalClds;
139 private Properties globalCldsProperties;
141 private CldsDao cldsDao;
143 private XslTransformer cldsBpmnTransformer;
145 private RefProp refProp;
147 private SdcCatalogServices sdcCatalogServices;
149 private DcaeDispatcherServices dcaeDispatcherServices;
151 private DcaeInventoryServices dcaeInventoryServices;
154 * @return list of CLDS-Monitoring-Details: CLOSELOOP_NAME | Close loop name
155 * used in the CLDS application (prefix: ClosedLoop- + unique ClosedLoop ID)
156 * MODEL_NAME | Model Name in CLDS application SERVICE_TYPE_ID | TypeId
157 * returned from the DCAE application when the ClosedLoop is submitted
158 * (DCAEServiceTypeRequest generated in DCAE application). DEPLOYMENT_ID |
159 * Id generated when the ClosedLoop is deployed in DCAE. TEMPLATE_NAME |
160 * Template used to generate the ClosedLoop model. ACTION_CD | Current state
161 * of the ClosedLoop in CLDS application.
164 @Path("/cldsDetails")
165 @Produces(MediaType.APPLICATION_JSON)
166 public List<CLDSMonitoringDetails> getCLDSDetails() {
167 Date startTime = new Date();
168 LoggingUtils.setRequestContext("CldsService: GET model details", getPrincipalName());
169 List<CLDSMonitoringDetails> cldsMonitoringDetailsList = new ArrayList<CLDSMonitoringDetails>();
170 cldsMonitoringDetailsList = cldsDao.getCLDSMonitoringDetails();
172 LoggingUtils.setTimeContext(startTime, new Date());
173 LoggingUtils.setResponseContext("0", "Get cldsDetails success", this.getClass().getName());
174 auditLogger.info("GET cldsDetails completed");
175 return cldsMonitoringDetailsList;
179 * CLDS IFO service will return 3 things 1. User Name 2. CLDS code version
180 * that is currently installed from pom.xml file 3. User permissions
184 @Produces(MediaType.APPLICATION_JSON)
185 public CldsInfo getCldsInfo() {
186 CldsInfo cldsInfo = new CldsInfo();
187 Date startTime = new Date();
188 LoggingUtils.setRequestContext("CldsService: GET cldsInfo", getPrincipalName());
189 LoggingUtils.setTimeContext(startTime, new Date());
191 cldsInfo.setUserName(getUserName());
192 // Get CLDS application version
193 String cldsVersion = "";
194 Properties props = new Properties();
195 ClassLoader loader = Thread.currentThread().getContextClassLoader();
196 try (InputStream resourceStream = loader.getResourceAsStream(RESOURCE_NAME)) {
197 props.load(resourceStream);
198 cldsVersion = props.getProperty("clds.version");
199 } catch (Exception ex) {
200 logger.error("Exception caught during the clds.version reading", ex);
202 cldsInfo.setCldsVersion(cldsVersion);
203 // Get the user list of permissions
204 cldsInfo.setPermissionReadCl(isAuthorizedNoException(permissionReadCl));
205 cldsInfo.setPermissionUpdateCl(isAuthorizedNoException(permissionUpdateCl));
206 cldsInfo.setPermissionReadTemplate(isAuthorizedNoException(permissionReadTemplate));
207 cldsInfo.setPermissionUpdateTemplate(isAuthorizedNoException(permissionUpdateTemplate));
209 LoggingUtils.setTimeContext(startTime, new Date());
210 LoggingUtils.setResponseContext("0", "Get cldsInfo success", this.getClass().getName());
211 securityLogger.info("GET cldsInfo completed");
216 * REST service that retrieves clds healthcheck information.
218 * @return CldsHealthCheck class containing healthcheck info
221 @Path("/healthcheck")
222 @Produces(MediaType.APPLICATION_JSON)
223 public CldsHealthCheck gethealthcheck() {
224 CldsHealthCheck cldsHealthCheck = new CldsHealthCheck();
225 Date startTime = new Date();
226 LoggingUtils.setRequestContext("CldsService: GET healthcheck", getPrincipalName());
227 LoggingUtils.setTimeContext(startTime, new Date());
229 cldsDao.doHealthCheck();
230 cldsHealthCheck.setHealthCheckComponent("CLDS-APP");
231 cldsHealthCheck.setHealthCheckStatus("UP");
232 cldsHealthCheck.setDescription("OK");
233 } catch (Exception e) {
234 logger.error("CLAMP application DB Error", e);
235 cldsHealthCheck.setHealthCheckComponent("CLDS-APP");
236 cldsHealthCheck.setHealthCheckStatus("DOWN");
237 cldsHealthCheck.setDescription("NOT-OK");
240 LoggingUtils.setTimeContext(startTime, new Date());
241 LoggingUtils.setResponseContext("0", "Get healthcheck success", this.getClass().getName());
242 securityLogger.info("GET healthcheck completed");
243 return cldsHealthCheck;
247 * REST service that retrieves BPMN for a CLDS model name from the database.
248 * This is subset of the json getModel. This is only expected to be used for
249 * testing purposes, not by the UI.
252 * @return bpmn xml text - content of bpmn given name
255 @Path("/model/bpmn/{modelName}")
256 @Produces(MediaType.TEXT_XML)
257 public String getBpmnXml(@PathParam("modelName") String modelName) {
258 Date startTime = new Date();
259 LoggingUtils.setRequestContext("CldsService: GET model bpmn", getPrincipalName());
260 isAuthorized(permissionReadCl);
261 logger.info("GET bpmnText for modelName={}", modelName);
262 CldsModel model = CldsModel.retrieve(cldsDao, modelName, false);
264 LoggingUtils.setTimeContext(startTime, new Date());
265 LoggingUtils.setResponseContext("0", "Get model bpmn success", this.getClass().getName());
266 auditLogger.info("GET model bpmn completed");
267 return model.getBpmnText();
271 * REST service that retrieves image for a CLDS model name from the
272 * database. This is subset of the json getModel. This is only expected to
273 * be used for testing purposes, not by the UI.
276 * @return image xml text - content of image given name
279 @Path("/model/image/{modelName}")
280 @Produces(MediaType.TEXT_XML)
281 public String getImageXml(@PathParam("modelName") String modelName) {
282 Date startTime = new Date();
283 LoggingUtils.setRequestContext("CldsService: GET model image", getPrincipalName());
284 isAuthorized(permissionReadCl);
285 logger.info("GET imageText for modelName={}", modelName);
286 CldsModel model = CldsModel.retrieve(cldsDao, modelName, false);
288 LoggingUtils.setTimeContext(startTime, new Date());
289 LoggingUtils.setResponseContext("0", "Get model image success", this.getClass().getName());
290 auditLogger.info("GET model image completed");
291 return model.getImageText();
295 * REST service that retrieves a CLDS model by name from the database.
298 * @return clds model - clds model for the given model name
301 @Path("/model/{modelName}")
302 @Produces(MediaType.APPLICATION_JSON)
303 public CldsModel getModel(@PathParam("modelName") String modelName) {
304 Date startTime = new Date();
305 LoggingUtils.setRequestContext("CldsService: GET model", getPrincipalName());
306 isAuthorized(permissionReadCl);
307 logger.debug("GET model for modelName={}", modelName);
308 CldsModel cldsModel = CldsModel.retrieve(cldsDao, modelName, false);
309 isAuthorizedForVf(cldsModel);
310 // Checking condition whether our CLDS model can call Inventory Method
311 if (cldsModel.canInventoryCall()) {
313 // Method to call dcae inventory and invoke insert event method
314 dcaeInventoryServices.setEventInventory(cldsModel, getUserId());
315 } catch (Exception e) {
316 LoggingUtils.setErrorContext("900", "Set event inventory error");
317 logger.error("getModel set event Inventory error:" + e);
321 LoggingUtils.setTimeContext(startTime, new Date());
322 LoggingUtils.setResponseContext("0", "Get model success", this.getClass().getName());
323 auditLogger.info("GET model completed");
328 * REST service that saves a CLDS model by name in the database.
333 @Path("/model/{modelName}")
334 @Consumes(MediaType.APPLICATION_JSON)
335 @Produces(MediaType.APPLICATION_JSON)
336 public CldsModel putModel(@PathParam("modelName") String modelName, CldsModel cldsModel) {
337 Date startTime = new Date();
338 LoggingUtils.setRequestContext("CldsService: PUT model", getPrincipalName());
339 isAuthorized(permissionUpdateCl);
340 isAuthorizedForVf(cldsModel);
341 logger.info("PUT model for modelName={}", modelName);
342 logger.info("PUT bpmnText={}", cldsModel.getBpmnText());
343 logger.info("PUT propText={}", cldsModel.getPropText());
344 logger.info("PUT imageText={}", cldsModel.getImageText());
345 cldsModel.setName(modelName);
346 if (cldsModel.getTemplateName() != null) {
347 CldsTemplate template = cldsDao.getTemplate(cldsModel.getTemplateName());
348 if (template != null) {
349 cldsModel.setTemplateId(template.getId());
350 cldsModel.setDocText(template.getPropText());
353 cldsModel.save(cldsDao, getUserId());
355 LoggingUtils.setTimeContext(startTime, new Date());
356 LoggingUtils.setResponseContext("0", "Put model success", this.getClass().getName());
357 auditLogger.info("PUT model completed");
362 * REST service that retrieves a list of CLDS model names.
364 * @return model names in JSON
367 @Path("/model-names")
368 @Produces(MediaType.APPLICATION_JSON)
369 public List<ValueItem> getModelNames() {
370 Date startTime = new Date();
371 LoggingUtils.setRequestContext("CldsService: GET model names", getPrincipalName());
372 isAuthorized(permissionReadCl);
373 logger.info("GET list of model names");
374 List<ValueItem> names = cldsDao.getBpmnNames();
376 LoggingUtils.setTimeContext(startTime, new Date());
377 LoggingUtils.setResponseContext("0", "Get model names success", this.getClass().getName());
378 auditLogger.info("GET model names completed");
383 * REST service that saves and processes an action for a CLDS model by name.
390 * @throws TransformerException
391 * In case of issues when doing the XSLT of the BPMN flow
392 * @throws ParseException
393 * In case of issues when parsing the JSON
394 * @throws GeneralSecurityException
395 * In case of issues when decrypting the password
396 * @throws DecoderException
397 * In case of issues with the Hex String decoding
400 @Path("/action/{action}/{modelName}")
401 @Consumes(MediaType.APPLICATION_JSON)
402 @Produces(MediaType.APPLICATION_JSON)
403 public CldsModel putModelAndProcessAction(@PathParam("action") String action,
404 @PathParam("modelName") String modelName, @QueryParam("test") String test, CldsModel model)
405 throws TransformerException, ParseException, GeneralSecurityException, DecoderException {
406 Date startTime = new Date();
407 LoggingUtils.setRequestContext("CldsService: Process model action", getPrincipalName());
408 String actionCd = action.toUpperCase();
409 SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage,
410 cldsPermissionInstance, actionCd);
411 isAuthorized(permisionManage);
412 isAuthorizedForVf(model);
413 String userId = getUserId();
414 String actionStateCd = CldsEvent.ACTION_STATE_INITIATED;
415 String processDefinitionKey = "clds-process-action-wf";
416 logger.info("PUT actionCd={}", actionCd);
417 logger.info("PUT actionStateCd={}", actionStateCd);
418 logger.info("PUT processDefinitionKey={}", processDefinitionKey);
419 logger.info("PUT modelName={}", modelName);
420 logger.info("PUT test={}", test);
421 logger.info("PUT bpmnText={}", model.getBpmnText());
422 logger.info("PUT propText={}", model.getPropText());
423 logger.info("PUT userId={}", userId);
424 logger.info("PUT getTypeId={}", model.getTypeId());
425 logger.info("PUT deploymentId={}", model.getDeploymentId());
426 if (model.getTemplateName() != null) {
427 CldsTemplate template = cldsDao.getTemplate(model.getTemplateName());
428 if (template != null) {
429 model.setTemplateId(template.getId());
430 model.setDocText(template.getPropText());
434 model.setName(modelName);
435 model.save(cldsDao, getUserId());
436 // get vars and format if necessary
437 String prop = model.getPropText();
438 String bpmn = model.getBpmnText();
439 String docText = model.getDocText();
440 String controlName = model.getControlName();
441 String bpmnJson = cldsBpmnTransformer.doXslTransformToString(bpmn);
442 logger.info("PUT bpmnJson={}", bpmnJson);
443 // Flag indicates whether it is triggered by Validation Test button from
445 boolean isTest = false;
446 if (test != null && test.equalsIgnoreCase("true")) {
449 String actionTestOverride = refProp.getStringValue("action.test.override");
450 if (actionTestOverride != null && actionTestOverride.equalsIgnoreCase("true")) {
451 logger.info("PUT actionTestOverride={}", actionTestOverride);
452 logger.info("PUT override test indicator and setting it to true");
456 logger.info("PUT isTest={}", isTest);
457 boolean isInsertTestEvent = false;
458 String insertTestEvent = refProp.getStringValue("action.insert.test.event");
459 if (insertTestEvent != null && insertTestEvent.equalsIgnoreCase("true")) {
460 isInsertTestEvent = true;
462 logger.info("PUT isInsertTestEvent={}", isInsertTestEvent);
463 // determine if requested action is permitted
464 model.validateAction(actionCd);
465 // input variables for Camel process
466 Map<String, Object> variables = new HashMap<>();
467 variables.put("actionCd", actionCd);
468 variables.put("modelProp", prop.getBytes());
469 variables.put("modelBpmnProp", bpmnJson);
470 variables.put("modelName", modelName);
471 variables.put("controlName", controlName);
472 variables.put("docText", docText.getBytes());
473 variables.put("isTest", isTest);
474 variables.put("userid", userId);
475 variables.put("isInsertTestEvent", isInsertTestEvent);
476 logger.info("modelProp - " + prop);
477 logger.info("docText - " + docText);
478 // ModelProperties modelProperties = new ModelProperties(modelName,
479 // controlName, actionCd, isTest, modelBpmnProp, modelProp);
481 String result = camelProxy.submit(actionCd, prop, bpmnJson, modelName, controlName, docText, isTest, userId,
483 logger.info("Starting Camel flow on request, result is: ", result);
484 } catch (SdcCommunicationException | PolicyClientException | BadRequestException e) {
485 logger.error("Exception occured during invoking Camel process", e);
486 throw new CldsConfigException(e.getMessage(), e);
488 // refresh model info from db (get fresh event info)
489 CldsModel retreivedModel = CldsModel.retrieve(cldsDao, modelName, false);
490 if (!isTest && (actionCd.equalsIgnoreCase(CldsEvent.ACTION_SUBMIT)
491 || actionCd.equalsIgnoreCase(CldsEvent.ACTION_RESUBMIT)
492 || actionCd.equalsIgnoreCase(CldsEvent.ACTION_SUBMITDCAE))) {
493 // To verify inventory status and modify model status to distribute
494 dcaeInventoryServices.setEventInventory(retreivedModel, getUserId());
495 retreivedModel.save(cldsDao, getUserId());
498 LoggingUtils.setTimeContext(startTime, new Date());
499 LoggingUtils.setResponseContext("0", "Process model action success", this.getClass().getName());
500 auditLogger.info("Process model action completed");
501 return retreivedModel;
505 * REST service that accepts events for a model.
512 @Consumes(MediaType.APPLICATION_JSON)
513 @Produces(MediaType.APPLICATION_JSON)
514 public String postDcaeEvent(@QueryParam("test") String test, DcaeEvent dcaeEvent) {
515 Date startTime = new Date();
516 LoggingUtils.setRequestContext("CldsService: Post dcae event", getPrincipalName());
517 String userid = null;
518 // TODO: allow auth checking to be turned off by removing the permission
520 if (cldsPermissionTypeClEvent != null && cldsPermissionTypeClEvent.length() > 0) {
521 SecureServicePermission permissionEvent = SecureServicePermission.create(cldsPermissionTypeClEvent,
522 cldsPermissionInstance, dcaeEvent.getEvent());
523 isAuthorized(permissionEvent);
524 userid = getUserId();
526 // Flag indicates whether it is triggered by Validation Test button from
528 boolean isTest = false;
529 if (test != null && test.equalsIgnoreCase("true")) {
532 int instanceCount = 0;
533 if (dcaeEvent.getInstances() != null) {
534 instanceCount = dcaeEvent.getInstances().size();
536 String msgInfo = "event=" + dcaeEvent.getEvent() + " serviceUUID=" + dcaeEvent.getServiceUUID()
537 + " resourceUUID=" + dcaeEvent.getResourceUUID() + " artifactName=" + dcaeEvent.getArtifactName()
538 + " instance count=" + instanceCount + " isTest=" + isTest;
539 logger.info("POST dcae event {}", msgInfo);
541 logger.warn("Ignorning test event from DCAE");
543 if (DcaeEvent.EVENT_DEPLOYMENT.equalsIgnoreCase(dcaeEvent.getEvent())) {
544 CldsModel.insertModelInstance(cldsDao, dcaeEvent, userid);
546 CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userid, dcaeEvent.getCldsActionCd(),
547 CldsEvent.ACTION_STATE_RECEIVED, null);
551 LoggingUtils.setTimeContext(startTime, new Date());
552 LoggingUtils.setResponseContext("0", "Post dcae event success", this.getClass().getName());
553 auditLogger.info("Post dcae event completed");
558 * REST service that retrieves sdc services
560 * @throws GeneralSecurityException
561 * In case of issue when decryting the SDC password
562 * @throws DecoderException
563 * In case of issues with the decoding of the Hex String
566 @Path("/sdc/services")
567 @Produces(MediaType.APPLICATION_JSON)
568 public String getSdcServices() throws GeneralSecurityException, DecoderException {
569 Date startTime = new Date();
570 LoggingUtils.setRequestContext("CldsService: GET sdc services", getPrincipalName());
572 String responseStr = sdcCatalogServices.getSdcServicesInformation(null);
574 retStr = createUiServiceFormatJson(responseStr);
575 } catch (IOException e) {
576 logger.error("IOException during SDC communication", e);
577 throw new SdcCommunicationException("IOException during SDC communication", e);
579 logger.info("value of sdcServices : {}", retStr);
581 LoggingUtils.setTimeContext(startTime, new Date());
582 LoggingUtils.setResponseContext("0", "Get sdc services success", this.getClass().getName());
583 auditLogger.info("GET sdc services completed");
588 * REST service that retrieves total properties required by UI
590 * @throws IOException
595 @Produces(MediaType.APPLICATION_JSON)
596 public String getSdcProperties() throws IOException {
597 return createPropertiesObjectByUUID(getGlobalCldsString(), "{}");
601 * REST service that retrieves total properties by using invariantUUID based
602 * on refresh and non refresh
604 * @throws GeneralSecurityException
605 * In case of issues with the decryting the encrypted password
606 * @throws DecoderException
607 * In case of issues with the decoding of the Hex String
608 * @throws IOException
609 * In case of issue to convert CldsServiceCache to InputStream
612 @Path("/properties/{serviceInvariantUUID}")
613 @Produces(MediaType.APPLICATION_JSON)
614 public String getSdcPropertiesByServiceUUIDForRefresh(
615 @PathParam("serviceInvariantUUID") String serviceInvariantUUID,
616 @DefaultValue("false") @QueryParam("refresh") boolean refresh)
617 throws GeneralSecurityException, DecoderException, IOException {
618 Date startTime = new Date();
619 LoggingUtils.setRequestContext("CldsService: GET sdc properties by uuid", getPrincipalName());
620 CldsServiceData cldsServiceData = new CldsServiceData();
621 cldsServiceData.setServiceInvariantUUID(serviceInvariantUUID);
623 cldsServiceData = cldsDao.getCldsServiceCache(serviceInvariantUUID);
625 if (sdcCatalogServices.isCldsSdcCacheDataExpired(cldsServiceData)) {
626 cldsServiceData = sdcCatalogServices.getCldsServiceDataWithAlarmConditions(serviceInvariantUUID);
627 cldsDao.setCldsServiceCache(new CldsDBServiceCache(cldsServiceData));
629 // filter out VFs the user is not authorized for
630 cldsServiceData.filterVfs(this);
631 // format retrieved data into properties json
632 String sdcProperties = sdcCatalogServices.createPropertiesObjectByUUID(getGlobalCldsString(), cldsServiceData);
634 LoggingUtils.setTimeContext(startTime, new Date());
635 LoggingUtils.setResponseContext("0", "Get sdc properties by uuid success", this.getClass().getName());
636 auditLogger.info("GET sdc properties by uuid completed");
637 return sdcProperties;
641 * Determine if the user is authorized for a particular VF by its invariant
644 * @param vfInvariantUuid
645 * @throws NotAuthorizedException
648 public boolean isAuthorizedForVf(String vfInvariantUuid) {
649 if (cldsPermissionTypeFilterVf != null && !cldsPermissionTypeFilterVf.isEmpty()) {
650 SecureServicePermission permission = SecureServicePermission.create(cldsPermissionTypeFilterVf,
651 cldsPermissionInstance, vfInvariantUuid);
652 return isAuthorized(permission);
654 // if CLDS_PERMISSION_TYPE_FILTER_VF property is not provided, then
655 // VF filtering is turned off
656 logger.warn("VF filtering turned off");
662 * Determine if the user is authorized for a particular VF by its invariant
663 * UUID. If not authorized, then NotAuthorizedException is thrown.
668 private boolean isAuthorizedForVf(CldsModel model) {
669 String vf = ModelProperties.getVf(model);
670 if (vf == null || vf.length() == 0) {
671 logger.info("VF not found in model");
674 return isAuthorizedForVf(vf);
678 private String createUiServiceFormatJson(String responseStr) throws IOException {
679 if (StringUtils.isBlank(responseStr)) {
682 ObjectMapper objectMapper = new ObjectMapper();
683 List<CldsSdcServiceInfo> rawList = objectMapper.readValue(responseStr,
684 objectMapper.getTypeFactory().constructCollectionType(List.class, CldsSdcServiceInfo.class));
685 ObjectNode invariantIdServiceNode = objectMapper.createObjectNode();
686 ObjectNode serviceNode = objectMapper.createObjectNode();
687 logger.info("value of cldsserviceiNfolist: {}", rawList);
688 if (rawList != null && !rawList.isEmpty()) {
689 List<CldsSdcServiceInfo> cldsSdcServiceInfoList = sdcCatalogServices.removeDuplicateServices(rawList);
690 for (CldsSdcServiceInfo currCldsSdcServiceInfo : cldsSdcServiceInfoList) {
691 if (currCldsSdcServiceInfo != null) {
692 invariantIdServiceNode.put(currCldsSdcServiceInfo.getInvariantUUID(),
693 currCldsSdcServiceInfo.getName());
696 serviceNode.putPOJO("service", invariantIdServiceNode);
698 return serviceNode.toString();
701 private String createPropertiesObjectByUUID(String globalProps, String cldsResponseStr) throws IOException {
702 ObjectMapper mapper = new ObjectMapper();
703 CldsSdcServiceDetail cldsSdcServiceDetail = mapper.readValue(cldsResponseStr, CldsSdcServiceDetail.class);
704 ObjectNode globalPropsJson = null;
705 if (cldsSdcServiceDetail != null && cldsSdcServiceDetail.getUuid() != null) {
707 * to create json with vf, alarm and locations
709 ObjectNode serviceObjectNode = createEmptyVfAlarmObject(mapper);
710 ObjectNode vfObjectNode = mapper.createObjectNode();
712 * to create json with vf and vfresourceId
714 createVfObjectNode(vfObjectNode, mapper, cldsSdcServiceDetail.getResources());
715 serviceObjectNode.putPOJO(cldsSdcServiceDetail.getInvariantUUID(), vfObjectNode);
716 ObjectNode byServiceBasicObjetNode = mapper.createObjectNode();
717 byServiceBasicObjetNode.putPOJO("byService", serviceObjectNode);
719 * to create json with VFC Node
721 ObjectNode emptyvfcobjectNode = createByVFCObjectNode(mapper, cldsSdcServiceDetail.getResources());
722 byServiceBasicObjetNode.putPOJO("byVf", emptyvfcobjectNode);
723 globalPropsJson = (ObjectNode) mapper.readValue(globalProps, JsonNode.class);
724 globalPropsJson.putPOJO("shared", byServiceBasicObjetNode);
725 logger.info("valuie of objNode: {}", globalPropsJson);
728 * to create json with total properties when no serviceUUID passed
730 globalPropsJson = (ObjectNode) mapper.readValue(globalProps, JsonNode.class);
732 return globalPropsJson.toString();
735 private ObjectNode createEmptyVfAlarmObject(ObjectMapper mapper) {
736 ObjectNode emptyObjectNode = mapper.createObjectNode();
737 emptyObjectNode.put("", "");
738 ObjectNode vfObjectNode = mapper.createObjectNode();
739 vfObjectNode.putPOJO("vf", emptyObjectNode);
740 vfObjectNode.putPOJO("location", emptyObjectNode);
741 vfObjectNode.putPOJO("alarmCondition", emptyObjectNode);
742 ObjectNode emptyServiceObjectNode = mapper.createObjectNode();
743 emptyServiceObjectNode.putPOJO("", vfObjectNode);
744 return emptyServiceObjectNode;
747 private void createVfObjectNode(ObjectNode vfObjectNode2, ObjectMapper mapper,
748 List<CldsSdcResource> rawCldsSdcResourceList) {
749 ObjectNode vfNode = mapper.createObjectNode();
751 // To remove repeated resource instance name from
752 // resourceInstanceList
753 List<CldsSdcResource> cldsSdcResourceList = sdcCatalogServices
754 .removeDuplicateSdcResourceInstances(rawCldsSdcResourceList);
756 * Creating vf resource node using cldsSdcResource Object
758 if (cldsSdcResourceList != null && !cldsSdcResourceList.isEmpty()) {
759 for (CldsSdcResource cldsSdcResource : cldsSdcResourceList) {
760 if (cldsSdcResource != null && "VF".equalsIgnoreCase(cldsSdcResource.getResoucreType())) {
761 vfNode.put(cldsSdcResource.getResourceUUID(), cldsSdcResource.getResourceName());
765 vfObjectNode2.putPOJO("vf", vfNode);
767 * creating location json object using properties file value
769 ObjectNode locationJsonNode;
771 locationJsonNode = (ObjectNode) mapper.readValue(refProp.getStringValue("ui.location.default"),
773 } catch (IOException e) {
774 logger.error("Unable to load ui.location.default JSON in clds-references.properties properly", e);
775 throw new CldsConfigException(
776 "Unable to load ui.location.default JSON in clds-references.properties properly", e);
778 vfObjectNode2.putPOJO("location", locationJsonNode);
780 * creating alarm json object using properties file value
782 String alarmStringValue = refProp.getStringValue("ui.alarm.default");
783 logger.info("value of alarm: {}", alarmStringValue);
784 ObjectNode alarmStringJsonNode;
786 alarmStringJsonNode = (ObjectNode) mapper.readValue(alarmStringValue, JsonNode.class);
787 } catch (IOException e) {
788 logger.error("Unable to ui.alarm.default JSON in clds-references.properties properly", e);
789 throw new CldsConfigException("Unable to load ui.alarm.default JSON in clds-references.properties properly",
792 vfObjectNode2.putPOJO("alarmCondition", alarmStringJsonNode);
795 private ObjectNode createByVFCObjectNode(ObjectMapper mapper, List<CldsSdcResource> cldsSdcResourceList) {
796 ObjectNode emptyObjectNode = mapper.createObjectNode();
797 ObjectNode emptyvfcobjectNode = mapper.createObjectNode();
798 ObjectNode vfCObjectNode = mapper.createObjectNode();
799 vfCObjectNode.putPOJO("vfC", emptyObjectNode);
800 ObjectNode subVfCObjectNode = mapper.createObjectNode();
801 subVfCObjectNode.putPOJO("vfc", emptyObjectNode);
802 if (cldsSdcResourceList != null && !cldsSdcResourceList.isEmpty()) {
803 for (CldsSdcResource cldsSdcResource : cldsSdcResourceList) {
804 if (cldsSdcResource != null && "VF".equalsIgnoreCase(cldsSdcResource.getResoucreType())) {
805 vfCObjectNode.putPOJO(cldsSdcResource.getResourceUUID(), subVfCObjectNode);
809 emptyvfcobjectNode.putPOJO("", vfCObjectNode);
810 return emptyvfcobjectNode;
814 @Path("/deploy/{modelName}")
815 @Consumes(MediaType.APPLICATION_JSON)
816 @Produces(MediaType.APPLICATION_JSON)
817 public CldsModel deployModel(@PathParam("action") String action, @PathParam("modelName") String modelName,
818 @QueryParam("test") String test, CldsModel model) {
819 Date startTime = new Date();
820 LoggingUtils.setRequestContext("CldsService: Deploy model", getPrincipalName());
822 checkForDuplicateServiceVf(modelName, model.getPropText());
823 } catch (IOException | BadRequestException e) {
824 logger.error("Exception occured during duplicate check for service and VF", e);
825 throw new CldsConfigException(e.getMessage(), e);
827 String deploymentId = "";
828 // If model is already deployed then pass same deployment id
829 if (model.getDeploymentId() != null && !model.getDeploymentId().isEmpty()) {
830 deploymentId = model.getDeploymentId();
832 deploymentId = "closedLoop_" + UUID.randomUUID() + "_deploymentId";
834 String createNewDeploymentStatusUrl = dcaeDispatcherServices.createNewDeployment(deploymentId,
836 String operationStatus = "processing";
837 long waitingTime = System.nanoTime() + TimeUnit.MINUTES.toNanos(10);
838 while ("processing".equalsIgnoreCase(operationStatus)) {
839 // Break the loop if waiting for more than 10 mins
840 if (waitingTime < System.nanoTime()) {
843 operationStatus = dcaeDispatcherServices.getOperationStatus(createNewDeploymentStatusUrl);
845 if ("succeeded".equalsIgnoreCase(operationStatus)) {
846 String artifactName = model.getControlName();
847 if (artifactName != null) {
848 artifactName = artifactName + ".yml";
850 DcaeEvent dcaeEvent = new DcaeEvent();
851 /* set dcae events */
852 dcaeEvent.setArtifactName(artifactName);
853 dcaeEvent.setEvent(DcaeEvent.EVENT_DEPLOYMENT);
854 CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), getUserId(), dcaeEvent.getCldsActionCd(),
855 CldsEvent.ACTION_STATE_RECEIVED, null);
856 model.setDeploymentId(deploymentId);
857 model.save(cldsDao, getUserId());
859 logger.info("Deploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
860 throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR,
861 "Deploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
863 logger.info("Deploy model (" + modelName + ") succeeded...Deployment Id is - " + deploymentId);
865 LoggingUtils.setTimeContext(startTime, new Date());
866 LoggingUtils.setResponseContext("0", "Deploy model success", this.getClass().getName());
867 auditLogger.info("Deploy model completed");
872 @Path("/undeploy/{modelName}")
873 @Consumes(MediaType.APPLICATION_JSON)
874 @Produces(MediaType.APPLICATION_JSON)
875 public CldsModel unDeployModel(@PathParam("action") String action, @PathParam("modelName") String modelName,
876 @QueryParam("test") String test, CldsModel model) throws IOException {
877 Date startTime = new Date();
878 LoggingUtils.setRequestContext("CldsService: Undeploy model", getPrincipalName());
879 String operationStatusUndeployUrl = dcaeDispatcherServices.deleteExistingDeployment(model.getDeploymentId(),
881 String operationStatus = "processing";
882 long waitingTime = System.nanoTime() + TimeUnit.MINUTES.toNanos(10);
883 while ("processing".equalsIgnoreCase(operationStatus)) {
884 if (waitingTime < System.nanoTime()) {
887 operationStatus = dcaeDispatcherServices.getOperationStatus(operationStatusUndeployUrl);
889 if ("succeeded".equalsIgnoreCase(operationStatus)) {
890 String artifactName = model.getControlName();
891 if (artifactName != null) {
892 artifactName = artifactName + ".yml";
894 DcaeEvent dcaeEvent = new DcaeEvent();
896 dcaeEvent.setArtifactName(artifactName);
897 dcaeEvent.setEvent(DcaeEvent.EVENT_UNDEPLOYMENT);
898 CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), dcaeEvent.getCldsActionCd(),
899 CldsEvent.ACTION_STATE_RECEIVED, null);
900 model.setDeploymentId(null);
901 model.save(cldsDao, getUserId());
903 logger.info("Undeploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
904 throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR,
905 "Undeploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
907 logger.info("Undeploy model (" + modelName + ") succeeded.");
909 LoggingUtils.setTimeContext(startTime, new Date());
910 LoggingUtils.setResponseContext("0", "Undeploy model success", this.getClass().getName());
911 auditLogger.info("Undeploy model completed");
915 private String getGlobalCldsString() {
917 if (null == globalCldsProperties) {
918 globalCldsProperties = new Properties();
919 globalCldsProperties.load(appContext.getResource(globalClds).getInputStream());
921 return (String) globalCldsProperties.get("globalCldsProps");
922 } catch (IOException e) {
923 logger.error("Unable to load the globalClds due to an exception", e);
924 throw new CldsConfigException("Unable to load the globalClds due to an exception", e);
928 private void checkForDuplicateServiceVf(String modelName, String modelPropText) throws IOException {
929 JsonNode modelJson = new ObjectMapper().readTree(modelPropText);
930 JsonNode globalNode = modelJson.get("global");
931 String service = AbstractModelElement.getValueByName(globalNode, "service");
932 List<String> resourceVf = AbstractModelElement.getValuesByName(globalNode, "vf");
933 if (service != null && resourceVf != null && !resourceVf.isEmpty()) {
934 List<CldsModelProp> cldsModelPropList = cldsDao.getDeployedModelProperties();
935 for (CldsModelProp cldsModelProp : cldsModelPropList) {
936 JsonNode currentJson = new ObjectMapper().readTree(cldsModelProp.getPropText());
937 JsonNode currentNode = currentJson.get("global");
938 String currentService = AbstractModelElement.getValueByName(currentNode, "service");
939 List<String> currentVf = AbstractModelElement.getValuesByName(currentNode, "vf");
940 if (currentVf != null && !currentVf.isEmpty()) {
941 if (!modelName.equalsIgnoreCase(cldsModelProp.getName()) && service.equalsIgnoreCase(currentService)
942 && resourceVf.get(0).equalsIgnoreCase(currentVf.get(0))) {
943 throw new BadRequestException("Same Service/VF already exists in " + cldsModelProp.getName()
944 + " model, please select different Service/VF.");