2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2021, 2023 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2023-2024 Nordix Foundation.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.controlloop.eventmanager;
24 import static org.assertj.core.api.Assertions.assertThat;
25 import static org.assertj.core.api.Assertions.assertThatCode;
26 import static org.assertj.core.api.Assertions.assertThatThrownBy;
27 import static org.junit.jupiter.api.Assertions.assertEquals;
28 import static org.junit.jupiter.api.Assertions.assertNotNull;
29 import static org.junit.jupiter.api.Assertions.assertNull;
30 import static org.junit.jupiter.api.Assertions.assertSame;
31 import static org.mockito.ArgumentMatchers.any;
32 import static org.mockito.Mockito.mock;
33 import static org.mockito.Mockito.verify;
34 import static org.mockito.Mockito.when;
36 import java.time.Instant;
37 import java.util.ArrayList;
38 import java.util.List;
40 import java.util.TreeMap;
41 import java.util.UUID;
42 import java.util.concurrent.ExecutorService;
43 import java.util.concurrent.atomic.AtomicReference;
44 import org.drools.core.WorkingMemory;
45 import org.drools.core.common.InternalFactHandle;
46 import org.junit.jupiter.api.BeforeEach;
47 import org.junit.jupiter.api.Test;
48 import org.onap.policy.common.utils.coder.Coder;
49 import org.onap.policy.common.utils.coder.CoderException;
50 import org.onap.policy.common.utils.coder.StandardYamlCoder;
51 import org.onap.policy.common.utils.resources.ResourceUtils;
52 import org.onap.policy.controlloop.ControlLoopEventStatus;
53 import org.onap.policy.controlloop.ControlLoopException;
54 import org.onap.policy.controlloop.ControlLoopTargetType;
55 import org.onap.policy.controlloop.VirtualControlLoopEvent;
56 import org.onap.policy.controlloop.VirtualControlLoopNotification;
57 import org.onap.policy.controlloop.actorserviceprovider.ActorService;
58 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
59 import org.onap.policy.controlloop.actorserviceprovider.OperationResult;
60 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
61 import org.onap.policy.controlloop.drl.legacy.ControlLoopParams;
62 import org.onap.policy.controlloop.eventmanager.ClEventManagerWithEvent.NewEventStatus;
63 import org.onap.policy.controlloop.ophistory.OperationHistoryDataManager;
64 import org.onap.policy.drools.core.lock.LockCallback;
65 import org.onap.policy.drools.core.lock.LockImpl;
66 import org.onap.policy.drools.core.lock.LockState;
67 import org.onap.policy.drools.system.PolicyEngine;
68 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
69 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
71 class ClEventManagerWithEventTest {
72 private static final UUID REQ_ID = UUID.randomUUID();
73 private static final String CL_NAME = "my-closed-loop-name";
74 private static final String POLICY_NAME = "my-policy-name";
75 private static final String POLICY_SCOPE = "my-scope";
76 private static final String POLICY_VERSION = "1.2.3";
77 private static final String SIMPLE_ACTOR = "First";
78 private static final String SIMPLE_OPERATION = "OperationA";
79 private static final String TARGET_PROP = "my-target-property";
80 private static final String MY_TARGET = "my-target";
81 private static final String EVENT_MGR_MULTI_YAML =
82 "../eventmanager/src/test/resources/eventManager/event-mgr-multi.yaml";
83 private static final String EVENT_MGR_SIMPLE_YAML =
84 "../eventmanager/src/test/resources/eventManager/event-mgr-simple.yaml";
85 private static final Coder yamlCoder = new StandardYamlCoder();
86 private static final String OUTCOME_MSG = "my outcome message";
88 private final PolicyEngine engineMgr = mock(PolicyEngine.class);
89 private final WorkingMemory workMem = mock(WorkingMemory.class);
90 private final InternalFactHandle factHandle = mock(InternalFactHandle.class);
91 private final EventManagerServices services = mock(EventManagerServices.class);
92 private final ActorService actors = mock(ActorService.class);
93 private final OperationHistoryDataManager dataMgr = mock(OperationHistoryDataManager.class);
94 private final ExecutorService executor = mock(ExecutorService.class);
96 private List<LockImpl> locks;
97 private ControlLoopParams params;
98 private VirtualControlLoopEvent event;
99 private ClEventManagerWithEvent<MyStep> mgr;
105 public void setUp() throws ControlLoopException, CoderException {
106 when(services.getActorService()).thenReturn(actors);
107 when(services.getDataManager()).thenReturn(dataMgr);
109 when(workMem.getFactHandle(any())).thenReturn(factHandle);
111 event = new VirtualControlLoopEvent();
112 event.setRequestId(REQ_ID);
113 event.setTarget(TARGET_PROP);
114 event.setAai(new TreeMap<>(Map.of(TARGET_PROP, MY_TARGET)));
115 event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
116 event.setClosedLoopControlName(CL_NAME);
117 event.setTargetType(ControlLoopTargetType.VNF);
119 params = new ControlLoopParams();
120 params.setClosedLoopControlName(CL_NAME);
121 params.setPolicyName(POLICY_NAME);
122 params.setPolicyScope(POLICY_SCOPE);
123 params.setPolicyVersion(POLICY_VERSION);
125 loadPolicy(EVENT_MGR_SIMPLE_YAML);
127 locks = new ArrayList<>();
129 mgr = new MyManager(services, params, event, workMem);
133 void testConstructor() {
134 assertEquals(POLICY_NAME, mgr.getPolicyName());
135 assertSame(event, mgr.getEvent());
138 assertThatCode(() -> mgr.checkEventSyntax(event)).doesNotThrowAnyException();
142 assertThatThrownBy(() -> new MyManager(services, params, event, workMem))
143 .isInstanceOf(ControlLoopException.class);
147 void testPopulateNotification() throws Exception {
148 loadPolicy(EVENT_MGR_MULTI_YAML);
149 mgr = new MyManager(services, params, event, workMem);
152 assertNotNull(mgr.makeNotification());
156 mgr.addToHistory(makeCompletedOutcome());
157 mgr.addToHistory(makeCompletedOutcome());
158 mgr.addToHistory(makeCompletedOutcome());
160 // check notification while running
161 VirtualControlLoopNotification notif = mgr.makeNotification();
162 assertThat(notif.getMessage()).contains(SIMPLE_ACTOR);
163 assertThat(notif.getHistory()).hasSize(3);
164 assertThat(notif.getAai()).isEqualTo(event.getAai());
165 assertThat(notif.getClosedLoopAlarmEnd()).isEqualTo(event.getClosedLoopAlarmEnd());
166 assertThat(notif.getClosedLoopAlarmStart()).isEqualTo(event.getClosedLoopAlarmStart());
167 assertThat(notif.getClosedLoopControlName()).isEqualTo(event.getClosedLoopControlName());
168 assertThat(notif.getClosedLoopEventClient()).isEqualTo(event.getClosedLoopEventClient());
169 assertThat(notif.getFrom()).isEqualTo("policy");
170 assertThat(notif.getTarget()).isEqualTo(event.getTarget());
171 assertThat(notif.getTargetType()).isEqualTo(event.getTargetType());
173 // indicate success and load the next policy - should clear the partial history
174 mgr.loadNextPolicy(OperationResult.SUCCESS);
176 // check notification
177 notif = mgr.makeNotification();
178 assertNull(notif.getMessage());
179 assertThat(notif.getHistory()).isEmpty();
181 // add outcomes and check again
182 mgr.addToHistory(makeCompletedOutcome());
183 mgr.addToHistory(makeCompletedOutcome());
185 notif = mgr.makeNotification();
186 assertNotNull(notif.getMessage());
188 // should only have history for last two outcomes
189 assertThat(notif.getHistory()).hasSize(2);
191 // indicate failure - should go to final state
192 mgr.loadNextPolicy(OperationResult.FAILURE);
194 // check notification
195 notif = mgr.makeNotification();
196 assertNull(notif.getMessage());
198 // should be no history
199 assertThat(notif.getHistory()).isEmpty();
202 assertThatThrownBy(() -> mgr.loadNextPolicy(null)).isInstanceOf(NullPointerException.class)
203 .hasMessageContaining("lastResult");
207 void testStoreInDataBase() throws ControlLoopException {
209 OperationOutcome outcome = makeOutcome();
210 mgr.addToHistory(outcome);
212 var peeked = mgr.getPartialHistory().peekLast();
213 assertNotNull(peeked);
214 mgr.storeInDataBase(peeked, MY_TARGET);
216 verify(dataMgr).store(REQ_ID.toString(), event.getClosedLoopControlName(), event, MY_TARGET,
217 peeked.getClOperation());
221 void testMakeControlLoopResponse() {
222 final var outcome = new OperationOutcome();
224 var resp = mgr.makeControlLoopResponse(outcome);
226 assertEquals("DCAE", resp.getTarget());
227 assertEquals(event.getClosedLoopControlName(), resp.getClosedLoopControlName());
228 assertEquals(event.getPolicyName(), resp.getPolicyName());
229 assertEquals(event.getPolicyVersion(), resp.getPolicyVersion());
230 assertEquals(REQ_ID, resp.getRequestId());
231 assertEquals(event.getVersion(), resp.getVersion());
235 void testOnNewEvent() {
236 var event2 = new VirtualControlLoopEvent(event);
237 assertEquals(NewEventStatus.FIRST_ONSET, mgr.onNewEvent(event2));
239 event2.setPayload("other payload");
240 assertEquals(NewEventStatus.SUBSEQUENT_ONSET, mgr.onNewEvent(event2));
241 assertEquals(NewEventStatus.SUBSEQUENT_ONSET, mgr.onNewEvent(event2));
242 assertEquals(NewEventStatus.FIRST_ONSET, mgr.onNewEvent(event));
244 event2.setClosedLoopEventStatus(ControlLoopEventStatus.ABATED);
245 assertEquals(NewEventStatus.FIRST_ABATEMENT, mgr.onNewEvent(event2));
247 assertEquals(NewEventStatus.SUBSEQUENT_ABATEMENT, mgr.onNewEvent(event2));
248 assertEquals(NewEventStatus.SUBSEQUENT_ABATEMENT, mgr.onNewEvent(event2));
250 event2.setClosedLoopEventStatus(null);
251 assertEquals(NewEventStatus.SYNTAX_ERROR, mgr.onNewEvent(event2));
255 void testCheckEventSyntax() {
256 // initially, it's valid
257 assertThatCode(() -> mgr.checkEventSyntax(event)).doesNotThrowAnyException();
259 event.setTarget(null);
260 assertThatCode(() -> mgr.checkEventSyntax(event)).isInstanceOf(ControlLoopException.class)
261 .hasMessage("No target field");
263 // abated supersedes previous errors - so it shouldn't throw an exception
264 event.setClosedLoopEventStatus(ControlLoopEventStatus.ABATED);
265 assertThatCode(() -> mgr.checkEventSyntax(event)).doesNotThrowAnyException();
267 event.setRequestId(null);
268 assertThatCode(() -> mgr.checkEventSyntax(event)).isInstanceOf(ControlLoopException.class)
269 .hasMessage("No request ID");
271 event.setClosedLoopControlName(null);
272 assertThatCode(() -> mgr.checkEventSyntax(event)).isInstanceOf(ControlLoopException.class)
273 .hasMessage("No control loop name");
277 void testValidateStatus() {
278 event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
279 assertThatCode(() -> mgr.checkEventSyntax(event)).doesNotThrowAnyException();
281 event.setClosedLoopEventStatus(ControlLoopEventStatus.ABATED);
282 assertThatCode(() -> mgr.checkEventSyntax(event)).doesNotThrowAnyException();
284 event.setClosedLoopEventStatus(null);
285 assertThatCode(() -> mgr.checkEventSyntax(event)).isInstanceOf(ControlLoopException.class)
286 .hasMessage("Invalid value in closedLoopEventStatus");
289 private void loadPolicy(String fileName) throws CoderException {
290 var template = yamlCoder.decode(ResourceUtils.getResourceAsString(fileName), ToscaServiceTemplate.class);
291 ToscaPolicy tosca = template.getToscaTopologyTemplate().getPolicies().get(0).values().iterator().next();
293 params.setToscaPolicy(tosca);
296 private OperationOutcome makeCompletedOutcome() {
297 var outcome = makeOutcome();
298 outcome.setEnd(outcome.getStart());
303 private OperationOutcome makeOutcome() {
304 var outcome = new OperationOutcome();
305 outcome.setActor(SIMPLE_ACTOR);
306 outcome.setOperation(SIMPLE_OPERATION);
307 outcome.setMessage(OUTCOME_MSG);
308 outcome.setResult(OperationResult.SUCCESS);
309 outcome.setStart(Instant.now());
310 outcome.setTarget(MY_TARGET);
316 private class MyManager extends ClEventManagerWithEvent<MyStep> {
317 private static final long serialVersionUID = 1L;
319 public MyManager(EventManagerServices services, ControlLoopParams params, VirtualControlLoopEvent event,
320 WorkingMemory workMem) throws ControlLoopException {
322 super(services, params, event, workMem);
326 protected ExecutorService getBlockingExecutor() {
331 protected void makeLock(String targetEntity, String requestId, int holdSec, LockCallback callback) {
332 LockImpl lock = new LockImpl(LockState.ACTIVE, targetEntity, requestId, holdSec, callback);
334 callback.lockAvailable(lock);
338 protected PolicyEngine getPolicyEngineManager() {
343 protected void loadPolicyStep(ControlLoopOperationParams params) {
344 getSteps().add(new MyStep(this, params, getEvent()));
348 private static class MyStep extends Step {
349 public MyStep(StepContext stepContext, ControlLoopOperationParams params, VirtualControlLoopEvent event) {
350 super(params, new AtomicReference<>());