48ca2905c12f7ee830aecc984fc37caf0e6e133c
[so.git] / bpmn / MSOInfrastructureBPMN / src / main / groovy / org / openecomp / mso / bpmn / infrastructure / scripts / CreateVfModuleVolumeInfraV1.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * OPENECOMP - MSO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. 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.openecomp.mso.bpmn.infrastructure.scripts
22
23 import org.openecomp.mso.bpmn.common.scripts.AaiUtil;
24 import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor;
25 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil;
26 import org.openecomp.mso.bpmn.common.scripts.VidUtils;
27 import org.openecomp.mso.bpmn.core.WorkflowException
28 import org.openecomp.mso.rest.APIResponse
29
30 import groovy.json.JsonSlurper
31
32 import org.camunda.bpm.engine.delegate.BpmnError
33 import org.camunda.bpm.engine.runtime.Execution;
34 import org.apache.commons.lang3.*
35
36 class CreateVfModuleVolumeInfraV1 extends AbstractServiceTaskProcessor {
37
38         public static final String  prefix='CVMVINFRAV1_'
39
40         /**
41          * Perform initial processing, such as request validation, initialization of variables, etc.
42          * * @param execution
43          */
44         public void preProcessRequest (Execution execution) {
45                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
46                 preProcessRequest(execution, isDebugEnabled)
47         }
48
49
50         /**
51          * Perform initial processing, such as request validation, initialization of variables, etc.
52          * @param execution
53          * @param isDebugEnabled
54          */
55         public void preProcessRequest (Execution execution, isDebugEnabled) {
56
57                 execution.setVariable("prefix",prefix)
58                 setSuccessIndicator(execution, false)
59                 execution.setVariable(prefix+'syncResponseSent', false)
60
61                 String createVolumeIncoming = validateRequest(execution, 'vnfId')
62                 utils.logAudit(createVolumeIncoming)
63
64                 try {
65                         def jsonSlurper = new JsonSlurper()
66                         Map reqMap = jsonSlurper.parseText(createVolumeIncoming)
67
68                         def serviceInstanceId = execution.getVariable('serviceInstanceId')
69                         def vnfId = execution.getVariable('vnfId')
70
71                         def vidUtils = new VidUtils(this)
72                         createVolumeIncoming = vidUtils.createXmlVolumeRequest(reqMap, 'CREATE_VF_MODULE_VOL', serviceInstanceId)
73
74                         execution.setVariable(prefix+'Request', createVolumeIncoming)
75                         execution.setVariable(prefix+'vnfId', vnfId)
76                         execution.setVariable(prefix+'isVidRequest', true)
77
78                         utils.log("DEBUG", "XML request:\n" + createVolumeIncoming, isDebugEnabled)
79
80                 }
81                 catch(groovy.json.JsonException je) {
82                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 2500, 'Request is not a valid JSON document')
83                 }
84
85                 execution.setVariable(prefix+'source', utils.getNodeText1(createVolumeIncoming, "source"))
86                 execution.setVariable(prefix+'volumeGroupName', utils.getNodeText1(createVolumeIncoming, 'volume-group-name'))
87                 execution.setVariable(prefix+'volumeOutputs', utils.getNodeXml(createVolumeIncoming, 'volume-outputs', false))
88
89                 execution.setVariable(prefix+'serviceType', 'service-instance')
90                 execution.setVariable(prefix+'serviceInstanceId', utils.getNodeText1(createVolumeIncoming, "service-instance-id"))
91
92                 // Generate volume group id
93                 String volumeGroupId = UUID.randomUUID()
94                 utils.log("DEBUG", "Generated volume group id: " + volumeGroupId, isDebugEnabled)
95
96                 def testGroupId = execution.getVariable('test-volume-group-id')
97                 if (testGroupId != null && testGroupId.trim() != '') {
98                         volumeGroupId = testGroupId
99                 }
100
101                 execution.setVariable(prefix+'volumeGroupId', volumeGroupId)
102
103         }
104
105
106         public void sendSyncResponse (Execution execution, isDebugEnabled) {
107                 def volumeGroupId = execution.getVariable(prefix+'volumeGroupId')
108                 def requestId = execution.getVariable("mso-request-id")
109                 def serviceInstanceId = execution.getVariable("serviceInstanceId")
110
111                 String syncResponse = """{"requestReferences":{"instanceId":"${volumeGroupId}","requestId":"${requestId}"}}""".trim()
112
113                 utils.log("DEBUG", "Sync Response: " + "\n" + syncResponse, isDebugEnabled)
114                 sendWorkflowResponse(execution, 200, syncResponse)
115
116                 execution.setVariable(prefix+'syncResponseSent', true)
117         }
118
119
120         public void sendSyncError (Execution execution, isDebugEnabled) {
121                 WorkflowException we = execution.getVariable('WorkflowException')
122                 def errorCode = we?.getErrorCode()
123                 def errorMessage = we?.getErrorMessage()
124                 //default to 400 since only invalid request will trigger this method
125                 sendWorkflowResponse(execution, 400, errorMessage)
126         }
127
128
129         /**
130          * Create a WorkflowException
131          * @param execution
132          * @param isDebugEnabled
133          */
134         public void buildWorkflowException(Execution execution, int errorCode, errorMessage, isDebugEnabled) {
135                 utils.log("DEBUG", errorMessage, isDebugEnabled)
136                 (new ExceptionUtil()).buildWorkflowException(execution, 2500, errorMessage)
137         }
138
139
140         public void prepareDbInfraSuccessRequest(Execution execution, isDebugEnabled) {
141                 def dbVnfOutputs = execution.getVariable(prefix+'volumeOutputs')
142                 def requestId = execution.getVariable('mso-request-id')
143                 def statusMessage = "VolumeGroup successfully created."
144                 def requestStatus = "COMPLETED"
145                 def progress = "100"
146
147                 try {
148                         String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth")
149                         utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugEnabled)
150                         
151                         def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey"))
152                         execution.setVariable("BasicAuthHeaderValueDB",encodedString)
153                 } catch (IOException ex) {
154                         String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage()
155                         utils.log("DEBUG", dataErrorMessage, isDebugEnabled)
156                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
157                 }
158                 
159                 /*
160                 from: $gVolumeGroup/aai:volume-group-id/text()
161                 to: vnfreq:volume-outputs/vnfreq:volume-group-id
162                 */
163                 // for now assume, generated volumeGroupId is accepted
164                 def volumeGroupId = execution.getVariable(prefix+'volumeGroupId')
165
166                 String dbRequest =
167                         """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
168                                 <soapenv:Header/>
169                                 <soapenv:Body>
170                                         <ns:updateInfraRequest xmlns:ns="http://org.openecomp.mso/requestsdb">
171                                                 <requestId>${requestId}</requestId>
172                                                 <lastModifiedBy>BPMN</lastModifiedBy>
173                                                 <statusMessage>${statusMessage}</statusMessage>
174                                                 <responseBody></responseBody>
175                                                 <requestStatus>${requestStatus}</requestStatus>
176                                                 <progress>${progress}</progress>
177                                                 <vnfOutputs>${dbVnfOutputs}</vnfOutputs>
178                                                 <volumeGroupId>${volumeGroupId}</volumeGroupId>
179                                         </ns:updateInfraRequest>
180                                 </soapenv:Body>
181                            </soapenv:Envelope>"""
182
183                 String buildDeleteDBRequestAsString = utils.formatXml(dbRequest)
184                 execution.setVariable(prefix+"createDBRequest", buildDeleteDBRequestAsString)
185
186                 utils.logAudit(buildDeleteDBRequestAsString)
187         }
188
189
190
191
192
193         public void postProcessResponse (Execution execution, isDebugEnabled) {
194
195                 def dbReturnCode = execution.getVariable(prefix+'dbReturnCode')
196                 def createDBResponse =  execution.getVariable(prefix+'createDBResponse')
197
198                 utils.logAudit('DB return code: ' + dbReturnCode)
199                 utils.logAudit('DB response: ' + createDBResponse)
200
201                 def requestId = execution.getVariable("mso-request-id")
202                 def source = execution.getVariable(prefix+'source')
203
204                 String msoCompletionRequest =
205                         """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"
206                                                         xmlns:ns="http://org.openecomp/mso/request/types/v1">
207                                         <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
208                                                 <request-id>${requestId}</request-id>
209                                                 <action>CREATE</action>
210                                                 <source>${source}</source>
211                                         </request-info>
212                                         <aetgt:status-message>Volume Group has been created successfully.</aetgt:status-message>
213                                         <aetgt:mso-bpel-name>BPMN VF Module Volume action: CREATE</aetgt:mso-bpel-name>
214                                 </aetgt:MsoCompletionRequest>"""
215
216                 String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
217
218                 utils.logAudit(createDBResponse)
219                 utils.logAudit(xmlMsoCompletionRequest)
220                 execution.setVariable(prefix+'Success', true)
221                 execution.setVariable(prefix+'CompleteMsoProcessRequest', xmlMsoCompletionRequest)
222                 utils.log("DEBUG", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled)
223
224         }
225
226         public void prepareFalloutHandlerRequest(Execution execution, isDebugEnabled) {
227
228                 WorkflowException we = execution.getVariable('WorkflowException')
229                 def errorCode = we?.getErrorCode()
230                 def errorMessage = we?.getErrorMessage()
231
232                 def requestId = execution.getVariable("mso-request-id")
233                 def source = execution.getVariable(prefix+'source')
234
235                 String falloutHandlerRequest =
236                         """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"
237                                                              xmlns:ns="http://org.openecomp/mso/request/types/v1"
238                                                              xmlns:wfsch="http://org.openecomp/mso/workflow/schema/v1">
239                                    <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
240                                       <request-id>${requestId}</request-id>
241                                       <action>CREATE</action>
242                                       <source>${source}</source>
243                                    </request-info>
244                                            <aetgt:WorkflowException>
245                                               <aetgt:ErrorMessage>${errorMessage}</aetgt:ErrorMessage>
246                                               <aetgt:ErrorCode>${errorCode}</aetgt:ErrorCode>
247                                                 </aetgt:WorkflowException>
248
249                                 </aetgt:FalloutHandlerRequest>"""
250
251                 // Format Response
252                 String xmlHandlerRequest = utils.formatXml(falloutHandlerRequest)
253                 utils.logAudit(xmlHandlerRequest)
254
255                 execution.setVariable(prefix+'FalloutHandlerRequest', xmlHandlerRequest)
256                 utils.log("ERROR", "Overall Error Response going to FalloutHandler: " + "\n" + xmlHandlerRequest, isDebugEnabled)
257         }
258
259
260         /**
261          * Query AAI service instance
262          * @param execution
263          * @param isDebugEnabled
264          */
265         public void callRESTQueryAAIServiceInstance(Execution execution, isDebugEnabled) {
266
267                 def request = execution.getVariable(prefix+"Request")
268                 def serviceInstanceId = utils.getNodeText1(request, "service-instance-id")
269
270                 AaiUtil aaiUtil = new AaiUtil(this)
271                 String aaiEndpoint = aaiUtil.getSearchNodesQueryEndpoint(execution)
272
273                 def String queryAAIRequest = aaiEndpoint + "?search-node-type=service-instance&filter=service-instance-id:EQUALS:" + serviceInstanceId
274                 utils.logAudit("AAI query service instance request: " + queryAAIRequest)
275
276                 APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIRequest)
277
278                 String returnCode = response.getStatusCode()
279                 String aaiResponseAsString = response.getResponseBodyAsString()
280                 aaiResponseAsString = StringEscapeUtils.unescapeXml(aaiResponseAsString)
281
282                 utils.logAudit("AAI query service instance return code: " + returnCode)
283                 utils.logAudit("AAI query service instance response: " + aaiResponseAsString)
284
285                 utils.log("DEBUG", "AAI query service instance return code: " + returnCode, isDebugEnabled)
286                 utils.log("DEBUG", "AAI query service instance response: " + aaiResponseAsString, isDebugEnabled)
287
288                 ExceptionUtil exceptionUtil = new ExceptionUtil()
289
290                 if (returnCode=='200') {
291                         utils.log("DEBUG", 'Service instance ' + serviceInstanceId + ' found in AAI.', isDebugEnabled)
292                 } else {
293                         if (returnCode=='404') {
294                                 def message = 'Service instance ' + serviceInstanceId + ' was not found in AAI. Return code: 404.'
295                                 utils.log("DEBUG", message, isDebugEnabled)
296                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, message)
297                         } else {
298                                 WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
299                                 throw new BpmnError("MSOWorkflowException")
300                         }
301                 }
302         }
303 }