Update license headers
[vid.git] / vid-app-common / src / main / java / org / onap / vid / job / command / ALaCarteServiceCommand.kt
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 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.onap.vid.job.command
22
23 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate
24 import org.onap.vid.changeManagement.RequestDetailsWrapper
25 import org.onap.vid.job.*
26 import org.onap.vid.model.Action
27 import org.onap.vid.model.serviceInstantiation.ServiceInstantiation
28 import org.onap.vid.mso.RestMsoImplementation
29 import org.onap.vid.mso.model.ServiceDeletionRequestDetails
30 import org.onap.vid.properties.VidProperties
31 import org.onap.vid.services.AsyncInstantiationBusinessLogic
32 import org.springframework.beans.factory.annotation.Autowired
33 import org.springframework.beans.factory.config.ConfigurableBeanFactory
34 import org.springframework.context.annotation.Scope
35 import org.springframework.http.HttpMethod
36 import org.springframework.stereotype.Component
37 import java.time.ZonedDateTime
38 import java.time.temporal.ChronoUnit
39 import java.util.*
40
41 class ServiceExpiryChecker : ExpiryChecker {
42
43     override fun isExpired(jobStartTime: ZonedDateTime?): Boolean {
44         val now = ZonedDateTime.now()
45         val maxHoursInProgress = VidProperties.getLongProperty(VidProperties.VID_JOB_MAX_HOURS_IN_PROGRESS)
46         val hoursBetween = ChronoUnit.HOURS.between(jobStartTime, now)
47         return maxHoursInProgress in 1..hoursBetween
48     }
49 }
50
51
52 @Component
53 @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
54 class ALaCarteServiceCommand @Autowired constructor(
55         inProgressStatusService: InProgressStatusService,
56         watchChildrenJobsBL: WatchChildrenJobsBL,
57         private val asyncInstantiationBL: AsyncInstantiationBusinessLogic,
58         private val jobsBrokerService: JobsBrokerService,
59         msoResultHandlerService: MsoResultHandlerService,
60         private val jobAdapter: JobAdapter,
61         restMso: RestMsoImplementation
62 ) : ResourceCommand(restMso, inProgressStatusService, msoResultHandlerService, watchChildrenJobsBL), JobCommand {
63
64     override fun getExpiryChecker(): ExpiryChecker {
65         return ServiceExpiryChecker();
66     }
67
68     companion object {
69         private val LOGGER = EELFLoggerDelegate.getLogger(ALaCarteServiceCommand::class.java)
70     }
71
72     override fun getRequest(): ServiceInstantiation {
73         return msoResultHandlerService.getRequest(sharedData)
74     }
75
76     override fun createChildren(): Job.JobStatus {
77         val dataForChild = buildDataForChild(getRequest())//.plus(ACTION_PHASE to actionPhase)
78
79         val childJobType = when (actionPhase) {
80             Action.Create -> JobType.InstanceGroupInstantiation
81             Action.Delete -> JobType.InstanceGroup
82             else -> return Job.JobStatus.COMPLETED
83         }
84
85         childJobs = getRequest().vnfGroups
86                 .map { jobAdapter.createChildJob(childJobType, Job.JobStatus.CREATING, it.value, sharedData, dataForChild) }
87                 .map { jobsBrokerService.add(it) }
88                 .map { it.toString() }
89
90         return Job.JobStatus.COMPLETED_WITH_NO_ACTION
91     }
92
93     private fun buildDataForChild(request: ServiceInstantiation): Map<String, Any> {
94         val commandParentData = CommandParentData()
95         commandParentData.addInstanceId(CommandParentData.CommandDataKey.SERVICE_INSTANCE_ID, request.instanceId)
96         commandParentData.addModelInfo(CommandParentData.CommandDataKey.SERVICE_MODEL_INFO, request.modelInfo)
97         return commandParentData.parentData
98     }
99
100     override fun planCreateMyselfRestCall(commandParentData: CommandParentData, request: JobAdapter.AsyncJobRequest, userId: String): MsoRestCallPlan {
101         TODO("not implemented")
102     }
103
104     override fun planDeleteMyselfRestCall(commandParentData: CommandParentData, request: JobAdapter.AsyncJobRequest, userId: String): MsoRestCallPlan {
105         val requestDetailsWrapper = generateServiceDeletionRequest()
106         val path = asyncInstantiationBL.getServiceDeletionPath(getRequest().instanceId)
107         return MsoRestCallPlan(HttpMethod.DELETE, path, Optional.of(requestDetailsWrapper), Optional.empty(),
108                 "delete instance with id ${getRequest().instanceId}")
109
110     }
111
112     override fun handleInProgressStatus(jobStatus: Job.JobStatus): Job.JobStatus {
113         if (jobStatus==Job.JobStatus.FAILED) {
114             asyncInstantiationBL.handleFailedInstantiation(sharedData.jobUuid)
115             return jobStatus
116         }
117
118         asyncInstantiationBL.updateServiceInfoAndAuditStatus(sharedData.jobUuid, jobStatus)
119         return  if (jobStatus == Job.JobStatus.PAUSE) Job.JobStatus.IN_PROGRESS else jobStatus
120     }
121
122
123     private fun generateServiceDeletionRequest(): RequestDetailsWrapper<ServiceDeletionRequestDetails> {
124         return asyncInstantiationBL.generateALaCarteServiceDeletionRequest(
125                 sharedData.jobUuid, getRequest(), sharedData.userId
126         )
127     }
128
129     override fun getExternalInProgressStatus() = Job.JobStatus.IN_PROGRESS
130
131     override fun isServiceCommand(): Boolean = true
132
133     override fun onFinal(jobStatus: Job.JobStatus) {
134         asyncInstantiationBL.updateServiceInfoAndAuditStatus(sharedData.jobUuid, jobStatus)
135     }
136
137     override fun onInitial(phase: Action) {
138         if (phase== Action.Delete) {
139             asyncInstantiationBL.updateServiceInfoAndAuditStatus(sharedData.jobUuid, Job.JobStatus.IN_PROGRESS)
140         }
141     }
142 }