587337b647ce4ef8c1e571b00a15597087f4c905
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.infrastructure.scripts
24
25
26 import com.google.common.reflect.TypeToken
27 import com.google.gson.Gson
28 import org.apache.http.util.EntityUtils
29 import org.onap.so.bpmn.common.resource.InstanceResourceList
30 import org.onap.so.bpmn.common.scripts.CatalogDbUtilsFactory
31 import org.onap.so.bpmn.core.domain.GroupResource
32 import org.onap.so.bpmn.core.domain.ModelInfo
33 import org.onap.so.bpmn.core.domain.ResourceType
34 import org.onap.so.bpmn.infrastructure.properties.BPMNProperties
35 import org.apache.commons.lang3.StringUtils
36 import org.apache.http.HttpResponse
37 import org.camunda.bpm.engine.delegate.BpmnError
38 import org.camunda.bpm.engine.delegate.DelegateExecution
39 import org.json.JSONObject
40 import org.onap.so.bpmn.common.recipe.BpmnRestClient
41 import org.onap.so.bpmn.common.recipe.ResourceInput
42 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
43 import org.onap.so.bpmn.common.scripts.CatalogDbUtils
44 import org.onap.so.bpmn.common.scripts.ExceptionUtil
45 import org.onap.so.bpmn.core.domain.AllottedResource
46 import org.onap.so.bpmn.core.domain.NetworkResource
47 import org.onap.so.bpmn.core.domain.Resource
48 import org.onap.so.bpmn.core.domain.ServiceDecomposition
49 import org.onap.so.bpmn.core.domain.VnfResource
50 import org.onap.so.bpmn.core.json.JsonUtils
51 import org.onap.so.bpmn.common.resource.ResourceRequestBuilder
52 import org.slf4j.Logger
53 import org.slf4j.LoggerFactory
54
55 import java.lang.reflect.Type
56
57
58 /**
59  * This groovy class supports the <class>DoCreateResources.bpmn</class> process.
60  *
61  * Inputs:
62  * @param - msoRequestId
63  * @param - globalSubscriberId - O
64  * @param - subscriptionServiceType - O
65  * @param - serviceInstanceId
66  * @param - serviceInstanceName - O
67  * @param - serviceInputParams (should contain aic_zone for serviceTypes TRANSPORT,ATM)
68  * @param - sdncVersion
69  *
70  * @param - addResourceList
71  *
72  * Outputs:
73  * @param - WorkflowException
74  */
75 public class DoCreateResources extends AbstractServiceTaskProcessor{
76     private static final Logger logger = LoggerFactory.getLogger( DoCreateResources.class);
77
78     ExceptionUtil exceptionUtil = new ExceptionUtil()
79     JsonUtils jsonUtil = new JsonUtils()
80     CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create()
81
82     public void preProcessRequest(DelegateExecution execution) {
83         logger.trace("preProcessRequest ")
84         String msg = ""
85
86         List addResourceList = execution.getVariable("addResourceList")
87         if (addResourceList == null) {
88             msg = "Input addResourceList is null"
89             logger.info(msg)
90             exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
91         }
92         else if (addResourceList.size() == 0) {
93             msg = "No resource in addResourceList"
94             logger.info(msg)
95         }
96         logger.trace("Exit preProcessRequest ")
97     }
98
99     // this method will convert resource list to instance_resource_list
100     public void prepareInstanceResourceList(DelegateExecution execution) {
101
102         String uuiRequest = execution.getVariable("uuiRequest")
103         List<Resource> sequencedResourceList = execution.getVariable("sequencedResourceList")
104         List<Resource> instanceResourceList = InstanceResourceList.getInstanceResourceList(sequencedResourceList, uuiRequest)
105
106         execution.setVariable("instanceResourceList", instanceResourceList)
107     }
108
109     public void sequenceResoure(DelegateExecution execution) {
110         logger.trace("Start sequenceResoure Process ")
111
112         String incomingRequest = execution.getVariable("uuiRequest")
113         String serviceModelUuid = jsonUtil.getJsonValue(incomingRequest,"service.serviceUuid")
114
115         List<Resource> addResourceList = execution.getVariable("addResourceList")
116
117         List<NetworkResource> networkResourceList = new ArrayList<NetworkResource>()
118
119         List<Resource> sequencedResourceList = new ArrayList<Resource>()
120
121         String serviceDecompose = execution.getVariable("serviceDecomposition")
122         String serviceModelName = jsonUtil.getJsonValue(serviceDecompose, "serviceResources.modelInfo.modelName")
123
124         // get Sequence from properties
125         def resourceSequence = BPMNProperties.getResourceSequenceProp(serviceModelName)
126
127         // get Sequence from csar(model)
128         if(resourceSequence == null) {
129             resourceSequence = ResourceRequestBuilder.getResourceSequence(serviceModelUuid)
130             logger.info("Get Sequence from csar : " + resourceSequence)
131         }
132
133         if(resourceSequence != null) {
134             for (resourceType in resourceSequence) {
135                 for (resource in addResourceList) {
136                     if (StringUtils.containsIgnoreCase(resource.getModelInfo().getModelName(), resourceType)) {
137                         sequencedResourceList.add(resource)
138
139                         // if resource type is vnfResource then check for groups also
140                         // Did not use continue because if same model type is used twice
141                         // then we would like to add it twice for processing
142                         // e.g.  S{ V1{G1, G2, G1}} --> S{ V1{G1, G1, G2}}
143                         if (resource instanceof VnfResource) {
144                             if (resource.getGroupOrder() != null && !StringUtils.isEmpty(resource.getGroupOrder())) {
145                                 String[] grpSequence = resource.getGroupOrder().split(",")
146                                 for (String grpType in grpSequence) {
147                                     for (GroupResource gResource in resource.getGroups()) {
148                                         if (StringUtils.containsIgnoreCase(gResource.getModelInfo().getModelName(), grpType)) {
149                                             sequencedResourceList.add(gResource)
150                                         }
151                                     }
152                                 }
153                             }
154                         }
155                         if (resource instanceof NetworkResource) {
156                             networkResourceList.add(resource)
157                         }
158                     }
159                 }
160             }
161         } else {
162
163             //define sequenced resource list, we deploy vf first and then network and then ar
164             //this is default sequence
165             List<VnfResource> vnfResourceList = new ArrayList<VnfResource>()
166             List<AllottedResource> arResourceList = new ArrayList<AllottedResource>()
167
168             for (Resource rc : addResourceList){
169                 if (rc instanceof VnfResource) {
170                     vnfResourceList.add(rc)
171                 } else if (rc instanceof NetworkResource) {
172                     networkResourceList.add(rc)
173                 } else if (rc instanceof AllottedResource) {
174                     arResourceList.add(rc)
175                 }
176             }
177             sequencedResourceList.addAll(vnfResourceList)
178             sequencedResourceList.addAll(networkResourceList)
179             sequencedResourceList.addAll(arResourceList)
180         }
181
182         String isContainsWanResource = networkResourceList.isEmpty() ? "false" : "true"
183         //if no networkResource, get SDNC config from properties file
184         if( "false".equals(isContainsWanResource)) {
185             String serviceNeedSDNC = "mso.workflow.custom." + serviceModelName + ".sdnc.need";
186             isContainsWanResource = BPMNProperties.getProperty(serviceNeedSDNC, isContainsWanResource)
187         }
188
189         execution.setVariable("isContainsWanResource", isContainsWanResource)
190         execution.setVariable("currentResourceIndex", 0)
191         execution.setVariable("sequencedResourceList", sequencedResourceList)
192         logger.info("sequencedResourceList: " + sequencedResourceList)
193         logger.trace("COMPLETED sequenceResoure Process ")
194     }
195
196     public prepareServiceTopologyRequest(DelegateExecution execution) {
197
198         logger.trace("======== Start prepareServiceTopologyRequest Process ======== ")
199
200         String serviceDecompose = execution.getVariable("serviceDecomposition")
201
202         execution.setVariable("operationType", "create")
203         execution.setVariable("resourceType", "")
204
205         String serviceInvariantUuid = jsonUtil.getJsonValue(serviceDecompose, "serviceResources.modelInfo.modelInvariantUuid")
206         String serviceUuid = jsonUtil.getJsonValue(serviceDecompose, "serviceResources.modelInfo.modelUuid")
207         String serviceModelName = jsonUtil.getJsonValue(serviceDecompose, "serviceResources.modelInfo.modelName")
208
209         execution.setVariable("modelInvariantUuid", serviceInvariantUuid)
210         execution.setVariable("modelUuid", serviceUuid)
211         execution.setVariable("serviceModelName", serviceModelName)
212
213         logger.trace("======== End prepareServiceTopologyRequest Process ======== ")
214     }
215
216     public void getCurrentResoure(DelegateExecution execution){
217         logger.trace("Start getCurrentResoure Process ")
218         def currentIndex = execution.getVariable("currentResourceIndex")
219         List<Resource> instanceResourceList = execution.getVariable("instanceResourceList")
220         Resource currentResource = instanceResourceList.get(currentIndex)
221         execution.setVariable("resourceType", currentResource.getModelInfo().getModelName())
222         logger.info("Now we deal with resource:" + currentResource.getModelInfo().getModelName())
223         logger.trace("COMPLETED getCurrentResource Process ")
224     }
225
226     public void parseNextResource(DelegateExecution execution){
227         logger.trace("Start parseNextResource Process ")
228         def currentIndex = execution.getVariable("currentResourceIndex")
229         def nextIndex =  currentIndex + 1
230         execution.setVariable("currentResourceIndex", nextIndex)
231         List<Resource> instanceResourceList = execution.getVariable("instanceResourceList")
232         if(nextIndex >= instanceResourceList.size()){
233             execution.setVariable("allResourceFinished", "true")
234         }else{
235             execution.setVariable("allResourceFinished", "false")
236         }
237         logger.trace("COMPLETED parseNextResource Process ")
238     }
239
240     public void prepareResourceRecipeRequest(DelegateExecution execution){
241         logger.trace("Start prepareResourceRecipeRequest Process ")
242         ResourceInput resourceInput = new ResourceInput()
243         String serviceInstanceName = execution.getVariable("serviceInstanceName")
244         String resourceType = execution.getVariable("resourceType")
245         String resourceInstanceName = resourceType + "_" + serviceInstanceName
246         resourceInput.setResourceInstanceName(resourceInstanceName)
247         logger.info("Prepare Resource Request resourceInstanceName:" + resourceInstanceName)
248         String globalSubscriberId = execution.getVariable("globalSubscriberId")
249         String serviceType = execution.getVariable("serviceType")
250         String serviceInstanceId = execution.getVariable("serviceInstanceId")
251         String operationId = execution.getVariable("operationId")
252         String operationType = "createInstance"
253         resourceInput.setGlobalSubscriberId(globalSubscriberId)
254         resourceInput.setServiceType(serviceType)
255         resourceInput.setServiceInstanceId(serviceInstanceId)
256         resourceInput.setOperationId(operationId)
257         resourceInput.setOperationType(operationType);
258         def currentIndex = execution.getVariable("currentResourceIndex")
259         List<Resource> sequencedResourceList = execution.getVariable("instanceResourceList")
260         Resource currentResource = sequencedResourceList.get(currentIndex)
261         resourceInput.setResourceModelInfo(currentResource.getModelInfo())
262         resourceInput.getResourceModelInfo().setModelType(currentResource.getResourceType().toString())
263         ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
264
265         if (currentResource.getResourceType() == ResourceType.VNF) {
266             execution.setVariable("vfModelInfo", currentResource.getModelInfo())
267         }
268
269         resourceInput.setVfModelInfo(execution.getVariable("vfModelInfo") as ModelInfo)
270         String vnfId = execution.getVariable("vnf-id")
271         if (vnfId != null) {
272             resourceInput.setVnfId(vnfId)
273         }
274
275
276         resourceInput.setServiceModelInfo(serviceDecomposition.getModelInfo())
277
278         String incomingRequest = execution.getVariable("uuiRequest")
279         //set the requestInputs from template  To Be Done
280         String uuiServiceParameters = jsonUtil.getJsonValue(incomingRequest, "service.parameters")
281
282         // current vfdata holds information for preparing input for resource
283         // e.g. it will hold
284         // { top_level_list_name, second_level_list_name, top_index, second_index, last processed node}
285         Map<String, Object> currentVFData = (Map) execution.getVariable("currentVFData")
286
287         if (null == currentVFData) {
288             currentVFData = new HashMap<>()
289         }
290         String resourceParameters = ResourceRequestBuilder.buildResourceRequestParameters(execution, currentResource, uuiServiceParameters, currentVFData)
291         resourceInput.setResourceParameters(resourceParameters)
292         resourceInput.setRequestsInputs(incomingRequest)
293         execution.setVariable("resourceInput", resourceInput.toString())
294         execution.setVariable("resourceModelUUID", resourceInput.getResourceModelInfo().getModelUuid())
295         execution.setVariable("currentVFData",currentVFData)
296         logger.trace("COMPLETED prepareResourceRecipeRequest Process ")
297     }
298
299     public void executeResourceRecipe(DelegateExecution execution){
300         logger.trace("Start executeResourceRecipe Process ")
301
302         try {
303             String requestId = execution.getVariable("msoRequestId")
304             String serviceInstanceId = execution.getVariable("serviceInstanceId")
305             String serviceType = execution.getVariable("serviceType")
306             String resourceInput = execution.getVariable("resourceInput")
307             String resourceModelUUID = execution.getVariable("resourceModelUUID")
308
309             // requestAction is action, not opertiontype
310             //String requestAction = resourceInput.getOperationType()
311             String requestAction = "createInstance"
312             JSONObject resourceRecipe = catalogDbUtils.getResourceRecipe(execution, resourceModelUUID, requestAction)
313
314             if (resourceRecipe != null) {
315                 String recipeURL = BPMNProperties.getProperty("bpelURL", "http://so-bpmn-infra.onap:8081") + resourceRecipe.getString("orchestrationUri")
316                 int recipeTimeOut = resourceRecipe.getInt("recipeTimeout")
317                 String recipeParamXsd = resourceRecipe.get("paramXSD")
318
319                 BpmnRestClient bpmnRestClient = new BpmnRestClient()
320                 HttpResponse resp = bpmnRestClient.post(recipeURL, requestId, recipeTimeOut, requestAction, serviceInstanceId, serviceType, resourceInput, recipeParamXsd)
321
322                 def currentIndex = execution.getVariable("currentResourceIndex")
323                 List<Resource> instanceResourceList = execution.getVariable("instanceResourceList") as List<Resource>
324                 Resource currentResource = instanceResourceList.get(currentIndex)
325                 if(ResourceType.VNF == currentResource.getResourceType()) {
326                     if (resp.getStatusLine().getStatusCode() > 199 && resp.getStatusLine().getStatusCode() < 300) {
327                         String responseString = EntityUtils.toString(resp.getEntity(), "UTF-8")
328                         if (responseString != null) {
329                             Gson gson = new Gson()
330                             Type type = new TypeToken<Map<String, String>>() {}.getType()
331                             Map<String, Object> map = gson.fromJson(responseString, type)
332                             Map<String, String> map1 = gson.fromJson(map.get("response"), type)
333                             execution.setVariable("vnf-id",map1.get("vnf-id"))
334                         }
335                     }
336                 }
337             } else {
338                 String exceptionMessage = "Resource receipe is not found for resource modeluuid: " + resourceModelUUID
339                 logger.trace(exceptionMessage)
340                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, exceptionMessage)
341             }
342
343             logger.trace("======== end executeResourceRecipe Process ======== ")
344         }catch(BpmnError b){
345             logger.debug("Rethrowing MSOWorkflowException")
346             throw b
347         }catch(Exception e){
348             logger.debug("Error occured within DoCreateResources executeResourceRecipe method: " + e)
349             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured during DoCreateResources executeResourceRecipe Catalog")
350         }
351     }
352
353     public void postConfigRequest(DelegateExecution execution){
354         //now do noting
355         ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
356         for (VnfResource resource : serviceDecomposition.vnfResources) {
357             resource.setOrchestrationStatus("Active")
358         }
359         execution.setVariable("serviceDecomposition", serviceDecomposition)
360     }
361 }