8efdb1fcba1b6b1a73e851e52734ddd876dbc9e7
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * unit test
4  * ================================================================================
5  * Copyright (C) 2017-2019 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.assertThatThrownBy;
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertFalse;
26 import static org.junit.Assert.assertNotNull;
27 import static org.junit.Assert.assertNull;
28 import static org.junit.Assert.assertSame;
29 import static org.junit.Assert.assertTrue;
30 import static org.mockito.Matchers.any;
31 import static org.mockito.Mockito.mock;
32 import static org.mockito.Mockito.never;
33 import static org.mockito.Mockito.verify;
34 import static org.mockito.Mockito.when;
35
36 import java.io.File;
37 import java.io.FileInputStream;
38 import java.io.IOException;
39 import java.io.InputStream;
40 import java.io.Serializable;
41 import java.nio.charset.StandardCharsets;
42 import java.time.Instant;
43 import java.util.HashMap;
44 import java.util.Map;
45 import java.util.UUID;
46 import org.apache.commons.io.IOUtils;
47 import org.junit.AfterClass;
48 import org.junit.Before;
49 import org.junit.BeforeClass;
50 import org.junit.Rule;
51 import org.junit.Test;
52 import org.junit.rules.ExpectedException;
53 import org.onap.policy.aai.AaiCqResponse;
54 import org.onap.policy.aai.AaiGetVnfResponse;
55 import org.onap.policy.aai.AaiGetVserverResponse;
56 import org.onap.policy.aai.AaiNqRequestError;
57 import org.onap.policy.aai.AaiNqResponseWrapper;
58 import org.onap.policy.aai.AaiNqVServer;
59 import org.onap.policy.aai.RelatedToProperty;
60 import org.onap.policy.aai.Relationship;
61 import org.onap.policy.aai.RelationshipData;
62 import org.onap.policy.aai.RelationshipList;
63 import org.onap.policy.aai.util.AaiException;
64 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
65 import org.onap.policy.common.utils.io.Serializer;
66 import org.onap.policy.controlloop.ControlLoopEventStatus;
67 import org.onap.policy.controlloop.ControlLoopException;
68 import org.onap.policy.controlloop.ControlLoopNotificationType;
69 import org.onap.policy.controlloop.SupportUtil;
70 import org.onap.policy.controlloop.VirtualControlLoopEvent;
71 import org.onap.policy.controlloop.VirtualControlLoopNotification;
72 import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager.NewEventStatus;
73 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
74 import org.onap.policy.controlloop.policy.PolicyResult;
75 import org.onap.policy.drools.core.lock.Lock;
76 import org.onap.policy.drools.core.lock.LockCallback;
77 import org.onap.policy.drools.system.PolicyEngineConstants;
78 import org.onap.policy.drools.utils.Pair;
79 import org.powermock.reflect.Whitebox;
80
81 public class ControlLoopEventManagerTest {
82     private static final String TARGET_LOCK_FIELD = "targetLock";
83     private static final String PROCESS_VSERVER_RESPONSE = "processVServerResponse";
84     private static final String ONSET_ONE = "onsetOne";
85     private static final String VSERVER_NAME = "vserver.vserver-name";
86     private static final String TEST_YAML = "src/test/resources/test.yaml";
87     private static final String SERVICE_TYPE = "service-subscription.service-type";
88     private static final String SERVICE_INSTANCE_NAME = "service-instance.service-instance-name";
89     private static final String SERVICE_INSTANCE_ID = "service-instance.service-instance-id";
90     private static final String SERVICE_INSTANCE = "service-instance";
91     private static final String VNF_NAME_TEXT = "lll_vnf_010317";
92     private static final String SERVICE_INSTANCE_NAME_TEXT = "lll_svc_010317";
93     private static final String VNF_NAME = "generic-vnf.vnf-name";
94     private static final String VNF_ID = "generic-vnf.vnf-id";
95     private static final String SERVICE_INSTANCE_UUID = "e1e9c97c-02c0-4919-9b4c-eb5d5ef68970";
96     private static final String MSO_CUSTOMER_ID = "customer.global-customer-id";
97     private static final String AAI_USERNAME = "aai.username";
98     private static final String AAI_URL = "aai.url";
99     private static final String AAI_PASS = "aai.password";
100     private static final String TWO_ONSET_TEST = "TwoOnsetTest";
101     private static final String MSO_1610_ST = "MSO_1610_ST";
102     private static final String MSO_DEV_SERVICE_TYPE = "MSO-dev-service-type";
103     private static final String VNF_UUID = "83f674e8-7555-44d7-9a39-bdc3770b0491";
104     private static final String AAI_SERVICE_SUBSCRIPTION_URI =
105                     "/aai/v11/business/customers/customer/MSO_1610_ST/service-subscriptions/service-subscription";
106     private static final String MSO_SERVICE_INSTANCE_URI = "/MSO-dev-service-type/service-instances/service-instance/";
107
108     private static final String PROCESS_VNF_RESPONSE_METHOD_NAME = "processVnfResponse";
109
110     private static final String INVALID_URL = "http://localhost:9999";
111
112
113     @Rule
114     public ExpectedException thrown = ExpectedException.none();
115
116     private VirtualControlLoopEvent onset;
117     private LockCallback callback;
118
119     /**
120      * Set up test class.
121      */
122     @BeforeClass
123     public static void setUpSimulator() throws Exception {
124         org.onap.policy.simulators.Util.buildAaiSim();
125
126         PolicyEngineConstants.getManager().setEnvironmentProperty(AAI_USERNAME, "AAI");
127         PolicyEngineConstants.getManager().setEnvironmentProperty(AAI_PASS, "AAI");
128         PolicyEngineConstants.getManager().setEnvironmentProperty(AAI_URL, "http://localhost:6666");
129     }
130
131     @AfterClass
132     public static void tearDownSimulator() {
133         HttpServletServerFactoryInstance.getServerFactory().destroy();
134     }
135
136     /**
137      * Setup.
138      */
139     @Before
140     public void setUp() {
141         callback = mock(LockCallback.class);
142
143         onset = new VirtualControlLoopEvent();
144         onset.setClosedLoopControlName("ControlLoop-vUSP");
145         onset.setRequestId(UUID.randomUUID());
146         onset.setTarget("VM_NAME");
147         onset.setClosedLoopAlarmStart(Instant.now());
148         onset.setAai(new HashMap<String, String>());
149         onset.getAai().put("cloud-region.identity-url", "foo");
150         onset.getAai().put("vserver.selflink", "bar");
151         onset.getAai().put(VNF_ID, VNF_UUID);
152         onset.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
153
154         PolicyEngineConstants.getManager().setEnvironmentProperty(AAI_URL, "http://localhost:6666");
155     }
156
157     @Test
158     public void testAaiVnfInfo() throws IOException {
159         final SupportUtil.Pair<ControlLoopPolicy, String> pair = SupportUtil.loadYaml(TEST_YAML);
160         onset.setClosedLoopControlName(pair.key.getControlLoop().getControlLoopName());
161         AaiGetVnfResponse response = getQueryByVnfId2();
162         assertNotNull(response);
163     }
164
165     @Test
166     public void testAaiVnfInfo2() throws IOException {
167         final SupportUtil.Pair<ControlLoopPolicy, String> pair = SupportUtil.loadYaml(TEST_YAML);
168         onset.setClosedLoopControlName(pair.key.getControlLoop().getControlLoopName());
169         AaiGetVnfResponse response = getQueryByVnfName2();
170         assertNotNull(response);
171     }
172
173     @Test
174     public void testAaiVserver() throws IOException {
175         final SupportUtil.Pair<ControlLoopPolicy, String> pair = SupportUtil.loadYaml(TEST_YAML);
176         onset.setClosedLoopControlName(pair.key.getControlLoop().getControlLoopName());
177         AaiGetVserverResponse response = getQueryByVserverName2();
178         assertNotNull(response);
179     }
180
181     @Test
182     public void abatementCheckEventSyntaxTest() throws ControlLoopException {
183         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
184         event.setClosedLoopControlName("abatementAAI");
185         event.setRequestId(UUID.randomUUID());
186         event.setTarget(VNF_ID);
187         event.setClosedLoopAlarmStart(Instant.now());
188         event.setClosedLoopEventStatus(ControlLoopEventStatus.ABATED);
189         ControlLoopEventManager manager = makeManager(event);
190         assertNull(manager.getVnfResponse());
191         assertNull(manager.getVserverResponse());
192         manager.checkEventSyntax(event);
193         assertNull(manager.getVnfResponse());
194         assertNull(manager.getVserverResponse());
195
196
197         event.setAai(new HashMap<>());
198         event.getAai().put(VNF_NAME, "abatementTest");
199         manager.checkEventSyntax(event);
200         assertNull(manager.getVnfResponse());
201         assertNull(manager.getVserverResponse());
202     }
203
204     @Test
205     public void subsequentOnsetTest() throws Exception {
206         UUID requestId = UUID.randomUUID();
207         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
208         event.setClosedLoopControlName(TWO_ONSET_TEST);
209         event.setRequestId(requestId);
210         event.setTarget(VNF_ID);
211         event.setClosedLoopAlarmStart(Instant.now());
212         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
213         event.setAai(new HashMap<>());
214         event.getAai().put(VNF_NAME, ONSET_ONE);
215
216         ControlLoopEventManager manager = makeManager(event);
217         VirtualControlLoopNotification notification = manager.activate(event);
218
219         assertNotNull(notification);
220         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
221
222         ControlLoopEventManager.NewEventStatus status = null;
223         status = manager.onNewEvent(event);
224         assertNotNull(status);
225         assertEquals(ControlLoopEventManager.NewEventStatus.FIRST_ONSET, status);
226
227         AaiGetVnfResponse response = manager.getVnfResponse();
228         assertNotNull(response);
229         assertNull(manager.getVserverResponse());
230
231         VirtualControlLoopEvent event2 = new VirtualControlLoopEvent();
232         event2.setClosedLoopControlName(TWO_ONSET_TEST);
233         event2.setRequestId(requestId);
234         event2.setTarget(VNF_ID);
235         event2.setClosedLoopAlarmStart(Instant.now());
236         event2.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
237         event2.setAai(new HashMap<>());
238         event2.getAai().put(VNF_NAME, "onsetTwo");
239
240
241         status = manager.onNewEvent(event2);
242         assertEquals(ControlLoopEventManager.NewEventStatus.SUBSEQUENT_ONSET, status);
243         AaiGetVnfResponse response2 = manager.getVnfResponse();
244         assertNotNull(response2);
245         // We should not have queried AAI, so the stored response should be the same
246         assertEquals(response, response2);
247         assertNull(manager.getVserverResponse());
248     }
249
250     /**
251      * Simulate a response.
252      */
253     public static AaiGetVnfResponse getQueryByVnfId2() {
254         AaiGetVnfResponse response = new AaiGetVnfResponse();
255
256         response.setVnfId(VNF_UUID);
257         response.setVnfName(VNF_NAME_TEXT);
258         response.setVnfType("Basa-122216-Service/VidVsamp12BaseVolume 1");
259         response.setServiceId("a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb");
260         response.setOrchestrationStatus("Created");
261         response.setInMaint(false);
262         response.setIsClosedLoopDisabled(false);
263         response.setResourceVersion("1494001988835");
264         response.setModelInvariantId("f18be3cd-d446-456e-9109-121d9b62feaa");
265
266         final RelationshipList relationshipList = new RelationshipList();
267         final Relationship relationship = new Relationship();
268         RelationshipData relationshipDataItem = new RelationshipData();
269
270         relationshipDataItem.setRelationshipKey(MSO_CUSTOMER_ID);
271         relationshipDataItem.setRelationshipValue(MSO_1610_ST);
272         relationship.getRelationshipData().add(relationshipDataItem);
273
274         relationshipDataItem.setRelationshipKey(SERVICE_TYPE);
275         relationshipDataItem.setRelationshipValue(MSO_DEV_SERVICE_TYPE);
276         relationship.getRelationshipData().add(relationshipDataItem);
277
278         relationshipDataItem.setRelationshipKey(SERVICE_INSTANCE_ID);
279         relationshipDataItem.setRelationshipValue(SERVICE_INSTANCE_UUID);
280         relationship.getRelationshipData().add(relationshipDataItem);
281
282         RelatedToProperty item = new RelatedToProperty();
283         item.setPropertyKey(SERVICE_INSTANCE_NAME);
284         item.setPropertyValue(SERVICE_INSTANCE_NAME_TEXT);
285         relationship.getRelatedToProperty().add(item);
286
287         relationship.setRelatedTo(SERVICE_INSTANCE);
288         relationship.setRelatedLink(
289                 AAI_SERVICE_SUBSCRIPTION_URI
290                         + MSO_SERVICE_INSTANCE_URI
291                         + SERVICE_INSTANCE_UUID);
292
293         relationshipList.getRelationships().add(relationship);
294         response.setRelationshipList(relationshipList);
295
296         return response;
297     }
298
299     /**
300      * Simulate a response.
301      */
302     public static AaiGetVnfResponse getQueryByVnfName2() {
303         AaiGetVnfResponse response = new AaiGetVnfResponse();
304
305         response.setVnfId(VNF_UUID);
306         response.setVnfName(VNF_NAME_TEXT);
307         response.setVnfType("Basa-122216-Service/VidVsamp12BaseVolume 1");
308         response.setServiceId("a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb");
309         response.setOrchestrationStatus("Created");
310         response.setInMaint(false);
311         response.setIsClosedLoopDisabled(false);
312         response.setResourceVersion("1494001988835");
313         response.setModelInvariantId("f18be3cd-d446-456e-9109-121d9b62feaa");
314
315         final RelationshipList relationshipList = new RelationshipList();
316         final Relationship relationship = new Relationship();
317         RelationshipData relationshipDataItem = new RelationshipData();
318
319         relationshipDataItem.setRelationshipKey(MSO_CUSTOMER_ID);
320         relationshipDataItem.setRelationshipValue(MSO_1610_ST);
321         relationship.getRelationshipData().add(relationshipDataItem);
322
323         relationshipDataItem.setRelationshipKey(SERVICE_TYPE);
324         relationshipDataItem.setRelationshipValue(MSO_DEV_SERVICE_TYPE);
325         relationship.getRelationshipData().add(relationshipDataItem);
326
327         relationshipDataItem.setRelationshipKey(SERVICE_INSTANCE_ID);
328         relationshipDataItem.setRelationshipValue(SERVICE_INSTANCE_UUID);
329         relationship.getRelationshipData().add(relationshipDataItem);
330
331         RelatedToProperty item = new RelatedToProperty();
332         item.setPropertyKey(SERVICE_INSTANCE_NAME);
333         item.setPropertyValue(SERVICE_INSTANCE_NAME_TEXT);
334         relationship.getRelatedToProperty().add(item);
335
336         relationship.setRelatedTo(SERVICE_INSTANCE);
337         relationship.setRelatedLink(
338                 AAI_SERVICE_SUBSCRIPTION_URI
339                         + MSO_SERVICE_INSTANCE_URI
340                         + SERVICE_INSTANCE_UUID);
341
342         relationshipList.getRelationships().add(relationship);
343         response.setRelationshipList(relationshipList);
344
345         return response;
346     }
347
348     /**
349      * Simulate a response.
350      */
351     public static AaiGetVserverResponse getQueryByVserverName2() {
352         final AaiGetVserverResponse response = new AaiGetVserverResponse();
353
354         AaiNqVServer svr = new AaiNqVServer();
355
356         svr.setVserverId("d0668d4f-c25e-4a1b-87c4-83845c01efd8");
357         svr.setVserverName("USMSO1SX7NJ0103UJZZ01-vjunos0");
358         svr.setVserverName2("vjunos0");
359         svr.setVserverSelflink(
360                 "https://aai-ext1.test.att.com:8443/aai/v7/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant/USMSO1SX7NJ0103UJZZ01%3A%3AuCPE-VMS/vservers/vserver/d0668d4f-c25e-4a1b-87c4-83845c01efd8");
361         svr.setInMaint(false);
362         svr.setIsClosedLoopDisabled(false);
363         svr.setResourceVersion("1494001931513");
364
365         final RelationshipList relationshipList = new RelationshipList();
366         final Relationship relationship = new Relationship();
367         RelationshipData relationshipDataItem = new RelationshipData();
368
369         relationshipDataItem.setRelationshipKey(MSO_CUSTOMER_ID);
370         relationshipDataItem.setRelationshipValue(MSO_1610_ST);
371         relationship.getRelationshipData().add(relationshipDataItem);
372
373         relationshipDataItem.setRelationshipKey(SERVICE_TYPE);
374         relationshipDataItem.setRelationshipValue(MSO_DEV_SERVICE_TYPE);
375         relationship.getRelationshipData().add(relationshipDataItem);
376
377         relationshipDataItem.setRelationshipKey(SERVICE_INSTANCE_ID);
378         relationshipDataItem.setRelationshipValue(SERVICE_INSTANCE_UUID);
379         relationship.getRelationshipData().add(relationshipDataItem);
380
381         RelatedToProperty item = new RelatedToProperty();
382         item.setPropertyKey(SERVICE_INSTANCE_NAME);
383         item.setPropertyValue(SERVICE_INSTANCE_NAME_TEXT);
384         relationship.getRelatedToProperty().add(item);
385
386         relationship.setRelatedTo(SERVICE_INSTANCE);
387         relationship.setRelatedLink(
388                 AAI_SERVICE_SUBSCRIPTION_URI
389                         + MSO_SERVICE_INSTANCE_URI
390                         + SERVICE_INSTANCE_UUID);
391
392         relationshipList.getRelationships().add(relationship);
393         svr.setRelationshipList(relationshipList);
394
395         response.getVserver().add(svr);
396
397         return response;
398     }
399
400     @Test
401     public void testMethods() {
402         UUID requestId = UUID.randomUUID();
403         ControlLoopEventManager clem = new ControlLoopEventManager("MyClosedLoopName", requestId);
404
405         assertEquals("MyClosedLoopName", clem.getClosedLoopControlName());
406         assertEquals(requestId, clem.getRequestId());
407
408         clem.setActivated(true);
409         assertEquals(true, clem.isActivated());
410
411         clem.setControlLoopResult("SUCCESS");
412         assertEquals("SUCCESS", clem.getControlLoopResult());
413
414         clem.setControlLoopTimedOut();
415         assertEquals(true, clem.isControlLoopTimedOut());
416
417         clem.setNumAbatements(12345);
418         assertEquals(Integer.valueOf(12345), clem.getNumAbatements());
419
420         clem.setNumOnsets(54321);
421         assertEquals(Integer.valueOf(54321), clem.getNumOnsets());
422
423         assertNull(clem.getOnsetEvent());
424         assertNull(clem.getAbatementEvent());
425         assertNull(clem.getProcessor());
426
427         assertEquals(true, clem.isControlLoopTimedOut());
428
429         assertNull(clem.unlockCurrentOperation());
430     }
431
432     @Test
433     public void testAlreadyActivated() {
434         UUID requestId = UUID.randomUUID();
435         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
436         event.setClosedLoopControlName(TWO_ONSET_TEST);
437         event.setRequestId(requestId);
438         event.setTarget(VNF_ID);
439         event.setClosedLoopAlarmStart(Instant.now());
440         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
441         event.setAai(new HashMap<>());
442         event.getAai().put(VNF_NAME, ONSET_ONE);
443
444         ControlLoopEventManager manager = makeManager(event);
445         manager.setActivated(true);
446         VirtualControlLoopNotification notification = manager.activate(event);
447         assertEquals(ControlLoopNotificationType.REJECTED, notification.getNotification());
448     }
449
450     @Test
451     public void testActivationYaml() throws IOException {
452
453         UUID requestId = UUID.randomUUID();
454         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
455         event.setClosedLoopControlName(TWO_ONSET_TEST);
456         event.setRequestId(requestId);
457         event.setTarget(VNF_ID);
458         event.setClosedLoopAlarmStart(Instant.now());
459         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
460         event.setAai(new HashMap<>());
461         event.getAai().put(VNF_NAME, ONSET_ONE);
462
463         ControlLoopEventManager manager = makeManager(event);
464
465         // Null YAML should fail
466         VirtualControlLoopNotification notificationNull = manager.activate(null, event);
467         assertNotNull(notificationNull);
468         assertEquals(ControlLoopNotificationType.REJECTED, notificationNull.getNotification());
469
470         // Empty YAML should fail
471         VirtualControlLoopNotification notificationEmpty = manager.activate("", event);
472         assertNotNull(notificationEmpty);
473         assertEquals(ControlLoopNotificationType.REJECTED, notificationEmpty.getNotification());
474
475         // Bad YAML should fail
476         InputStream isBad = new FileInputStream(new File("src/test/resources/notutf8.yaml"));
477         final String yamlStringBad = IOUtils.toString(isBad, StandardCharsets.UTF_8);
478
479         VirtualControlLoopNotification notificationBad = manager.activate(yamlStringBad, event);
480         assertNotNull(notificationBad);
481         assertEquals(ControlLoopNotificationType.REJECTED, notificationBad.getNotification());
482
483
484         InputStream is = new FileInputStream(new File(TEST_YAML));
485         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
486
487         VirtualControlLoopNotification notification = manager.activate(yamlString, event);
488         assertNotNull(notification);
489         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
490
491         // Another activate should fail
492         VirtualControlLoopNotification notificationActive = manager.activate(yamlString, event);
493         assertNotNull(notificationActive);
494         assertEquals(ControlLoopNotificationType.REJECTED, notificationActive.getNotification());
495     }
496
497     @Test
498     public void testControlLoopFinal() throws Exception {
499         UUID requestId = UUID.randomUUID();
500         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
501         event.setClosedLoopControlName(TWO_ONSET_TEST);
502         event.setRequestId(requestId);
503         event.setTarget(VNF_ID);
504         event.setClosedLoopAlarmStart(Instant.now());
505         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
506         event.setAai(new HashMap<>());
507         event.getAai().put(VNF_NAME, ONSET_ONE);
508
509         ControlLoopEventManager manager = makeManager(event);
510         ControlLoopEventManager manager2 = manager;
511         assertThatThrownBy(manager2::isControlLoopFinal).isInstanceOf(ControlLoopException.class)
512                         .hasMessage("ControlLoopEventManager MUST be activated first.");
513
514         manager.setActivated(true);
515         assertThatThrownBy(manager2::isControlLoopFinal).isInstanceOf(ControlLoopException.class)
516                         .hasMessage("No onset event for ControlLoopEventManager.");
517
518         manager.setActivated(false);
519
520         InputStream is = new FileInputStream(new File(TEST_YAML));
521         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
522
523         VirtualControlLoopNotification notification = manager.activate(yamlString, event);
524         assertNotNull(notification);
525         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
526
527         VirtualControlLoopNotification clfNotification = manager.isControlLoopFinal();
528         assertNull(clfNotification);
529
530         // serialize and de-serialize manager
531         manager = Serializer.roundTrip(manager);
532
533         manager.getProcessor().nextPolicyForResult(PolicyResult.SUCCESS);
534         clfNotification = manager.isControlLoopFinal();
535         assertNotNull(clfNotification);
536         assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, clfNotification.getNotification());
537
538         manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestId());
539         notification = manager.activate(yamlString, event);
540         assertNotNull(notification);
541         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
542
543         manager.getProcessor().nextPolicyForResult(PolicyResult.FAILURE_EXCEPTION);
544         clfNotification = manager.isControlLoopFinal();
545         assertNotNull(clfNotification);
546         assertEquals(ControlLoopNotificationType.FINAL_FAILURE, clfNotification.getNotification());
547
548         manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestId());
549         notification = manager.activate(yamlString, event);
550         assertNotNull(notification);
551         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
552
553         manager.getProcessor().nextPolicyForResult(PolicyResult.FAILURE_GUARD);
554         clfNotification = manager.isControlLoopFinal();
555         assertNotNull(clfNotification);
556         assertEquals(ControlLoopNotificationType.FINAL_FAILURE, clfNotification.getNotification());
557
558         manager.setControlLoopTimedOut();
559         clfNotification = manager.isControlLoopFinal();
560         assertNotNull(clfNotification);
561         assertEquals(ControlLoopNotificationType.FINAL_FAILURE, clfNotification.getNotification());
562     }
563
564     @Test
565     public void testProcessControlLoop() throws Exception {
566         UUID requestId = UUID.randomUUID();
567         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
568         event.setClosedLoopControlName(TWO_ONSET_TEST);
569         event.setRequestId(requestId);
570         event.setTarget(VNF_ID);
571         event.setClosedLoopAlarmStart(Instant.now());
572         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
573         event.setAai(new HashMap<>());
574         event.getAai().put(VNF_NAME, ONSET_ONE);
575
576         ControlLoopEventManager manager = makeManager(event);
577         ControlLoopEventManager manager2 = manager;
578         assertThatThrownBy(manager2::processControlLoop).isInstanceOf(ControlLoopException.class)
579                         .hasMessage("ControlLoopEventManager MUST be activated first.");
580
581         manager.setActivated(true);
582         assertThatThrownBy(manager2::processControlLoop).isInstanceOf(ControlLoopException.class)
583                         .hasMessage("No onset event for ControlLoopEventManager.");
584
585         manager.setActivated(false);
586
587         InputStream is = new FileInputStream(new File(TEST_YAML));
588         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
589
590         VirtualControlLoopNotification notification = manager.activate(yamlString, event);
591         assertNotNull(notification);
592         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
593
594         ControlLoopOperationManager clom = manager.processControlLoop();
595         assertNotNull(clom);
596         assertNull(clom.getOperationResult());
597
598         // serialize and de-serialize manager
599         manager = Serializer.roundTrip(manager);
600
601         // Test operation in progress
602         ControlLoopEventManager manager3 = manager;
603         assertThatThrownBy(manager3::processControlLoop).isInstanceOf(ControlLoopException.class)
604                         .hasMessage("Already working an Operation, do not call this method.");
605
606         manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestId());
607         notification = manager.activate(yamlString, event);
608         assertNotNull(notification);
609         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
610
611         manager.getProcessor().nextPolicyForResult(PolicyResult.FAILURE_GUARD);
612         VirtualControlLoopNotification clfNotification = manager.isControlLoopFinal();
613         assertNotNull(clfNotification);
614         assertEquals(ControlLoopNotificationType.FINAL_FAILURE, clfNotification.getNotification());
615
616         // Test operation completed
617         ControlLoopEventManager manager4 = manager;
618         assertThatThrownBy(manager4::processControlLoop).isInstanceOf(ControlLoopException.class)
619                         .hasMessage("Control Loop is in FINAL state, do not call this method.");
620
621         manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestId());
622         notification = manager.activate(yamlString, event);
623         assertNotNull(notification);
624         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
625         manager.getProcessor().nextPolicyForResult(PolicyResult.FAILURE);
626
627         // Test operation with no next policy defined
628         ControlLoopEventManager manager5 = manager;
629         assertThatThrownBy(manager5::processControlLoop).isInstanceOf(ControlLoopException.class)
630                         .hasMessage("The target type is null");
631     }
632
633     @Test
634     public void testFinishOperation() throws Exception {
635         InputStream isStd = new FileInputStream(new File(TEST_YAML));
636         final String yamlStringStd = IOUtils.toString(isStd, StandardCharsets.UTF_8);
637
638         VirtualControlLoopEvent event = makeEvent();
639
640         ControlLoopEventManager manager = makeManager(event);
641         ControlLoopEventManager manager2 = manager;
642         assertThatThrownBy(() -> manager2.finishOperation(null)).isInstanceOf(ControlLoopException.class)
643                         .hasMessage("No operation to finish.");
644
645         manager.setActivated(true);
646         assertThatThrownBy(() -> manager2.finishOperation(null)).isInstanceOf(ControlLoopException.class)
647                         .hasMessage("No operation to finish.");
648
649         manager.setActivated(false);
650
651         InputStream is = new FileInputStream(new File("src/test/resources/testSOactor.yaml"));
652         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
653
654         VirtualControlLoopNotification notification = manager.activate(yamlString, event);
655         assertNotNull(notification);
656         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
657
658         // serialize and de-serialize manager
659         manager = Serializer.roundTrip(manager);
660
661         ControlLoopOperationManager clom = manager.processControlLoop();
662         assertNotNull(clom);
663         assertNull(clom.getOperationResult());
664
665         clom.startOperation(event);
666
667         // This call should be exception free
668         manager.finishOperation(clom);
669
670         ControlLoopEventManager otherManager = makeManager(event);
671         VirtualControlLoopNotification otherNotification = otherManager.activate(yamlStringStd, event);
672         assertNotNull(otherNotification);
673         assertEquals(ControlLoopNotificationType.ACTIVE, otherNotification.getNotification());
674
675         ControlLoopOperationManager otherClom = otherManager.processControlLoop();
676         assertNotNull(otherClom);
677         assertNull(otherClom.getOperationResult());
678
679         otherManager.finishOperation(clom);
680     }
681
682     @Test
683     public void testLockCurrentOperation_testUnlockCurrentOperation() throws Exception {
684         VirtualControlLoopEvent event = makeEvent();
685
686         ControlLoopEventManager manager = makeManager(event);
687
688         manager.setActivated(false);
689
690         InputStream is = new FileInputStream(new File("src/test/resources/testSOactor.yaml"));
691         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
692
693         VirtualControlLoopNotification notification = manager.activate(yamlString, event);
694         assertNotNull(notification);
695         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
696
697         ControlLoopEventManager manager2 = manager;
698         assertThatThrownBy(() -> manager2.lockCurrentOperation(callback)).isInstanceOf(ControlLoopException.class)
699                         .hasMessage("Do not have a current operation.");
700
701         assertNull(manager.unlockCurrentOperation());
702
703         ControlLoopOperationManager clom = manager.processControlLoop();
704         assertNotNull(clom);
705         assertNull(clom.getOperationResult());
706
707         Pair<Lock, Lock> lockPair = manager.lockCurrentOperation(callback);
708         assertNull(lockPair.first());
709         assertNotNull(lockPair.second());
710
711         // pseudo lock - session should NOT have been notified of the change
712         verify(callback, never()).lockAvailable(any());
713         verify(callback, never()).lockUnavailable(any());
714
715         // repeat - should cause an extension
716         Lock lock = lockPair.second();
717         lockPair = manager.lockCurrentOperation(callback);
718
719         /*
720          * even with a pseudo lock, the session should have been notified that it was
721          * extended
722          */
723
724         verify(callback).lockAvailable(lock);
725
726         assertSame(lock, manager.unlockCurrentOperation());
727
728         assertNull(lockPair.first());
729         assertNull(lockPair.second());
730
731         // force it to use a pseudo lock
732         manager.setUseTargetLock(false);
733         lockPair = manager.lockCurrentOperation(callback);
734         assertNull(lockPair.first());
735         assertNotNull(lockPair.second());
736
737         lock = lockPair.second();
738
739         lockPair = manager.lockCurrentOperation(callback);
740         assertNull(lockPair.first());
741         assertNull(lockPair.second());
742
743         // first lock uses a pseudo lock, so it will only update when extended
744         verify(callback).lockAvailable(lock);
745
746         // force it to re-create the lock due to change in resource ID
747         lock = mock(Lock.class);
748         when(lock.getResourceId()).thenReturn("different");
749         Whitebox.setInternalState(manager, TARGET_LOCK_FIELD, lock);
750
751         lockPair = manager.lockCurrentOperation(callback);
752         assertSame(lock, lockPair.first());
753         assertNotNull(lockPair.second());
754
755         lock = lockPair.second();
756
757         lockPair = manager.lockCurrentOperation(callback);
758         assertNull(lockPair.first());
759         assertNull(lockPair.second());
760
761         // first lock uses a pseudo lock, so it won't do an update
762         verify(callback).lockAvailable(lock);
763
764         assertSame(lock, manager.unlockCurrentOperation());
765         assertNull(manager.unlockCurrentOperation());
766
767         // try again - this time don't return the fact handle- no change in count
768         lockPair = manager.lockCurrentOperation(callback);
769         assertNull(lockPair.first());
770         assertNotNull(lockPair.second());
771     }
772
773     @Test
774     public void testOnNewEvent() throws Exception {
775         UUID requestId = UUID.randomUUID();
776         VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
777         onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST);
778         onsetEvent.setRequestId(requestId);
779         onsetEvent.setTarget(VNF_ID);
780         onsetEvent.setClosedLoopAlarmStart(Instant.now());
781         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
782         onsetEvent.setAai(new HashMap<>());
783         onsetEvent.getAai().put(VNF_NAME, ONSET_ONE);
784
785         VirtualControlLoopEvent abatedEvent = new VirtualControlLoopEvent();
786         abatedEvent.setClosedLoopControlName(TWO_ONSET_TEST);
787         abatedEvent.setRequestId(requestId);
788         abatedEvent.setTarget(VNF_ID);
789         abatedEvent.setClosedLoopAlarmStart(Instant.now());
790         abatedEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ABATED);
791         abatedEvent.setAai(new HashMap<>());
792         abatedEvent.getAai().put(VNF_NAME, ONSET_ONE);
793
794         ControlLoopEventManager manager = makeManager(onsetEvent);
795
796         InputStream is = new FileInputStream(new File(TEST_YAML));
797         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
798
799         VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent);
800         assertNotNull(notification);
801         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
802
803         assertEquals(NewEventStatus.FIRST_ONSET, manager.onNewEvent(onsetEvent));
804         assertEquals(NewEventStatus.FIRST_ABATEMENT, manager.onNewEvent(abatedEvent));
805         assertEquals(NewEventStatus.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent));
806
807         VirtualControlLoopEvent checkSyntaxEvent = new VirtualControlLoopEvent();
808         checkSyntaxEvent.setAai(null);
809         checkSyntaxEvent.setClosedLoopAlarmEnd(null);
810         checkSyntaxEvent.setClosedLoopAlarmStart(null);
811         checkSyntaxEvent.setClosedLoopControlName(null);
812         checkSyntaxEvent.setClosedLoopEventClient(null);
813         checkSyntaxEvent.setClosedLoopEventStatus(null);
814         checkSyntaxEvent.setFrom(null);
815         checkSyntaxEvent.setPolicyName(null);
816         checkSyntaxEvent.setPolicyScope(null);
817         checkSyntaxEvent.setPolicyVersion(null);
818         checkSyntaxEvent.setRequestId(null);
819         checkSyntaxEvent.setTarget(null);
820         checkSyntaxEvent.setTargetType(null);
821         checkSyntaxEvent.setVersion(null);
822
823         assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent));
824
825         checkSyntaxEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
826         assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent));
827
828         checkSyntaxEvent.setClosedLoopControlName(null);
829         assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent));
830
831         checkSyntaxEvent.setClosedLoopControlName("");
832         assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent));
833
834         checkSyntaxEvent.setClosedLoopControlName(TWO_ONSET_TEST);
835         assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent));
836
837         checkSyntaxEvent.setRequestId(null);
838         assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent));
839
840         checkSyntaxEvent.setRequestId(requestId);
841         assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent));
842
843         checkSyntaxEvent.setAai(null);
844         assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent));
845
846         checkSyntaxEvent.setAai(new HashMap<>());
847         assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent));
848
849         checkSyntaxEvent.setTarget("");
850         assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent));
851
852         checkSyntaxEvent.setTarget(null);
853         assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent));
854
855         checkSyntaxEvent.setTarget("");
856         assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent));
857
858         checkSyntaxEvent.setTarget("OZ");
859         assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent));
860
861         checkSyntaxEvent.setTarget("VM_NAME");
862         assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent));
863
864         checkSyntaxEvent.setTarget("VNF_NAME");
865         assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent));
866
867         checkSyntaxEvent.setTarget(VSERVER_NAME);
868         assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent));
869
870         checkSyntaxEvent.setTarget(VNF_ID);
871         assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent));
872
873         checkSyntaxEvent.setTarget(VNF_NAME);
874         assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent));
875
876         checkSyntaxEvent.setAai(null);
877         assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent));
878
879         checkSyntaxEvent.setAai(new HashMap<>());
880         assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent));
881
882         checkSyntaxEvent.getAai().put(VNF_NAME, ONSET_ONE);
883         assertEquals(NewEventStatus.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent));
884
885         checkSyntaxEvent.getAai().put(VSERVER_NAME, ONSET_ONE);
886         assertEquals(NewEventStatus.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent));
887
888         checkSyntaxEvent.getAai().put(VNF_ID, ONSET_ONE);
889         assertEquals(NewEventStatus.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent));
890     }
891
892     @Test
893     public void testControlLoopTimeout() throws IOException {
894         UUID requestId = UUID.randomUUID();
895         VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
896         onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST);
897         onsetEvent.setRequestId(requestId);
898         onsetEvent.setTarget(VNF_ID);
899         onsetEvent.setClosedLoopAlarmStart(Instant.now());
900         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
901         onsetEvent.setAai(new HashMap<>());
902         onsetEvent.getAai().put(VNF_NAME, ONSET_ONE);
903
904         ControlLoopEventManager manager = makeManager(onsetEvent);
905         assertTrue(0 == manager.getControlLoopTimeout(null));
906         assertTrue(120 == manager.getControlLoopTimeout(120));
907
908         InputStream is = new FileInputStream(new File(TEST_YAML));
909         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
910
911         VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent);
912         assertNotNull(notification);
913         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
914
915         assertEquals(60, manager.getControlLoopTimeout(null));
916     }
917
918     @Test
919     public void testControlLoopTimeout_ZeroTimeout() throws IOException {
920         UUID requestId = UUID.randomUUID();
921         VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
922         onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST);
923         onsetEvent.setRequestId(requestId);
924         onsetEvent.setTarget(VNF_ID);
925         onsetEvent.setClosedLoopAlarmStart(Instant.now());
926         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
927         onsetEvent.setAai(new HashMap<>());
928         onsetEvent.getAai().put(VNF_NAME, ONSET_ONE);
929
930         ControlLoopEventManager manager = makeManager(onsetEvent);
931
932         InputStream is = new FileInputStream(new File("src/test/resources/test-zero-timeout.yaml"));
933         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
934
935         VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent);
936         assertNotNull(notification);
937         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
938
939         assertTrue(0 == manager.getControlLoopTimeout(null));
940         assertTrue(120 == manager.getControlLoopTimeout(120));
941     }
942
943     @Test
944     public void testControlLoopTimeout_NullTimeout() throws IOException {
945         UUID requestId = UUID.randomUUID();
946         VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
947         onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST);
948         onsetEvent.setRequestId(requestId);
949         onsetEvent.setTarget(VNF_ID);
950         onsetEvent.setClosedLoopAlarmStart(Instant.now());
951         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
952         onsetEvent.setAai(new HashMap<>());
953         onsetEvent.getAai().put(VNF_NAME, ONSET_ONE);
954
955         ControlLoopEventManager manager = makeManager(onsetEvent);
956
957         InputStream is = new FileInputStream(new File("src/test/resources/test-null-timeout.yaml"));
958         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
959
960         VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent);
961         assertNotNull(notification);
962         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
963
964         assertTrue(0 == manager.getControlLoopTimeout(null));
965         assertTrue(120 == manager.getControlLoopTimeout(120));
966     }
967
968     @Test
969     public void testQueryAai_AlreadyDisabled() throws AaiException {
970         onset.getAai().put(ControlLoopEventManager.GENERIC_VNF_IS_CLOSED_LOOP_DISABLED, Boolean.TRUE.toString());
971         onset.getAai().put(ControlLoopEventManager.GENERIC_VNF_PROV_STATUS, ControlLoopEventManager.PROV_STATUS_ACTIVE);
972
973         ControlLoopEventManager mgr = makeManager(onset);
974
975         assertThatThrownBy(() -> mgr.queryAai(onset)).isInstanceOf(AaiException.class)
976                         .hasMessage("is-closed-loop-disabled is set to true on VServer or VNF");
977         assertNull(mgr.getVnfResponse());
978         assertNull(mgr.getVserverResponse());
979     }
980
981     @Test
982     public void testQueryAai_AlreadyInactive() throws AaiException {
983         onset.getAai().put(ControlLoopEventManager.GENERIC_VNF_IS_CLOSED_LOOP_DISABLED, Boolean.FALSE.toString());
984         onset.getAai().put(ControlLoopEventManager.GENERIC_VNF_PROV_STATUS, "not-active2");
985
986         ControlLoopEventManager mgr = makeManager(onset);
987
988         assertThatThrownBy(() -> mgr.queryAai(onset)).isInstanceOf(AaiException.class)
989                         .hasMessage("prov-status is not ACTIVE on VServer or VNF");
990         assertNull(mgr.getVnfResponse());
991         assertNull(mgr.getVserverResponse());
992     }
993
994     @Test
995     public void testQueryAai_QueryVnfById() throws AaiException {
996         ControlLoopEventManager mgr = null;
997
998         mgr = makeManager(onset);
999         mgr.queryAai(onset);
1000
1001         assertNotNull(mgr.getVnfResponse());
1002         assertNull(mgr.getVserverResponse());
1003
1004         AaiGetVnfResponse vnfresp = mgr.getVnfResponse();
1005
1006         // should not re-query
1007         mgr.queryAai(onset);
1008
1009         assertEquals(vnfresp, mgr.getVnfResponse());
1010         assertNull(mgr.getVserverResponse());
1011     }
1012
1013     @Test
1014     public void testQueryAai_QueryVnfByName() throws AaiException {
1015         ControlLoopEventManager mgr = null;
1016
1017         // vnf query by name
1018         onset.getAai().remove(ControlLoopEventManager.GENERIC_VNF_VNF_ID);
1019         onset.getAai().put(ControlLoopEventManager.GENERIC_VNF_VNF_NAME, "AVNFName");
1020
1021         mgr = makeManager(onset);
1022         mgr.queryAai(onset);
1023
1024         assertNotNull(mgr.getVnfResponse());
1025         assertNull(mgr.getVserverResponse());
1026
1027         AaiGetVnfResponse vnfresp = mgr.getVnfResponse();
1028
1029         // should not re-query
1030         mgr.queryAai(onset);
1031
1032         assertEquals(vnfresp, mgr.getVnfResponse());
1033         assertNull(mgr.getVserverResponse());
1034     }
1035
1036     @Test
1037     public void testQueryAai_QueryVnfById_Disabled() {
1038         onset.getAai().put(ControlLoopEventManager.GENERIC_VNF_VNF_ID, "disableClosedLoop");
1039
1040         ControlLoopEventManager mgr = makeManager(onset);
1041
1042         assertThatThrownBy(() -> mgr.queryAai(onset)).isInstanceOf(AaiException.class)
1043                         .hasMessage("is-closed-loop-disabled is set to true (query by vnf-id)");
1044
1045         assertNotNull(mgr.getVnfResponse());
1046         assertNull(mgr.getVserverResponse());
1047     }
1048
1049     @Test
1050     public void testQueryAai_QueryVserver() throws AaiException {
1051         onset.getAai().remove(ControlLoopEventManager.GENERIC_VNF_VNF_ID);
1052         onset.getAai().put(ControlLoopEventManager.VSERVER_VSERVER_NAME, "AVserver");
1053
1054         ControlLoopEventManager mgr = makeManager(onset);
1055         mgr.queryAai(onset);
1056
1057         assertNull(mgr.getVnfResponse());
1058         assertNotNull(mgr.getVserverResponse());
1059
1060         AaiGetVserverResponse vsvresp = mgr.getVserverResponse();
1061
1062         // should not re-query
1063         mgr.queryAai(onset);
1064
1065         assertNull(mgr.getVnfResponse());
1066         assertEquals(vsvresp, mgr.getVserverResponse());
1067     }
1068
1069     @Test
1070     public void testQueryAai_QueryVserver_Disabled() {
1071         onset.getAai().remove(ControlLoopEventManager.GENERIC_VNF_VNF_ID);
1072         onset.getAai().put(ControlLoopEventManager.VSERVER_VSERVER_NAME, "disableClosedLoop");
1073
1074         ControlLoopEventManager mgr = makeManager(onset);
1075
1076         assertThatThrownBy(() -> mgr.queryAai(onset)).isInstanceOf(AaiException.class)
1077                         .hasMessage("is-closed-loop-disabled is set to true (query by vserver-name)");
1078
1079         assertNull(mgr.getVnfResponse());
1080         assertNotNull(mgr.getVserverResponse());
1081     }
1082
1083     @Test(expected = AaiException.class)
1084     public void testQueryAai_QueryException() throws AaiException {
1085         // Force AAI errors
1086         PolicyEngineConstants.getManager().setEnvironmentProperty(AAI_URL, INVALID_URL);
1087
1088         makeManager(onset).queryAai(onset);
1089     }
1090
1091     @Test
1092     public void testProcessVnfResponse_Success() throws Exception {
1093         AaiGetVnfResponse resp = new AaiGetVnfResponse();
1094         resp.setIsClosedLoopDisabled(false);
1095         resp.setProvStatus(ControlLoopEventManager.PROV_STATUS_ACTIVE);
1096         Whitebox.invokeMethod(ControlLoopEventManager.class, PROCESS_VNF_RESPONSE_METHOD_NAME, resp, true);
1097     }
1098
1099     @Test
1100     public void testProcessVnfResponse_NullResponse() throws Exception {
1101         thrown.expect(AaiException.class);
1102         thrown.expectMessage("AAI Response is null (query by vnf-id)");
1103
1104         AaiGetVnfResponse resp = null;
1105         Whitebox.invokeMethod(ControlLoopEventManager.class, PROCESS_VNF_RESPONSE_METHOD_NAME, resp, true);
1106     }
1107
1108     @Test
1109     public void testProcessVnfResponse_Error() throws Exception {
1110         thrown.expect(AaiException.class);
1111         thrown.expectMessage("AAI Responded with a request error (query by vnf-name)");
1112
1113         AaiGetVnfResponse resp = new AaiGetVnfResponse();
1114
1115         resp.setRequestError(new AaiNqRequestError());
1116
1117         resp.setIsClosedLoopDisabled(false);
1118         resp.setProvStatus(ControlLoopEventManager.PROV_STATUS_ACTIVE);
1119         Whitebox.invokeMethod(ControlLoopEventManager.class, PROCESS_VNF_RESPONSE_METHOD_NAME, resp, false);
1120     }
1121
1122     @Test
1123     public void testProcessVnfResponse_Disabled() throws Exception {
1124         thrown.expect(AaiException.class);
1125         thrown.expectMessage("is-closed-loop-disabled is set to true (query by vnf-id)");
1126
1127         AaiGetVnfResponse resp = new AaiGetVnfResponse();
1128         resp.setIsClosedLoopDisabled(true);
1129         resp.setProvStatus(ControlLoopEventManager.PROV_STATUS_ACTIVE);
1130         Whitebox.invokeMethod(ControlLoopEventManager.class, PROCESS_VNF_RESPONSE_METHOD_NAME, resp, true);
1131     }
1132
1133     @Test
1134     public void testProcessVnfResponse_Inactive() throws Exception {
1135         thrown.expect(AaiException.class);
1136         thrown.expectMessage("prov-status is not ACTIVE (query by vnf-name)");
1137
1138         AaiGetVnfResponse resp = new AaiGetVnfResponse();
1139         resp.setIsClosedLoopDisabled(false);
1140         resp.setProvStatus("inactive1");
1141         Whitebox.invokeMethod(ControlLoopEventManager.class, PROCESS_VNF_RESPONSE_METHOD_NAME, resp, false);
1142     }
1143
1144     @Test
1145     public void testProcessVserverResponse_Success() throws Exception {
1146         AaiGetVserverResponse resp = new AaiGetVserverResponse();
1147
1148         AaiNqVServer svr = new AaiNqVServer();
1149         resp.getVserver().add(svr);
1150
1151         svr.setIsClosedLoopDisabled(false);
1152         svr.setProvStatus(ControlLoopEventManager.PROV_STATUS_ACTIVE);
1153         Whitebox.invokeMethod(ControlLoopEventManager.class, PROCESS_VSERVER_RESPONSE, resp);
1154     }
1155
1156     @Test
1157     public void testProcessVserverResponse_NullResponse() throws Exception {
1158         thrown.expect(AaiException.class);
1159         thrown.expectMessage("AAI Response is null (query by vserver-name)");
1160
1161         AaiGetVserverResponse resp = null;
1162         Whitebox.invokeMethod(ControlLoopEventManager.class, PROCESS_VSERVER_RESPONSE, resp);
1163     }
1164
1165     @Test
1166     public void testProcessVserverResponse_Error() throws Exception {
1167         thrown.expect(AaiException.class);
1168         thrown.expectMessage("AAI Responded with a request error (query by vserver-name)");
1169
1170         AaiGetVserverResponse resp = new AaiGetVserverResponse();
1171
1172         resp.setRequestError(new AaiNqRequestError());
1173
1174         AaiNqVServer svr = new AaiNqVServer();
1175         resp.getVserver().add(svr);
1176
1177         svr.setIsClosedLoopDisabled(false);
1178         svr.setProvStatus(ControlLoopEventManager.PROV_STATUS_ACTIVE);
1179
1180         Whitebox.invokeMethod(ControlLoopEventManager.class, PROCESS_VSERVER_RESPONSE, resp);
1181     }
1182
1183     @Test
1184     public void testProcessVserverResponse_Disabled() throws Exception {
1185         thrown.expect(AaiException.class);
1186         thrown.expectMessage("is-closed-loop-disabled is set to true (query by vserver-name)");
1187
1188         AaiGetVserverResponse resp = new AaiGetVserverResponse();
1189         AaiNqVServer svr = new AaiNqVServer();
1190         resp.getVserver().add(svr);
1191
1192         svr.setIsClosedLoopDisabled(true);
1193         svr.setProvStatus(ControlLoopEventManager.PROV_STATUS_ACTIVE);
1194         Whitebox.invokeMethod(ControlLoopEventManager.class, PROCESS_VSERVER_RESPONSE, resp);
1195     }
1196
1197     @Test
1198     public void testProcessVserverResponse_Inactive() throws Exception {
1199         thrown.expect(AaiException.class);
1200         thrown.expectMessage("prov-status is not ACTIVE (query by vserver-name)");
1201
1202         AaiGetVserverResponse resp = new AaiGetVserverResponse();
1203         AaiNqVServer svr = new AaiNqVServer();
1204         resp.getVserver().add(svr);
1205
1206         svr.setIsClosedLoopDisabled(false);
1207         svr.setProvStatus("inactive1");
1208         Whitebox.invokeMethod(ControlLoopEventManager.class, PROCESS_VSERVER_RESPONSE, resp);
1209     }
1210
1211     @Test
1212     public void testIsClosedLoopDisabled() {
1213         Map<String, String> aai = onset.getAai();
1214
1215         // null, null
1216         aai.remove(ControlLoopEventManager.GENERIC_VNF_IS_CLOSED_LOOP_DISABLED);
1217         aai.remove(ControlLoopEventManager.VSERVER_IS_CLOSED_LOOP_DISABLED);
1218         assertFalse(ControlLoopEventManager.isClosedLoopDisabled(onset));
1219
1220         // null, false
1221         aai.remove(ControlLoopEventManager.GENERIC_VNF_IS_CLOSED_LOOP_DISABLED);
1222         aai.put(ControlLoopEventManager.VSERVER_IS_CLOSED_LOOP_DISABLED, Boolean.FALSE.toString());
1223         assertFalse(ControlLoopEventManager.isClosedLoopDisabled(onset));
1224
1225         // false, null
1226         aai.put(ControlLoopEventManager.GENERIC_VNF_IS_CLOSED_LOOP_DISABLED, Boolean.FALSE.toString());
1227         aai.remove(ControlLoopEventManager.VSERVER_IS_CLOSED_LOOP_DISABLED);
1228         assertFalse(ControlLoopEventManager.isClosedLoopDisabled(onset));
1229
1230         // null, true
1231         aai.remove(ControlLoopEventManager.GENERIC_VNF_IS_CLOSED_LOOP_DISABLED);
1232         aai.put(ControlLoopEventManager.VSERVER_IS_CLOSED_LOOP_DISABLED, Boolean.TRUE.toString());
1233         assertTrue(ControlLoopEventManager.isClosedLoopDisabled(onset));
1234
1235         // true, null
1236         aai.put(ControlLoopEventManager.GENERIC_VNF_IS_CLOSED_LOOP_DISABLED, Boolean.TRUE.toString());
1237         aai.remove(ControlLoopEventManager.VSERVER_IS_CLOSED_LOOP_DISABLED);
1238         assertTrue(ControlLoopEventManager.isClosedLoopDisabled(onset));
1239     }
1240
1241     @Test
1242     public void testIsProvStatusInactive() {
1243         Map<String, String> aai = onset.getAai();
1244
1245         // null, null
1246         aai.remove(ControlLoopEventManager.GENERIC_VNF_PROV_STATUS);
1247         aai.remove(ControlLoopEventManager.VSERVER_PROV_STATUS);
1248         assertFalse(ControlLoopEventManager.isProvStatusInactive(onset));
1249
1250         // null, active
1251         aai.remove(ControlLoopEventManager.GENERIC_VNF_PROV_STATUS);
1252         aai.put(ControlLoopEventManager.VSERVER_PROV_STATUS, ControlLoopEventManager.PROV_STATUS_ACTIVE);
1253         assertFalse(ControlLoopEventManager.isProvStatusInactive(onset));
1254
1255         // active, null
1256         aai.put(ControlLoopEventManager.GENERIC_VNF_PROV_STATUS, ControlLoopEventManager.PROV_STATUS_ACTIVE);
1257         aai.remove(ControlLoopEventManager.VSERVER_PROV_STATUS);
1258         assertFalse(ControlLoopEventManager.isProvStatusInactive(onset));
1259
1260         // null, inactive
1261         aai.remove(ControlLoopEventManager.GENERIC_VNF_PROV_STATUS);
1262         aai.put(ControlLoopEventManager.VSERVER_PROV_STATUS, "other1");
1263         assertTrue(ControlLoopEventManager.isProvStatusInactive(onset));
1264
1265         // inactive, null
1266         aai.put(ControlLoopEventManager.GENERIC_VNF_PROV_STATUS, "other2");
1267         aai.remove(ControlLoopEventManager.VSERVER_PROV_STATUS);
1268         assertTrue(ControlLoopEventManager.isProvStatusInactive(onset));
1269     }
1270
1271     @Test
1272     public void testIsAaiTrue() {
1273         assertTrue(ControlLoopEventManager.isAaiTrue("tRuE"));
1274         assertTrue(ControlLoopEventManager.isAaiTrue("T"));
1275         assertTrue(ControlLoopEventManager.isAaiTrue("t"));
1276         assertTrue(ControlLoopEventManager.isAaiTrue("yES"));
1277         assertTrue(ControlLoopEventManager.isAaiTrue("Y"));
1278         assertTrue(ControlLoopEventManager.isAaiTrue("y"));
1279
1280         assertFalse(ControlLoopEventManager.isAaiTrue("no"));
1281         assertFalse(ControlLoopEventManager.isAaiTrue(null));
1282     }
1283
1284     @Test
1285     public void testGetNqVserverFromAai() {
1286
1287         // empty vserver name
1288         ControlLoopEventManager manager = makeManager(onset);
1289         manager.activate(onset);
1290         assertNull(manager.getNqVserverFromAai());
1291
1292
1293         // re-create manager with a vserver name in the onset
1294         onset.getAai().put(ControlLoopEventManager.VSERVER_VSERVER_NAME, "my-name");
1295         manager = makeManager(onset);
1296         manager.activate(onset);
1297
1298         AaiNqResponseWrapper resp = manager.getNqVserverFromAai();
1299         assertNotNull(resp);
1300         assertEquals(onset.getRequestId(), resp.getRequestId());
1301         assertNotNull(resp.getAaiNqResponse());
1302         assertFalse(resp.getAaiNqResponse().getInventoryResponseItems().isEmpty());
1303
1304         // re-query should return the same object
1305         assertTrue(resp == manager.getNqVserverFromAai());
1306
1307
1308         // Force AAI error
1309         PolicyEngineConstants.getManager().setEnvironmentProperty(AAI_URL, INVALID_URL);
1310
1311         // re-create manager
1312         manager = makeManager(onset);
1313         manager.activate(onset);
1314         assertNull(manager.getNqVserverFromAai());
1315     }
1316
1317     @Test
1318     public void testGetCqResponseEmptyVserver() throws AaiException {
1319         ControlLoopEventManager mgr = makeManager(onset);
1320         mgr.queryAai(onset);
1321
1322         assertThatThrownBy(() -> mgr.getCqResponse(onset)).isInstanceOf(AaiException.class)
1323                         .hasMessage("Vserver name is missing");
1324     }
1325
1326     @Test
1327     public void testGetCqResponse() throws AaiException {
1328         ControlLoopEventManager mgr = makeManager(onset);
1329         mgr.queryAai(onset);
1330         onset.getAai().put(VSERVER_NAME, "sample");
1331
1332         AaiCqResponse aaiCqResponse = mgr.getCqResponse(onset);
1333         assertNotNull(aaiCqResponse);
1334     }
1335
1336     private VirtualControlLoopEvent makeEvent() {
1337         UUID requestId = UUID.randomUUID();
1338         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
1339         event.setClosedLoopControlName(TWO_ONSET_TEST);
1340         event.setRequestId(requestId);
1341         event.setTarget(VNF_ID);
1342         event.setClosedLoopAlarmStart(Instant.now());
1343         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
1344         event.setAai(new HashMap<>());
1345         event.getAai().put(VNF_ID, ONSET_ONE);
1346         return event;
1347     }
1348
1349     private ControlLoopEventManager makeManager(VirtualControlLoopEvent event) {
1350         return new MyManager(event.getClosedLoopControlName(), event.getRequestId());
1351     }
1352
1353     private static class MyManager extends ControlLoopEventManager implements Serializable {
1354         private static final long serialVersionUID = 1L;
1355
1356         public MyManager(String closedLoopControlName, UUID requestId) {
1357             super(closedLoopControlName, requestId);
1358         }
1359
1360         @Override
1361         protected Lock createRealLock(String targetEntity, UUID requestId, int holdSec, LockCallback callback) {
1362             return createPseudoLock(targetEntity, requestId, holdSec, callback);
1363         }
1364     }
1365 }