Implant vid-app-common org.onap.vid.job (main and test)
[vid.git] / vid-app-common / src / main / java / org / onap / vid / job / command / VnfCommand.kt
1 package org.onap.vid.job.command
2
3 import org.apache.commons.collections.MapUtils
4 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate
5 import org.onap.vid.asdc.AsdcCatalogException
6 import org.onap.vid.job.*
7 import org.onap.vid.job.impl.JobSharedData
8 import org.onap.vid.model.Action
9 import org.onap.vid.model.serviceInstantiation.BaseResource
10 import org.onap.vid.model.serviceInstantiation.VfModule
11 import org.onap.vid.model.serviceInstantiation.Vnf
12 import org.onap.vid.mso.RestMsoImplementation
13 import org.onap.vid.properties.Features
14 import org.onap.vid.services.AsyncInstantiationBusinessLogic
15 import org.springframework.beans.factory.annotation.Autowired
16 import org.springframework.beans.factory.config.ConfigurableBeanFactory
17 import org.springframework.context.annotation.Scope
18 import org.springframework.http.HttpMethod
19 import org.springframework.stereotype.Component
20 import org.togglz.core.manager.FeatureManager
21 import java.util.*
22 import java.util.stream.Collectors
23 import kotlin.properties.Delegates
24
25 const val NEED_TO_CREATE_BASE_MODULE = "needToCreateBaseModule"
26
27 @Component
28 @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
29 class VnfCommand @Autowired constructor(
30         private val asyncInstantiationBL: AsyncInstantiationBusinessLogic,
31         restMso: RestMsoImplementation,
32         private val msoRequestBuilder: MsoRequestBuilder,
33         msoResultHandlerService: MsoResultHandlerService,
34         inProgressStatusService:InProgressStatusService,
35         watchChildrenJobsBL: WatchChildrenJobsBL,
36         jobsBrokerService: JobsBrokerService,
37         jobAdapter: JobAdapter,
38         private val featureManager: FeatureManager
39 ) : ResourceCommand(restMso, inProgressStatusService, msoResultHandlerService,
40         watchChildrenJobsBL, jobsBrokerService, jobAdapter), JobCommand {
41
42     private var needToCreateBaseModule:Boolean by Delegates.notNull<Boolean>()
43
44     override fun getData(): Map<String, Any?> {
45         return super.getData() + mapOf(NEED_TO_CREATE_BASE_MODULE to needToCreateBaseModule)
46     }
47
48     override fun init(sharedData: JobSharedData, commandData: Map<String, Any>): ResourceCommand {
49         super<ResourceCommand>.init(sharedData, commandData)
50         needToCreateBaseModule = commandData.getOrDefault(NEED_TO_CREATE_BASE_MODULE, actionPhase != Action.Delete) as Boolean
51         return this
52     }
53
54
55     override fun createChildren(): Job.JobStatus {
56         val request:Vnf = getRequest()
57         if(isNeedToCreateChildJobs()){
58             val dataForChild = buildDataForChild(request, actionPhase)
59             val vfModules:List<VfModule> = request.vfModules.values.stream().flatMap { vfKey -> vfKey.values.stream() }.collect(Collectors.toList<VfModule>())
60
61             try {
62                 childJobs = pushChildrenJobsToBroker(vfModules.filter { filterModuleByNeedToCreateBase(it) }, dataForChild, JobType.VolumeGroupInstantiation)
63             } catch (e: AsdcCatalogException) {
64                 LOGGER.error("Failed to retrieve service definitions from SDC, for VfModule is BaseModule.. Error: " + e.message , e)
65                 return Job.JobStatus.FAILED
66             }
67         }
68
69         return Job.JobStatus.COMPLETED_WITH_NO_ACTION
70     }
71
72     private fun filterModuleByNeedToCreateBase(it: VfModule):Boolean {
73         return needToCreateBaseModule ==
74             commandUtils.isVfModuleBaseModule(
75                 commandParentData.getModelInfo(CommandParentData.CommandDataKey.SERVICE_MODEL_INFO).getModelVersionId(),
76                 it.modelInfo.modelVersionId)
77     }
78
79     override fun planCreateMyselfRestCall(commandParentData: CommandParentData, request: JobAdapter.AsyncJobRequest, userId: String, testApi: String?): MsoRestCallPlan {
80         val serviceInstanceId = commandParentData.getInstanceId(CommandParentData.CommandDataKey.SERVICE_INSTANCE_ID)
81         val serviceModelInfo = commandParentData.getModelInfo(CommandParentData.CommandDataKey.SERVICE_MODEL_INFO)
82
83         val instantiatePath = asyncInstantiationBL.getVnfInstantiationPath(serviceInstanceId)
84
85         val requestDetailsWrapper = msoRequestBuilder.generateVnfInstantiationRequest(
86                 request as Vnf,
87                 serviceModelInfo, serviceInstanceId,
88                 userId,
89                 testApi
90         )
91
92         val actionDescription = "create vnf in $serviceInstanceId"
93
94         return MsoRestCallPlan(HttpMethod.POST, instantiatePath, Optional.of(requestDetailsWrapper), Optional.empty(), actionDescription)
95
96     }
97
98     override fun addMyselfToChildrenData(commandParentData: CommandParentData, request: BaseResource) {
99         commandParentData.addModelInfo(CommandParentData.CommandDataKey.VNF_MODEL_INFO, request.modelInfo);
100         commandParentData.addInstanceId(CommandParentData.CommandDataKey.VNF_INSTANCE_ID, getActualInstanceId(request))
101     }
102
103     override fun getRequest(): Vnf {
104         return sharedData.request as Vnf
105     }
106
107     private fun isNeedToCreateChildJobs(): Boolean {
108         return featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE) &&
109                 MapUtils.isNotEmpty(getRequest().vfModules)
110     }
111
112     override fun planDeleteMyselfRestCall(commandParentData: CommandParentData, request: JobAdapter.AsyncJobRequest, userId: String): MsoRestCallPlan {
113         val serviceInstanceId = commandParentData.getInstanceId(CommandParentData.CommandDataKey.SERVICE_INSTANCE_ID)
114         val path = asyncInstantiationBL.getVnfDeletionPath(serviceInstanceId, getRequest().instanceId)
115         val requestDetailsWrapper = msoRequestBuilder.generateDeleteVnfRequest(getRequest(), userId)
116         return MsoRestCallPlan(HttpMethod.DELETE, path, Optional.of(requestDetailsWrapper), Optional.of(userId),
117                 "delete vnf ${getRequest().instanceId} from service $serviceInstanceId")
118
119     }
120
121     companion object {
122         private val LOGGER = EELFLoggerDelegate.getLogger(VnfCommand::class.java)
123     }
124
125     //in Delete phase - we delete all non-base vf-modules first, before base vf-module
126     //in Create phase - we create base vf-module first, and then all the others
127     override fun watchChildren(): Job.JobStatus {
128         val childrenStatus:Job.JobStatus = comulateStatusAndUpdatePropertyIfFinal(watchChildrenJobsBL.retrieveChildrenJobsStatus(childJobs))
129         if (!childrenStatus.isFinal ||
130                 childrenStatus.isFailure ||
131                 (actionPhase == Action.Create && !needToCreateBaseModule) ||
132                 (actionPhase == Action.Delete && needToCreateBaseModule)) {
133             return childrenStatus
134         }
135
136         needToCreateBaseModule = !needToCreateBaseModule;
137         createChildren()
138         return Job.JobStatus.IN_PROGRESS
139     }
140 }