d571c00f47d1aa1bea3d08b2a1fb369aee223c23
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoCreateResources.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License")
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20  
21 package org.onap.so.bpmn.infrastructure.scripts
22
23 import org.codehaus.jackson.map.ObjectMapper
24 import org.onap.so.bpmn.infrastructure.properties.BPMNProperties
25
26 import java.util.ArrayList
27 import java.util.Iterator
28 import java.util.List
29 import org.apache.commons.lang3.StringUtils
30 import org.apache.http.HttpResponse
31 import org.camunda.bpm.engine.delegate.BpmnError
32 import org.camunda.bpm.engine.delegate.DelegateExecution
33 import org.codehaus.groovy.runtime.ArrayUtil
34 import org.codehaus.groovy.runtime.ScriptBytecodeAdapter
35 import org.codehaus.groovy.runtime.callsite.CallSite
36 import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation
37 import org.codehaus.groovy.runtime.typehandling.ShortTypeHandling
38 import org.json.JSONArray
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.onap.so.logger.MessageEnum
53 import org.onap.so.logger.MsoLogger
54
55
56
57 /**
58  * This groovy class supports the <class>DoCreateResources.bpmn</class> process.
59  * 
60  * Inputs:
61  * @param - msoRequestId
62  * @param - globalSubscriberId - O
63  * @param - subscriptionServiceType - O
64  * @param - serviceInstanceId
65  * @param - serviceInstanceName - O
66  * @param - serviceInputParams (should contain aic_zone for serviceTypes TRANSPORT,ATM)
67  * @param - sdncVersion 
68  *
69  * @param - addResourceList
70  *
71  * Outputs:
72  * @param - WorkflowException
73
74  */
75 public class DoCreateResources extends AbstractServiceTaskProcessor{
76         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateResources.class);
77
78         ExceptionUtil exceptionUtil = new ExceptionUtil()
79         JsonUtils jsonUtil = new JsonUtils()
80         CatalogDbUtils cutils = new CatalogDbUtils()
81
82     public void preProcessRequest(DelegateExecution execution)
83     {
84                 msoLogger.trace("preProcessRequest ")
85                 String msg = ""
86                 
87         List addResourceList = execution.getVariable("addResourceList")
88         if (addResourceList == null)
89         {
90             msg = "Input addResourceList is null"
91             msoLogger.info(msg)
92             exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)  
93         }
94         else if (addResourceList.size() == 0)
95         {
96             msg = "No resource in addResourceList"
97             msoLogger.info(msg)
98         }
99         msoLogger.trace("Exit preProcessRequest ")
100     }
101     
102     public void sequenceResoure(DelegateExecution execution)
103     {
104         msoLogger.trace("Start sequenceResoure Process ")
105         
106         String serviceModelUUID = execution.getVariable("modelUuid")      
107                
108         List<Resource> addResourceList = execution.getVariable("addResourceList")        
109
110         List<NetworkResource> networkResourceList = new ArrayList<NetworkResource>()
111
112         List<Resource> sequencedResourceList = new ArrayList<Resource>()
113
114         String serviceDecompose = execution.getVariable("serviceDecomposition")
115         String serviceModelName = jsonUtil.getJsonValue(serviceDecompose, "serviceResources.modelInfo.modelName")
116         def resourceSequence = BPMNProperties.getResourceSequenceProp(serviceModelName)
117
118         if(resourceSequence != null) {
119             // sequence is defined in config file
120         for (resourceType in resourceSequence) {
121             for (resource in addResourceList) {
122                 if (StringUtils.containsIgnoreCase(resource.getModelInfo().getModelName(), resourceType)) {
123                     sequencedResourceList.add(resource)
124
125                     if (resource instanceof NetworkResource) {
126                         networkResourceList.add(resource)
127                     }
128                 }
129             }
130         }        
131         } else {
132         
133         //define sequenced resource list, we deploy vf first and then network and then ar
134         //this is defaule sequence
135         List<VnfResource> vnfResourceList = new ArrayList<VnfResource>()
136         List<AllottedResource> arResourceList = new ArrayList<AllottedResource>()
137
138         for (Resource rc : addResourceList){
139             if (rc instanceof VnfResource) {
140                 vnfResourceList.add(rc)
141             } else if (rc instanceof NetworkResource) {
142                 networkResourceList.add(rc)
143             } else if (rc instanceof AllottedResource) {
144                 arResourceList.add(rc)
145             }
146         }
147         sequencedResourceList.addAll(vnfResourceList)
148         sequencedResourceList.addAll(networkResourceList)
149         sequencedResourceList.addAll(arResourceList)
150         }
151
152         String isContainsWanResource = networkResourceList.isEmpty() ? "false" : "true"
153         execution.setVariable("isContainsWanResource", isContainsWanResource)
154         execution.setVariable("currentResourceIndex", 0)
155         execution.setVariable("sequencedResourceList", sequencedResourceList)
156         msoLogger.info("sequencedResourceList: " + sequencedResourceList) 
157         msoLogger.trace("COMPLETED sequenceResoure Process ")
158     }   
159    
160     public prepareServiceTopologyRequest(DelegateExecution execution) {
161
162         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
163         utils.log("INFO", "======== Start prepareServiceTopologyRequest Process ======== ", isDebugEnabled)
164
165         String serviceDecompose = execution.getVariable("serviceDecomposition")
166
167         execution.setVariable("operationType", "create")
168         execution.setVariable("resourceType", "")
169
170         String serviceInvariantUuid = jsonUtil.getJsonValue(serviceDecompose, "serviceResources.modelInfo.modelInvariantUuid")
171         String serviceUuid = jsonUtil.getJsonValue(serviceDecompose, "serviceResources.modelInfo.modelUuid")
172         String serviceModelName = jsonUtil.getJsonValue(serviceDecompose, "serviceResources.modelInfo.modelName")
173
174         execution.setVariable("modelInvariantUuid", serviceInvariantUuid)
175         execution.setVariable("modelUuid", serviceUuid)
176         execution.setVariable("serviceModelName", serviceModelName)
177
178         utils.log("INFO", "======== End prepareServiceTopologyRequest Process ======== ", isDebugEnabled)
179     }
180    
181     public void getCurrentResoure(DelegateExecution execution){
182             msoLogger.trace("Start getCurrentResoure Process ")    
183             def currentIndex = execution.getVariable("currentResourceIndex")
184             List<Resource> sequencedResourceList = execution.getVariable("sequencedResourceList")  
185             Resource currentResource = sequencedResourceList.get(currentIndex)
186             execution.setVariable("resourceType", currentResource.getModelInfo().getModelName())
187             msoLogger.info("Now we deal with resouce:" + currentResource.getModelInfo().getModelName())  
188             msoLogger.trace("COMPLETED getCurrentResoure Process ")  
189     }
190     
191     public void parseNextResource(DelegateExecution execution){
192         msoLogger.trace("Start parseNextResource Process ")    
193         def currentIndex = execution.getVariable("currentResourceIndex")
194         def nextIndex =  currentIndex + 1
195         execution.setVariable("currentResourceIndex", nextIndex)
196         List<String> sequencedResourceList = execution.getVariable("sequencedResourceList")    
197         if(nextIndex >= sequencedResourceList.size()){
198             execution.setVariable("allResourceFinished", "true")
199         }else{
200             execution.setVariable("allResourceFinished", "false")
201         }
202         msoLogger.trace("COMPLETED parseNextResource Process ")       
203     }    
204
205          public void prepareResourceRecipeRequest(DelegateExecution execution){
206                  msoLogger.trace("Start prepareResourceRecipeRequest Process ")
207                  ResourceInput resourceInput = new ResourceInput()
208                  String serviceInstanceName = execution.getVariable("serviceInstanceName")
209          String resourceType = execution.getVariable("resourceType")
210                  String resourceInstanceName = resourceType + "_" + serviceInstanceName
211                  resourceInput.setResourceInstanceName(resourceInstanceName)
212                  msoLogger.info("Prepare Resource Request resourceInstanceName:" + resourceInstanceName)
213                  String globalSubscriberId = execution.getVariable("globalSubscriberId")
214                  String serviceType = execution.getVariable("serviceType")
215                  String serviceInstanceId = execution.getVariable("serviceInstanceId")
216                  String operationId = execution.getVariable("operationId")
217                  String operationType = "createInstance"
218                  resourceInput.setGlobalSubscriberId(globalSubscriberId)
219                  resourceInput.setServiceType(serviceType)
220                  resourceInput.setServiceInstanceId(serviceInstanceId)
221                  resourceInput.setOperationId(operationId)
222                  resourceInput.setOperationType(operationType);
223                  def currentIndex = execution.getVariable("currentResourceIndex")
224                  List<Resource> sequencedResourceList = execution.getVariable("sequencedResourceList")
225                  Resource currentResource = sequencedResourceList.get(currentIndex)
226                  resourceInput.setResourceModelInfo(currentResource.getModelInfo());
227                  ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
228                  resourceInput.setServiceModelInfo(serviceDecomposition.getModelInfo());
229                  def String resourceCustomizationUuid = currentResource.getModelInfo().getModelCustomizationUuid();
230                  
231                  String incomingRequest = execution.getVariable("uuiRequest")
232                  //set the requestInputs from tempalte  To Be Done
233                  String serviceModelUuid = jsonUtil.getJsonValue(incomingRequest,"service.serviceUuid")
234                  String serviceParameters = jsonUtil.getJsonValue(incomingRequest, "service.parameters")
235                  String resourceParameters = ResourceRequestBuilder.buildResourceRequestParameters(execution, serviceModelUuid, resourceCustomizationUuid, serviceParameters)
236                  resourceInput.setResourceParameters(resourceParameters)
237                  resourceInput.setRequestsInputs(incomingRequest)
238                  execution.setVariable("resourceInput", resourceInput)
239                  msoLogger.trace("COMPLETED prepareResourceRecipeRequest Process ")
240          }
241          
242          public void executeResourceRecipe(DelegateExecution execution){
243                  msoLogger.trace("Start executeResourceRecipe Process ")
244                  
245                  try {
246                          String requestId = execution.getVariable("msoRequestId")
247                          String serviceInstanceId = execution.getVariable("serviceInstanceId")
248                          String serviceType = execution.getVariable("serviceType")
249                          ResourceInput resourceInput = execution.getVariable("resourceInput")
250                          
251                          // requestAction is action, not opertiontype
252                          //String requestAction = resourceInput.getOperationType()
253                          String requestAction = "createInstance"
254                          JSONObject resourceRecipe = cutils.getResourceRecipe(execution, resourceInput.getResourceModelInfo().getModelUuid(), requestAction)
255
256                  if (resourceRecipe != null) {
257                          String recipeURL = BPMNProperties.getProperty("bpelURL", "http://mso:8080") + resourceRecipe.getString("orchestrationUri")
258                                  int recipeTimeOut = resourceRecipe.getInt("recipeTimeout")
259                                  String recipeParamXsd = resourceRecipe.get("paramXSD")
260                                  HttpResponse resp = BpmnRestClient.post(recipeURL, requestId, recipeTimeOut, requestAction, serviceInstanceId, serviceType, resourceInput.toString(), recipeParamXsd)
261                  } else {
262                      String exceptionMessage = "Resource receipe is not found for resource modeluuid: " +
263                              resourceInput.getResourceModelInfo().getModelUuid()
264                      msoLogger.trace(exceptionMessage)
265                      exceptionUtil.buildAndThrowWorkflowException(execution, 500, exceptionMessage)
266                  }
267
268                  msoLogger.trace("======== end executeResourceRecipe Process ======== ")
269                  }catch(BpmnError b){
270                          msoLogger.debug("Rethrowing MSOWorkflowException")
271                          throw b
272                  }catch(Exception e){
273                          msoLogger.debug("Error occured within DoCreateResources executeResourceRecipe method: " + e)
274                          exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured during DoCreateResources executeResourceRecipe Catalog")
275                  }
276          }
277          
278      public void postConfigRequest(DelegateExecution execution){
279          //now do noting
280      }
281 }