a9b88c2d3b143963b9ecb1c984d42ce2c95d0d5b
[cps.git] /
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2022-2024 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.impl.inventory.sync
23
24 import com.hazelcast.map.IMap
25 import org.onap.cps.ncmp.impl.inventory.models.YangModelCmHandle
26 import org.onap.cps.ncmp.impl.utils.Sleeper
27 import org.onap.cps.api.model.DataNode
28 import spock.lang.Specification
29
30 import java.util.concurrent.ArrayBlockingQueue
31 import java.util.concurrent.locks.Lock
32
33 class ModuleSyncWatchdogSpec extends Specification {
34
35     def mockModuleOperationsUtils = Mock(ModuleOperationsUtils)
36
37     def static testQueueCapacity = 50 + 2 * ModuleSyncWatchdog.MODULE_SYNC_BATCH_SIZE
38
39     def moduleSyncWorkQueue = new ArrayBlockingQueue(testQueueCapacity)
40
41     def mockModuleSyncStartedOnCmHandles = Mock(IMap<String, Object>)
42
43     def mockModuleSyncTasks = Mock(ModuleSyncTasks)
44
45     def spiedAsyncTaskExecutor = Spy(AsyncTaskExecutor)
46
47     def mockCpsAndNcmpLock = Mock(IMap<String,String>)
48
49     def spiedSleeper = Spy(Sleeper)
50
51     def objectUnderTest = new ModuleSyncWatchdog(mockModuleOperationsUtils, moduleSyncWorkQueue , mockModuleSyncStartedOnCmHandles, mockModuleSyncTasks, spiedAsyncTaskExecutor, mockCpsAndNcmpLock, spiedSleeper)
52
53     void setup() {
54         spiedAsyncTaskExecutor.setupThreadPool()
55     }
56
57     def 'Module sync advised cm handles with #scenario.'() {
58         given: 'module sync utilities returns #numberOfAdvisedCmHandles advised cm handles'
59             mockModuleOperationsUtils.getAdvisedCmHandleIds() >> createCmHandleIds(numberOfAdvisedCmHandles)
60         and: 'module sync utilities returns no failed (locked) cm handles'
61             mockModuleOperationsUtils.getCmHandlesThatFailedModelSyncOrUpgrade() >> []
62         and: 'the work queue can be locked'
63             mockCpsAndNcmpLock.tryLock('workQueueLock') >> true
64         and: 'the executor has enough available threads'
65             spiedAsyncTaskExecutor.getAsyncTaskParallelismLevel() >> 3
66         when: ' module sync is started'
67             objectUnderTest.moduleSyncAdvisedCmHandles()
68         then: 'it performs #expectedNumberOfTaskExecutions tasks'
69             expectedNumberOfTaskExecutions * spiedAsyncTaskExecutor.executeTask(*_)
70         and: 'the executing thread is unlocked'
71             1 * mockCpsAndNcmpLock.unlock('workQueueLock')
72         where: 'the following parameter are used'
73             scenario              | numberOfAdvisedCmHandles                                          || expectedNumberOfTaskExecutions
74             'none at all'         | 0                                                                 || 0
75             'less then 1 batch'   | 1                                                                 || 1
76             'exactly 1 batch'     | ModuleSyncWatchdog.MODULE_SYNC_BATCH_SIZE                         || 1
77             '2 batches'           | 2 * ModuleSyncWatchdog.MODULE_SYNC_BATCH_SIZE                     || 2
78             'queue capacity'      | testQueueCapacity                                                 || 3
79             'over queue capacity' | testQueueCapacity + 2 * ModuleSyncWatchdog.MODULE_SYNC_BATCH_SIZE || 3
80     }
81
82     def 'Module sync cm handles starts with no available threads.'() {
83         given: 'module sync utilities returns a advise cm handles'
84             mockModuleOperationsUtils.getAdvisedCmHandleIds() >> createCmHandleIds(1)
85         and: 'the work queue can be locked'
86             mockCpsAndNcmpLock.tryLock('workQueueLock') >> true
87         and: 'the executor first has no threads but has one thread on the second attempt'
88             spiedAsyncTaskExecutor.getAsyncTaskParallelismLevel() >>> [ 0, 1 ]
89         when: ' module sync is started'
90             objectUnderTest.moduleSyncAdvisedCmHandles()
91         then: 'it performs one task'
92             1 * spiedAsyncTaskExecutor.executeTask(*_)
93     }
94
95     def 'Module sync advised cm handle already handled by other thread.'() {
96         given: 'module sync utilities returns an advised cm handle'
97             mockModuleOperationsUtils.getAdvisedCmHandleIds() >> createCmHandleIds(1)
98         and: 'the work queue can be locked'
99             mockCpsAndNcmpLock.tryLock('workQueueLock') >> true
100         and: 'the executor has a thread available'
101             spiedAsyncTaskExecutor.getAsyncTaskParallelismLevel() >> 1
102         and: 'the semaphore cache indicates the cm handle is already being processed'
103             mockModuleSyncStartedOnCmHandles.putIfAbsent(*_) >> 'Started'
104         when: ' module sync is started'
105             objectUnderTest.moduleSyncAdvisedCmHandles()
106         then: 'it does NOT execute a task to process the (empty) batch'
107             0 * spiedAsyncTaskExecutor.executeTask(*_)
108     }
109
110     def 'Module sync with previous cm handle(s) left in work queue.'() {
111         given: 'there is still a cm handle in the queue'
112             moduleSyncWorkQueue.offer('ch-1')
113         and: 'sync utilities returns many advise cm handles'
114             mockModuleOperationsUtils.getAdvisedCmHandleIds() >> createCmHandleIds(500)
115         and: 'the executor has plenty threads available'
116             spiedAsyncTaskExecutor.getAsyncTaskParallelismLevel() >> 10
117         when: ' module sync is started'
118             objectUnderTest.moduleSyncAdvisedCmHandles()
119         then: 'it does executes only one task to process the remaining handle in the queue'
120             1 * spiedAsyncTaskExecutor.executeTask(*_)
121     }
122
123     def 'Reset failed cm handles.'() {
124         given: 'module sync utilities returns failed cm handles'
125             def failedCmHandles = [new YangModelCmHandle()]
126             mockModuleOperationsUtils.getCmHandlesThatFailedModelSyncOrUpgrade() >> failedCmHandles
127         when: 'reset failed cm handles is started'
128             objectUnderTest.setPreviouslyLockedCmHandlesToAdvised()
129         then: 'it is delegated to the module sync task (service)'
130             1 * mockModuleSyncTasks.setCmHandlesToAdvised(failedCmHandles)
131     }
132
133     def 'Module Sync Locking.'() {
134         given: 'module sync utilities returns an advised cm handle'
135             mockModuleOperationsUtils.getAdvisedCmHandleIds() >> createCmHandleIds(1)
136         and: 'can be locked is : #canLock'
137             mockCpsAndNcmpLock.tryLock('workQueueLock') >> canLock
138         when: 'attempt to populate the work queue'
139             objectUnderTest.populateWorkQueueIfNeeded()
140         then: 'the queue remains empty is #expectQueueRemainsEmpty'
141             assert moduleSyncWorkQueue.isEmpty() == expectQueueRemainsEmpty
142         and: 'unlock is called only when thread is able to enter the critical section'
143             expectedInvocationToUnlock * mockCpsAndNcmpLock.unlock('workQueueLock')
144         where: 'the following lock states are applied'
145             canLock || expectQueueRemainsEmpty || expectedInvocationToUnlock
146             false   || true                    || 0
147             true    || false                   || 1
148     }
149
150     def 'Sleeper gets interrupted.'() {
151         given: 'sleeper gets interrupted'
152             spiedSleeper.haveALittleRest(_) >> { throw new InterruptedException() }
153         when: 'the watchdog attempts to sleep to save cpu cycles'
154             objectUnderTest.preventBusyWait()
155         then: 'no exception is thrown'
156             noExceptionThrown()
157     }
158
159     def createCmHandleIds(numberOfCmHandles) {
160         return (numberOfCmHandles > 0) ? (1..numberOfCmHandles).collect { 'ch-'+it } : []
161     }
162 }