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