00746d4e65a16fab83f1449314989217f1546c82
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2020  Telecom Italia
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 com.fasterxml.jackson.databind.ObjectMapper
24 import org.camunda.bpm.engine.delegate.DelegateExecution
25 import org.onap.aai.domain.yang.CloudRegion
26 import org.onap.aai.domain.yang.GenericVnf
27 import org.onap.aai.domain.yang.ModelVer
28 import org.onap.aai.domain.yang.ServiceInstance
29 import org.onap.aai.domain.yang.ServiceSubscription
30 import org.onap.aai.domain.yang.SliceProfile
31 import org.onap.aai.domain.yang.Tenant
32 import org.onap.aai.domain.yang.VfModule
33 import org.onap.aaiclient.client.aai.AAIObjectType
34 import org.onap.aaiclient.client.aai.AAIResourcesClient
35 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
36 import org.onap.aaiclient.client.aai.entities.Relationships
37 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
38 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
39 import org.onap.logging.filter.base.ONAPComponents
40 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
41 import org.onap.so.bpmn.common.scripts.ExceptionUtil
42 import org.onap.so.bpmn.common.scripts.RequestDBUtil
43 import org.onap.so.bpmn.core.UrnPropertiesReader
44 import org.onap.so.bpmn.core.json.JsonUtils
45 import org.onap.so.client.HttpClient
46 import org.onap.so.db.request.beans.OperationStatus
47 import org.onap.so.requestsdb.RequestsDbConstant
48 import org.onap.so.serviceinstancebeans.CloudConfiguration
49 import org.onap.so.serviceinstancebeans.LineOfBusiness
50 import org.onap.so.serviceinstancebeans.ModelInfo
51 import org.onap.so.serviceinstancebeans.ModelType
52 import org.onap.so.serviceinstancebeans.OwningEntity
53 import org.onap.so.serviceinstancebeans.Project
54 import org.onap.so.serviceinstancebeans.RequestDetails
55 import org.onap.so.serviceinstancebeans.RequestInfo
56 import org.onap.so.serviceinstancebeans.RequestParameters
57 import org.onap.so.serviceinstancebeans.Resources
58 import org.onap.so.serviceinstancebeans.Service
59 import org.onap.so.serviceinstancebeans.SubscriberInfo
60 import org.onap.so.serviceinstancebeans.VfModules
61 import org.onap.so.serviceinstancebeans.Vnfs
62 import org.slf4j.Logger
63 import org.slf4j.LoggerFactory
64
65 import javax.ws.rs.core.Response
66
67
68  class DoCommonCoreNSSI extends AbstractServiceTaskProcessor {
69
70     private final String PREFIX ="DoCommonCoreNSSI"
71
72     private static final Logger LOGGER = LoggerFactory.getLogger( DoCommonCoreNSSI.class)
73
74     private JsonUtils jsonUtil = new JsonUtils()
75     private ExceptionUtil exceptionUtil = new ExceptionUtil()
76     private RequestDBUtil requestDBUtil = new RequestDBUtil()
77
78     @Override
79     void preProcessRequest(DelegateExecution execution) {
80         LOGGER.trace("${getPrefix()} Start preProcessRequest")
81
82         def currentNSSI = execution.getVariable("currentNSSI")
83         if (!currentNSSI) {
84             String msg = "currentNSSI is null"
85             LOGGER.error(msg)
86             exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
87         }
88
89         LOGGER.trace("***** ${getPrefix()} Exit preProcessRequest")
90     }
91
92
93     /**
94      * Queries Network Service Instance in AAI
95      * @param execution
96      */
97     void getNetworkServiceInstance(DelegateExecution execution) {
98         LOGGER.trace("${getPrefix()} Start getNetworkServiceInstance")
99
100         AAIResourcesClient client = getAAIClient()
101
102         def currentNSSI = execution.getVariable("currentNSSI")
103
104         String nssiId = currentNSSI['nssiId']
105
106         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId)
107         Optional<ServiceInstance> nssiOpt = client.get(ServiceInstance.class, nssiUri)
108
109         if (nssiOpt.isPresent()) {
110             ServiceInstance nssi = nssiOpt.get()
111             currentNSSI['nssi'] = nssi
112
113             ServiceInstance networkServiceInstance = handleNetworkInstance(execution, nssiId, nssiUri, client)
114             currentNSSI['networkServiceInstance'] = networkServiceInstance
115         }
116         else {
117             String msg = String.format("NSSI %s not found in AAI", nssiId)
118             LOGGER.error(msg)
119             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
120         }
121
122         LOGGER.trace("${getPrefix()} Exit getNetworkServiceInstance")
123     }
124
125
126     /**
127      * Handles Network Service
128      * @param nssiId
129      * @param nssiUri
130      * @param client
131      * @return Network Service Instance
132      */
133     private ServiceInstance handleNetworkInstance(DelegateExecution execution, String nssiId, AAIResourceUri nssiUri, AAIResourcesClient client ) {
134         ServiceInstance networkServiceInstance = null
135
136         def currentNSSI = execution.getVariable("currentNSSI")
137
138         AAIResultWrapper wrapper = client.get(nssiUri)
139         Optional<Relationships> relationships = wrapper.getRelationships()
140
141         if (relationships.isPresent()) {
142             for (AAIResourceUri networkServiceInstanceUri : relationships.get().getRelatedAAIUris(AAIObjectType.SERVICE_INSTANCE)) {
143                 Optional<ServiceInstance> networkServiceInstanceOpt = client.get(ServiceInstance.class, networkServiceInstanceUri)
144                 if (networkServiceInstanceOpt.isPresent()) {
145                     networkServiceInstance = networkServiceInstanceOpt.get()
146
147                     if (networkServiceInstance.getServiceRole() == "Network Service") { // Network Service role
148                         currentNSSI['networkServiceInstanceUri'] = networkServiceInstanceUri
149                         break
150                     }
151                 }
152                 else {
153                     String msg = String.format("No Network Service Instance found for NSSI %s in AAI", nssiId)
154                     LOGGER.error(msg)
155                     exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
156                 }
157             }
158         }
159         else {
160             String msg = String.format("No relationship presented for NSSI %s in AAI", nssiId)
161             LOGGER.error(msg)
162             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
163         }
164
165         if(networkServiceInstance == null) {
166             String msg = String.format("No Network Service Instance found for NSSI %s in AAI", nssiId)
167             LOGGER.error(msg)
168             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
169         }
170
171         return networkServiceInstance
172     }
173
174
175     /**
176      * Queries constitute VNF from Network Service Instance
177      * @param execution
178      */
179     void getConstituteVNFFromNetworkServiceInst(DelegateExecution execution) {
180         LOGGER.trace("${getPrefix()} Start getConstituteVNFFromNetworkServiceInst")
181
182         def currentNSSI = execution.getVariable("currentNSSI")
183
184         AAIResourcesClient client = getAAIClient()
185
186         AAIResourceUri networkServiceInstanceUri = (AAIResourceUri)currentNSSI['networkServiceInstanceUri']
187         AAIResultWrapper wrapper = client.get(networkServiceInstanceUri);
188         Optional<Relationships> relationships = wrapper.getRelationships()
189         if (relationships.isPresent()) {
190             for (AAIResourceUri constituteVnfUri : relationships.get().getRelatedAAIUris(AAIObjectType.GENERIC_VNF)) {
191                 currentNSSI['constituteVnfUri'] = constituteVnfUri
192                 Optional<GenericVnf> constituteVnfOpt = client.get(GenericVnf.class, constituteVnfUri)
193                 if(constituteVnfOpt.isPresent()) {
194                     GenericVnf constituteVnf = constituteVnfOpt.get()
195                     currentNSSI['constituteVnf'] = constituteVnf
196                 }
197                 else {
198                     String msg = String.format("No constitute VNF found for Network Service Instance %s in AAI", ((ServiceInstance)currentNSSI['networkServiceInstance']).getServiceInstanceId())
199                     LOGGER.error(msg)
200                     exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
201                 }
202
203                 break  // Should be only one constitute VNF
204             }
205         }
206         else {
207             String msg = String.format("No relationship presented for Network Service Instance %s in AAI", ((ServiceInstance)currentNSSI['networkServiceInstance']).getServiceInstanceId())
208             LOGGER.error(msg)
209             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
210         }
211
212         LOGGER.trace("${getPrefix()} Exit getConstituteVNFFromNetworkServiceInst")
213
214     }
215
216
217     /**
218      * Retrieves NSSI associated profiles from AAI
219      * @param execution
220      */
221     void getNSSIAssociatedProfiles(DelegateExecution execution) {
222         LOGGER.trace("${getPrefix()} Start getNSSIAssociatedProfiles")
223
224         def currentNSSI = execution.getVariable("currentNSSI")
225
226         ServiceInstance nssi = (ServiceInstance)currentNSSI['nssi']
227
228         List<SliceProfile> associatedProfiles = nssi.getSliceProfiles().getSliceProfile()
229
230         if(associatedProfiles.isEmpty()) {
231             String msg = String.format("No associated profiles found for NSSI %s in AAI", nssi.getServiceInstanceId())
232             LOGGER.error(msg)
233             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
234         }
235         else {
236             currentNSSI['associatedProfiles'] =  associatedProfiles
237         }
238
239         LOGGER.trace("${getPrefix()} Exit getNSSIAssociatedProfiles")
240     }
241
242
243     /**
244      * Calculates a final list of S-NSSAI
245      * @param execution
246      */
247     void calculateSNSSAI(DelegateExecution execution) {
248         LOGGER.trace("${getPrefix()} Start calculateSNSSAI")
249
250         def currentNSSI = execution.getVariable("currentNSSI")
251
252         List<SliceProfile> associatedProfiles = (List<SliceProfile>)currentNSSI['associatedProfiles']
253
254         String currentSNSSAI = currentNSSI['S-NSSAI']
255
256         List<String> snssais = new ArrayList<>()
257
258         String isCreateSliceProfileInstanceVar = execution.getVariable("isCreateSliceProfileInstance" )
259
260         boolean isCreateSliceProfileInstance = Boolean.parseBoolean(isCreateSliceProfileInstanceVar)
261
262         if(isCreateSliceProfileInstance) { // Slice Profile Instance has to be created
263             for (SliceProfile associatedProfile : associatedProfiles) {
264                 snssais.add(associatedProfile.getSNssai())
265             }
266
267             snssais.add(currentSNSSAI)
268         }
269         else { // Slice profile instance has to be deleted
270             for (SliceProfile associatedProfile : associatedProfiles) {
271                 if (!associatedProfile.getSNssai().equals(currentSNSSAI)) { // not current S-NSSAI
272                     snssais.add(associatedProfile.getSNssai())
273                 } else {
274                     currentNSSI['sliceProfileS-NSSAI'] = associatedProfile
275                 }
276             }
277         }
278
279         currentNSSI['S-NSSAIs'] = snssais
280
281         LOGGER.trace("${getPrefix()} Exit calculateSNSSAI")
282     }
283
284
285     /**
286      * Invoke PUT Service Instance API
287      * @param execution
288      */
289     void invokePUTServiceInstance(DelegateExecution execution) {
290         LOGGER.trace("${getPrefix()} Start invokePUTServiceInstance")
291
292         def currentNSSI = execution.getVariable("currentNSSI")
293
294         try {
295             //url:/onap/so/infra/serviceInstantiation/v7/serviceInstances/{serviceInstanceId}/vnfs/{vnfId}"
296             def nsmfЕndpoint = UrnPropertiesReader.getVariable("mso.infra.endpoint.url", execution) // ???
297
298             ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
299
300             GenericVnf constituteVnf = (GenericVnf)currentNSSI['constituteVnf']
301
302             String url = String.format("${nsmfЕndpoint}/serviceInstantiation/v7/serviceInstances/%s/vnfs/%s", networkServiceInstance.getServiceInstanceId(), constituteVnf.getVnfId())
303
304             String msoKey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
305             String basicAuth =  UrnPropertiesReader.getVariable("mso.infra.endpoint.auth", execution)
306
307             def authHeader = ""
308             String basicAuthValue = encryptBasicAuth(basicAuth, msoKey) //utils.encrypt(basicAuth, msoKey)
309             String responseAuthHeader = getAuthHeader(execution, basicAuthValue, msoKey) //utils.getBasicAuth(basicAuthValue, msoKey)
310
311             String errorCode = jsonUtil.getJsonValue(responseAuthHeader, "errorCode")
312             if(errorCode == null || errorCode.isEmpty()) { // No error
313                 authHeader = responseAuthHeader
314             }
315             else {
316                 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(responseAuthHeader, "errorMessage"))
317             }
318
319             def requestDetails = ""
320             String prepareRequestDetailsResponse = prepareRequestDetails(execution)
321             errorCode = jsonUtil.getJsonValue(prepareRequestDetailsResponse, "errorCode")
322             if(errorCode == null || errorCode.isEmpty()) { // No error
323                 requestDetails = prepareRequestDetailsResponse
324             }
325             else {
326                 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(prepareRequestDetailsResponse, "errorMessage"))
327             }
328
329             String callPUTServiceInstanceResponse = callPUTServiceInstance(url, authHeader, requestDetails)
330             String putServiceInstanceResponse = ""
331
332             if(errorCode == null || errorCode.isEmpty()) { // No error
333                 putServiceInstanceResponse = callPUTServiceInstanceResponse // check the response ???
334             }
335             else {
336                 LOGGER.error(jsonUtil.getJsonValue(callPUTServiceInstanceResponse, "errorMessage"))
337                 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(callPUTServiceInstanceResponse, "errorMessage"))
338             }
339
340         } catch (any) {
341             String msg = "Exception in ${getPrefix()}.invokePUTServiceInstance. " + any.getCause()
342             LOGGER.error(msg)
343             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
344         }
345
346         LOGGER.trace("${getPrefix()} Exit invokePUTServiceInstance")
347     }
348
349
350     String callPUTServiceInstance(String url, String authHeader, String requestDetailsStr) {
351         String errorCode = ""
352         String errorMessage = ""
353         String response
354
355         try {
356             HttpClient httpClient = getHttpClientFactory().newJsonClient(new URL(url), ONAPComponents.EXTERNAL)
357             httpClient.addAdditionalHeader("Authorization", authHeader)
358             httpClient.addAdditionalHeader("Accept", "application/json")
359
360             Response httpResponse = httpClient.put(requestDetailsStr) // check http code ???
361
362
363             if (httpResponse.hasEntity()) {
364                 response = httpResponse.readEntity(String.class)
365             }
366             else {
367                 errorCode = 500
368                 errorMessage = "No response received."
369
370                 response =  "{\n" +
371                         " \"errorCode\": \"${errorCode}\",\n" +
372                         " \"errorMessage\": \"${errorMessage}\"\n" +
373                         "}"
374             }
375         }
376         catch (any) {
377             String msg = "Exception in ${getPrefix()}.invokePUTServiceInstance. " + any.getCause()
378             LOGGER.error(msg)
379
380             response =  "{\n" +
381                     " \"errorCode\": \"7000\",\n" +
382                     " \"errorMessage\": \"${msg}\"\n" +
383                     "}"
384
385         }
386
387         return response
388
389     }
390
391
392     /**
393      * Prepare model info
394      * @param execution
395      * @param requestDetails
396      * @return ModelInfo
397      */
398     ModelInfo prepareModelInfo(DelegateExecution execution) {
399
400         def currentNSSI = execution.getVariable("currentNSSI")
401         ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
402
403         ModelInfo modelInfo = new ModelInfo()
404
405         modelInfo.setModelType(ModelType.service)
406         modelInfo.setModelInvariantId(networkServiceInstance.getModelInvariantId())
407
408         AAIResourcesClient client = getAAIClient()
409
410         AAIResourceUri modelVerUrl = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, networkServiceInstance.getModelInvariantId(), networkServiceInstance.getModelVersionId())
411         Optional<ModelVer> modelVerOpt = client.get(ModelVer.class, modelVerUrl)
412
413         if (modelVerOpt.isPresent()) {
414             modelInfo.setModelVersionId(modelVerOpt.get().getModelVersionId())
415             modelInfo.setModelName(modelVerOpt.get().getModelName())
416             modelInfo.setModelVersion(modelVerOpt.get().getModelVersion())
417         }
418
419         return modelInfo
420     }
421
422
423     /**
424      * Prepares subscriber info
425      * @param execution
426      * @return SubscriberInfo
427      */
428     SubscriberInfo prepareSubscriberInfo(DelegateExecution execution) {
429         def currentNSSI = execution.getVariable("currentNSSI")
430
431         String globalSubscriberId = currentNSSI['globalSubscriberId']
432
433         String subscriberName = currentNSSI['subscriberName']
434
435         SubscriberInfo subscriberInfo = new SubscriberInfo()
436         subscriberInfo.setGlobalSubscriberId(globalSubscriberId)
437         subscriberInfo.setSubscriberName(subscriberName)
438
439         /*
440         AAIResourcesClient client = getAAIClient()
441
442         Customer customer = null
443
444         AAIResourceUri networkServiceInstanceUri = currentNSSI['networkServiceInstanceUri']
445         AAIResultWrapper wrapper = client.get(networkServiceInstanceUri)
446         Optional<Relationships> serviceSubscriptionRelationshipsOps = wrapper.getRelationships()
447         if(serviceSubscriptionRelationshipsOps.isPresent()) {
448             List<AAIResourceUri> serviceSubscriptionRelatedAAIUris = serviceSubscriptionRelationshipsOps.get().getRelatedAAIUris(AAIObjectType.SERVICE_SUBSCRIPTION)
449             if(!(serviceSubscriptionRelatedAAIUris == null || serviceSubscriptionRelatedAAIUris.isEmpty())) {
450                 AAIResourceUri serviceSubscriptionUri = serviceSubscriptionRelatedAAIUris.get(0) // Many-To-One relation
451                 Optional<ServiceSubscription> serviceSubscriptionOpt = client.get(ServiceSubscription.class, serviceSubscriptionUri)
452
453                 if(serviceSubscriptionOpt.isPresent()) {
454                     currentNSSI['serviceSubscription'] = serviceSubscriptionOpt.get()
455                 }
456
457                 wrapper = client.get(serviceSubscriptionUri)
458                 Optional<Relationships> customerRelationshipsOps = wrapper.getRelationships()
459                 if(customerRelationshipsOps.isPresent()) {
460                     List<AAIResourceUri> customerRelatedAAIUris = customerRelationshipsOps.get().getRelatedAAIUris(AAIObjectType.CUSTOMER)
461                     if(!(customerRelatedAAIUris == null || customerRelatedAAIUris.isEmpty())) {
462                         Optional<Customer> customerOpt = client.get(Customer.class, customerRelatedAAIUris.get(0)) // Many-To-One relation
463                         if(customerOpt.isPresent()) {
464                             customer = customerOpt.get()
465                             subscriberInfo.setSubscriberName(customer.getSubscriberName())
466                         }
467                     }
468                 }
469             }
470
471         } */
472
473         return subscriberInfo
474     }
475
476
477     /**
478      * Prepares Request Info
479      * @param execution
480      * @return RequestInfo
481      */
482     RequestInfo prepareRequestInfo(DelegateExecution execution, ServiceInstance networkServiceInstance) {
483         def currentNSSI = execution.getVariable("currentNSSI")
484
485         String serviceId = currentNSSI['serviceId']
486
487         RequestInfo requestInfo = new RequestInfo()
488
489         requestInfo.setInstanceName(networkServiceInstance.getServiceInstanceName())
490         requestInfo.setSource("VID")
491         requestInfo.setProductFamilyId(serviceId)
492         requestInfo.setRequestorId("NBI")
493
494         return requestInfo
495     }
496
497
498     /**
499      * Prepares Model Info
500      * @param networkServiceInstance
501      * @param modelInfo
502      * @return ModelInfo
503      */
504     ModelInfo prepareServiceModelInfo(ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
505
506         ModelInfo serviceModelInfo = new ModelInfo()
507         serviceModelInfo.setModelType(ModelType.service)
508         serviceModelInfo.setModelInvariantId(networkServiceInstance.getModelInvariantId())
509
510         serviceModelInfo.setModelVersionId(modelInfo.getModelVersionId())
511         serviceModelInfo.setModelName(modelInfo.getModelName())
512         serviceModelInfo.setModelVersion(modelInfo.getModelVersion())
513
514         return serviceModelInfo
515     }
516
517
518     /**
519      * Prepares Cloud configuration
520      * @param execution
521      * @return CloudConfiguration
522      */
523     CloudConfiguration prepareCloudConfiguration(DelegateExecution execution) {
524         def currentNSSI = execution.getVariable("currentNSSI")
525
526         CloudConfiguration cloudConfiguration = new CloudConfiguration()
527
528         AAIResourcesClient client = getAAIClient()
529
530         AAIResourceUri constituteVnfUri = currentNSSI['constituteVnfUri']
531         AAIResultWrapper wrapper = client.get(constituteVnfUri)
532         Optional<Relationships> cloudRegionRelationshipsOps = wrapper.getRelationships()
533
534         if(cloudRegionRelationshipsOps.isPresent()) {
535             List<AAIResourceUri> cloudRegionRelatedAAIUris = cloudRegionRelationshipsOps.get().getRelatedAAIUris(AAIObjectType.CLOUD_REGION)
536             if (!(cloudRegionRelatedAAIUris == null || cloudRegionRelatedAAIUris.isEmpty())) {
537                 AAIResourceUri cloudRegionRelatedAAIUri = cloudRegionRelatedAAIUris.get(0)
538                 currentNSSI['cloudRegionRelatedAAIUri'] = cloudRegionRelatedAAIUri
539
540                 Optional<CloudRegion> cloudRegionrOpt = client.get(CloudRegion.class, cloudRegionRelatedAAIUris.get(0))
541                 CloudRegion cloudRegion = null
542                 if (cloudRegionrOpt.isPresent()) {
543                     cloudRegion = cloudRegionrOpt.get()
544                     cloudConfiguration.setLcpCloudRegionId(cloudRegion.getCloudRegionId())
545                     for (Tenant tenant : cloudRegion.getTenants().getTenant()) {
546                         cloudConfiguration.setTenantId(tenant.getTenantId())
547                         break // only one is required
548                     }
549
550                     cloudConfiguration.setCloudOwner(cloudRegion.getCloudOwner())
551                 }
552             }
553         }
554
555         return cloudConfiguration
556     }
557
558
559     /**
560      * Prepares a list of VF Modules
561      * @param execution
562      * @param constituteVnf
563      * @return List<VfModules>
564      */
565     List<VfModules> prepareVfModules(DelegateExecution execution, GenericVnf constituteVnf) {
566
567         AAIResourcesClient client = getAAIClient()
568
569         List<VfModules> vfModuless = new ArrayList<>()
570         for (VfModule vfModule : constituteVnf.getVfModules().getVfModule()) {
571             VfModules vfmodules = new VfModules()
572
573             ModelInfo vfModuleModelInfo = new ModelInfo()
574             vfModuleModelInfo.setModelInvariantUuid(vfModule.getModelInvariantId())
575             vfModuleModelInfo.setModelCustomizationId(vfModule.getModelCustomizationId())
576
577             AAIResourceUri vfModuleUrl = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, vfModule.getModelInvariantId(), vfModule.getModelVersionId())
578
579             Optional<ModelVer> vfModuleModelVerOpt = client.get(ModelVer.class, vfModuleUrl)
580
581             if (vfModuleModelVerOpt.isPresent()) {
582                 vfModuleModelInfo.setModelVersionId(vfModuleModelVerOpt.get().getModelVersionId())
583                 vfModuleModelInfo.setModelName(vfModuleModelVerOpt.get().getModelName())
584                 vfModuleModelInfo.setModelVersion(vfModuleModelVerOpt.get().getModelVersion())
585             }
586             vfmodules.setModelInfo(vfModuleModelInfo)
587
588             vfmodules.setInstanceName(vfModule.getVfModuleName())
589
590             vfModuless.add(vfmodules)
591         }
592
593         return vfModuless
594     }
595
596
597     /**
598      * prepares VNF Model Info
599      * @param execution
600      * @param constituteVnf
601      * @return ModelInfo
602      */
603     ModelInfo prepareVNFModelInfo(DelegateExecution execution, GenericVnf constituteVnf) {
604         ModelInfo vnfModelInfo = new ModelInfo()
605
606         AAIResourcesClient client = getAAIClient()
607
608         vnfModelInfo.setModelInvariantUuid(constituteVnf.getModelInvariantId())
609         vnfModelInfo.setModelCustomizationId(constituteVnf.getModelCustomizationId())
610         vnfModelInfo.setModelInstanceName(constituteVnf.getVnfName())
611
612         AAIResourceUri vnfModelUrl = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, constituteVnf.getModelInvariantId(), constituteVnf.getModelVersionId())
613
614         Optional<ModelVer> vnfModelVerOpt = client.get(ModelVer.class, vnfModelUrl)
615
616         if (vnfModelVerOpt.isPresent()) {
617             vnfModelInfo.setModelVersionId(vnfModelVerOpt.get().getModelVersionId())
618             vnfModelInfo.setModelName(vnfModelVerOpt.get().getModelName())
619             vnfModelInfo.setModelVersion(vnfModelVerOpt.get().getModelVersion())
620         }
621
622         return vnfModelInfo
623     }
624
625
626     List<Map<String, Object>> prepareInstanceParams(DelegateExecution execution) {
627         def currentNSSI = execution.getVariable("currentNSSI")
628
629         List<Map<String, Object>> instanceParams = new ArrayList<>()
630         Map<String, Object> instanceParamsMap = new HashMap<>()
631
632         // Supported S-NSSAI
633         List<String> snssais = (List<String>) currentNSSI['S-NSSAIs']
634
635         ServiceInstance nssi = (ServiceInstance) currentNSSI['nssi']
636
637         String orchStatus = nssi.getOrchestrationStatus()
638
639
640         List<Map<String, String>> snssaiList = new ArrayList<>()
641
642         for(String snssai:snssais) {
643             Map<String, String> snssaisMap = new HashMap<>()
644             snssaisMap.put("snssai", snssai)
645             snssaisMap.put("status", orchStatus)
646             snssaiList.add(snssaisMap)
647         }
648
649         //    Map<String, List<Map<String, String>>> supportedNssaiDetails = new HashMap<>()
650         //    supportedNssaiDetails.put("sNssai", supportedNssaiDetails)
651
652         ObjectMapper mapper = new ObjectMapper()
653
654         String supportedNssaiDetailsStr = mapper.writeValueAsString(snssaiList)
655
656
657         instanceParamsMap.put("k8s-rb-profile-name", "default") // ???
658         instanceParamsMap.put("config-type", "day2") // ???
659         instanceParamsMap.put("supportedNssai", supportedNssaiDetailsStr)
660         instanceParams.add(instanceParamsMap)
661
662         return instanceParams
663     }
664
665     /**
666      * Prepares Resources
667      * @param execution
668      * @return Resources
669      */
670     Resources prepareResources(DelegateExecution execution) {
671         def currentNSSI = execution.getVariable("currentNSSI")
672
673         Resources resources = new Resources()
674
675         // VNFs
676         List<Vnfs> vnfs = new ArrayList<>()
677         // VNF
678         Vnfs vnf = new Vnfs()
679
680         // Line of Business
681         LineOfBusiness lob = new LineOfBusiness()
682         lob.setLineOfBusinessName("VNF")
683         vnf.setLineOfBusiness(lob)
684
685         // Product family ID
686         GenericVnf constituteVnf = (GenericVnf)currentNSSI['constituteVnf']
687         vnf.setProductFamilyId(constituteVnf.getServiceId())
688
689         // Cloud configuration
690         vnf.setCloudConfiguration(prepareCloudConfiguration(execution))
691
692         // VF Modules
693         vnf.setVfModules(prepareVfModules(execution, constituteVnf))
694
695         // Model Info
696         vnf.setModelInfo(prepareVNFModelInfo(execution, constituteVnf))
697
698         // Instance name
699         vnf.setInstanceName(constituteVnf.getVnfName())
700
701         // Instance params
702         vnf.setInstanceParams(prepareInstanceParams(execution))
703
704         // No platform data
705
706         vnfs.add(vnf)
707         resources.setVnfs(vnfs)
708
709         return resources
710     }
711
712
713     /**
714      * Prepare Service
715      * @return Service
716      */
717     Service prepareService(DelegateExecution execution, ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
718         Service service = new Service()
719
720         // Model Info
721         service.setModelInfo(prepareServiceModelInfo(networkServiceInstance, modelInfo))
722
723         service.setInstanceName(networkServiceInstance.getServiceInstanceName())
724
725         // Resources
726         service.setResources(prepareResources(execution))
727
728         return service
729
730     }
731
732
733     /**
734      * Prepares request parameters
735      * @param execution
736      * @return RequestParameters
737      */
738     RequestParameters prepareRequestParameters(DelegateExecution execution, ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
739         def currentNSSI = execution.getVariable("currentNSSI")
740
741         RequestParameters requestParameters = new RequestParameters()
742
743         ServiceSubscription serviceSubscription = (ServiceSubscription)currentNSSI['serviceSubscription']
744
745         if(serviceSubscription != null) {
746             requestParameters.setSubscriptionServiceType(serviceSubscription.getServiceType())
747         }
748
749         // User params
750         List<Map<String, Object>> userParams = new ArrayList<>()
751
752         Map<String, Object> userParam = new HashMap<>()
753         userParam.put("Homing_Solution", "none")
754         userParams.add(userParam)
755
756         // Service
757         Map<String, Object> serviceMap = new HashMap<>()
758         serviceMap.put("service", prepareService(execution, networkServiceInstance, modelInfo))
759         userParams.add(serviceMap)
760         requestParameters.setUserParams(userParams)
761
762         return requestParameters
763     }
764
765
766     /**
767      * Prepare Owning Entity
768      * @param execution
769      * @return OwningEntity
770      */
771     OwningEntity prepareOwningEntity(DelegateExecution execution) {
772         def currentNSSI = execution.getVariable("currentNSSI")
773
774         AAIResourcesClient client = getAAIClient()
775
776         AAIResourceUri networkServiceInstanceUri = (AAIResourceUri)currentNSSI['networkServiceInstanceUri']
777
778         OwningEntity owningEntity = new OwningEntity()
779         AAIResultWrapper wrapper = client.get(networkServiceInstanceUri)
780         Optional<Relationships> owningEntityRelationshipsOps = wrapper.getRelationships()
781         if (owningEntityRelationshipsOps.isPresent()) {
782             List<AAIResourceUri> owningEntityRelatedAAIUris = owningEntityRelationshipsOps.get().getRelatedAAIUris(AAIObjectType.OWNING_ENTITY)
783
784             if (!(owningEntityRelatedAAIUris == null || owningEntityRelatedAAIUris.isEmpty())) {
785                 Optional<org.onap.aai.domain.yang.OwningEntity> owningEntityOpt = client.get(org.onap.aai.domain.yang.OwningEntity.class, owningEntityRelatedAAIUris.get(0)) // Many-To-One relation
786                 if (owningEntityOpt.isPresent()) {
787                     owningEntity.setOwningEntityId(owningEntityOpt.get().getOwningEntityId())
788                     owningEntity.setOwningEntityName(owningEntityOpt.get().getOwningEntityName())
789
790                 }
791             }
792         }
793
794         return owningEntity
795     }
796
797
798     /**
799      * Prepares Project
800      * @param execution
801      * @return Project
802      */
803     Project prepareProject(DelegateExecution execution) {
804         def currentNSSI = execution.getVariable("currentNSSI")
805
806         AAIResourcesClient client = getAAIClient()
807
808         Project project = new Project()
809
810         AAIResourceUri cloudRegionRelatedAAIUri = (AAIResourceUri)currentNSSI['cloudRegionRelatedAAIUri']
811
812         if (cloudRegionRelatedAAIUri != null) {
813             AAIResultWrapper wrapper = client.get(cloudRegionRelatedAAIUri)
814             Optional<Relationships> cloudRegionOps = wrapper.getRelationships()
815             if (cloudRegionOps.isPresent()) {
816                 List<AAIResourceUri> projectAAIUris = cloudRegionOps.get().getRelatedAAIUris(AAIObjectType.PROJECT)
817                 if (!(projectAAIUris == null || projectAAIUris.isEmpty())) {
818                     Optional<org.onap.aai.domain.yang.Project> projectOpt = client.get(org.onap.aai.domain.yang.Project.class, projectAAIUris.get(0))
819                     if (projectOpt.isPresent()) {
820                         project.setProjectName(projectOpt.get().getProjectName())
821                     }
822                 }
823             }
824         }
825
826         return project
827     }
828
829
830     /**
831      * Prepares RequestDetails object
832      * @param execution
833      * @return
834      */
835     String prepareRequestDetails(DelegateExecution execution) {
836         String errorCode = ""
837         String errorMessage = ""
838         String response
839
840         RequestDetails requestDetails = new RequestDetails()
841
842         def currentNSSI = execution.getVariable("currentNSSI")
843
844         ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
845
846         try {
847             // Model Info
848             ModelInfo modelInfo = prepareModelInfo(execution)
849             requestDetails.setModelInfo(modelInfo)
850
851             // Subscriber Info
852             requestDetails.setSubscriberInfo(prepareSubscriberInfo(execution))
853
854             // Request Info
855             requestDetails.setRequestInfo(prepareRequestInfo(execution, networkServiceInstance))
856
857             // Request Parameters
858             requestDetails.setRequestParameters(prepareRequestParameters(execution, networkServiceInstance, modelInfo))
859
860             // Cloud configuration
861             requestDetails.setCloudConfiguration(prepareCloudConfiguration(execution))
862
863             // Owning entity
864             requestDetails.setOwningEntity(prepareOwningEntity(execution))
865
866             // Project
867             requestDetails.setProject(prepareProject(execution))
868
869             ObjectMapper mapper = new ObjectMapper()
870
871             response = mapper.writeValueAsString(requestDetails)
872         }
873         catch (any) {
874             String msg = "Exception in ${getPrefix()}.prepareRequestDetails. " + any.getCause()
875             LOGGER.error(msg)
876
877             response =  "{\n" +
878                     " \"errorCode\": \"7000\",\n" +
879                     " \"errorMessage\": \"${msg}\"\n" +
880                     "}"
881
882         }
883
884         return response
885     }
886
887
888     String getAuthHeader(DelegateExecution execution, String basicAuthValue, String msokey) {
889         String response = ""
890         String errorCode = ""
891         String errorMessage = ""
892
893         LOGGER.debug("Obtained BasicAuth username and password for OOF: " + basicAuthValue)
894         try {
895             response = utils.getBasicAuth(basicAuthValue, msokey)
896         } catch (Exception ex) {
897             LOGGER.error("Unable to encode username and password string: ", ex)
898
899             errorCode = "401"
900             errorMessage = "Internal Error - Unable to encode username and password string"
901
902             response =  "{\n" +
903                     " \"errorCode\": \"${errorCode}\",\n" +
904                     " \"errorMessage\": \"${errorMessage}\"\n" +
905                     "}"
906         }
907
908         return response
909     }
910
911
912     String encryptBasicAuth(String basicAuth, String msoKey) {
913         return utils.encrypt(basicAuth, msoKey)
914     }
915
916
917     /**
918      * Removes Slice Profile association with NSSI
919      * @param execution
920      */
921     void removeSPAssociationWithNSSI(DelegateExecution execution) {
922         LOGGER.trace("${getPrefix()} Start removeSPAssociationWithNSSI")
923
924         AAIResourcesClient client = getAAIClient()
925
926         def currentNSSI = execution.getVariable("currentNSSI")
927
928         ServiceInstance nssi = (ServiceInstance)currentNSSI['nssi']
929
930         String nssiId = currentNSSI['nssiId']
931         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, nssiId)
932
933         List<SliceProfile> associatedProfiles = nssi.getSliceProfiles().getSliceProfile()
934
935         String currentSNSSAI = currentNSSI['S-NSSAI']
936
937         associatedProfiles.removeIf({ associatedProfile -> (associatedProfile.getSNssai().equals(currentSNSSAI)) })
938
939         try {
940             getAAIClient().update(nssiUri, nssi)
941         }catch(Exception e){
942             exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile association with NSSI update call: " + e.getMessage())
943         }
944
945         LOGGER.trace("${getPrefix()} Exit removeSPAssociationWithNSSI")
946     }
947
948
949     /**
950      * Deletes Slice Profile Instance
951      * @param execution
952      */
953     void deleteSliceProfileInstance(DelegateExecution execution) {
954         LOGGER.trace("${getPrefix()} Start deleteSliceProfileInstance")
955
956         AAIResourcesClient client = getAAIClient()
957
958         def currentNSSI = execution.getVariable("currentNSSI")
959
960         SliceProfile sliceProfileContainsSNSSAI = (SliceProfile)currentNSSI['sliceProfileS-NSSAI']
961
962         String globalSubscriberId = currentNSSI['globalSubscriberId']
963         String serviceType = currentNSSI['serviceType']
964         String nssiId = currentNSSI['nssiId']
965
966         // global-customer-id, service-type, service-instance-id, profile-id
967         AAIResourceUri sliceProfileUri = AAIUriFactory.createResourceUri(AAIObjectType.SLICE_PROFILE, globalSubscriberId, serviceType, nssiId, sliceProfileContainsSNSSAI.getProfileId())
968
969         try {
970             getAAIClient().delete(sliceProfileUri)
971         }catch(Exception e){
972             exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile Instance delete call: " + e.getMessage())
973         }
974
975         LOGGER.trace("${getPrefix()} Exit deleteSliceProfileInstance")
976     }
977
978
979     /**
980      * Updates operation status
981      * @param execution
982      */
983     void updateServiceOperationStatus(DelegateExecution execution) {
984         LOGGER.trace("${getPrefix()} Start updateServiceOperationStatus")
985
986         def currentNSSI = execution.getVariable("currentNSSI")
987
988         OperationStatus operationStatus = new OperationStatus()
989         operationStatus.setServiceId(currentNSSI['e2eServiceInstanceId'] as String)
990         operationStatus.setOperationId(currentNSSI['operationId'] as String)
991         operationStatus.setOperation(currentNSSI['operationType'] as String)
992         operationStatus.setResult(RequestsDbConstant.Status.FINISHED)
993
994         requestDBUtil.prepareUpdateOperationStatus(execution, operationStatus)
995
996         LOGGER.trace("${getPrefix()} Exit updateServiceOperationStatus")
997     }
998
999
1000     /**
1001      * Returns AAI client
1002      * @return AAI client
1003      */
1004     AAIResourcesClient getAAIClient() {
1005         return new AAIResourcesClient()
1006     }
1007
1008
1009     String getPrefix() {
1010         return PREFIX
1011     }
1012 }