1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
|
/*-
* ============LICENSE_START=======================================================
* ONAP CLAMP
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights
* reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END============================================
* ===================================================================
* ECOMP is a trademark and service mark of AT&T Intellectual Property.
*/
package org.onap.clamp.clds.service;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.xml.transform.TransformerException;
import org.apache.camel.Produce;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.lang3.StringUtils;
import org.json.simple.parser.ParseException;
import org.onap.clamp.clds.camel.CamelProxy;
import org.onap.clamp.clds.client.DcaeDispatcherServices;
import org.onap.clamp.clds.client.DcaeInventoryServices;
import org.onap.clamp.clds.client.req.sdc.SdcCatalogServices;
import org.onap.clamp.clds.config.CldsReferenceProperties;
import org.onap.clamp.clds.dao.CldsDao;
import org.onap.clamp.clds.exception.CldsConfigException;
import org.onap.clamp.clds.exception.policy.PolicyClientException;
import org.onap.clamp.clds.exception.sdc.SdcCommunicationException;
import org.onap.clamp.clds.model.CLDSMonitoringDetails;
import org.onap.clamp.clds.model.CldsDBServiceCache;
import org.onap.clamp.clds.model.CldsEvent;
import org.onap.clamp.clds.model.CldsHealthCheck;
import org.onap.clamp.clds.model.CldsInfo;
import org.onap.clamp.clds.model.CldsModel;
import org.onap.clamp.clds.model.CldsModelProp;
import org.onap.clamp.clds.model.CldsServiceData;
import org.onap.clamp.clds.model.CldsTemplate;
import org.onap.clamp.clds.model.DcaeEvent;
import org.onap.clamp.clds.model.ValueItem;
import org.onap.clamp.clds.model.properties.AbstractModelElement;
import org.onap.clamp.clds.model.properties.ModelProperties;
import org.onap.clamp.clds.model.sdc.SdcResource;
import org.onap.clamp.clds.model.sdc.SdcServiceDetail;
import org.onap.clamp.clds.model.sdc.SdcServiceInfo;
import org.onap.clamp.clds.transform.XslTransformer;
import org.onap.clamp.clds.util.LoggingUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
/**
* Service to save and retrieve the CLDS model attributes.
*/
@Component
@Path("/clds")
public class CldsService extends SecureServiceBase {
@Produce(uri = "direct:processSubmit")
private CamelProxy camelProxy;
protected static final EELFLogger securityLogger = EELFManager.getInstance().getSecurityLogger();
@Autowired
private ApplicationContext appContext;
private static final String RESOURCE_NAME = "clds-version.properties";
@Value("${CLDS_PERMISSION_TYPE_CL:permission-type-cl}")
private String cldsPersmissionTypeCl;
@Value("${CLDS_PERMISSION_TYPE_CL_MANAGE:permission-type-cl-manage}")
private String cldsPermissionTypeClManage;
@Value("${CLDS_PERMISSION_TYPE_CL_EVENT:permission-type-cl-event}")
private String cldsPermissionTypeClEvent;
@Value("${CLDS_PERMISSION_TYPE_FILTER_VF:permission-type-filter-vf}")
private String cldsPermissionTypeFilterVf;
@Value("${CLDS_PERMISSION_TYPE_TEMPLATE:permission-type-template}")
private String cldsPermissionTypeTemplate;
@Value("${CLDS_PERMISSION_INSTANCE:dev}")
private String cldsPermissionInstance;
private SecureServicePermission permissionReadCl;
private SecureServicePermission permissionUpdateCl;
private SecureServicePermission permissionReadTemplate;
private SecureServicePermission permissionUpdateTemplate;
@PostConstruct
private final void afterConstruction() {
permissionReadCl = SecureServicePermission.create(cldsPersmissionTypeCl, cldsPermissionInstance, "read");
permissionUpdateCl = SecureServicePermission.create(cldsPersmissionTypeCl, cldsPermissionInstance, "update");
permissionReadTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance,
"read");
permissionUpdateTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance,
"update");
}
@Value("${org.onap.clamp.config.files.globalClds:'classpath:/clds/globalClds.properties'}")
private String globalClds;
private Properties globalCldsProperties;
@Autowired
private CldsDao cldsDao;
@Autowired
private XslTransformer cldsBpmnTransformer;
@Autowired
private CldsReferenceProperties refProp;
@Autowired
private SdcCatalogServices sdcCatalogServices;
@Autowired
private DcaeDispatcherServices dcaeDispatcherServices;
@Autowired
private DcaeInventoryServices dcaeInventoryServices;
/*
* @return list of CLDS-Monitoring-Details: CLOSELOOP_NAME | Close loop name
* used in the CLDS application (prefix: ClosedLoop- + unique ClosedLoop ID)
* MODEL_NAME | Model Name in CLDS application SERVICE_TYPE_ID | TypeId
* returned from the DCAE application when the ClosedLoop is submitted
* (DCAEServiceTypeRequest generated in DCAE application). DEPLOYMENT_ID |
* Id generated when the ClosedLoop is deployed in DCAE. TEMPLATE_NAME |
* Template used to generate the ClosedLoop model. ACTION_CD | Current state
* of the ClosedLoop in CLDS application.
*/
@GET
@Path("/cldsDetails")
@Produces(MediaType.APPLICATION_JSON)
public List<CLDSMonitoringDetails> getCLDSDetails() {
Date startTime = new Date();
LoggingUtils.setRequestContext("CldsService: GET model details", getPrincipalName());
List<CLDSMonitoringDetails> cldsMonitoringDetailsList = new ArrayList<CLDSMonitoringDetails>();
cldsMonitoringDetailsList = cldsDao.getCLDSMonitoringDetails();
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
LoggingUtils.setResponseContext("0", "Get cldsDetails success", this.getClass().getName());
auditLogger.info("GET cldsDetails completed");
return cldsMonitoringDetailsList;
}
/*
* CLDS IFO service will return 3 things 1. User Name 2. CLDS code version
* that is currently installed from pom.xml file 3. User permissions
*/
@GET
@Path("/cldsInfo")
@Produces(MediaType.APPLICATION_JSON)
public CldsInfo getCldsInfo() {
CldsInfo cldsInfo = new CldsInfo();
Date startTime = new Date();
LoggingUtils.setRequestContext("CldsService: GET cldsInfo", getPrincipalName());
LoggingUtils.setTimeContext(startTime, new Date());
// Get the user info
cldsInfo.setUserName(getUserName());
// Get CLDS application version
String cldsVersion = "";
Properties props = new Properties();
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try (InputStream resourceStream = loader.getResourceAsStream(RESOURCE_NAME)) {
props.load(resourceStream);
cldsVersion = props.getProperty("clds.version");
} catch (Exception ex) {
logger.error("Exception caught during the clds.version reading", ex);
}
cldsInfo.setCldsVersion(cldsVersion);
// Get the user list of permissions
cldsInfo.setPermissionReadCl(isAuthorizedNoException(permissionReadCl));
cldsInfo.setPermissionUpdateCl(isAuthorizedNoException(permissionUpdateCl));
cldsInfo.setPermissionReadTemplate(isAuthorizedNoException(permissionReadTemplate));
cldsInfo.setPermissionUpdateTemplate(isAuthorizedNoException(permissionUpdateTemplate));
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
LoggingUtils.setResponseContext("0", "Get cldsInfo success", this.getClass().getName());
securityLogger.info("GET cldsInfo completed");
return cldsInfo;
}
/**
* REST service that retrieves clds healthcheck information.
*
* @return CldsHealthCheck class containing healthcheck info
*/
@GET
@Path("/healthcheck")
@Produces(MediaType.APPLICATION_JSON)
public CldsHealthCheck gethealthcheck() {
CldsHealthCheck cldsHealthCheck = new CldsHealthCheck();
Date startTime = new Date();
LoggingUtils.setRequestContext("CldsService: GET healthcheck", getPrincipalName());
LoggingUtils.setTimeContext(startTime, new Date());
try {
cldsDao.doHealthCheck();
cldsHealthCheck.setHealthCheckComponent("CLDS-APP");
cldsHealthCheck.setHealthCheckStatus("UP");
cldsHealthCheck.setDescription("OK");
} catch (Exception e) {
logger.error("CLAMP application DB Error", e);
cldsHealthCheck.setHealthCheckComponent("CLDS-APP");
cldsHealthCheck.setHealthCheckStatus("DOWN");
cldsHealthCheck.setDescription("NOT-OK");
}
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
LoggingUtils.setResponseContext("0", "Get healthcheck success", this.getClass().getName());
securityLogger.info("GET healthcheck completed");
return cldsHealthCheck;
}
/**
* REST service that retrieves BPMN for a CLDS model name from the database.
* This is subset of the json getModel. This is only expected to be used for
* testing purposes, not by the UI.
*
* @param modelName
* @return bpmn xml text - content of bpmn given name
*/
@GET
@Path("/model/bpmn/{modelName}")
@Produces(MediaType.TEXT_XML)
public String getBpmnXml(@PathParam("modelName") String modelName) {
Date startTime = new Date();
LoggingUtils.setRequestContext("CldsService: GET model bpmn", getPrincipalName());
isAuthorized(permissionReadCl);
logger.info("GET bpmnText for modelName={}", modelName);
CldsModel model = CldsModel.retrieve(cldsDao, modelName, false);
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
LoggingUtils.setResponseContext("0", "Get model bpmn success", this.getClass().getName());
auditLogger.info("GET model bpmn completed");
return model.getBpmnText();
}
/**
* REST service that retrieves image for a CLDS model name from the
* database. This is subset of the json getModel. This is only expected to
* be used for testing purposes, not by the UI.
*
* @param modelName
* @return image xml text - content of image given name
*/
@GET
@Path("/model/image/{modelName}")
@Produces(MediaType.TEXT_XML)
public String getImageXml(@PathParam("modelName") String modelName) {
Date startTime = new Date();
LoggingUtils.setRequestContext("CldsService: GET model image", getPrincipalName());
isAuthorized(permissionReadCl);
logger.info("GET imageText for modelName={}", modelName);
CldsModel model = CldsModel.retrieve(cldsDao, modelName, false);
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
LoggingUtils.setResponseContext("0", "Get model image success", this.getClass().getName());
auditLogger.info("GET model image completed");
return model.getImageText();
}
/**
* REST service that retrieves a CLDS model by name from the database.
*
* @param modelName
* @return clds model - clds model for the given model name
*/
@GET
@Path("/model/{modelName}")
@Produces(MediaType.APPLICATION_JSON)
public CldsModel getModel(@PathParam("modelName") String modelName) {
Date startTime = new Date();
LoggingUtils.setRequestContext("CldsService: GET model", getPrincipalName());
isAuthorized(permissionReadCl);
logger.debug("GET model for modelName={}", modelName);
CldsModel cldsModel = CldsModel.retrieve(cldsDao, modelName, false);
isAuthorizedForVf(cldsModel);
// Checking condition whether our CLDS model can call Inventory Method
if (cldsModel.canInventoryCall()) {
try {
// Method to call dcae inventory and invoke insert event method
dcaeInventoryServices.setEventInventory(cldsModel, getUserId());
} catch (Exception e) {
LoggingUtils.setErrorContext("900", "Set event inventory error");
logger.error("getModel set event Inventory error:" + e);
}
}
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
LoggingUtils.setResponseContext("0", "Get model success", this.getClass().getName());
auditLogger.info("GET model completed");
return cldsModel;
}
/**
* REST service that saves a CLDS model by name in the database.
*
* @param modelName
*/
@PUT
@Path("/model/{modelName}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CldsModel putModel(@PathParam("modelName") String modelName, CldsModel cldsModel) {
Date startTime = new Date();
LoggingUtils.setRequestContext("CldsService: PUT model", getPrincipalName());
isAuthorized(permissionUpdateCl);
isAuthorizedForVf(cldsModel);
logger.info("PUT model for modelName={}", modelName);
logger.info("PUT bpmnText={}", cldsModel.getBpmnText());
logger.info("PUT propText={}", cldsModel.getPropText());
logger.info("PUT imageText={}", cldsModel.getImageText());
cldsModel.setName(modelName);
if (cldsModel.getTemplateName() != null) {
CldsTemplate template = cldsDao.getTemplate(cldsModel.getTemplateName());
if (template != null) {
cldsModel.setTemplateId(template.getId());
cldsModel.setDocText(template.getPropText());
// This is to provide the Bpmn XML when Template part in UI is
// disabled
cldsModel.setBpmnText(template.getBpmnText());
}
}
cldsModel.save(cldsDao, getUserId());
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
LoggingUtils.setResponseContext("0", "Put model success", this.getClass().getName());
auditLogger.info("PUT model completed");
return cldsModel;
}
/**
* REST service that retrieves a list of CLDS model names.
*
* @return model names in JSON
*/
@GET
@Path("/model-names")
@Produces(MediaType.APPLICATION_JSON)
public List<ValueItem> getModelNames() {
Date startTime = new Date();
LoggingUtils.setRequestContext("CldsService: GET model names", getPrincipalName());
isAuthorized(permissionReadCl);
logger.info("GET list of model names");
List<ValueItem> names = cldsDao.getBpmnNames();
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
LoggingUtils.setResponseContext("0", "Get model names success", this.getClass().getName());
auditLogger.info("GET model names completed");
return names;
}
/**
* REST service that saves and processes an action for a CLDS model by name.
*
* @param action
* @param modelName
* @param test
* @param model
* @return
* @throws TransformerException
* In case of issues when doing the XSLT of the BPMN flow
* @throws ParseException
* In case of issues when parsing the JSON
* @throws GeneralSecurityException
* In case of issues when decrypting the password
* @throws DecoderException
* In case of issues with the Hex String decoding
*/
@PUT
@Path("/action/{action}/{modelName}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CldsModel putModelAndProcessAction(@PathParam("action") String action,
@PathParam("modelName") String modelName, @QueryParam("test") String test, CldsModel model)
throws TransformerException, ParseException, GeneralSecurityException, DecoderException {
Date startTime = new Date();
LoggingUtils.setRequestContext("CldsService: Process model action", getPrincipalName());
String actionCd = action.toUpperCase();
SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage,
cldsPermissionInstance, actionCd);
isAuthorized(permisionManage);
isAuthorizedForVf(model);
String userId = getUserId();
String actionStateCd = CldsEvent.ACTION_STATE_INITIATED;
String processDefinitionKey = "clds-process-action-wf";
logger.info("PUT actionCd={}", actionCd);
logger.info("PUT actionStateCd={}", actionStateCd);
logger.info("PUT processDefinitionKey={}", processDefinitionKey);
logger.info("PUT modelName={}", modelName);
logger.info("PUT test={}", test);
logger.info("PUT bpmnText={}", model.getBpmnText());
logger.info("PUT propText={}", model.getPropText());
logger.info("PUT userId={}", userId);
logger.info("PUT getTypeId={}", model.getTypeId());
logger.info("PUT deploymentId={}", model.getDeploymentId());
if (model.getTemplateName() != null) {
CldsTemplate template = cldsDao.getTemplate(model.getTemplateName());
if (template != null) {
model.setTemplateId(template.getId());
model.setDocText(template.getPropText());
// This is to provide the Bpmn XML when Template part in UI is
// disabled
model.setBpmnText(template.getBpmnText());
}
}
// save model to db
model.setName(modelName);
model.save(cldsDao, getUserId());
// get vars and format if necessary
String prop = model.getPropText();
String bpmn = model.getBpmnText();
String docText = model.getDocText();
String controlName = model.getControlName();
String bpmnJson = cldsBpmnTransformer.doXslTransformToString(bpmn);
logger.info("PUT bpmnJson={}", bpmnJson);
// Flag indicates whether it is triggered by Validation Test button from
// UI
boolean isTest = false;
if (test != null && test.equalsIgnoreCase("true")) {
isTest = true;
} else {
String actionTestOverride = refProp.getStringValue("action.test.override");
if (actionTestOverride != null && actionTestOverride.equalsIgnoreCase("true")) {
logger.info("PUT actionTestOverride={}", actionTestOverride);
logger.info("PUT override test indicator and setting it to true");
isTest = true;
}
}
logger.info("PUT isTest={}", isTest);
boolean isInsertTestEvent = false;
String insertTestEvent = refProp.getStringValue("action.insert.test.event");
if (insertTestEvent != null && insertTestEvent.equalsIgnoreCase("true")) {
isInsertTestEvent = true;
}
logger.info("PUT isInsertTestEvent={}", isInsertTestEvent);
// determine if requested action is permitted
model.validateAction(actionCd);
logger.info("modelProp - " + prop);
logger.info("docText - " + docText);
try {
String result = camelProxy.submit(actionCd, prop, bpmnJson, modelName, controlName, docText, isTest, userId,
isInsertTestEvent);
logger.info("Starting Camel flow on request, result is: ", result);
} catch (SdcCommunicationException | PolicyClientException | BadRequestException e) {
logger.error("Exception occured during invoking Camel process", e);
throw new CldsConfigException(e.getMessage(), e);
}
// refresh model info from db (get fresh event info)
CldsModel retreivedModel = CldsModel.retrieve(cldsDao, modelName, false);
if (!isTest && (actionCd.equalsIgnoreCase(CldsEvent.ACTION_SUBMIT)
|| actionCd.equalsIgnoreCase(CldsEvent.ACTION_RESUBMIT)
|| actionCd.equalsIgnoreCase(CldsEvent.ACTION_SUBMITDCAE))) {
// To verify inventory status and modify model status to distribute
dcaeInventoryServices.setEventInventory(retreivedModel, getUserId());
retreivedModel.save(cldsDao, getUserId());
}
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
LoggingUtils.setResponseContext("0", "Process model action success", this.getClass().getName());
auditLogger.info("Process model action completed");
return retreivedModel;
}
/**
* REST service that accepts events for a model.
*
* @param test
* @param dcaeEvent
*/
@POST
@Path("/dcae/event")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String postDcaeEvent(@QueryParam("test") String test, DcaeEvent dcaeEvent) {
Date startTime = new Date();
LoggingUtils.setRequestContext("CldsService: Post dcae event", getPrincipalName());
String userid = null;
// TODO: allow auth checking to be turned off by removing the permission
// type property
if (cldsPermissionTypeClEvent != null && cldsPermissionTypeClEvent.length() > 0) {
SecureServicePermission permissionEvent = SecureServicePermission.create(cldsPermissionTypeClEvent,
cldsPermissionInstance, dcaeEvent.getEvent());
isAuthorized(permissionEvent);
userid = getUserId();
}
// Flag indicates whether it is triggered by Validation Test button from
// UI
boolean isTest = false;
if (test != null && test.equalsIgnoreCase("true")) {
isTest = true;
}
int instanceCount = 0;
if (dcaeEvent.getInstances() != null) {
instanceCount = dcaeEvent.getInstances().size();
}
String msgInfo = "event=" + dcaeEvent.getEvent() + " serviceUUID=" + dcaeEvent.getServiceUUID()
+ " resourceUUID=" + dcaeEvent.getResourceUUID() + " artifactName=" + dcaeEvent.getArtifactName()
+ " instance count=" + instanceCount + " isTest=" + isTest;
logger.info("POST dcae event {}", msgInfo);
if (isTest) {
logger.warn("Ignorning test event from DCAE");
} else {
if (DcaeEvent.EVENT_DEPLOYMENT.equalsIgnoreCase(dcaeEvent.getEvent())) {
CldsModel.insertModelInstance(cldsDao, dcaeEvent, userid);
} else {
CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userid, dcaeEvent.getCldsActionCd(),
CldsEvent.ACTION_STATE_RECEIVED, null);
}
}
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
LoggingUtils.setResponseContext("0", "Post dcae event success", this.getClass().getName());
auditLogger.info("Post dcae event completed");
return msgInfo;
}
/**
* REST service that retrieves sdc services
*
* @throws GeneralSecurityException
* In case of issue when decryting the SDC password
* @throws DecoderException
* In case of issues with the decoding of the Hex String
*/
@GET
@Path("/sdc/services")
@Produces(MediaType.APPLICATION_JSON)
public String getSdcServices() throws GeneralSecurityException, DecoderException {
Date startTime = new Date();
LoggingUtils.setRequestContext("CldsService: GET sdc services", getPrincipalName());
String retStr;
String responseStr = sdcCatalogServices.getSdcServicesInformation(null);
try {
retStr = createUiServiceFormatJson(responseStr);
} catch (IOException e) {
logger.error("IOException during SDC communication", e);
throw new SdcCommunicationException("IOException during SDC communication", e);
}
logger.info("value of sdcServices : {}", retStr);
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
LoggingUtils.setResponseContext("0", "Get sdc services success", this.getClass().getName());
auditLogger.info("GET sdc services completed");
return retStr;
}
/**
* REST service that retrieves total properties required by UI
*
* @throws IOException
* In case of issues
*/
@GET
@Path("/properties")
@Produces(MediaType.APPLICATION_JSON)
public String getSdcProperties() throws IOException {
return createPropertiesObjectByUUID(getGlobalCldsString(), "{}");
}
/**
* REST service that retrieves total properties by using invariantUUID based
* on refresh and non refresh
*
* @throws GeneralSecurityException
* In case of issues with the decryting the encrypted password
* @throws DecoderException
* In case of issues with the decoding of the Hex String
* @throws IOException
* In case of issue to convert CldsServiceCache to InputStream
*/
@GET
@Path("/properties/{serviceInvariantUUID}")
@Produces(MediaType.APPLICATION_JSON)
public String getSdcPropertiesByServiceUUIDForRefresh(
@PathParam("serviceInvariantUUID") String serviceInvariantUUID,
@DefaultValue("false") @QueryParam("refresh") boolean refresh)
throws GeneralSecurityException, DecoderException, IOException {
Date startTime = new Date();
LoggingUtils.setRequestContext("CldsService: GET sdc properties by uuid", getPrincipalName());
CldsServiceData cldsServiceData = new CldsServiceData();
cldsServiceData.setServiceInvariantUUID(serviceInvariantUUID);
if (!refresh) {
cldsServiceData = cldsDao.getCldsServiceCache(serviceInvariantUUID);
}
if (sdcCatalogServices.isCldsSdcCacheDataExpired(cldsServiceData)) {
cldsServiceData = sdcCatalogServices.getCldsServiceDataWithAlarmConditions(serviceInvariantUUID);
cldsDao.setCldsServiceCache(new CldsDBServiceCache(cldsServiceData));
}
// filter out VFs the user is not authorized for
cldsServiceData.filterVfs(this);
// format retrieved data into properties json
String sdcProperties = sdcCatalogServices.createPropertiesObjectByUUID(getGlobalCldsString(), cldsServiceData);
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
LoggingUtils.setResponseContext("0", "Get sdc properties by uuid success", this.getClass().getName());
auditLogger.info("GET sdc properties by uuid completed");
return sdcProperties;
}
/**
* Determine if the user is authorized for a particular VF by its invariant
* UUID.
*
* @param vfInvariantUuid
* @throws NotAuthorizedException
* @return
*/
public boolean isAuthorizedForVf(String vfInvariantUuid) {
if (cldsPermissionTypeFilterVf != null && !cldsPermissionTypeFilterVf.isEmpty()) {
SecureServicePermission permission = SecureServicePermission.create(cldsPermissionTypeFilterVf,
cldsPermissionInstance, vfInvariantUuid);
return isAuthorized(permission);
} else {
// if CLDS_PERMISSION_TYPE_FILTER_VF property is not provided, then
// VF filtering is turned off
logger.warn("VF filtering turned off");
return true;
}
}
/**
* Determine if the user is authorized for a particular VF by its invariant
* UUID. If not authorized, then NotAuthorizedException is thrown.
*
* @param model
* @return
*/
private boolean isAuthorizedForVf(CldsModel model) {
String vf = ModelProperties.getVf(model);
if (vf == null || vf.length() == 0) {
logger.info("VF not found in model");
return true;
} else {
return isAuthorizedForVf(vf);
}
}
private String createUiServiceFormatJson(String responseStr) throws IOException {
if (StringUtils.isBlank(responseStr)) {
return "";
}
ObjectMapper objectMapper = new ObjectMapper();
List<SdcServiceInfo> rawList = objectMapper.readValue(responseStr,
objectMapper.getTypeFactory().constructCollectionType(List.class, SdcServiceInfo.class));
ObjectNode invariantIdServiceNode = objectMapper.createObjectNode();
ObjectNode serviceNode = objectMapper.createObjectNode();
logger.info("value of cldsserviceiNfolist: {}", rawList);
if (rawList != null && !rawList.isEmpty()) {
List<SdcServiceInfo> cldsSdcServiceInfoList = sdcCatalogServices.removeDuplicateServices(rawList);
for (SdcServiceInfo currCldsSdcServiceInfo : cldsSdcServiceInfoList) {
if (currCldsSdcServiceInfo != null) {
invariantIdServiceNode.put(currCldsSdcServiceInfo.getInvariantUUID(),
currCldsSdcServiceInfo.getName());
}
}
serviceNode.putPOJO("service", invariantIdServiceNode);
}
return serviceNode.toString();
}
private String createPropertiesObjectByUUID(String globalProps, String cldsResponseStr) throws IOException {
ObjectMapper mapper = new ObjectMapper();
SdcServiceDetail cldsSdcServiceDetail = mapper.readValue(cldsResponseStr, SdcServiceDetail.class);
ObjectNode globalPropsJson = null;
if (cldsSdcServiceDetail != null && cldsSdcServiceDetail.getUuid() != null) {
/**
* to create json with vf, alarm and locations
*/
ObjectNode serviceObjectNode = createEmptyVfAlarmObject(mapper);
ObjectNode vfObjectNode = mapper.createObjectNode();
/**
* to create json with vf and vfresourceId
*/
createVfObjectNode(vfObjectNode, mapper, cldsSdcServiceDetail.getResources());
serviceObjectNode.putPOJO(cldsSdcServiceDetail.getInvariantUUID(), vfObjectNode);
ObjectNode byServiceBasicObjetNode = mapper.createObjectNode();
byServiceBasicObjetNode.putPOJO("byService", serviceObjectNode);
/**
* to create json with VFC Node
*/
ObjectNode emptyvfcobjectNode = createByVFCObjectNode(mapper, cldsSdcServiceDetail.getResources());
byServiceBasicObjetNode.putPOJO("byVf", emptyvfcobjectNode);
globalPropsJson = (ObjectNode) mapper.readValue(globalProps, JsonNode.class);
globalPropsJson.putPOJO("shared", byServiceBasicObjetNode);
logger.info("valuie of objNode: {}", globalPropsJson);
} else {
/**
* to create json with total properties when no serviceUUID passed
*/
globalPropsJson = (ObjectNode) mapper.readValue(globalProps, JsonNode.class);
}
return globalPropsJson.toString();
}
private ObjectNode createEmptyVfAlarmObject(ObjectMapper mapper) {
ObjectNode emptyObjectNode = mapper.createObjectNode();
emptyObjectNode.put("", "");
ObjectNode vfObjectNode = mapper.createObjectNode();
vfObjectNode.putPOJO("vf", emptyObjectNode);
vfObjectNode.putPOJO("location", emptyObjectNode);
vfObjectNode.putPOJO("alarmCondition", emptyObjectNode);
ObjectNode emptyServiceObjectNode = mapper.createObjectNode();
emptyServiceObjectNode.putPOJO("", vfObjectNode);
return emptyServiceObjectNode;
}
private void createVfObjectNode(ObjectNode vfObjectNode2, ObjectMapper mapper,
List<SdcResource> rawCldsSdcResourceList) {
ObjectNode vfNode = mapper.createObjectNode();
vfNode.put("", "");
// To remove repeated resource instance name from
// resourceInstanceList
List<SdcResource> cldsSdcResourceList = sdcCatalogServices
.removeDuplicateSdcResourceInstances(rawCldsSdcResourceList);
/**
* Creating vf resource node using cldsSdcResource Object
*/
if (cldsSdcResourceList != null && !cldsSdcResourceList.isEmpty()) {
for (SdcResource cldsSdcResource : cldsSdcResourceList) {
if (cldsSdcResource != null && "VF".equalsIgnoreCase(cldsSdcResource.getResoucreType())) {
vfNode.put(cldsSdcResource.getResourceUUID(), cldsSdcResource.getResourceName());
}
}
}
vfObjectNode2.putPOJO("vf", vfNode);
/**
* creating location json object using properties file value
*/
ObjectNode locationJsonNode;
try {
locationJsonNode = (ObjectNode) mapper.readValue(refProp.getStringValue("ui.location.default"),
JsonNode.class);
} catch (IOException e) {
logger.error("Unable to load ui.location.default JSON in clds-references.properties properly", e);
throw new CldsConfigException(
"Unable to load ui.location.default JSON in clds-references.properties properly", e);
}
vfObjectNode2.putPOJO("location", locationJsonNode);
/**
* creating alarm json object using properties file value
*/
String alarmStringValue = refProp.getStringValue("ui.alarm.default");
logger.info("value of alarm: {}", alarmStringValue);
ObjectNode alarmStringJsonNode;
try {
alarmStringJsonNode = (ObjectNode) mapper.readValue(alarmStringValue, JsonNode.class);
} catch (IOException e) {
logger.error("Unable to ui.alarm.default JSON in clds-references.properties properly", e);
throw new CldsConfigException("Unable to load ui.alarm.default JSON in clds-references.properties properly",
e);
}
vfObjectNode2.putPOJO("alarmCondition", alarmStringJsonNode);
}
private ObjectNode createByVFCObjectNode(ObjectMapper mapper, List<SdcResource> cldsSdcResourceList) {
ObjectNode emptyObjectNode = mapper.createObjectNode();
ObjectNode emptyvfcobjectNode = mapper.createObjectNode();
ObjectNode vfCObjectNode = mapper.createObjectNode();
vfCObjectNode.putPOJO("vfC", emptyObjectNode);
ObjectNode subVfCObjectNode = mapper.createObjectNode();
subVfCObjectNode.putPOJO("vfc", emptyObjectNode);
if (cldsSdcResourceList != null && !cldsSdcResourceList.isEmpty()) {
for (SdcResource cldsSdcResource : cldsSdcResourceList) {
if (cldsSdcResource != null && "VF".equalsIgnoreCase(cldsSdcResource.getResoucreType())) {
vfCObjectNode.putPOJO(cldsSdcResource.getResourceUUID(), subVfCObjectNode);
}
}
}
emptyvfcobjectNode.putPOJO("", vfCObjectNode);
return emptyvfcobjectNode;
}
@PUT
@Path("/deploy/{modelName}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CldsModel deployModel(@PathParam("action") String action, @PathParam("modelName") String modelName,
@QueryParam("test") String test, CldsModel model) {
Date startTime = new Date();
LoggingUtils.setRequestContext("CldsService: Deploy model", getPrincipalName());
try {
checkForDuplicateServiceVf(modelName, model.getPropText());
} catch (IOException | BadRequestException e) {
logger.error("Exception occured during duplicate check for service and VF", e);
throw new CldsConfigException(e.getMessage(), e);
}
String deploymentId = "";
// If model is already deployed then pass same deployment id
if (model.getDeploymentId() != null && !model.getDeploymentId().isEmpty()) {
deploymentId = model.getDeploymentId();
} else {
deploymentId = "closedLoop_" + UUID.randomUUID() + "_deploymentId";
}
String createNewDeploymentStatusUrl = dcaeDispatcherServices.createNewDeployment(deploymentId,
model.getTypeId());
String operationStatus = "processing";
long waitingTime = System.nanoTime() + TimeUnit.MINUTES.toNanos(10);
while ("processing".equalsIgnoreCase(operationStatus)) {
// Break the loop if waiting for more than 10 mins
if (waitingTime < System.nanoTime()) {
break;
}
operationStatus = dcaeDispatcherServices.getOperationStatus(createNewDeploymentStatusUrl);
}
if ("succeeded".equalsIgnoreCase(operationStatus)) {
String artifactName = model.getControlName();
if (artifactName != null) {
artifactName = artifactName + ".yml";
}
DcaeEvent dcaeEvent = new DcaeEvent();
/* set dcae events */
dcaeEvent.setArtifactName(artifactName);
dcaeEvent.setEvent(DcaeEvent.EVENT_DEPLOYMENT);
CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), getUserId(), dcaeEvent.getCldsActionCd(),
CldsEvent.ACTION_STATE_RECEIVED, null);
model.setDeploymentId(deploymentId);
model.save(cldsDao, getUserId());
} else {
logger.info("Deploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR,
"Deploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
}
logger.info("Deploy model (" + modelName + ") succeeded...Deployment Id is - " + deploymentId);
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
LoggingUtils.setResponseContext("0", "Deploy model success", this.getClass().getName());
auditLogger.info("Deploy model completed");
return model;
}
@PUT
@Path("/undeploy/{modelName}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CldsModel unDeployModel(@PathParam("action") String action, @PathParam("modelName") String modelName,
@QueryParam("test") String test, CldsModel model) throws IOException {
Date startTime = new Date();
LoggingUtils.setRequestContext("CldsService: Undeploy model", getPrincipalName());
String operationStatusUndeployUrl = dcaeDispatcherServices.deleteExistingDeployment(model.getDeploymentId(),
model.getTypeId());
String operationStatus = "processing";
long waitingTime = System.nanoTime() + TimeUnit.MINUTES.toNanos(10);
while ("processing".equalsIgnoreCase(operationStatus)) {
if (waitingTime < System.nanoTime()) {
break;
}
operationStatus = dcaeDispatcherServices.getOperationStatus(operationStatusUndeployUrl);
}
if ("succeeded".equalsIgnoreCase(operationStatus)) {
String artifactName = model.getControlName();
if (artifactName != null) {
artifactName = artifactName + ".yml";
}
DcaeEvent dcaeEvent = new DcaeEvent();
// set dcae events
dcaeEvent.setArtifactName(artifactName);
dcaeEvent.setEvent(DcaeEvent.EVENT_UNDEPLOYMENT);
CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), dcaeEvent.getCldsActionCd(),
CldsEvent.ACTION_STATE_RECEIVED, null);
model.setDeploymentId(null);
model.save(cldsDao, getUserId());
} else {
logger.info("Undeploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR,
"Undeploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
}
logger.info("Undeploy model (" + modelName + ") succeeded.");
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
LoggingUtils.setResponseContext("0", "Undeploy model success", this.getClass().getName());
auditLogger.info("Undeploy model completed");
return model;
}
private String getGlobalCldsString() {
try {
if (null == globalCldsProperties) {
globalCldsProperties = new Properties();
globalCldsProperties.load(appContext.getResource(globalClds).getInputStream());
}
return (String) globalCldsProperties.get("globalCldsProps");
} catch (IOException e) {
logger.error("Unable to load the globalClds due to an exception", e);
throw new CldsConfigException("Unable to load the globalClds due to an exception", e);
}
}
private void checkForDuplicateServiceVf(String modelName, String modelPropText) throws IOException {
JsonNode modelJson = new ObjectMapper().readTree(modelPropText);
JsonNode globalNode = modelJson.get("global");
String service = AbstractModelElement.getValueByName(globalNode, "service");
List<String> resourceVf = AbstractModelElement.getValuesByName(globalNode, "vf");
if (service != null && resourceVf != null && !resourceVf.isEmpty()) {
List<CldsModelProp> cldsModelPropList = cldsDao.getDeployedModelProperties();
for (CldsModelProp cldsModelProp : cldsModelPropList) {
JsonNode currentJson = new ObjectMapper().readTree(cldsModelProp.getPropText());
JsonNode currentNode = currentJson.get("global");
String currentService = AbstractModelElement.getValueByName(currentNode, "service");
List<String> currentVf = AbstractModelElement.getValuesByName(currentNode, "vf");
if (currentVf != null && !currentVf.isEmpty()) {
if (!modelName.equalsIgnoreCase(cldsModelProp.getName()) && service.equalsIgnoreCase(currentService)
&& resourceVf.get(0).equalsIgnoreCase(currentVf.get(0))) {
throw new BadRequestException("Same Service/VF already exists in " + cldsModelProp.getName()
+ " model, please select different Service/VF.");
}
}
}
}
}
}
|