Robustness cleaning of in progress cache
[cps.git] / cps-ncmp-service / src / test / groovy / org / onap / cps / ncmp / api / inventory / sync / ModuleSyncTasksSpec.groovy
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2022 Nordix Foundation
4  *  Modifications Copyright (C) 2022 Bell Canada
5  *  ================================================================================
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  *  SPDX-License-Identifier: Apache-2.0
19  *  ============LICENSE_END=========================================================
20  */
21
22 package org.onap.cps.ncmp.api.inventory.sync
23
24 import com.hazelcast.config.Config
25 import com.hazelcast.instance.impl.HazelcastInstanceFactory
26 import com.hazelcast.map.IMap
27 import org.onap.cps.ncmp.api.impl.event.lcm.LcmEventsCmHandleStateHandler
28 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle
29 import org.onap.cps.ncmp.api.inventory.CmHandleState
30 import org.onap.cps.ncmp.api.inventory.CompositeState
31 import org.onap.cps.ncmp.api.inventory.CompositeStateBuilder
32 import org.onap.cps.ncmp.api.inventory.InventoryPersistence
33 import org.onap.cps.ncmp.api.inventory.LockReasonCategory
34 import org.onap.cps.spi.model.DataNode
35 import spock.lang.Specification
36 import java.util.concurrent.atomic.AtomicInteger
37
38 class ModuleSyncTasksSpec extends Specification {
39
40     def mockInventoryPersistence = Mock(InventoryPersistence)
41
42     def mockSyncUtils = Mock(SyncUtils)
43
44     def mockModuleSyncService = Mock(ModuleSyncService)
45
46     def mockLcmEventsCmHandleStateHandler = Mock(LcmEventsCmHandleStateHandler)
47
48     IMap<String, Object> moduleSyncStartedOnCmHandles = HazelcastInstanceFactory
49             .getOrCreateHazelcastInstance(new Config('hazelcastInstanceName'))
50             .getMap('mapInstanceName')
51
52     def batchCount = new AtomicInteger(5)
53
54     def objectUnderTest = new ModuleSyncTasks(mockInventoryPersistence, mockSyncUtils, mockModuleSyncService,
55             mockLcmEventsCmHandleStateHandler, moduleSyncStartedOnCmHandles)
56
57     def 'Module Sync ADVISED cm handles.'() {
58         given: 'cm handles in an ADVISED state'
59             def cmHandle1 = advisedCmHandleAsDataNode('cm-handle-1')
60             def cmHandle2 = advisedCmHandleAsDataNode('cm-handle-2')
61         and: 'the inventory persistence cm handle returns a ADVISED state for the any handle'
62             mockInventoryPersistence.getCmHandleState(_) >> new CompositeState(cmHandleState: CmHandleState.ADVISED)
63         when: 'module sync poll is executed'
64             objectUnderTest.performModuleSync([cmHandle1, cmHandle2], batchCount)
65         then: 'module sync service deletes schemas set of each cm handle if it already exists'
66             1 * mockModuleSyncService.deleteSchemaSetIfExists('cm-handle-1')
67             1 * mockModuleSyncService.deleteSchemaSetIfExists('cm-handle-2')
68         and: 'module sync service is invoked for each cm handle'
69             1 * mockModuleSyncService.syncAndCreateSchemaSetAndAnchor(_) >> { args -> assertYamgModelCmHandleArgument(args, 'cm-handle-1') }
70             1 * mockModuleSyncService.syncAndCreateSchemaSetAndAnchor(_) >> { args -> assertYamgModelCmHandleArgument(args, 'cm-handle-2') }
71         and: 'the state handler is called for the both cm handles'
72             1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_) >> { args ->
73                 assertBatch(args, ['cm-handle-1', 'cm-handle-2'], CmHandleState.READY)
74             }
75         and: 'batch count is decremented by one'
76             assert batchCount.get() == 4
77     }
78
79     def 'Module Sync ADVISED cm handle with failure during sync.'() {
80         given: 'a cm handle in an ADVISED state'
81             def cmHandle = advisedCmHandleAsDataNode('cm-handle')
82         and: 'the inventory persistence cm handle returns a ADVISED state for the cm handle'
83             def cmHandleState = new CompositeState(cmHandleState: CmHandleState.ADVISED)
84             1 * mockInventoryPersistence.getCmHandleState('cm-handle') >> cmHandleState
85         and: 'module sync service attempts to sync the cm handle and throws an exception'
86             1 * mockModuleSyncService.syncAndCreateSchemaSetAndAnchor(*_) >> { throw new Exception('some exception') }
87         when: 'module sync is executed'
88             objectUnderTest.performModuleSync([cmHandle], batchCount)
89         then: 'update lock reason, details and attempts is invoked'
90             1 * mockSyncUtils.updateLockReasonDetailsAndAttempts(cmHandleState, LockReasonCategory.LOCKED_MODULE_SYNC_FAILED, 'some exception')
91         and: 'the state handler is called to update the state to LOCKED'
92             1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_) >> { args ->
93                 assertBatch(args, ['cm-handle'], CmHandleState.LOCKED)
94             }
95         and: 'batch count is decremented by one'
96             assert batchCount.get() == 4
97     }
98
99     def 'Reset failed CM Handles #scenario.'() {
100         given: 'cm handles in an locked state'
101             def lockedState = new CompositeStateBuilder().withCmHandleState(CmHandleState.LOCKED)
102                     .withLockReason(LockReasonCategory.LOCKED_MODULE_SYNC_FAILED, '').withLastUpdatedTimeNow().build()
103             def yangModelCmHandle1 = new YangModelCmHandle(id: 'cm-handle-1', compositeState: lockedState)
104             def yangModelCmHandle2 = new YangModelCmHandle(id: 'cm-handle-2', compositeState: lockedState)
105             def expectedCmHandleStatePerCmHandle = [(yangModelCmHandle1): CmHandleState.ADVISED]
106         and: 'clear in progress map'
107             resetModuleSyncStartedOnCmHandles(moduleSyncStartedOnCmHandles)
108         and: 'add cm handle entry into progress map'
109             moduleSyncStartedOnCmHandles.put('cm-handle-1', 'started')
110             moduleSyncStartedOnCmHandles.put('cm-handle-2', 'started')
111         and: 'sync utils retry locked cm handle returns #isReadyForRetry'
112             mockSyncUtils.isReadyForRetry(lockedState) >>> isReadyForRetry
113         when: 'resetting failed cm handles'
114             objectUnderTest.resetFailedCmHandles([yangModelCmHandle1, yangModelCmHandle2])
115         then: 'updated to state "ADVISED" from "READY" is called as often as there are cm handles ready for retry'
116             expectedNumberOfInvocationsToUpdateCmHandleState * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(expectedCmHandleStatePerCmHandle)
117         and: 'after reset performed size of in progress map'
118             assert moduleSyncStartedOnCmHandles.size() == inProgressMapSize
119         where:
120             scenario                        | isReadyForRetry | inProgressMapSize || expectedNumberOfInvocationsToUpdateCmHandleState
121             'retry locked cm handle'        | [true, false]   | 1                 || 1
122             'do not retry locked cm handle' | [false, false]  | 2                 || 0
123     }
124
125     def 'Module Sync ADVISED cm handle without entry in progress map.'() {
126         given: 'cm handles in an ADVISED state'
127             def cmHandle1 = advisedCmHandleAsDataNode('cm-handle-1')
128         and: 'the inventory persistence cm handle returns a ADVISED state for the any handle'
129             mockInventoryPersistence.getCmHandleState(_) >> new CompositeState(cmHandleState: CmHandleState.ADVISED)
130         and: 'entry in progress map for other cm handle'
131             moduleSyncStartedOnCmHandles.put('other-cm-handle', 'started')
132         when: 'module sync poll is executed'
133             objectUnderTest.performModuleSync([cmHandle1], batchCount)
134         then: 'module sync service is invoked for cm handle'
135             1 * mockModuleSyncService.syncAndCreateSchemaSetAndAnchor(_) >> { args -> assertYamgModelCmHandleArgument(args, 'cm-handle-1') }
136         and: 'the entry for other cm handle is still in the progress map'
137             assert moduleSyncStartedOnCmHandles.get('other-cm-handle') != null
138     }
139
140     def advisedCmHandleAsDataNode(cmHandleId) {
141         return new DataNode(anchorName: cmHandleId, leaves: ['id': cmHandleId, 'cm-handle-state': 'ADVISED'])
142     }
143
144     def assertYamgModelCmHandleArgument(args, expectedCmHandleId) {
145         {
146             def yangModelCmHandle = args[0]
147             assert yangModelCmHandle.id == expectedCmHandleId
148         }
149         return true
150     }
151
152     def assertBatch(args, expectedCmHandleStatePerCmHandleIds, expectedCmHandleState) {
153         {
154             Map<YangModelCmHandle, CmHandleState> actualCmHandleStatePerCmHandle = args[0]
155             assert actualCmHandleStatePerCmHandle.size() == expectedCmHandleStatePerCmHandleIds.size()
156             actualCmHandleStatePerCmHandle.each {
157                 assert expectedCmHandleStatePerCmHandleIds.contains(it.key.id)
158                 assert it.value == expectedCmHandleState
159             }
160         }
161         return true
162     }
163
164     def resetModuleSyncStartedOnCmHandles(moduleSyncStartedOnCmHandles) {
165         moduleSyncStartedOnCmHandles.clear();
166     }
167 }