0b37abb1492ed13fb34382b90e2b95ab4efc7e37
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020 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.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertFalse;
27 import static org.junit.Assert.assertNotNull;
28 import static org.junit.Assert.assertSame;
29 import static org.junit.Assert.assertTrue;
30 import static org.mockito.Mockito.verify;
31
32 import java.io.IOException;
33 import java.util.ArrayList;
34 import java.util.List;
35 import java.util.UUID;
36 import java.util.concurrent.CompletableFuture;
37 import java.util.concurrent.ExecutorService;
38 import org.junit.Before;
39 import org.junit.Test;
40 import org.mockito.ArgumentCaptor;
41 import org.mockito.Mock;
42 import org.mockito.MockitoAnnotations;
43 import org.onap.policy.common.utils.coder.Coder;
44 import org.onap.policy.common.utils.coder.CoderException;
45 import org.onap.policy.common.utils.coder.StandardYamlCoder;
46 import org.onap.policy.common.utils.io.Serializer;
47 import org.onap.policy.common.utils.resources.ResourceUtils;
48 import org.onap.policy.controlloop.ControlLoopException;
49 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
50 import org.onap.policy.controlloop.drl.legacy.ControlLoopParams;
51 import org.onap.policy.controlloop.policy.PolicyResult;
52 import org.onap.policy.controlloop.policy.Target;
53 import org.onap.policy.controlloop.policy.TargetType;
54 import org.onap.policy.drools.core.lock.LockCallback;
55 import org.onap.policy.drools.core.lock.LockImpl;
56 import org.onap.policy.drools.core.lock.LockState;
57 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
58 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
59
60 public class ControlLoopEventManagerTest {
61     private static final UUID REQ_ID = UUID.randomUUID();
62     private static final String CL_NAME = "my-closed-loop-name";
63     private static final String POLICY_NAME = "my-policy-name";
64     private static final String POLICY_SCOPE = "my-scope";
65     private static final String POLICY_VERSION = "1.2.3";
66     private static final String LOCK1 = "my-lock-A";
67     private static final String LOCK2 = "my-lock-B";
68     private static final Coder yamlCoder = new StandardYamlCoder();
69     private static final String MY_KEY = "def";
70
71     @Mock
72     private ExecutorService executor;
73
74     private long preCreateTimeMs;
75     private List<LockImpl> locks;
76     private Target target;
77     private ToscaPolicy tosca;
78     private ControlLoopParams params;
79     private ControlLoopEventManager mgr;
80
81     /**
82      * Sets up.
83      */
84     @Before
85     public void setUp() throws ControlLoopException, CoderException {
86         MockitoAnnotations.initMocks(this);
87
88         target = new Target();
89         target.setType(TargetType.VNF);
90
91         params = new ControlLoopParams();
92         params.setClosedLoopControlName(CL_NAME);
93         params.setPolicyName(POLICY_NAME);
94         params.setPolicyScope(POLICY_SCOPE);
95         params.setPolicyVersion(POLICY_VERSION);
96
97         loadPolicy("eventManager/event-mgr-simple.yaml");
98
99         locks = new ArrayList<>();
100
101         preCreateTimeMs = System.currentTimeMillis();
102
103         MyManager.executor = executor;
104         MyManager.locks = locks;
105
106         mgr = new MyManager(params, REQ_ID);
107     }
108
109     @Test
110     public void testConstructor() {
111         assertEquals(POLICY_NAME, mgr.getPolicyName());
112
113         assertTrue(mgr.isActive());
114         assertEquals(CL_NAME, mgr.getClosedLoopControlName());
115         assertSame(REQ_ID, mgr.getRequestId());
116         assertEquals(POLICY_NAME, mgr.getPolicyName());
117         assertEquals(POLICY_VERSION, mgr.getPolicyVersion());
118         assertNotNull(mgr.getProcessor());
119         assertThat(mgr.getEndTimeMs()).isGreaterThanOrEqualTo(preCreateTimeMs);
120     }
121
122     @Test
123     public void testGetCreateCount() throws ControlLoopException {
124         long original = ControlLoopEventManager.getCreateCount();
125
126         new MyManager(params, REQ_ID);
127         assertEquals(original + 1, ControlLoopEventManager.getCreateCount());
128
129         new MyManager(params, REQ_ID);
130         assertEquals(original + 2, ControlLoopEventManager.getCreateCount());
131     }
132
133     @Test
134     public void testIsActive() throws Exception {
135         mgr = new ControlLoopEventManager(params, REQ_ID);
136         assertTrue(mgr.isActive());
137
138         ControlLoopEventManager mgr2 = Serializer.roundTrip(mgr);
139         assertFalse(mgr2.isActive());
140     }
141
142     @Test
143     public void testDestroy() throws IOException {
144         mgr.requestLock(LOCK1);
145         mgr.requestLock(LOCK2);
146         mgr.requestLock(LOCK1);
147
148         // ensure destroy() doesn't throw an exception if the object is deserialized
149         ControlLoopEventManager mgr2 = Serializer.roundTrip(mgr);
150         assertThatCode(() -> mgr2.destroy()).doesNotThrowAnyException();
151
152         // locks should not have been freed
153         for (LockImpl lock : locks) {
154             assertFalse(lock.isUnavailable());
155         }
156
157         mgr.destroy();
158
159         runExecutor();
160
161         for (LockImpl lock : locks) {
162             assertTrue(lock.isUnavailable());
163         }
164     }
165
166     @Test
167     public void testDetmControlLoopTimeoutMs() throws Exception {
168         long timeMs = 1200 * 1000L;
169         long end = mgr.getEndTimeMs();
170         assertThat(end).isGreaterThanOrEqualTo(preCreateTimeMs + timeMs).isLessThan(preCreateTimeMs + timeMs + 5000);
171     }
172
173     @Test
174     public void testRequestLock() {
175         final CompletableFuture<OperationOutcome> future1 = mgr.requestLock(LOCK1);
176         assertTrue(mgr.getOutcomes().isEmpty());
177
178         final CompletableFuture<OperationOutcome> future2 = mgr.requestLock(LOCK2);
179         assertTrue(mgr.getOutcomes().isEmpty());
180
181         assertSame(future1, mgr.requestLock(LOCK1));
182         assertTrue(mgr.getOutcomes().isEmpty());
183
184         assertEquals(2, locks.size());
185
186         assertTrue(future1.isDone());
187         assertTrue(future2.isDone());
188
189         // indicate that the first lock failed
190         locks.get(0).notifyUnavailable();
191
192         verifyLock(PolicyResult.FAILURE);
193         assertTrue(mgr.getOutcomes().isEmpty());
194     }
195
196     private void verifyLock(PolicyResult result) {
197         OperationOutcome outcome = mgr.getOutcomes().poll();
198         assertNotNull(outcome);
199         assertEquals(ActorConstants.LOCK_ACTOR, outcome.getActor());
200         assertEquals(ActorConstants.LOCK_OPERATION, outcome.getOperation());
201         assertNotNull(outcome.getEnd());
202         assertTrue(outcome.isFinalOutcome());
203         assertEquals(result, outcome.getResult());
204     }
205
206     @Test
207     public void testOnStart() {
208         OperationOutcome outcome1 = new OperationOutcome();
209         OperationOutcome outcome2 = new OperationOutcome();
210
211         mgr.onStart(outcome1);
212         mgr.onStart(outcome2);
213
214         assertSame(outcome1, mgr.getOutcomes().poll());
215         assertSame(outcome2, mgr.getOutcomes().poll());
216         assertTrue(mgr.getOutcomes().isEmpty());
217     }
218
219     @Test
220     public void testOnComplete() {
221         OperationOutcome outcome1 = new OperationOutcome();
222         OperationOutcome outcome2 = new OperationOutcome();
223
224         mgr.onComplete(outcome1);
225         mgr.onComplete(outcome2);
226
227         assertSame(outcome1, mgr.getOutcomes().poll());
228         assertSame(outcome2, mgr.getOutcomes().poll());
229         assertTrue(mgr.getOutcomes().isEmpty());
230     }
231
232     @Test
233     public void testContains_testGetProperty_testSetProperty_testRemoveProperty() {
234         mgr.setProperty("abc", "a string");
235         mgr.setProperty(MY_KEY, 100);
236
237         assertTrue(mgr.contains(MY_KEY));
238         assertFalse(mgr.contains("ghi"));
239
240         String strValue = mgr.getProperty("abc");
241         assertEquals("a string", strValue);
242
243         int intValue = mgr.getProperty(MY_KEY);
244         assertEquals(100, intValue);
245
246         mgr.removeProperty(MY_KEY);
247         assertFalse(mgr.contains(MY_KEY));
248     }
249
250     @Test
251     public void testToString() {
252         assertNotNull(mgr.toString());
253     }
254
255     private void loadPolicy(String fileName) throws CoderException {
256         ToscaServiceTemplate template =
257                         yamlCoder.decode(ResourceUtils.getResourceAsString(fileName), ToscaServiceTemplate.class);
258         tosca = template.getToscaTopologyTemplate().getPolicies().get(0).values().iterator().next();
259
260         params.setToscaPolicy(tosca);
261     }
262
263     private void runExecutor() {
264         ArgumentCaptor<Runnable> runCaptor = ArgumentCaptor.forClass(Runnable.class);
265         verify(executor).execute(runCaptor.capture());
266
267         runCaptor.getValue().run();
268     }
269
270
271     private static class MyManager extends ControlLoopEventManager {
272         private static final long serialVersionUID = 1L;
273
274         private static ExecutorService executor;
275         private static List<LockImpl> locks;
276
277         public MyManager(ControlLoopParams params, UUID requestId)
278                         throws ControlLoopException {
279             super(params, requestId);
280         }
281
282         @Override
283         protected ExecutorService getBlockingExecutor() {
284             return executor;
285         }
286
287         @Override
288         protected void makeLock(String targetEntity, String requestId, int holdSec, LockCallback callback) {
289             LockImpl lock = new LockImpl(LockState.ACTIVE, targetEntity, requestId, holdSec, callback);
290             locks.add(lock);
291             callback.lockAvailable(lock);
292         }
293     }
294 }