2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2021 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.controlloop.eventmanager;
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;
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.junit.Before;
49 import org.junit.Test;
50 import org.junit.runner.RunWith;
51 import org.kie.api.runtime.rule.FactHandle;
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;
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";
95 private PolicyEngine engineMgr;
97 private WorkingMemory workMem;
99 private FactHandle factHandle;
101 private Operator policyOperator;
103 private Operation policyOperation;
105 private Actor policyActor;
107 private ExecutorService executor;
109 private EventManagerServices services;
111 private ActorService actors;
113 private MyStep stepa;
115 private MyStep stepb;
117 private List<LockImpl> locks;
118 private ToscaPolicy tosca;
119 private ControlLoopParams params;
120 private ClEventManagerWithSteps<MyStep> mgr;
126 public void setUp() throws ControlLoopException, CoderException {
127 when(services.getActorService()).thenReturn(actors);
129 when(workMem.getFactHandle(any())).thenReturn(factHandle);
131 params = new ControlLoopParams();
132 params.setClosedLoopControlName(CL_NAME);
133 params.setPolicyName(POLICY_NAME);
134 params.setPolicyScope(POLICY_SCOPE);
135 params.setPolicyVersion(POLICY_VERSION);
137 loadPolicy(EVENT_MGR_SIMPLE_YAML);
139 locks = new ArrayList<>();
141 mgr = new MyManager(services, params, REQ_ID, workMem);
145 public void testConstructor() {
146 assertEquals(POLICY_NAME, mgr.getPolicyName());
149 assertThatThrownBy(() -> new MyManager(services, params, null, workMem))
150 .isInstanceOf(ControlLoopException.class);
154 public void testDestroy_testGetSteps() {
155 // add some steps to the queue
156 mgr.getSteps().add(stepa);
157 mgr.getSteps().add(stepb);
161 verify(stepa).cancel();
162 verify(stepb).cancel();
164 // if superclass destroy() was invoked, then freeLock() should have been submitted
166 verify(executor).execute(any());
170 public void testOnStart() throws ControlLoopException {
171 OperationOutcome outcome = makeOutcome();
174 mgr.onStart(outcome);
176 assertSame(outcome, mgr.getOutcomes().poll());
177 assertThat(mgr.getOutcomes()).isEmpty();
179 verify(workMem).update(factHandle, mgr);
183 public void testOnComplete() throws ControlLoopException {
184 OperationOutcome outcome = makeCompletedOutcome();
187 mgr.onComplete(outcome);
189 assertSame(outcome, mgr.getOutcomes().poll());
190 assertThat(mgr.getOutcomes()).isEmpty();
192 verify(workMem).update(factHandle, mgr);
196 public void testToString() {
197 assertNotNull(mgr.toString());
201 public void testStart() throws ControlLoopException {
206 assertThatCode(() -> mgr.start()).isInstanceOf(IllegalStateException.class)
207 .hasMessage("manager already started");
211 * Tests start() when the manager is not in working memory.
214 public void testStartNotInWorkingMemory() throws ControlLoopException {
215 when(workMem.getFactHandle(any())).thenReturn(null);
217 assertThatCode(() -> mgr.start()).isInstanceOf(IllegalStateException.class)
218 .hasMessage("manager is not in working memory");
222 * Tests start() when the manager is not active.
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));
231 assertThatCode(() -> mgr.start()).isInstanceOf(IllegalStateException.class)
232 .hasMessage("manager is no longer active");
236 public void testAbort() {
237 mgr.abort(ClEventManagerWithSteps.State.DONE, OperationFinalResult.FINAL_FAILURE_GUARD, "some message");
239 assertEquals(ClEventManagerWithSteps.State.DONE, mgr.getState());
240 assertEquals(OperationFinalResult.FINAL_FAILURE_GUARD, mgr.getFinalResult());
241 assertEquals("some message", mgr.getFinalMessage());
244 assertThatThrownBy(() -> mgr.abort(null, OperationFinalResult.FINAL_FAILURE_GUARD, ""))
245 .isInstanceOf(NullPointerException.class).hasMessageContaining("finalState");
249 public void testLoadNextPolicy() throws Exception {
250 loadPolicy(EVENT_MGR_MULTI_YAML);
251 mgr = new MyManager(services, params, REQ_ID, workMem);
253 // start and load step for first policy
255 assertEquals("OperationA", mgr.getSteps().poll().getOperationName());
256 assertNull(mgr.getFinalResult());
258 // indicate success and load next policy
259 mgr.loadNextPolicy(OperationResult.SUCCESS);
260 assertEquals("OperationB", mgr.getSteps().poll().getOperationName());
261 assertNull(mgr.getFinalResult());
263 // indicate failure - should go to final failure
264 mgr.loadNextPolicy(OperationResult.FAILURE);
265 assertEquals(OperationFinalResult.FINAL_FAILURE, mgr.getFinalResult());
269 public void testLoadPolicy() throws ControlLoopException {
270 // start() will invoke loadPolicy()
273 assertNull(mgr.getFinalResult());
275 MyStep step = mgr.getSteps().peek();
277 assertEquals("First", step.getActorName());
278 assertEquals("OperationA", step.getOperationName());
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());
294 public void testLoadPreprocessorSteps() {
295 stepa = new MyStep(mgr, ControlLoopOperationParams.builder().build()) {
297 protected Operation buildOperation() {
298 return policyOperation;
302 Deque<MyStep> steps = mgr.getSteps();
306 mgr.loadPreprocessorSteps();
308 // no additional steps should have been loaded
309 assertThat(steps).hasSize(2);
311 assertSame(stepa, steps.poll());
312 assertSame(stepb, steps.poll());
313 assertThat(steps).isEmpty();
315 assertNotNull(stepa.getOperation());
316 assertNull(stepb.getOperation());
320 * Tests loadPreprocessorSteps() when there are too many steps in the queue.
323 public void testLoadPreprocessorStepsTooManySteps() {
324 stepa = new MyStep(mgr, ControlLoopOperationParams.builder().build()) {
326 protected Operation buildOperation() {
327 return policyOperation;
331 Deque<MyStep> steps = mgr.getSteps();
333 // load up a bunch of steps
334 for (int nsteps = 0; nsteps < ClEventManagerWithSteps.MAX_STEPS; ++nsteps) {
339 assertThatIllegalStateException().isThrownBy(() -> mgr.loadPreprocessorSteps()).withMessage("too many steps");
341 // add another step, should still fail
343 assertThatIllegalStateException().isThrownBy(() -> mgr.loadPreprocessorSteps()).withMessage("too many steps");
345 // remove two steps - should now succeed
349 int nsteps = steps.size();
351 mgr.loadPreprocessorSteps();
352 assertEquals(nsteps, steps.size());
356 public void testExecuteStep() {
357 // no steps to execute
358 assertFalse(mgr.executeStep());
360 // add a step to the queue
361 mgr.getSteps().add(stepa);
363 // step returns false
364 when(stepa.start(anyLong())).thenReturn(false);
365 assertFalse(mgr.executeStep());
368 when(stepa.start(anyLong())).thenReturn(true);
369 assertTrue(mgr.executeStep());
373 public void testNextStep() {
374 mgr.getSteps().add(stepa);
378 assertThat(mgr.getSteps()).isEmpty();
382 public void testDeliver() {
383 mgr.deliver(MY_SINK, null, "null notification", "null rule");
384 verify(engineMgr, never()).deliver(any(), any());
386 mgr.deliver(MY_SINK, "publishA", "A notification", "A rule");
387 verify(engineMgr).deliver(MY_SINK, "publishA");
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();
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();
399 params.setToscaPolicy(tosca);
402 private OperationOutcome makeCompletedOutcome() {
403 OperationOutcome outcome = makeOutcome();
404 outcome.setEnd(outcome.getStart());
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);
422 private class MyManager extends ClEventManagerWithSteps<MyStep> {
423 private static final long serialVersionUID = 1L;
425 public MyManager(EventManagerServices services, ControlLoopParams params, UUID requestId, WorkingMemory workMem)
426 throws ControlLoopException {
428 super(services, params, requestId, workMem);
432 protected ExecutorService getBlockingExecutor() {
437 protected void makeLock(String targetEntity, String requestId, int holdSec, LockCallback callback) {
438 LockImpl lock = new LockImpl(LockState.ACTIVE, targetEntity, requestId, holdSec, callback);
440 callback.lockAvailable(lock);
444 protected PolicyEngine getPolicyEngineManager() {
449 protected void loadPolicyStep(ControlLoopOperationParams params) {
450 getSteps().add(new MyStep(this, params));
455 private static class RealManager extends ClEventManagerWithSteps<MyStep> {
456 private static final long serialVersionUID = 1L;
458 public RealManager(EventManagerServices services, ControlLoopParams params, UUID requestId,
459 WorkingMemory workMem) throws ControlLoopException {
461 super(services, params, requestId, workMem);
465 protected void loadPolicyStep(ControlLoopOperationParams params) {
466 getSteps().add(new MyStep(this, params));
470 private static class MyStep extends Step {
471 public MyStep(StepContext stepContext, ControlLoopOperationParams params) {
472 super(params, new AtomicReference<>());