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.apache.commons.lang3.ObjectUtils.defaultIfNull
26 import org.onap.logging.ref.slf4j.ONAPLogConstants
27 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate
28 import org.onap.vid.changeManagement.RequestDetailsWrapper
29 import org.onap.vid.exceptions.AbortingException
30 import org.onap.vid.exceptions.TryAgainException
31 import org.onap.vid.job.*
32 import org.onap.vid.job.Job.JobStatus
33 import org.onap.vid.job.impl.JobSharedData
34 import org.onap.vid.model.Action
35 import org.onap.vid.model.RequestReferencesContainer
36 import org.onap.vid.model.serviceInstantiation.BaseResource
37 import org.onap.vid.mso.RestMsoImplementation
38 import org.onap.vid.utils.JACKSON_OBJECT_MAPPER
39 import org.onap.vid.utils.getEnumFromMapOfStrings
41 import org.springframework.http.HttpMethod
45 const val INTERNAL_STATE = "internalState"
46 const val ACTION_PHASE = "actionPhase"
47 const val CHILD_JOBS = "childJobs"
48 const val MSO_RESOURCE_ID = "msoResourceIds"
49 const val CUMULATIVE_STATUS = "cumulativeStatus"
51 enum class InternalState constructor(val immediate:Boolean=false) {
53 CREATING_CHILDREN(true),
63 data class NextInternalState(val nextActionPhase: Action, val nextInternalState: InternalState)
66 data class MsoRestCallPlan(
67 val httpMethod: HttpMethod,
69 val payload: Optional<RequestDetailsWrapper<out Any>>,
70 val userId: Optional<String>,
71 val actionDescription: String
74 abstract class ResourceCommand(
75 protected val restMso: RestMsoImplementation,
76 protected val inProgressStatusService: InProgressStatusService,
77 protected val msoResultHandlerService: MsoResultHandlerService,
78 protected val watchChildrenJobsBL: WatchChildrenJobsBL,
79 private val jobsBrokerService: JobsBrokerService,
80 private val jobAdapter: JobAdapter
81 ) : CommandBase(), JobCommand {
84 private val Logger = EELFLoggerDelegate.getLogger(ResourceCommand::class.java)
87 abstract fun createChildren():JobStatus
89 abstract fun planCreateMyselfRestCall(commandParentData: CommandParentData, request: JobAdapter.AsyncJobRequest, userId: String, testApi: String?): MsoRestCallPlan
91 abstract fun planDeleteMyselfRestCall(commandParentData: CommandParentData, request: JobAdapter.AsyncJobRequest, userId: String): MsoRestCallPlan
93 private val commandByInternalState: Map<InternalState, () -> JobStatus> = hashMapOf(
94 Pair(InternalState.CREATING_CHILDREN, ::createChildren),
95 Pair(InternalState.WATCHING, ::watchChildren),
96 Pair(InternalState.CREATE_MYSELF, ::createMyself),
97 Pair(InternalState.RESUME_MYSELF, ::resumeMyself),
98 Pair(InternalState.DELETE_MYSELF, ::deleteMyself),
99 Pair(InternalState.IN_PROGRESS, ::inProgress),
100 Pair(InternalState.REPLACE_MYSELF, ::replaceMyself)
103 private lateinit var internalState:InternalState
104 protected lateinit var actionPhase: Action
105 protected var commandParentData: CommandParentData = CommandParentData()
106 protected var msoResourceIds: MsoResourceIds = EMPTY_MSO_RESOURCE_ID
107 protected var childJobs:List<String> = emptyList()
108 private lateinit var cumulativeStatus:JobStatus
111 override fun call(): NextCommand {
112 var jobStatus:JobStatus = if (internalState!=InternalState.TERMINAL) invokeCommand() else cumulativeStatus
113 jobStatus = comulateStatusAndUpdatePropertyIfFinal(jobStatus)
116 Logger.debug("job: ${this.javaClass.simpleName} ${sharedData.jobUuid} $actionPhase ${getActionType()} $internalState $jobStatus $childJobs")
117 } catch (e:Exception) { /* do nothing. Just failed to log...*/}
119 if (shallStopJob(jobStatus)) {
121 return NextCommand(jobStatus)
124 val (nextActionPhase, nextInternalState) = calcNextInternalState(jobStatus, internalState, actionPhase)
125 Logger.debug("next state for job ${sharedData.jobUuid} is $nextInternalState")
126 actionPhase = nextActionPhase
127 internalState = nextInternalState
129 if (internalState==InternalState.TERMINAL) {
131 return NextCommand(jobStatus)
134 jobStatus = getExternalInProgressStatus()
135 Logger.debug("next status for job ${sharedData.jobUuid} is $jobStatus")
136 // if (internalState.immediate) return call() //shortcut instead of execute another command
137 return NextCommand(jobStatus, this)
140 //we want to stop in faliures, except for service witn no action, since service with no action trigger 2 phases (delete and create)
141 protected fun shallStopJob(jobStatus: JobStatus) =
142 jobStatus.isFailure && !(isServiceCommand() && getActionType()==Action.None)
144 //this method is used to expose the job status after successful completion of current state
145 //should be override by subclass (like ServiceCommand) that need to return other default job status
146 protected open fun getExternalInProgressStatus() = JobStatus.RESOURCE_IN_PROGRESS
148 private fun invokeCommand(): JobStatus {
150 commandByInternalState.getOrDefault(internalState, ::throwIllegalState).invoke()
152 catch (exception: TryAgainException) {
153 Logger.warn("caught TryAgainException. Set job status to IN_PROGRESS")
154 JobStatus.IN_PROGRESS
156 catch (exception: AbortingException) {
157 Logger.error("caught AbortingException. Set job status to FAILED")
162 private fun throwIllegalState():JobStatus {
163 throw IllegalStateException("can't find action for pashe $actionPhase and state $internalState")
166 private fun calcNextInternalState(jobStatus: JobStatus, internalState: InternalState, actionPhase: Action): NextInternalState {
168 val nextInternalState = when (actionPhase) {
169 Action.Delete -> calcNextStateDeletePhase(jobStatus, internalState)
170 Action.Create -> calcNextStateCreatePhase(jobStatus, internalState)
171 else -> InternalState.TERMINAL
174 if (nextInternalState == InternalState.TERMINAL
175 && actionPhase == Action.Delete
176 && isServiceCommand()) {
177 // Loop over to "Create" phase
178 return NextInternalState(Action.Create, InternalState.INITIAL)
181 return NextInternalState(actionPhase, nextInternalState)
185 //no need to refer to failed (final) states here
186 //This method is called only for non final states or COMPLETED
187 protected fun calcNextStateDeletePhase(jobStatus: JobStatus, internalState: InternalState): InternalState {
188 return when (internalState) {
190 InternalState.CREATING_CHILDREN -> InternalState.WATCHING
192 InternalState.WATCHING -> {
194 !jobStatus.isFinal -> InternalState.WATCHING
195 isNeedToDeleteMyself() -> InternalState.DELETE_MYSELF
196 else -> InternalState.TERMINAL
200 InternalState.DELETE_MYSELF -> InternalState.IN_PROGRESS
202 InternalState.IN_PROGRESS -> {
203 if (jobStatus == JobStatus.COMPLETED) InternalState.TERMINAL else InternalState.IN_PROGRESS
206 else -> InternalState.TERMINAL
210 protected fun calcNextStateCreatePhase(jobStatus: JobStatus, internalState: InternalState): InternalState {
211 return when (internalState) {
213 InternalState.CREATE_MYSELF -> when (jobStatus) {
214 JobStatus.IN_PROGRESS -> InternalState.CREATE_MYSELF
215 else -> InternalState.IN_PROGRESS
218 InternalState.RESUME_MYSELF -> when (jobStatus) {
219 JobStatus.IN_PROGRESS -> InternalState.RESUME_MYSELF
220 else -> InternalState.IN_PROGRESS
223 InternalState.REPLACE_MYSELF -> when (jobStatus) {
224 JobStatus.IN_PROGRESS -> InternalState.REPLACE_MYSELF
225 else -> InternalState.IN_PROGRESS
228 InternalState.IN_PROGRESS -> {
230 jobStatus != JobStatus.COMPLETED -> InternalState.IN_PROGRESS
231 isDescendantHasAction(Action.Create) -> InternalState.CREATING_CHILDREN
232 isDescendantHasAction(Action.Upgrade) -> InternalState.CREATING_CHILDREN
233 else -> InternalState.TERMINAL
237 InternalState.CREATING_CHILDREN -> InternalState.WATCHING
239 InternalState.WATCHING -> {
241 !jobStatus.isFinal -> InternalState.WATCHING
242 else -> InternalState.TERMINAL
246 else -> InternalState.TERMINAL
250 override fun getData(): Map<String, Any?> {
252 ACTION_PHASE to actionPhase,
253 INTERNAL_STATE to internalState,
254 MSO_RESOURCE_ID to msoResourceIds,
255 CHILD_JOBS to childJobs,
256 CUMULATIVE_STATUS to cumulativeStatus
257 ) + commandParentData.parentData
260 override fun init(sharedData: JobSharedData, commandData: Map<String, Any>): ResourceCommand {
262 val resourceIdsRaw:Any? = commandData[MSO_RESOURCE_ID]
263 commandParentData.initParentData(commandData)
265 if (resourceIdsRaw != null) JACKSON_OBJECT_MAPPER.convertValue(resourceIdsRaw)
266 else EMPTY_MSO_RESOURCE_ID
268 childJobs = JACKSON_OBJECT_MAPPER.convertValue(commandData.getOrDefault(CHILD_JOBS, emptyList<String>()))
269 cumulativeStatus = getEnumFromMapOfStrings(commandData, CUMULATIVE_STATUS, JobStatus.COMPLETED_WITH_NO_ACTION)
270 actionPhase = getEnumFromMapOfStrings(commandData, ACTION_PHASE, Action.Delete)
271 internalState = calcInitialState(commandData, actionPhase)
275 fun calcInitialState(commandData: Map<String, Any>, phase: Action):InternalState {
276 val status:InternalState = getEnumFromMapOfStrings(commandData, INTERNAL_STATE, InternalState.INITIAL)
277 if (status == InternalState.INITIAL) {
279 return when (phase) {
280 Action.Delete -> when {
281 isDescendantHasAction(phase) -> InternalState.CREATING_CHILDREN
282 isNeedToDeleteMyself() -> InternalState.DELETE_MYSELF
283 else -> InternalState.TERMINAL
285 Action.Create -> when {
286 isNeedToCreateMyself() -> InternalState.CREATE_MYSELF
287 isNeedToResumeMySelf() -> InternalState.RESUME_MYSELF
288 isNeedToReplaceMySelf() -> InternalState.REPLACE_MYSELF
289 isDescendantHasAction(phase) -> InternalState.CREATING_CHILDREN
290 isDescendantHasAction(Action.Upgrade) -> InternalState.CREATING_CHILDREN
291 else -> InternalState.TERMINAL
293 else -> throw IllegalStateException("state $internalState is not supported yet")
299 //command may override it in order to do something while init state
300 protected open fun onInitial(phase: Action) {
304 //command may override it in order to do something while final status
305 protected open fun onFinal(jobStatus: JobStatus) {
309 protected open fun getRequest(): BaseResource {
310 return sharedData.request as BaseResource
313 protected open fun getActionType(): Action {
314 return getRequest().action
317 protected open fun isServiceCommand(): Boolean = false
319 protected open fun isNeedToDeleteMyself(): Boolean = getActionType() == Action.Delete
321 protected open fun isNeedToCreateMyself(): Boolean = getActionType() == Action.Create
323 protected open fun isNeedToResumeMySelf(): Boolean = getActionType() == Action.Resume
325 protected open fun isNeedToReplaceMySelf(): Boolean = false
327 protected open fun inProgress(): JobStatus {
328 val requestId:String = msoResourceIds.requestId;
330 val jobStatus = inProgressStatusService.call(getExpiryChecker(), sharedData, requestId)
331 handleInProgressStatus(jobStatus)
332 } catch (e: javax.ws.rs.ProcessingException) {
333 // Retry when we can't connect MSO during getStatus
334 Logger.error(EELFLoggerDelegate.errorLogger, "Cannot get orchestration status for {}, will retry: {}", requestId, e, e)
335 JobStatus.IN_PROGRESS;
336 } catch (e: InProgressStatusService.BadResponseFromMso) {
337 inProgressStatusService.handleFailedMsoResponse(sharedData.jobUuid, requestId, e.msoResponse)
338 JobStatus.IN_PROGRESS
339 } catch (e: RuntimeException) {
340 Logger.error(EELFLoggerDelegate.errorLogger, "Cannot get orchestration status for {}, stopping: {}", requestId, e, e)
345 fun createMyself(): JobStatus {
346 val createMyselfCommand = planCreateMyselfRestCall(commandParentData, sharedData.request, sharedData.userId, sharedData.testApi)
347 return executeAndHandleMsoInstanceRequest(createMyselfCommand)
350 protected open fun resumeMyself(): JobStatus {
351 throw NotImplementedError("Resume is not implemented for this command " + this.javaClass)
354 protected open fun replaceMyself(): JobStatus {
355 throw NotImplementedError("Replace is not implemented for this command " + this.javaClass)
358 fun deleteMyself(): JobStatus {
359 val deleteMyselfCommand = planDeleteMyselfRestCall(commandParentData, sharedData.request, sharedData.userId)
360 return executeAndHandleMsoInstanceRequest(deleteMyselfCommand)
363 protected fun executeAndHandleMsoInstanceRequest(restCallPlan: MsoRestCallPlan): JobStatus {
364 //make sure requestIds are unique
365 MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, UUID.randomUUID().toString())
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> {
434 return setPositionWhereIsMissing(children)
435 .map { jobAdapter.createChildJob(jobType ?: it.first.jobType, it.first, sharedData, dataForChild, it.second) }
436 .map { jobsBrokerService.add(it) }
437 .map { it.toString() }
440 protected fun setPositionWhereIsMissing(children: Collection<BaseResource>): List<Pair<BaseResource, Int>> {
441 var orderingPosition = children.map{ defaultIfNull(it.position, 0) }.max() ?: 0
443 .map {Pair(it, it.position ?: ++orderingPosition)}