Merge changes from topics "VID-14", "VID-13", "VID-12"
[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.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
39 import java.util.*
40
41
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"
47
48 enum class InternalState constructor(val immediate:Boolean=false) {
49     INITIAL,
50     CREATING_CHILDREN(true),
51     WATCHING,
52     DELETE_MYSELF,
53     CREATE_MYSELF,
54     IN_PROGRESS,
55     TERMINAL,
56     RESUME_MYSELF,
57     REPLACE_MYSELF,
58 }
59
60 data class NextInternalState(val nextActionPhase: Action, val nextInternalState: InternalState)
61
62
63 data class MsoRestCallPlan(
64         val httpMethod: HttpMethod,
65         val path: String,
66         val payload: Optional<RequestDetailsWrapper<out Any>>,
67         val userId: Optional<String>,
68         val actionDescription: String
69 )
70
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 {
79
80     companion object {
81         private val Logger = EELFLoggerDelegate.getLogger(ResourceCommand::class.java)
82     }
83
84     abstract fun createChildren():JobStatus
85
86     abstract fun planCreateMyselfRestCall(commandParentData: CommandParentData, request: JobAdapter.AsyncJobRequest, userId: String, testApi: String?): MsoRestCallPlan
87
88     abstract fun planDeleteMyselfRestCall(commandParentData: CommandParentData, request: JobAdapter.AsyncJobRequest, userId: String): MsoRestCallPlan
89
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)
98     )
99
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
106
107
108     override fun call(): NextCommand {
109         var jobStatus:JobStatus = if (internalState!=InternalState.TERMINAL) invokeCommand() else cumulativeStatus
110         jobStatus = comulateStatusAndUpdatePropertyIfFinal(jobStatus)
111
112         try {
113             Logger.debug("job: ${this.javaClass.simpleName} ${sharedData.jobUuid} $actionPhase ${getActionType()} $internalState $jobStatus $childJobs")
114         } catch (e:Exception) { /* do nothing. Just failed to log...*/}
115
116         if (shallStopJob(jobStatus)) {
117             onFinal(jobStatus)
118             return NextCommand(jobStatus)
119         }
120
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
125
126         if (internalState==InternalState.TERMINAL) {
127             onFinal(jobStatus)
128             return NextCommand(jobStatus)
129         }
130
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)
135     }
136
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)
140
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
144
145     private fun invokeCommand(): JobStatus {
146         return try {
147             commandByInternalState.getOrDefault(internalState, ::throwIllegalState).invoke()
148         }
149         catch (exception: TryAgainException) {
150             Logger.warn("caught TryAgainException. Set job status to IN_PROGRESS")
151             JobStatus.IN_PROGRESS
152         }
153         catch (exception: AbortingException) {
154             Logger.error("caught AbortingException. Set job status to FAILED")
155             JobStatus.FAILED;
156         }
157     }
158
159     private fun throwIllegalState():JobStatus {
160              throw IllegalStateException("can't find action for pashe $actionPhase and state $internalState")
161     }
162
163     private fun calcNextInternalState(jobStatus: JobStatus, internalState: InternalState, actionPhase: Action): NextInternalState {
164
165         val nextInternalState = when (actionPhase) {
166             Action.Delete -> calcNextStateDeletePhase(jobStatus, internalState)
167             Action.Create -> calcNextStateCreatePhase(jobStatus, internalState)
168             else -> InternalState.TERMINAL
169         }
170
171         if (nextInternalState == InternalState.TERMINAL
172                 && actionPhase == Action.Delete
173                 && isServiceCommand()) {
174             // Loop over to "Create" phase
175             return NextInternalState(Action.Create, InternalState.INITIAL)
176         }
177
178         return NextInternalState(actionPhase, nextInternalState)
179
180     }
181
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) {
186
187             InternalState.CREATING_CHILDREN -> InternalState.WATCHING
188
189             InternalState.WATCHING -> {
190                 when {
191                     !jobStatus.isFinal -> InternalState.WATCHING
192                     isNeedToDeleteMyself() -> InternalState.DELETE_MYSELF
193                     else -> InternalState.TERMINAL
194                 }
195             }
196
197             InternalState.DELETE_MYSELF -> InternalState.IN_PROGRESS
198
199             InternalState.IN_PROGRESS -> {
200                 if (jobStatus == JobStatus.COMPLETED) InternalState.TERMINAL else InternalState.IN_PROGRESS
201             }
202
203             else -> InternalState.TERMINAL
204         }
205     }
206
207     protected fun calcNextStateCreatePhase(jobStatus: JobStatus, internalState: InternalState): InternalState {
208         return when (internalState) {
209
210             InternalState.CREATE_MYSELF -> when (jobStatus) {
211                 JobStatus.IN_PROGRESS -> InternalState.CREATE_MYSELF
212                 else -> InternalState.IN_PROGRESS
213             }
214
215             InternalState.RESUME_MYSELF -> when (jobStatus) {
216                 JobStatus.IN_PROGRESS -> InternalState.RESUME_MYSELF
217                 else -> InternalState.IN_PROGRESS
218             }
219
220             InternalState.REPLACE_MYSELF -> when (jobStatus) {
221                 JobStatus.IN_PROGRESS -> InternalState.REPLACE_MYSELF
222                 else -> InternalState.IN_PROGRESS
223             }
224
225             InternalState.REPLACE_MYSELF -> when (jobStatus) {
226                 JobStatus.IN_PROGRESS -> InternalState.REPLACE_MYSELF
227                 else -> InternalState.IN_PROGRESS
228             }
229
230             InternalState.IN_PROGRESS -> {
231                 when {
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
236                 }
237             }
238
239             InternalState.CREATING_CHILDREN -> InternalState.WATCHING
240
241             InternalState.WATCHING -> {
242                 when {
243                     !jobStatus.isFinal -> InternalState.WATCHING
244                     else -> InternalState.TERMINAL
245                 }
246             }
247
248             else -> InternalState.TERMINAL
249         }
250     }
251
252     override fun getData(): Map<String, Any?> {
253         return mapOf(
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
260     }
261
262     override fun init(sharedData: JobSharedData, commandData: Map<String, Any>): ResourceCommand {
263         init(sharedData)
264         val resourceIdsRaw:Any? = commandData[MSO_RESOURCE_ID]
265         commandParentData.initParentData(commandData)
266         msoResourceIds =
267                 if (resourceIdsRaw != null) JACKSON_OBJECT_MAPPER.convertValue(resourceIdsRaw)
268                 else EMPTY_MSO_RESOURCE_ID
269
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)
274         return this
275     }
276
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) {
280             onInitial(phase)
281             return when (phase) {
282                 Action.Delete -> when {
283                     isDescendantHasAction(phase) -> InternalState.CREATING_CHILDREN
284                     isNeedToDeleteMyself() -> InternalState.DELETE_MYSELF
285                     else -> InternalState.TERMINAL
286                 }
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
294                 }
295                 else -> throw IllegalStateException("state $internalState is not supported yet")
296             }
297         }
298         return status
299     }
300
301     //command may override it in order to do something while init state
302     protected open fun onInitial(phase: Action) {
303         //do nothing
304     }
305
306     //command may override it in order to do something while final status
307     protected open fun onFinal(jobStatus: JobStatus) {
308         //do nothing
309     }
310
311     protected open fun getRequest(): BaseResource {
312         return sharedData.request as BaseResource
313     }
314
315     protected open fun getActionType(): Action {
316         return getRequest().action
317     }
318
319     protected open fun isServiceCommand(): Boolean = false
320
321     protected open fun isNeedToDeleteMyself(): Boolean = getActionType() == Action.Delete
322
323     protected open fun isNeedToCreateMyself(): Boolean = getActionType() == Action.Create
324
325     protected open fun isNeedToResumeMySelf(): Boolean = getActionType() == Action.Resume
326
327     protected open fun isNeedToReplaceMySelf(): Boolean = false
328
329     protected open fun inProgress(): JobStatus {
330         val requestId:String = msoResourceIds.requestId;
331         return try {
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)
343             JobStatus.STOPPED
344         }
345     }
346
347     fun createMyself(): JobStatus {
348         val createMyselfCommand = planCreateMyselfRestCall(commandParentData, sharedData.request, sharedData.userId, sharedData.testApi)
349         return executeAndHandleMsoInstanceRequest(createMyselfCommand)
350     }
351
352     protected open fun resumeMyself(): JobStatus {
353         throw NotImplementedError("Resume is not implemented for this command " + this.javaClass)
354     }
355
356     protected open fun replaceMyself(): JobStatus {
357         throw NotImplementedError("Replace is not implemented for this command " + this.javaClass)
358     }
359
360     fun deleteMyself(): JobStatus {
361         val deleteMyselfCommand = planDeleteMyselfRestCall(commandParentData, sharedData.request, sharedData.userId)
362         return executeAndHandleMsoInstanceRequest(deleteMyselfCommand)
363     }
364
365     protected fun executeAndHandleMsoInstanceRequest(restCallPlan: MsoRestCallPlan): JobStatus {
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         var counter = 0;
435         return  children
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() }
440     }
441
442 }
443
444
445