send unqiue request ids to MSO in async instantiation
[vid.git] / vid-app-common / src / main / java / org / onap / vid / job / command / ResourceCommand.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
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
40 import org.slf4j.MDC
41 import org.springframework.http.HttpMethod
42 import java.util.*
43
44
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"
50
51 enum class InternalState constructor(val immediate:Boolean=false) {
52     INITIAL,
53     CREATING_CHILDREN(true),
54     WATCHING,
55     DELETE_MYSELF,
56     CREATE_MYSELF,
57     IN_PROGRESS,
58     TERMINAL,
59     RESUME_MYSELF,
60     REPLACE_MYSELF,
61 }
62
63 data class NextInternalState(val nextActionPhase: Action, val nextInternalState: InternalState)
64
65
66 data class MsoRestCallPlan(
67         val httpMethod: HttpMethod,
68         val path: String,
69         val payload: Optional<RequestDetailsWrapper<out Any>>,
70         val userId: Optional<String>,
71         val actionDescription: String
72 )
73
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 {
82
83     companion object {
84         private val Logger = EELFLoggerDelegate.getLogger(ResourceCommand::class.java)
85     }
86
87     abstract fun createChildren():JobStatus
88
89     abstract fun planCreateMyselfRestCall(commandParentData: CommandParentData, request: JobAdapter.AsyncJobRequest, userId: String, testApi: String?): MsoRestCallPlan
90
91     abstract fun planDeleteMyselfRestCall(commandParentData: CommandParentData, request: JobAdapter.AsyncJobRequest, userId: String): MsoRestCallPlan
92
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)
101     )
102
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
109
110
111     override fun call(): NextCommand {
112         var jobStatus:JobStatus = if (internalState!=InternalState.TERMINAL) invokeCommand() else cumulativeStatus
113         jobStatus = comulateStatusAndUpdatePropertyIfFinal(jobStatus)
114
115         try {
116             Logger.debug("job: ${this.javaClass.simpleName} ${sharedData.jobUuid} $actionPhase ${getActionType()} $internalState $jobStatus $childJobs")
117         } catch (e:Exception) { /* do nothing. Just failed to log...*/}
118
119         if (shallStopJob(jobStatus)) {
120             onFinal(jobStatus)
121             return NextCommand(jobStatus)
122         }
123
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
128
129         if (internalState==InternalState.TERMINAL) {
130             onFinal(jobStatus)
131             return NextCommand(jobStatus)
132         }
133
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)
138     }
139
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)
143
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
147
148     private fun invokeCommand(): JobStatus {
149         return try {
150             commandByInternalState.getOrDefault(internalState, ::throwIllegalState).invoke()
151         }
152         catch (exception: TryAgainException) {
153             Logger.warn("caught TryAgainException. Set job status to IN_PROGRESS")
154             JobStatus.IN_PROGRESS
155         }
156         catch (exception: AbortingException) {
157             Logger.error("caught AbortingException. Set job status to FAILED")
158             JobStatus.FAILED;
159         }
160     }
161
162     private fun throwIllegalState():JobStatus {
163              throw IllegalStateException("can't find action for pashe $actionPhase and state $internalState")
164     }
165
166     private fun calcNextInternalState(jobStatus: JobStatus, internalState: InternalState, actionPhase: Action): NextInternalState {
167
168         val nextInternalState = when (actionPhase) {
169             Action.Delete -> calcNextStateDeletePhase(jobStatus, internalState)
170             Action.Create -> calcNextStateCreatePhase(jobStatus, internalState)
171             else -> InternalState.TERMINAL
172         }
173
174         if (nextInternalState == InternalState.TERMINAL
175                 && actionPhase == Action.Delete
176                 && isServiceCommand()) {
177             // Loop over to "Create" phase
178             return NextInternalState(Action.Create, InternalState.INITIAL)
179         }
180
181         return NextInternalState(actionPhase, nextInternalState)
182
183     }
184
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) {
189
190             InternalState.CREATING_CHILDREN -> InternalState.WATCHING
191
192             InternalState.WATCHING -> {
193                 when {
194                     !jobStatus.isFinal -> InternalState.WATCHING
195                     isNeedToDeleteMyself() -> InternalState.DELETE_MYSELF
196                     else -> InternalState.TERMINAL
197                 }
198             }
199
200             InternalState.DELETE_MYSELF -> InternalState.IN_PROGRESS
201
202             InternalState.IN_PROGRESS -> {
203                 if (jobStatus == JobStatus.COMPLETED) InternalState.TERMINAL else InternalState.IN_PROGRESS
204             }
205
206             else -> InternalState.TERMINAL
207         }
208     }
209
210     protected fun calcNextStateCreatePhase(jobStatus: JobStatus, internalState: InternalState): InternalState {
211         return when (internalState) {
212
213             InternalState.CREATE_MYSELF -> when (jobStatus) {
214                 JobStatus.IN_PROGRESS -> InternalState.CREATE_MYSELF
215                 else -> InternalState.IN_PROGRESS
216             }
217
218             InternalState.RESUME_MYSELF -> when (jobStatus) {
219                 JobStatus.IN_PROGRESS -> InternalState.RESUME_MYSELF
220                 else -> InternalState.IN_PROGRESS
221             }
222
223             InternalState.REPLACE_MYSELF -> when (jobStatus) {
224                 JobStatus.IN_PROGRESS -> InternalState.REPLACE_MYSELF
225                 else -> InternalState.IN_PROGRESS
226             }
227
228             InternalState.IN_PROGRESS -> {
229                 when {
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
234                 }
235             }
236
237             InternalState.CREATING_CHILDREN -> InternalState.WATCHING
238
239             InternalState.WATCHING -> {
240                 when {
241                     !jobStatus.isFinal -> InternalState.WATCHING
242                     else -> InternalState.TERMINAL
243                 }
244             }
245
246             else -> InternalState.TERMINAL
247         }
248     }
249
250     override fun getData(): Map<String, Any?> {
251         return mapOf(
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
258     }
259
260     override fun init(sharedData: JobSharedData, commandData: Map<String, Any>): ResourceCommand {
261         init(sharedData)
262         val resourceIdsRaw:Any? = commandData[MSO_RESOURCE_ID]
263         commandParentData.initParentData(commandData)
264         msoResourceIds =
265                 if (resourceIdsRaw != null) JACKSON_OBJECT_MAPPER.convertValue(resourceIdsRaw)
266                 else EMPTY_MSO_RESOURCE_ID
267
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)
272         return this
273     }
274
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) {
278             onInitial(phase)
279             return when (phase) {
280                 Action.Delete -> when {
281                     isDescendantHasAction(phase) -> InternalState.CREATING_CHILDREN
282                     isNeedToDeleteMyself() -> InternalState.DELETE_MYSELF
283                     else -> InternalState.TERMINAL
284                 }
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
292                 }
293                 else -> throw IllegalStateException("state $internalState is not supported yet")
294             }
295         }
296         return status
297     }
298
299     //command may override it in order to do something while init state
300     protected open fun onInitial(phase: Action) {
301         //do nothing
302     }
303
304     //command may override it in order to do something while final status
305     protected open fun onFinal(jobStatus: JobStatus) {
306         //do nothing
307     }
308
309     protected open fun getRequest(): BaseResource {
310         return sharedData.request as BaseResource
311     }
312
313     protected open fun getActionType(): Action {
314         return getRequest().action
315     }
316
317     protected open fun isServiceCommand(): Boolean = false
318
319     protected open fun isNeedToDeleteMyself(): Boolean = getActionType() == Action.Delete
320
321     protected open fun isNeedToCreateMyself(): Boolean = getActionType() == Action.Create
322
323     protected open fun isNeedToResumeMySelf(): Boolean = getActionType() == Action.Resume
324
325     protected open fun isNeedToReplaceMySelf(): Boolean = false
326
327     protected open fun inProgress(): JobStatus {
328         val requestId:String = msoResourceIds.requestId;
329         return try {
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)
341             JobStatus.STOPPED
342         }
343     }
344
345     fun createMyself(): JobStatus {
346         val createMyselfCommand = planCreateMyselfRestCall(commandParentData, sharedData.request, sharedData.userId, sharedData.testApi)
347         return executeAndHandleMsoInstanceRequest(createMyselfCommand)
348     }
349
350     protected open fun resumeMyself(): JobStatus {
351         throw NotImplementedError("Resume is not implemented for this command " + this.javaClass)
352     }
353
354     protected open fun replaceMyself(): JobStatus {
355         throw NotImplementedError("Replace is not implemented for this command " + this.javaClass)
356     }
357
358     fun deleteMyself(): JobStatus {
359         val deleteMyselfCommand = planDeleteMyselfRestCall(commandParentData, sharedData.request, sharedData.userId)
360         return executeAndHandleMsoInstanceRequest(deleteMyselfCommand)
361     }
362
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),
370                 restCallPlan.path,
371                 restCallPlan.userId
372         )
373
374         val msoResult = if (isServiceCommand()) {
375             msoResultHandlerService.handleRootResponse(sharedData, msoResponse)
376         } else {
377             msoResultHandlerService.handleResponse(sharedData, msoResponse, restCallPlan.actionDescription)
378         }
379
380         this.msoResourceIds = msoResult.msoResourceIds
381         return msoResult.jobStatus
382     }
383
384     protected open fun getExpiryChecker(): ExpiryChecker = ExpiryChecker {false}
385
386     protected open fun handleInProgressStatus(jobStatus: JobStatus): JobStatus {
387         return if (jobStatus == JobStatus.PAUSE) JobStatus.IN_PROGRESS else jobStatus
388     }
389
390     protected open fun watchChildren():JobStatus {
391         return watchChildrenJobsBL.retrieveChildrenJobsStatus(childJobs)
392     }
393
394     protected fun comulateStatusAndUpdatePropertyIfFinal(internalStateStatus: JobStatus): JobStatus {
395         val status = watchChildrenJobsBL.cumulateJobStatus(internalStateStatus, cumulativeStatus)
396
397         //we want to update cumulativeStatus only for final status
398         if (status.isFinal) {
399             cumulativeStatus = status;
400         }
401
402         return status
403     }
404
405     protected fun buildDataForChild(request: BaseResource, actionPhase: Action): Map<String, Any> {
406         addMyselfToChildrenData(commandParentData, request)
407         commandParentData.setActionPhase(actionPhase)
408         return commandParentData.parentData
409     }
410
411     protected open fun addMyselfToChildrenData(commandParentData: CommandParentData, request: BaseResource) {
412         // Nothing by default
413     }
414
415     protected open fun isDescendantHasAction(phase:Action):Boolean = isDescendantHasAction(getRequest(), phase, true )
416
417
418     @JvmOverloads
419     fun isDescendantHasAction(request: BaseResource, phase: Action, isFirstLevel:Boolean=true): Boolean {
420         if (!isFirstLevel && request.action == phase) {
421             return true;
422         }
423
424         return request.children.map {this.isDescendantHasAction(it, phase, false)}.any {it}
425     }
426
427     protected fun getActualInstanceId(request: BaseResource):String =
428             if (getActionType() == Action.Create) msoResourceIds.instanceId else request.instanceId
429
430
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() }
438     }
439
440     protected fun setPositionWhereIsMissing(children: Collection<BaseResource>): List<Pair<BaseResource, Int>> {
441         var orderingPosition = children.map{ defaultIfNull(it.position, 0) }.max() ?: 0
442         return  children
443                 .map {Pair(it, it.position ?: ++orderingPosition)}
444     }
445 }
446
447
448