004cc52308561512cb9c90e7bd605c369523f347
[cps.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2022-2025 OpenInfra Foundation Europe. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *       http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.ncmp.impl.inventory.sync.lcm
22
23 import ch.qos.logback.classic.Level
24 import ch.qos.logback.classic.Logger
25 import ch.qos.logback.classic.spi.ILoggingEvent
26 import ch.qos.logback.core.read.ListAppender
27 import org.onap.cps.ncmp.api.inventory.DataStoreSyncState
28 import org.onap.cps.ncmp.api.inventory.models.CompositeState
29 import org.onap.cps.ncmp.impl.inventory.InventoryPersistence
30 import org.onap.cps.ncmp.impl.inventory.models.YangModelCmHandle
31 import org.slf4j.LoggerFactory
32 import spock.lang.Specification
33
34 import static java.util.Collections.EMPTY_LIST
35 import static java.util.Collections.EMPTY_MAP
36 import static org.onap.cps.ncmp.api.inventory.models.CmHandleState.ADVISED
37 import static org.onap.cps.ncmp.api.inventory.models.CmHandleState.DELETED
38 import static org.onap.cps.ncmp.api.inventory.models.CmHandleState.DELETING
39 import static org.onap.cps.ncmp.api.inventory.models.CmHandleState.LOCKED
40 import static org.onap.cps.ncmp.api.inventory.models.CmHandleState.READY
41 import static org.onap.cps.ncmp.api.inventory.models.LockReasonCategory.MODULE_SYNC_FAILED
42
43 class LcmEventsCmHandleStateHandlerImplSpec extends Specification {
44
45     def logAppender = Spy(ListAppender<ILoggingEvent>)
46
47     void setup() {
48         def logger = LoggerFactory.getLogger(LcmEventsCmHandleStateHandlerImpl)
49         logger.setLevel(Level.DEBUG)
50         logger.addAppender(logAppender)
51         logAppender.start()
52     }
53
54     void cleanup() {
55         ((Logger) LoggerFactory.getLogger(LcmEventsCmHandleStateHandlerImpl.class)).detachAndStopAllAppenders()
56     }
57
58     def mockInventoryPersistence = Mock(InventoryPersistence)
59     def mockLcmEventsCreator = Mock(LcmEventsProducerHelper)
60     def mockLcmEventsProducer = Mock(LcmEventsProducer)
61     def mockCmHandleStateMonitor = Mock(CmHandleStateMonitor)
62
63     def lcmEventsCmHandleStateHandlerAsyncHelper = new LcmEventsCmHandleStateHandlerAsyncHelper(mockLcmEventsCreator, mockLcmEventsProducer)
64     def objectUnderTest = new LcmEventsCmHandleStateHandlerImpl(mockInventoryPersistence, lcmEventsCmHandleStateHandlerAsyncHelper, mockCmHandleStateMonitor)
65
66     def cmHandleId = 'cmhandle-id-1'
67     def compositeState
68     def yangModelCmHandle
69
70     def 'Update and Send Events on State Change #stateChange'() {
71         given: 'Cm Handle represented as YangModelCmHandle'
72             compositeState = new CompositeState(cmHandleState: fromCmHandleState)
73             yangModelCmHandle = new YangModelCmHandle(id: cmHandleId, dmiProperties: [], publicProperties: [], compositeState: compositeState)
74         when: 'update state is invoked'
75             objectUnderTest.updateCmHandleStateBatch(Map.of(yangModelCmHandle, toCmHandleState))
76         then: 'state is saved using inventory persistence'
77             1 * mockInventoryPersistence.saveCmHandleStateBatch(_) >> {
78                 args -> {
79                     def cmHandleStatePerCmHandleId = args[0] as Map<String, CompositeState>
80                     assert cmHandleStatePerCmHandleId.get(cmHandleId).cmHandleState == toCmHandleState
81                 }
82             }
83         and: 'log message shows state change at DEBUG level'
84             def loggingEvent = logAppender.list[0]
85             assert loggingEvent.level == Level.DEBUG
86             assert loggingEvent.formattedMessage == "${cmHandleId} is now in ${toCmHandleState} state"
87         and: 'event service is called to send event'
88             1 * mockLcmEventsProducer.sendLcmEvent(cmHandleId, _, _)
89         where: 'state change parameters are provided'
90             stateChange           | fromCmHandleState | toCmHandleState
91             'ADVISED to READY'    | ADVISED           | READY
92             'READY to LOCKED'     | READY             | LOCKED
93             'ADVISED to LOCKED'   | ADVISED           | LOCKED
94             'ADVISED to DELETING' | ADVISED           | DELETING
95     }
96
97     def 'Update and Send Events on State Change from non-existing to ADVISED'() {
98         given: 'Cm Handle represented as YangModelCmHandle'
99             yangModelCmHandle = new YangModelCmHandle(id: cmHandleId, dmiProperties: [], publicProperties: [])
100         when: 'update state is invoked'
101             objectUnderTest.updateCmHandleStateBatch(Map.of(yangModelCmHandle, ADVISED))
102         then: 'CM-handle is saved using inventory persistence'
103             1 * mockInventoryPersistence.saveCmHandleBatch(List.of(yangModelCmHandle))
104         and: 'event service is called to send event'
105             1 * mockLcmEventsProducer.sendLcmEvent(cmHandleId, _, _)
106         and: 'a log entry is written'
107             assert getLogMessage(0) == "${cmHandleId} is now in ADVISED state"
108     }
109
110     def 'Update and Send Events on State Change from LOCKED to ADVISED'() {
111         given: 'Cm Handle represented as YangModelCmHandle in LOCKED state'
112             compositeState = new CompositeState(cmHandleState: LOCKED,
113                 lockReason: CompositeState.LockReason.builder().lockReasonCategory(MODULE_SYNC_FAILED).details('some lock details').build())
114             yangModelCmHandle = new YangModelCmHandle(id: cmHandleId, dmiProperties: [], publicProperties: [], compositeState: compositeState)
115         when: 'update state is invoked'
116             objectUnderTest.updateCmHandleStateBatch(Map.of(yangModelCmHandle, ADVISED))
117         then: 'state is saved using inventory persistence and old lock reason details are retained'
118             1 * mockInventoryPersistence.saveCmHandleStateBatch(_) >> {
119                 args -> {
120                     def cmHandleStatePerCmHandleId = args[0] as Map<String, CompositeState>
121                     assert cmHandleStatePerCmHandleId.get(cmHandleId).lockReason.details == 'some lock details'
122                 }
123             }
124         and: 'event service is called to send event'
125             1 * mockLcmEventsProducer.sendLcmEvent(cmHandleId, _, _)
126         and: 'a log entry is written'
127             assert getLogMessage(0) == "${cmHandleId} is now in ADVISED state"
128     }
129
130     def 'Update and Send Events on State Change to from ADVISED to READY'() {
131         given: 'Cm Handle represented as YangModelCmHandle'
132             compositeState = new CompositeState(cmHandleState: ADVISED)
133             yangModelCmHandle = new YangModelCmHandle(id: cmHandleId, dmiProperties: [], publicProperties: [], compositeState: compositeState)
134         and: 'global sync flag is set'
135             compositeState.setDataSyncEnabled(false)
136         when: 'update cmhandle state is invoked'
137             objectUnderTest.updateCmHandleStateBatch(Map.of(yangModelCmHandle, READY))
138         then: 'state is saved using inventory persistence with expected dataSyncState'
139             1 * mockInventoryPersistence.saveCmHandleStateBatch(_) >> {
140                 args-> {
141                     def cmHandleStatePerCmHandleId = args[0] as Map<String, CompositeState>
142                     assert cmHandleStatePerCmHandleId.get(cmHandleId).dataSyncEnabled == false
143                     assert cmHandleStatePerCmHandleId.get(cmHandleId).dataStores.operationalDataStore.dataStoreSyncState == DataStoreSyncState.NONE_REQUESTED
144                 }
145             }
146         and: 'event service is called to send event'
147             1 * mockLcmEventsProducer.sendLcmEvent(cmHandleId, _, _)
148         and: 'a log entry is written'
149             assert getLogMessage(0) == "${cmHandleId} is now in READY state"
150     }
151
152     def 'Update cmHandle state from READY to DELETING' (){
153         given: 'cm Handle as Yang model'
154             compositeState = new CompositeState(cmHandleState: READY)
155             yangModelCmHandle = new YangModelCmHandle(id: cmHandleId, dmiProperties: [], publicProperties: [], compositeState: compositeState)
156         when: 'updating cm handle state to "DELETING"'
157             objectUnderTest.updateCmHandleStateBatch(Map.of(yangModelCmHandle, DELETING))
158         then: 'the cm handle state is as expected'
159             yangModelCmHandle.getCompositeState().getCmHandleState() == DELETING
160         and: 'method to persist cm handle state is called once'
161             1 * mockInventoryPersistence.saveCmHandleStateBatch(Map.of(yangModelCmHandle.getId(), yangModelCmHandle.getCompositeState()))
162         and: 'the method to send Lcm event is called once'
163             1 * mockLcmEventsProducer.sendLcmEvent(cmHandleId, _, _)
164     }
165
166     def 'Update cmHandle state to DELETING to DELETED' (){
167         given: 'cm Handle with state "DELETING" as Yang model '
168             compositeState = new CompositeState(cmHandleState: DELETING)
169             yangModelCmHandle = new YangModelCmHandle(id: cmHandleId, dmiProperties: [], publicProperties: [], compositeState: compositeState)
170         when: 'updating cm handle state to "DELETED"'
171             objectUnderTest.updateCmHandleStateBatch(Map.of(yangModelCmHandle, DELETED))
172         then: 'the cm handle state is as expected'
173             yangModelCmHandle.getCompositeState().getCmHandleState() == DELETED
174         and: 'the method to send Lcm event is called once'
175             1 * mockLcmEventsProducer.sendLcmEvent(cmHandleId, _, _)
176     }
177
178     def 'No state change and no event to be sent'() {
179         given: 'Cm Handle batch with same state transition as before'
180             def cmHandleStateMap = setupBatch('NO_CHANGE')
181         when: 'updating a batch of changes'
182             objectUnderTest.updateCmHandleStateBatch(cmHandleStateMap)
183         then: 'no changes are persisted'
184             1 * mockInventoryPersistence.saveCmHandleBatch(EMPTY_LIST)
185             1 * mockInventoryPersistence.saveCmHandleStateBatch(EMPTY_MAP)
186         and: 'no event will be sent'
187             0 * mockLcmEventsProducer.sendLcmEvent(*_)
188     }
189
190     def 'Batch of new cm handles provided'() {
191         given: 'A batch of new cm handles'
192             def yangModelCmHandlesToBeCreated = setupBatch('NEW')
193         when: 'instantiating a batch of new cm handles'
194             objectUnderTest.initiateStateAdvised(yangModelCmHandlesToBeCreated)
195         then: 'new cm handles are saved using inventory persistence'
196             1 * mockInventoryPersistence.saveCmHandleBatch(_) >> {
197                 args -> {
198                     assert (args[0] as Collection<YangModelCmHandle>).id.containsAll('cmhandle1', 'cmhandle2')
199                 }
200             }
201         and: 'no state updates are persisted'
202             1 * mockInventoryPersistence.saveCmHandleStateBatch(EMPTY_MAP)
203         and: 'event service is called to send events'
204             2 * mockLcmEventsProducer.sendLcmEvent(_, _, _)
205         and: 'two log entries are written'
206             assert getLogMessage(0) == 'cmhandle1 is now in ADVISED state'
207             assert getLogMessage(1) == 'cmhandle2 is now in ADVISED state'
208     }
209
210     def 'Batch of existing cm handles is updated'() {
211         given: 'A batch of updated cm handles'
212             def cmHandleStateMap = setupBatch('UPDATE')
213         when: 'updating a batch of changes'
214             objectUnderTest.updateCmHandleStateBatch(cmHandleStateMap)
215         then: 'existing cm handles composite states are persisted'
216             1 * mockInventoryPersistence.saveCmHandleStateBatch(_) >> {
217                 args -> {
218                     assert (args[0] as Map<String, CompositeState>).keySet().containsAll(['cmhandle1', 'cmhandle2'])
219                 }
220             }
221         and: 'no new handles are persisted'
222             1 * mockInventoryPersistence.saveCmHandleBatch(EMPTY_LIST)
223         and: 'event service is called to send events'
224             2 * mockLcmEventsProducer.sendLcmEvent(_, _, _)
225         and: 'two log entries are written'
226             assert getLogMessage(0) == 'cmhandle1 is now in READY state'
227             assert getLogMessage(1) == 'cmhandle2 is now in DELETING state'
228     }
229
230     def 'Batch of existing cm handles is deleted'() {
231         given: 'A batch of deleted cm handles'
232             def cmHandleStateMap = setupBatch('DELETED')
233         when: 'updating a batch of changes'
234             objectUnderTest.updateCmHandleStateBatch(cmHandleStateMap)
235         then: 'state of deleted handles is not persisted'
236             1 * mockInventoryPersistence.saveCmHandleStateBatch(EMPTY_MAP)
237         and: 'no new handles are persisted'
238             1 * mockInventoryPersistence.saveCmHandleBatch(EMPTY_LIST)
239         and: 'event service is called to send events'
240             2 * mockLcmEventsProducer.sendLcmEvent(_, _, _)
241         and: 'two log entries are written'
242             assert getLogMessage(0) == 'cmhandle1 is now in DELETED state'
243             assert getLogMessage(1) == 'cmhandle2 is now in DELETED state'
244     }
245
246     def 'Log entries and events are not sent when an error occurs during persistence'() {
247         given: 'A batch of updated cm handles'
248             def cmHandleStateMap = setupBatch('UPDATE')
249         and: 'an error will be thrown when trying to persist'
250             mockInventoryPersistence.saveCmHandleStateBatch(_) >> { throw new RuntimeException() }
251         when: 'updating a batch of changes'
252             objectUnderTest.updateCmHandleStateBatch(cmHandleStateMap)
253         then: 'the exception is not handled'
254             thrown(RuntimeException)
255         and: 'no events are sent'
256             0 * mockLcmEventsProducer.sendLcmEvent(_, _, _)
257         and: 'no log entries are written'
258             assert logAppender.list.empty
259     }
260
261     def setupBatch(type) {
262
263         def yangModelCmHandle1 = new YangModelCmHandle(id: 'cmhandle1', dmiProperties: [], publicProperties: [])
264         def yangModelCmHandle2 = new YangModelCmHandle(id: 'cmhandle2', dmiProperties: [], publicProperties: [])
265
266         switch (type) {
267             case 'NEW':
268                 return [yangModelCmHandle1, yangModelCmHandle2]
269
270             case 'DELETED':
271                 yangModelCmHandle1.compositeState = new CompositeState(cmHandleState: READY)
272                 yangModelCmHandle2.compositeState = new CompositeState(cmHandleState: READY)
273                 return [(yangModelCmHandle1): DELETED, (yangModelCmHandle2): DELETED]
274
275             case 'UPDATE':
276                 yangModelCmHandle1.compositeState = new CompositeState(cmHandleState: ADVISED)
277                 yangModelCmHandle2.compositeState = new CompositeState(cmHandleState: READY)
278                 return [(yangModelCmHandle1): READY, (yangModelCmHandle2): DELETING]
279
280             case 'NO_CHANGE':
281                 yangModelCmHandle1.compositeState = new CompositeState(cmHandleState: ADVISED)
282                 yangModelCmHandle2.compositeState = new CompositeState(cmHandleState: READY)
283                 return [(yangModelCmHandle1): ADVISED, (yangModelCmHandle2): READY]
284
285             default:
286                 throw new IllegalArgumentException("batch type '${type}' not recognized")
287         }
288     }
289
290     def getLogMessage(index) {
291         return logAppender.list[index].formattedMessage
292     }
293 }