DCAE-D be initial commit
[sdc/dcae-d/dt-be-main.git] / dcaedt_be / src / main / java / org / onap / sdc / dcae / composition / controller / BlueprintController.java
1 package org.onap.sdc.dcae.composition.controller;
2
3 import org.apache.commons.lang.StringUtils;
4 import org.onap.sdc.common.onaplog.Enums.LogLevel;
5 import org.onap.sdc.dcae.composition.restmodels.MessageResponse;
6 import org.onap.sdc.dcae.catalog.asdc.ASDC;
7 import org.onap.sdc.dcae.catalog.asdc.ASDCUtils;
8 import org.onap.sdc.dcae.catalog.asdc.Blueprinter;
9 import org.onap.sdc.dcae.composition.restmodels.sdc.*;
10 import org.onap.sdc.dcae.utils.Normalizers;
11 import org.onap.sdc.dcae.composition.util.DcaeBeConstants;
12 import org.onap.sdc.dcae.enums.ArtifactType;
13 import org.onap.sdc.dcae.enums.AssetType;
14 import org.onap.sdc.dcae.enums.LifecycleOperationType;
15 import org.onap.sdc.dcae.errormng.ActionStatus;
16 import org.onap.sdc.dcae.errormng.ErrConfMgr;
17 import org.onap.sdc.dcae.errormng.ErrConfMgr.ApiType;
18 import org.onap.sdc.dcae.utils.SdcRestClientUtils;
19 import org.springframework.beans.factory.annotation.Autowired;
20 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
21 import org.springframework.http.HttpStatus;
22 import org.springframework.http.ResponseEntity;
23 import org.springframework.util.Base64Utils;
24 import org.springframework.util.CollectionUtils;
25 import org.springframework.web.bind.annotation.*;
26
27 import javax.annotation.PostConstruct;
28 import java.io.StringReader;
29 import java.net.URI;
30
31 @RestController
32 @EnableAutoConfiguration
33 @CrossOrigin
34 public class BlueprintController extends BaseController{
35
36         @Autowired
37         private Blueprinter blueprinter;
38
39         @Autowired
40         private ASDC asdc;
41
42         private static final String CREATE_DESC = "creating new artifact blueprint on the service vfi";
43         private static final String UPDATE_DESC = "updating artifact blueprint on the service vfi";
44
45
46
47         @PostConstruct
48         public void init(){
49                 URI sdcUri = URI.create(systemProperties.getProperties().getProperty(DcaeBeConstants.Config.URI));
50                 asdc.setUri(sdcUri);
51                 debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "SDC uri: {}", sdcUri);
52         }
53
54         /***
55          * VFCMT - Resource, blueprint - as an artifact as an service. 
56          * @param userId
57          * @param vfcmtUuid
58          * @param serviceUuid
59          * @param serviceInstanceName
60          * @param monitoringFlowType
61          * @return ResponseEntity
62          */
63                 @RequestMapping(value = "/createBluePrint/{VFCMTUuid}/{serviceUuid}/{instanceName}/{monitoringFlowType}", method = RequestMethod.POST)
64                 public ResponseEntity createBluePrint(@RequestHeader("USER_ID") String userId,
65                                 @PathVariable("VFCMTUuid") String vfcmtUuid,
66                                 @PathVariable("serviceUuid") String serviceUuid,
67                                 @PathVariable("instanceName") String serviceInstanceName,
68                                 @PathVariable("monitoringFlowType") String monitoringFlowType,
69                                 @ModelAttribute("requestId") String requestId) {
70                         try {
71                                 
72                                 ResourceDetailed vfcmt = baseBusinessLogic.getSdcRestClient().getResource(vfcmtUuid, requestId);
73                                 debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), vfcmt.toString());
74                                 checkVfcmtType(vfcmt);
75                                 Artifact cdumpArtifactData = findCdumpArtifactData(vfcmt);
76                                 if (null != cdumpArtifactData) {
77                                         debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Found the cdump (composition.yml) on top of VFCMT {}", vfcmtUuid);
78                                         String cdump = baseBusinessLogic.getSdcRestClient().getResourceArtifact(vfcmtUuid, cdumpArtifactData.getArtifactUUID(), requestId);
79                                         debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "---------------------------------------------------------------CDUMP: -----------------------------------------------------------------------------");
80                                         debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), cdump);
81                                         debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "---------------------------------------------------------------------------------------------------------------------------------------------------");
82                                         ASDCUtils utils = new ASDCUtils(asdc, blueprinter);
83
84                                         debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Going to use python procedure to create a blueprint....");
85                                         String resultBlueprintCreation;
86                                         try{
87                                                 resultBlueprintCreation = utils.buildBlueprintViaToscaLab(new StringReader(cdump)).waitForResult().waitForResult();
88                                         }catch (Exception e){
89                                                 return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.GENERATE_BLUEPRINT_ERROR, e.getMessage(), vfcmt.getName());
90                                         }
91                                         if (StringUtils.isEmpty(resultBlueprintCreation)) {
92                                                 return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.GENERATE_BLUEPRINT_ERROR, "", vfcmt.getName());
93                                         }
94
95                                         // 1806 US374595 flowType in cdump
96                                         String flowTypeFromCdump = StringUtils.substringBetween(cdump,"\"flowType\":\"","\"");
97                                         if(StringUtils.isNotBlank(flowTypeFromCdump)) {
98                                                 monitoringFlowType = flowTypeFromCdump;
99                                         }
100                                         // saving to serviceVfInstance
101                                         Artifact savedBluePrint = saveBluePrint(userId, serviceUuid, serviceInstanceName, resultBlueprintCreation, monitoringFlowType, vfcmt.getName(), requestId);
102                                         if(savedBluePrint!=null){
103                                                 MessageResponse response = new MessageResponse();
104                                                 response.setSuccessResponse("Blueprint build complete \n. Blueprint="+savedBluePrint.getArtifactName());
105                                                 //1806 US374593 - certify VFCMT after BP generation
106                                                 certifyVfcmt(vfcmt, requestId);
107                                                 return new ResponseEntity<>(response, HttpStatus.OK);
108                                         }
109                                         else{
110                                                 return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.SUBMIT_BLUEPRINT_ERROR);
111                                         }
112
113                                 }else{
114                                         return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.MISSING_TOSCA_FILE, "", vfcmt.getName());
115                                 }
116                         } catch (Exception e) {
117                                 return handleException(e, ApiType.SUBMIT_BLUEPRINT);
118                         }
119                 }
120                 
121                 
122         /********************* private function ********************/
123
124         /**
125          * @param userId
126          * @param serviceUuid
127          * @param resourceInstanceName
128          * @param bluePrint
129          * @param monitoringFlowType
130          * @param vfcmtName
131          * @param requestId
132          * @return
133          * @throws Exception
134          */
135         private Artifact saveBluePrint(String userId, String serviceUuid, String resourceInstanceName, String bluePrint, String monitoringFlowType, String vfcmtName, String requestId) throws Exception {
136                 
137                 debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "BLUEPRINT:\n{}", bluePrint);
138                 try {
139                         ServiceDetailed service = baseBusinessLogic.getSdcRestClient().getService(serviceUuid, requestId);
140                         //Validations
141                         checkUserIfResourceCheckedOut(userId, service);
142                         ResourceInstance vfi = findVfiOnService(service, resourceInstanceName);
143                         if(null == vfi){
144                                 debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "VF instance {} not found on service {}", resourceInstanceName, serviceUuid);
145                                 return null;
146                         }
147
148                         debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), service.toString());
149
150                         String normalizedArtifactLabel = Normalizers.normalizeArtifactLabel("blueprint-" + monitoringFlowType);
151                         Artifact blueprintArtifact = CollectionUtils.isEmpty(vfi.getArtifacts()) ? null : vfi.getArtifacts().stream()
152                                         .filter(p -> normalizedArtifactLabel.equals(Normalizers.normalizeArtifactLabel(p.getArtifactLabel())))
153                                         .findAny()
154                                         .orElse(null);
155
156                         boolean isNeed2Checkout = isNeedToCheckOut(service.getLifecycleState());
157                         if (isNeed2Checkout) {
158                                 Asset result = checkout(userId, serviceUuid, AssetType.SERVICE, requestId);
159                                 if (result != null) {
160                                         serviceUuid = result.getUuid();
161                                         debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "New service after checkout is: {}", serviceUuid);
162                                 }
163                         }
164                         //update mode
165                         if (null != blueprintArtifact) {
166                                 debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Found that service {} already consist of {} ----> updateMode", serviceUuid, normalizedArtifactLabel);
167                                 blueprintArtifact.setDescription(UPDATE_DESC);
168                                 blueprintArtifact.setPayloadData(Base64Utils.encodeToString(bluePrint.getBytes()));
169                                 blueprintArtifact = baseBusinessLogic.getSdcRestClient().updateVfInstanceArtifact(userId, serviceUuid, Normalizers.normalizeComponentInstanceName(resourceInstanceName), blueprintArtifact, requestId);
170                         //create mode
171                         } else {
172                                 debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Service {} does not consist {} ----> createMode", serviceUuid, normalizedArtifactLabel);
173                                 blueprintArtifact = SdcRestClientUtils.generateDeploymentArtifact(CREATE_DESC, generateBlueprintFileName(monitoringFlowType, vfcmtName), ArtifactType.DCAE_INVENTORY_BLUEPRINT.name(), normalizedArtifactLabel, bluePrint.getBytes());
174                                 blueprintArtifact = baseBusinessLogic.getSdcRestClient().createVfInstanceArtifact(userId, serviceUuid, Normalizers.normalizeComponentInstanceName(resourceInstanceName), blueprintArtifact, requestId);
175                         }
176
177                         //No need to check the service in in 1806
178 //                      Asset blueprintAsJson = checkin(user_id, serviceUuid, AssetType.SERVICE);
179 //                      debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "service result after check-in: {}", blueprintAsJson.toString());
180
181                         return blueprintArtifact;
182
183                 } catch (Exception e) {
184                         errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Error occurred while trying to save blueprint {}", e.toString());
185                         throw e;
186                 }
187         }
188
189         /**
190          * 
191          * @param monitoringFlowType
192          * @param vfcmtName
193          * @return
194          */
195         private String generateBlueprintFileName(String monitoringFlowType, String vfcmtName) {
196                 StringBuffer sb = new StringBuffer();
197                 sb.append(monitoringFlowType);
198                 sb.append(".");
199                 sb.append(Normalizers.normalizeComponentName(vfcmtName));
200                 sb.append(".");
201                 sb.append(DcaeBeConstants.Composition.fileNames.EVENT_PROC_BP_YAML);
202                 return sb.toString();
203         }
204
205         private ResourceInstance findVfiOnService(ServiceDetailed service, String vfiName) {
206                 return null == service ? null : CollectionUtils.isEmpty(service.getResources()) ? null : service.getResources().stream().filter(p -> vfiName.equals(p.getResourceInstanceName())).findAny().orElse(null);
207         }
208
209         private Artifact findCdumpArtifactData(ResourceDetailed vfcmt) {
210                 return null == vfcmt ? null : CollectionUtils.isEmpty(vfcmt.getArtifacts()) ? null : vfcmt.getArtifacts().stream()
211                                 .filter(p -> DcaeBeConstants.Composition.fileNames.COMPOSITION_YML.equals(p.getArtifactName())).findAny().orElse(null);
212         }
213
214         private void certifyVfcmt(ResourceDetailed vfcmt, String requestId){
215                 String state = vfcmt.getLifecycleState();
216                 if(null == state) {
217                         debugLogger.log(LogLevel.ERROR, this.getClass().getName(), "Couldn't read Vfcmt lifecycle state");
218                         return;
219                 }
220                 DcaeBeConstants.LifecycleStateEnum lifeCycleState = DcaeBeConstants.LifecycleStateEnum.findState(state);
221                 if(null == lifeCycleState) {
222                         debugLogger.log(LogLevel.ERROR, this.getClass().getName(), "Undefined lifecycle state: {}", state);
223                         return;
224                 }
225                 try{
226                         switch (lifeCycleState){
227                         case NOT_CERTIFIED_CHECKOUT:
228                                 baseBusinessLogic.getSdcRestClient().changeResourceLifecycleState(vfcmt.getLastUpdaterUserId(), vfcmt.getUuid(), LifecycleOperationType.CHECKIN.name(), "check in VFCMT after blueprint successful submission", requestId);
229                         case NOT_CERTIFIED_CHECKIN:
230                                 baseBusinessLogic.getSdcRestClient().changeResourceLifecycleState(vfcmt.getLastUpdaterUserId(), vfcmt.getUuid(), LifecycleOperationType.CERTIFY.name(), "certify VFCMT after blueprint successful submission", requestId);
231                         }
232                 }
233                 catch (Exception e){
234                         //informative only. no message to user (TBA)
235                         debugLogger.log(LogLevel.ERROR, this.getClass().getName(), "Error occurred during vfcmt lifecycle operation: {}", e.toString());
236                 }
237         }
238
239 }