2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.vid.job.command
24 import com.fasterxml.jackson.module.kotlin.convertValue
25 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate
26 import org.onap.vid.changeManagement.RequestDetailsWrapper
27 import org.onap.vid.exceptions.AbortingException
28 import org.onap.vid.exceptions.TryAgainException
29 import org.onap.vid.job.*
30 import org.onap.vid.job.Job.JobStatus
31 import org.onap.vid.job.impl.JobSharedData
32 import org.onap.vid.model.Action
33 import org.onap.vid.model.RequestReferencesContainer
34 import org.onap.vid.model.serviceInstantiation.BaseResource
35 import org.onap.vid.mso.RestMsoImplementation
36 import org.onap.vid.utils.JACKSON_OBJECT_MAPPER
37 import org.onap.vid.utils.getEnumFromMapOfStrings
38 import org.springframework.http.HttpMethod
42 const val INTERNAL_STATE = "internalState"
43 const val ACTION_PHASE = "actionPhase"
44 const val CHILD_JOBS = "childJobs"
45 const val MSO_RESOURCE_ID = "msoResourceIds"
46 const val CUMULATIVE_STATUS = "cumulativeStatus"
48 enum class InternalState constructor(val immediate:Boolean=false) {
50 CREATING_CHILDREN(true),
60 data class NextInternalState(val nextActionPhase: Action, val nextInternalState: InternalState)
63 data class MsoRestCallPlan(
64 val httpMethod: HttpMethod,
66 val payload: Optional<RequestDetailsWrapper<out Any>>,
67 val userId: Optional<String>,
68 val actionDescription: String
71 abstract class ResourceCommand(
72 protected val restMso: RestMsoImplementation,
73 protected val inProgressStatusService: InProgressStatusService,
74 protected val msoResultHandlerService: MsoResultHandlerService,
75 protected val watchChildrenJobsBL: WatchChildrenJobsBL,
76 private val jobsBrokerService: JobsBrokerService,
77 private val jobAdapter: JobAdapter
78 ) : CommandBase(), JobCommand {
81 private val Logger = EELFLoggerDelegate.getLogger(ResourceCommand::class.java)
84 abstract fun createChildren():JobStatus
86 abstract fun planCreateMyselfRestCall(commandParentData: CommandParentData, request: JobAdapter.AsyncJobRequest, userId: String, testApi: String?): MsoRestCallPlan
88 abstract fun planDeleteMyselfRestCall(commandParentData: CommandParentData, request: JobAdapter.AsyncJobRequest, userId: String): MsoRestCallPlan
90 private val commandByInternalState: Map<InternalState, () -> JobStatus> = hashMapOf(
91 Pair(InternalState.CREATING_CHILDREN, ::createChildren),
92 Pair(InternalState.WATCHING, ::watchChildren),
93 Pair(InternalState.CREATE_MYSELF, ::createMyself),
94 Pair(InternalState.RESUME_MYSELF, ::resumeMyself),
95 Pair(InternalState.DELETE_MYSELF, ::deleteMyself),
96 Pair(InternalState.IN_PROGRESS, ::inProgress),
97 Pair(InternalState.REPLACE_MYSELF, ::replaceMyself)
100 private lateinit var internalState:InternalState
101 protected lateinit var actionPhase: Action
102 protected var commandParentData: CommandParentData = CommandParentData()
103 protected var msoResourceIds: MsoResourceIds = EMPTY_MSO_RESOURCE_ID
104 protected var childJobs:List<String> = emptyList()
105 private lateinit var cumulativeStatus:JobStatus
108 override fun call(): NextCommand {
109 var jobStatus:JobStatus = if (internalState!=InternalState.TERMINAL) invokeCommand() else cumulativeStatus
110 jobStatus = comulateStatusAndUpdatePropertyIfFinal(jobStatus)
113 Logger.debug("job: ${this.javaClass.simpleName} ${sharedData.jobUuid} $actionPhase ${getActionType()} $internalState $jobStatus $childJobs")
114 } catch (e:Exception) { /* do nothing. Just failed to log...*/}
116 if (shallStopJob(jobStatus)) {
118 return NextCommand(jobStatus)
121 val (nextActionPhase, nextInternalState) = calcNextInternalState(jobStatus, internalState, actionPhase)
122 Logger.debug("next state for job ${sharedData.jobUuid} is $nextInternalState")
123 actionPhase = nextActionPhase
124 internalState = nextInternalState
126 if (internalState==InternalState.TERMINAL) {
128 return NextCommand(jobStatus)
131 jobStatus = getExternalInProgressStatus()
132 Logger.debug("next status for job ${sharedData.jobUuid} is $jobStatus")
133 // if (internalState.immediate) return call() //shortcut instead of execute another command
134 return NextCommand(jobStatus, this)
137 //we want to stop in faliures, except for service witn no action, since service with no action trigger 2 phases (delete and create)
138 protected fun shallStopJob(jobStatus: JobStatus) =
139 jobStatus.isFailure && !(isServiceCommand() && getActionType()==Action.None)
141 //this method is used to expose the job status after successful completion of current state
142 //should be override by subclass (like ServiceCommand) that need to return other default job status
143 protected open fun getExternalInProgressStatus() = JobStatus.RESOURCE_IN_PROGRESS
145 private fun invokeCommand(): JobStatus {
147 commandByInternalState.getOrDefault(internalState, ::throwIllegalState).invoke()
149 catch (exception: TryAgainException) {
150 Logger.warn("caught TryAgainException. Set job status to IN_PROGRESS")
151 JobStatus.IN_PROGRESS
153 catch (exception: AbortingException) {
154 Logger.error("caught AbortingException. Set job status to FAILED")
159 private fun throwIllegalState():JobStatus {
160 throw IllegalStateException("can't find action for pashe $actionPhase and state $internalState")
163 private fun calcNextInternalState(jobStatus: JobStatus, internalState: InternalState, actionPhase: Action): NextInternalState {
165 val nextInternalState = when (actionPhase) {
166 Action.Delete -> calcNextStateDeletePhase(jobStatus, internalState)
167 Action.Create -> calcNextStateCreatePhase(jobStatus, internalState)
168 else -> InternalState.TERMINAL
171 if (nextInternalState == InternalState.TERMINAL
172 && actionPhase == Action.Delete
173 && isServiceCommand()) {
174 // Loop over to "Create" phase
175 return NextInternalState(Action.Create, InternalState.INITIAL)
178 return NextInternalState(actionPhase, nextInternalState)
182 //no need to refer to failed (final) states here
183 //This method is called only for non final states or COMPLETED
184 protected fun calcNextStateDeletePhase(jobStatus: JobStatus, internalState: InternalState): InternalState {
185 return when (internalState) {
187 InternalState.CREATING_CHILDREN -> InternalState.WATCHING
189 InternalState.WATCHING -> {
191 !jobStatus.isFinal -> InternalState.WATCHING
192 isNeedToDeleteMyself() -> InternalState.DELETE_MYSELF
193 else -> InternalState.TERMINAL
197 InternalState.DELETE_MYSELF -> InternalState.IN_PROGRESS
199 InternalState.IN_PROGRESS -> {
200 if (jobStatus == JobStatus.COMPLETED) InternalState.TERMINAL else InternalState.IN_PROGRESS
203 else -> InternalState.TERMINAL
207 protected fun calcNextStateCreatePhase(jobStatus: JobStatus, internalState: InternalState): InternalState {
208 return when (internalState) {
210 InternalState.CREATE_MYSELF -> when (jobStatus) {
211 JobStatus.IN_PROGRESS -> InternalState.CREATE_MYSELF
212 else -> InternalState.IN_PROGRESS
215 InternalState.RESUME_MYSELF -> when (jobStatus) {
216 JobStatus.IN_PROGRESS -> InternalState.RESUME_MYSELF
217 else -> InternalState.IN_PROGRESS
220 InternalState.REPLACE_MYSELF -> when (jobStatus) {
221 JobStatus.IN_PROGRESS -> InternalState.REPLACE_MYSELF
222 else -> InternalState.IN_PROGRESS
225 InternalState.REPLACE_MYSELF -> when (jobStatus) {
226 JobStatus.IN_PROGRESS -> InternalState.REPLACE_MYSELF
227 else -> InternalState.IN_PROGRESS
230 InternalState.IN_PROGRESS -> {
232 jobStatus != JobStatus.COMPLETED -> InternalState.IN_PROGRESS
233 isDescendantHasAction(Action.Create) -> InternalState.CREATING_CHILDREN
234 isDescendantHasAction(Action.Upgrade) -> InternalState.CREATING_CHILDREN
235 else -> InternalState.TERMINAL
239 InternalState.CREATING_CHILDREN -> InternalState.WATCHING
241 InternalState.WATCHING -> {
243 !jobStatus.isFinal -> InternalState.WATCHING
244 else -> InternalState.TERMINAL
248 else -> InternalState.TERMINAL
252 override fun getData(): Map<String, Any?> {
254 ACTION_PHASE to actionPhase,
255 INTERNAL_STATE to internalState,
256 MSO_RESOURCE_ID to msoResourceIds,
257 CHILD_JOBS to childJobs,
258 CUMULATIVE_STATUS to cumulativeStatus
259 ) + commandParentData.parentData
262 override fun init(sharedData: JobSharedData, commandData: Map<String, Any>): ResourceCommand {
264 val resourceIdsRaw:Any? = commandData[MSO_RESOURCE_ID]
265 commandParentData.initParentData(commandData)
267 if (resourceIdsRaw != null) JACKSON_OBJECT_MAPPER.convertValue(resourceIdsRaw)
268 else EMPTY_MSO_RESOURCE_ID
270 childJobs = JACKSON_OBJECT_MAPPER.convertValue(commandData.getOrDefault(CHILD_JOBS, emptyList<String>()))
271 cumulativeStatus = getEnumFromMapOfStrings(commandData, CUMULATIVE_STATUS, JobStatus.COMPLETED_WITH_NO_ACTION)
272 actionPhase = getEnumFromMapOfStrings(commandData, ACTION_PHASE, Action.Delete)
273 internalState = calcInitialState(commandData, actionPhase)
277 fun calcInitialState(commandData: Map<String, Any>, phase: Action):InternalState {
278 val status:InternalState = getEnumFromMapOfStrings(commandData, INTERNAL_STATE, InternalState.INITIAL)
279 if (status == InternalState.INITIAL) {
281 return when (phase) {
282 Action.Delete -> when {
283 isDescendantHasAction(phase) -> InternalState.CREATING_CHILDREN
284 isNeedToDeleteMyself() -> InternalState.DELETE_MYSELF
285 else -> InternalState.TERMINAL
287 Action.Create -> when {
288 isNeedToCreateMyself() -> InternalState.CREATE_MYSELF
289 isNeedToResumeMySelf() -> InternalState.RESUME_MYSELF
290 isNeedToReplaceMySelf() -> InternalState.REPLACE_MYSELF
291 isDescendantHasAction(phase) -> InternalState.CREATING_CHILDREN
292 isDescendantHasAction(Action.Upgrade) -> InternalState.CREATING_CHILDREN
293 else -> InternalState.TERMINAL
295 else -> throw IllegalStateException("state $internalState is not supported yet")
301 //command may override it in order to do something while init state
302 protected open fun onInitial(phase: Action) {
306 //command may override it in order to do something while final status
307 protected open fun onFinal(jobStatus: JobStatus) {
311 protected open fun getRequest(): BaseResource {
312 return sharedData.request as BaseResource
315 protected open fun getActionType(): Action {
316 return getRequest().action
319 protected open fun isServiceCommand(): Boolean = false
321 protected open fun isNeedToDeleteMyself(): Boolean = getActionType() == Action.Delete
323 protected open fun isNeedToCreateMyself(): Boolean = getActionType() == Action.Create
325 protected open fun isNeedToResumeMySelf(): Boolean = getActionType() == Action.Resume
327 protected open fun isNeedToReplaceMySelf(): Boolean = false
329 protected open fun inProgress(): JobStatus {
330 val requestId:String = msoResourceIds.requestId;
332 val jobStatus = inProgressStatusService.call(getExpiryChecker(), sharedData, requestId)
333 handleInProgressStatus(jobStatus)
334 } catch (e: javax.ws.rs.ProcessingException) {
335 // Retry when we can't connect MSO during getStatus
336 Logger.error(EELFLoggerDelegate.errorLogger, "Cannot get orchestration status for {}, will retry: {}", requestId, e, e)
337 JobStatus.IN_PROGRESS;
338 } catch (e: InProgressStatusService.BadResponseFromMso) {
339 inProgressStatusService.handleFailedMsoResponse(sharedData.jobUuid, requestId, e.msoResponse)
340 JobStatus.IN_PROGRESS
341 } catch (e: RuntimeException) {
342 Logger.error(EELFLoggerDelegate.errorLogger, "Cannot get orchestration status for {}, stopping: {}", requestId, e, e)
347 fun createMyself(): JobStatus {
348 val createMyselfCommand = planCreateMyselfRestCall(commandParentData, sharedData.request, sharedData.userId, sharedData.testApi)
349 return executeAndHandleMsoInstanceRequest(createMyselfCommand)
352 protected open fun resumeMyself(): JobStatus {
353 throw NotImplementedError("Resume is not implemented for this command " + this.javaClass)
356 protected open fun replaceMyself(): JobStatus {
357 throw NotImplementedError("Replace is not implemented for this command " + this.javaClass)
360 fun deleteMyself(): JobStatus {
361 val deleteMyselfCommand = planDeleteMyselfRestCall(commandParentData, sharedData.request, sharedData.userId)
362 return executeAndHandleMsoInstanceRequest(deleteMyselfCommand)
365 protected fun executeAndHandleMsoInstanceRequest(restCallPlan: MsoRestCallPlan): JobStatus {
366 val msoResponse = restMso.restCall(
367 restCallPlan.httpMethod,
368 RequestReferencesContainer::class.java,
369 restCallPlan.payload.orElse(null),
374 val msoResult = if (isServiceCommand()) {
375 msoResultHandlerService.handleRootResponse(sharedData, msoResponse)
377 msoResultHandlerService.handleResponse(sharedData, msoResponse, restCallPlan.actionDescription)
380 this.msoResourceIds = msoResult.msoResourceIds
381 return msoResult.jobStatus
384 protected open fun getExpiryChecker(): ExpiryChecker = ExpiryChecker {false}
386 protected open fun handleInProgressStatus(jobStatus: JobStatus): JobStatus {
387 return if (jobStatus == JobStatus.PAUSE) JobStatus.IN_PROGRESS else jobStatus
390 protected open fun watchChildren():JobStatus {
391 return watchChildrenJobsBL.retrieveChildrenJobsStatus(childJobs)
394 protected fun comulateStatusAndUpdatePropertyIfFinal(internalStateStatus: JobStatus): JobStatus {
395 val status = watchChildrenJobsBL.cumulateJobStatus(internalStateStatus, cumulativeStatus)
397 //we want to update cumulativeStatus only for final status
398 if (status.isFinal) {
399 cumulativeStatus = status;
405 protected fun buildDataForChild(request: BaseResource, actionPhase: Action): Map<String, Any> {
406 addMyselfToChildrenData(commandParentData, request)
407 commandParentData.setActionPhase(actionPhase)
408 return commandParentData.parentData
411 protected open fun addMyselfToChildrenData(commandParentData: CommandParentData, request: BaseResource) {
412 // Nothing by default
415 protected open fun isDescendantHasAction(phase:Action):Boolean = isDescendantHasAction(getRequest(), phase, true )
419 fun isDescendantHasAction(request: BaseResource, phase: Action, isFirstLevel:Boolean=true): Boolean {
420 if (!isFirstLevel && request.action == phase) {
424 return request.children.map {this.isDescendantHasAction(it, phase, false)}.any {it}
427 protected fun getActualInstanceId(request: BaseResource):String =
428 if (getActionType() == Action.Create) msoResourceIds.instanceId else request.instanceId
431 protected fun pushChildrenJobsToBroker(children:Collection<BaseResource>,
432 dataForChild: Map<String, Any>,
433 jobType: JobType?=null): List<String> {
436 .map {Pair(it, counter++)}
437 .map { jobAdapter.createChildJob(jobType ?: it.first.jobType, it.first, sharedData, dataForChild, it.second) }
438 .map { jobsBrokerService.add(it) }
439 .map { it.toString() }