Updating tests to account for Drools upgrade
[policy/drools-applications.git] / controlloop / common / eventmanager / src / test / java / org / onap / policy / controlloop / eventmanager / ClEventManagerWithStepsTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2021, 2023 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.policy.controlloop.eventmanager;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.assertj.core.api.Assertions.assertThatCode;
25 import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
26 import static org.assertj.core.api.Assertions.assertThatThrownBy;
27 import static org.junit.Assert.assertEquals;
28 import static org.junit.Assert.assertFalse;
29 import static org.junit.Assert.assertNotNull;
30 import static org.junit.Assert.assertNull;
31 import static org.junit.Assert.assertSame;
32 import static org.junit.Assert.assertTrue;
33 import static org.mockito.ArgumentMatchers.any;
34 import static org.mockito.ArgumentMatchers.anyLong;
35 import static org.mockito.Mockito.never;
36 import static org.mockito.Mockito.verify;
37 import static org.mockito.Mockito.when;
38
39 import java.time.Instant;
40 import java.util.ArrayList;
41 import java.util.Deque;
42 import java.util.List;
43 import java.util.UUID;
44 import java.util.concurrent.ExecutorService;
45 import java.util.concurrent.ForkJoinPool;
46 import java.util.concurrent.atomic.AtomicReference;
47 import org.drools.core.WorkingMemory;
48 import org.drools.core.common.InternalFactHandle;
49 import org.junit.Before;
50 import org.junit.Test;
51 import org.junit.runner.RunWith;
52 import org.mockito.Mock;
53 import org.mockito.junit.MockitoJUnitRunner;
54 import org.onap.policy.common.utils.coder.Coder;
55 import org.onap.policy.common.utils.coder.CoderException;
56 import org.onap.policy.common.utils.coder.StandardYamlCoder;
57 import org.onap.policy.common.utils.io.Serializer;
58 import org.onap.policy.common.utils.resources.ResourceUtils;
59 import org.onap.policy.controlloop.ControlLoopException;
60 import org.onap.policy.controlloop.actorserviceprovider.ActorService;
61 import org.onap.policy.controlloop.actorserviceprovider.Operation;
62 import org.onap.policy.controlloop.actorserviceprovider.OperationFinalResult;
63 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
64 import org.onap.policy.controlloop.actorserviceprovider.OperationResult;
65 import org.onap.policy.controlloop.actorserviceprovider.Operator;
66 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
67 import org.onap.policy.controlloop.actorserviceprovider.spi.Actor;
68 import org.onap.policy.controlloop.drl.legacy.ControlLoopParams;
69 import org.onap.policy.drools.core.lock.LockCallback;
70 import org.onap.policy.drools.core.lock.LockImpl;
71 import org.onap.policy.drools.core.lock.LockState;
72 import org.onap.policy.drools.system.PolicyEngine;
73 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
74 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
75
76 @RunWith(MockitoJUnitRunner.class)
77 public class ClEventManagerWithStepsTest {
78     private static final UUID REQ_ID = UUID.randomUUID();
79     private static final String CL_NAME = "my-closed-loop-name";
80     private static final String POLICY_NAME = "my-policy-name";
81     private static final String POLICY_SCOPE = "my-scope";
82     private static final String POLICY_VERSION = "1.2.3";
83     private static final String SIMPLE_ACTOR = "First";
84     private static final String SIMPLE_OPERATION = "OperationA";
85     private static final String MY_TARGET = "my-target";
86     private static final String EVENT_MGR_MULTI_YAML =
87                     "../eventmanager/src/test/resources/eventManager/event-mgr-multi.yaml";
88     private static final String EVENT_MGR_SIMPLE_YAML =
89                     "../eventmanager/src/test/resources/eventManager/event-mgr-simple.yaml";
90     private static final Coder yamlCoder = new StandardYamlCoder();
91     private static final String OUTCOME_MSG = "my outcome message";
92     private static final String MY_SINK = "my-topic-sink";
93
94     @Mock
95     private PolicyEngine engineMgr;
96     @Mock
97     private WorkingMemory workMem;
98     @Mock
99     private InternalFactHandle factHandle;
100     @Mock
101     private Operator policyOperator;
102     @Mock
103     private Operation policyOperation;
104     @Mock
105     private Actor policyActor;
106     @Mock
107     private ExecutorService executor;
108     @Mock
109     private EventManagerServices services;
110     @Mock
111     private ActorService actors;
112     @Mock
113     private MyStep stepa;
114     @Mock
115     private MyStep stepb;
116
117     private List<LockImpl> locks;
118     private ToscaPolicy tosca;
119     private ControlLoopParams params;
120     private ClEventManagerWithSteps<MyStep> mgr;
121
122     /**
123      * Sets up.
124      */
125     @Before
126     public void setUp() throws ControlLoopException, CoderException {
127         when(services.getActorService()).thenReturn(actors);
128
129         when(workMem.getFactHandle(any())).thenReturn(factHandle);
130
131         params = new ControlLoopParams();
132         params.setClosedLoopControlName(CL_NAME);
133         params.setPolicyName(POLICY_NAME);
134         params.setPolicyScope(POLICY_SCOPE);
135         params.setPolicyVersion(POLICY_VERSION);
136
137         loadPolicy(EVENT_MGR_SIMPLE_YAML);
138
139         locks = new ArrayList<>();
140
141         mgr = new MyManager(services, params, REQ_ID, workMem);
142     }
143
144     @Test
145     public void testConstructor() {
146         assertEquals(POLICY_NAME, mgr.getPolicyName());
147
148         // invalid
149         assertThatThrownBy(() -> new MyManager(services, params, null, workMem))
150                         .isInstanceOf(ControlLoopException.class);
151     }
152
153     @Test
154     public void testDestroy_testGetSteps() {
155         // add some steps to the queue
156         mgr.getSteps().add(stepa);
157         mgr.getSteps().add(stepb);
158
159         mgr.destroy();
160
161         verify(stepa).cancel();
162         verify(stepb).cancel();
163
164         // if superclass destroy() was invoked, then freeLock() should have been submitted
165         // to the executor
166         verify(executor).execute(any());
167     }
168
169     @Test
170     public void testOnStart() throws ControlLoopException {
171         OperationOutcome outcome = makeOutcome();
172
173         mgr.start();
174         mgr.onStart(outcome);
175
176         assertSame(outcome, mgr.getOutcomes().poll());
177         assertThat(mgr.getOutcomes()).isEmpty();
178
179         verify(workMem).update(factHandle, mgr);
180     }
181
182     @Test
183     public void testOnComplete() throws ControlLoopException {
184         OperationOutcome outcome = makeCompletedOutcome();
185
186         mgr.start();
187         mgr.onComplete(outcome);
188
189         assertSame(outcome, mgr.getOutcomes().poll());
190         assertThat(mgr.getOutcomes()).isEmpty();
191
192         verify(workMem).update(factHandle, mgr);
193     }
194
195     @Test
196     public void testToString() {
197         assertNotNull(mgr.toString());
198     }
199
200     @Test
201     public void testStart() throws ControlLoopException {
202         // start it
203         mgr.start();
204
205         // cannot re-start
206         assertThatCode(() -> mgr.start()).isInstanceOf(IllegalStateException.class)
207                         .hasMessage("manager already started");
208     }
209
210     /**
211      * Tests start() when the manager is not in working memory.
212      */
213     @Test
214     public void testStartNotInWorkingMemory() throws ControlLoopException {
215         when(workMem.getFactHandle(any())).thenReturn(null);
216
217         assertThatCode(() -> mgr.start()).isInstanceOf(IllegalStateException.class)
218                         .hasMessage("manager is not in working memory");
219     }
220
221     /**
222      * Tests start() when the manager is not active.
223      */
224     @Test
225     public void testStartInactive() throws Exception {
226         // make an inactive manager by deserializing it
227         RealManager mgr2 = Serializer.roundTrip(new RealManager(services, params, REQ_ID, workMem));
228         mgr = mgr2;
229
230         // cannot re-start
231         assertThatCode(() -> mgr.start()).isInstanceOf(IllegalStateException.class)
232                         .hasMessage("manager is no longer active");
233     }
234
235     @Test
236     public void testAbort() {
237         mgr.abort(ClEventManagerWithSteps.State.DONE, OperationFinalResult.FINAL_FAILURE_GUARD, "some message");
238
239         assertEquals(ClEventManagerWithSteps.State.DONE, mgr.getState());
240         assertEquals(OperationFinalResult.FINAL_FAILURE_GUARD, mgr.getFinalResult());
241         assertEquals("some message", mgr.getFinalMessage());
242
243         // try null state
244         assertThatThrownBy(() -> mgr.abort(null, OperationFinalResult.FINAL_FAILURE_GUARD, ""))
245                         .isInstanceOf(NullPointerException.class).hasMessageContaining("finalState");
246     }
247
248     @Test
249     public void testLoadNextPolicy() throws Exception {
250         loadPolicy(EVENT_MGR_MULTI_YAML);
251         mgr = new MyManager(services, params, REQ_ID, workMem);
252
253         // start and load step for first policy
254         mgr.start();
255         assertEquals("OperationA", mgr.getSteps().poll().getOperationName());
256         assertNull(mgr.getFinalResult());
257
258         // indicate success and load next policy
259         mgr.loadNextPolicy(OperationResult.SUCCESS);
260         assertEquals("OperationB", mgr.getSteps().poll().getOperationName());
261         assertNull(mgr.getFinalResult());
262
263         // indicate failure - should go to final failure
264         mgr.loadNextPolicy(OperationResult.FAILURE);
265         assertEquals(OperationFinalResult.FINAL_FAILURE, mgr.getFinalResult());
266     }
267
268     @Test
269     public void testLoadPolicy() throws ControlLoopException {
270         // start() will invoke loadPolicy()
271         mgr.start();
272
273         assertNull(mgr.getFinalResult());
274
275         MyStep step = mgr.getSteps().peek();
276         assertNotNull(step);
277         assertEquals("First", step.getActorName());
278         assertEquals("OperationA", step.getOperationName());
279
280         ControlLoopOperationParams params2 = step.getParams();
281         assertSame(actors, params2.getActorService());
282         assertSame(REQ_ID, params2.getRequestId());
283         assertSame(ForkJoinPool.commonPool(), params2.getExecutor());
284         assertNotNull(params2.getTargetType());
285         assertNotNull(params2.getTargetEntityIds());
286         assertEquals(Integer.valueOf(300), params2.getTimeoutSec());
287         assertEquals(Integer.valueOf(0), params2.getRetry());
288         assertThat(params2.getPayload()).isEmpty();
289         assertNotNull(params2.getStartCallback());
290         assertNotNull(params2.getCompleteCallback());
291     }
292
293     @Test
294     public void testLoadPreprocessorSteps() {
295         stepa = new MyStep(mgr, ControlLoopOperationParams.builder().build()) {
296             @Override
297             protected Operation buildOperation() {
298                 return policyOperation;
299             }
300         };
301
302         Deque<MyStep> steps = mgr.getSteps();
303         steps.add(stepa);
304         steps.add(stepb);
305
306         mgr.loadPreprocessorSteps();
307
308         // no additional steps should have been loaded
309         assertThat(steps).hasSize(2);
310
311         assertSame(stepa, steps.poll());
312         assertSame(stepb, steps.poll());
313         assertThat(steps).isEmpty();
314
315         assertNotNull(stepa.getOperation());
316         assertNull(stepb.getOperation());
317     }
318
319     /**
320      * Tests loadPreprocessorSteps() when there are too many steps in the queue.
321      */
322     @Test
323     public void testLoadPreprocessorStepsTooManySteps() {
324         stepa = new MyStep(mgr, ControlLoopOperationParams.builder().build()) {
325             @Override
326             protected Operation buildOperation() {
327                 return policyOperation;
328             }
329         };
330
331         Deque<MyStep> steps = mgr.getSteps();
332
333         // load up a bunch of steps
334         for (int nsteps = 0; nsteps < ClEventManagerWithSteps.MAX_STEPS; ++nsteps) {
335             steps.add(stepa);
336         }
337
338         // should fail
339         assertThatIllegalStateException().isThrownBy(() -> mgr.loadPreprocessorSteps()).withMessage("too many steps");
340
341         // add another step, should still fail
342         steps.add(stepa);
343         assertThatIllegalStateException().isThrownBy(() -> mgr.loadPreprocessorSteps()).withMessage("too many steps");
344
345         // remove two steps - should now succeed
346         steps.remove();
347         steps.remove();
348
349         int nsteps = steps.size();
350
351         mgr.loadPreprocessorSteps();
352         assertEquals(nsteps, steps.size());
353     }
354
355     @Test
356     public void testExecuteStep() {
357         // no steps to execute
358         assertFalse(mgr.executeStep());
359
360         // add a step to the queue
361         mgr.getSteps().add(stepa);
362
363         // step returns false
364         when(stepa.start(anyLong())).thenReturn(false);
365         assertFalse(mgr.executeStep());
366
367         // step returns true
368         when(stepa.start(anyLong())).thenReturn(true);
369         assertTrue(mgr.executeStep());
370     }
371
372     @Test
373     public void testNextStep() {
374         mgr.getSteps().add(stepa);
375
376         mgr.nextStep();
377
378         assertThat(mgr.getSteps()).isEmpty();
379     }
380
381     @Test
382     public void testDeliver() {
383         mgr.deliver(MY_SINK, null, "null notification", "null rule");
384         verify(engineMgr, never()).deliver(any(), any());
385
386         mgr.deliver(MY_SINK, "publishA", "A notification", "A rule");
387         verify(engineMgr).deliver(MY_SINK, "publishA");
388
389         // cause deliver() to throw an exception
390         when(engineMgr.deliver(any(), any())).thenThrow(new IllegalStateException("expected exception"));
391         assertThatCode(() -> mgr.deliver(MY_SINK, "publishB", "B notification", "B rule")).doesNotThrowAnyException();
392     }
393
394     private void loadPolicy(String fileName) throws CoderException {
395         ToscaServiceTemplate template =
396                         yamlCoder.decode(ResourceUtils.getResourceAsString(fileName), ToscaServiceTemplate.class);
397         tosca = template.getToscaTopologyTemplate().getPolicies().get(0).values().iterator().next();
398
399         params.setToscaPolicy(tosca);
400     }
401
402     private OperationOutcome makeCompletedOutcome() {
403         OperationOutcome outcome = makeOutcome();
404         outcome.setEnd(outcome.getStart());
405
406         return outcome;
407     }
408
409     private OperationOutcome makeOutcome() {
410         OperationOutcome outcome = new OperationOutcome();
411         outcome.setActor(SIMPLE_ACTOR);
412         outcome.setOperation(SIMPLE_OPERATION);
413         outcome.setMessage(OUTCOME_MSG);
414         outcome.setResult(OperationResult.SUCCESS);
415         outcome.setStart(Instant.now());
416         outcome.setTarget(MY_TARGET);
417
418         return outcome;
419     }
420
421
422     private class MyManager extends ClEventManagerWithSteps<MyStep> {
423         private static final long serialVersionUID = 1L;
424
425         public MyManager(EventManagerServices services, ControlLoopParams params, UUID requestId, WorkingMemory workMem)
426                         throws ControlLoopException {
427
428             super(services, params, requestId, workMem);
429         }
430
431         @Override
432         protected ExecutorService getBlockingExecutor() {
433             return executor;
434         }
435
436         @Override
437         protected void makeLock(String targetEntity, String requestId, int holdSec, LockCallback callback) {
438             LockImpl lock = new LockImpl(LockState.ACTIVE, targetEntity, requestId, holdSec, callback);
439             locks.add(lock);
440             callback.lockAvailable(lock);
441         }
442
443         @Override
444         protected PolicyEngine getPolicyEngineManager() {
445             return engineMgr;
446         }
447
448         @Override
449         protected void loadPolicyStep(ControlLoopOperationParams params) {
450             getSteps().add(new MyStep(this, params));
451         }
452     }
453
454
455     private static class RealManager extends ClEventManagerWithSteps<MyStep> {
456         private static final long serialVersionUID = 1L;
457
458         public RealManager(EventManagerServices services, ControlLoopParams params, UUID requestId,
459                         WorkingMemory workMem) throws ControlLoopException {
460
461             super(services, params, requestId, workMem);
462         }
463
464         @Override
465         protected void loadPolicyStep(ControlLoopOperationParams params) {
466             getSteps().add(new MyStep(this, params));
467         }
468     }
469
470     private static class MyStep extends Step {
471         public MyStep(StepContext stepContext, ControlLoopOperationParams params) {
472             super(params, new AtomicReference<>());
473         }
474     }
475 }