568f8bcd4f9502cb38c93db9d4ed7db0afa97866
[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.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertFalse;
25 import static org.junit.Assert.assertNotNull;
26 import static org.junit.Assert.assertNull;
27 import static org.junit.Assert.assertTrue;
28 import static org.junit.Assert.fail;
29
30 import java.io.File;
31 import java.io.FileInputStream;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.nio.charset.StandardCharsets;
35 import java.time.Instant;
36 import java.util.HashMap;
37 import java.util.UUID;
38 import javax.persistence.EntityManager;
39 import javax.persistence.EntityManagerFactory;
40 import javax.persistence.NoResultException;
41 import javax.persistence.NonUniqueResultException;
42 import javax.persistence.Persistence;
43 import javax.persistence.Query;
44 import org.apache.commons.io.IOUtils;
45 import org.junit.AfterClass;
46 import org.junit.BeforeClass;
47 import org.junit.Test;
48 import org.onap.policy.aai.util.AaiException;
49 import org.onap.policy.appc.CommonHeader;
50 import org.onap.policy.appc.Response;
51 import org.onap.policy.appc.ResponseCode;
52 import org.onap.policy.appc.ResponseStatus;
53 import org.onap.policy.appclcm.LcmCommonHeader;
54 import org.onap.policy.appclcm.LcmRequest;
55 import org.onap.policy.appclcm.LcmRequestWrapper;
56 import org.onap.policy.appclcm.LcmResponse;
57 import org.onap.policy.appclcm.LcmResponseWrapper;
58 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
59 import org.onap.policy.common.utils.io.Serializer;
60 import org.onap.policy.controlloop.ControlLoopEventStatus;
61 import org.onap.policy.controlloop.ControlLoopException;
62 import org.onap.policy.controlloop.ControlLoopNotificationType;
63 import org.onap.policy.controlloop.ControlLoopTargetType;
64 import org.onap.policy.controlloop.SupportUtil;
65 import org.onap.policy.controlloop.VirtualControlLoopEvent;
66 import org.onap.policy.controlloop.VirtualControlLoopNotification;
67 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
68 import org.onap.policy.controlloop.policy.Policy;
69 import org.onap.policy.controlloop.policy.PolicyResult;
70 import org.onap.policy.controlloop.policy.Target;
71 import org.onap.policy.controlloop.policy.TargetType;
72 import org.onap.policy.controlloop.processor.ControlLoopProcessor;
73 import org.onap.policy.drools.system.PolicyEngine;
74 import org.onap.policy.so.SoResponse;
75 import org.onap.policy.so.SoResponseWrapper;
76 import org.onap.policy.vfc.VfcResponse;
77 import org.onap.policy.vfc.VfcResponseDescriptor;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
80
81 public class ControlLoopOperationManagerTest {
82     private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManagerTest.class);
83
84
85     private static VirtualControlLoopEvent onset;
86
87     static {
88         onset = new VirtualControlLoopEvent();
89         onset.setRequestId(UUID.randomUUID());
90         onset.setTarget("generic-vnf.vnf-name");
91         onset.setTargetType(ControlLoopTargetType.VNF);
92         onset.setClosedLoopAlarmStart(Instant.now());
93         onset.setAai(new HashMap<>());
94         onset.getAai().put("generic-vnf.vnf-name", "testTriggerSource");
95         onset.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
96
97         /* Set environment properties */
98         PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666");
99         PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI");
100         PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI");
101     }
102
103     private static EntityManagerFactory emf;
104     private static EntityManager em;
105
106
107     private static int getCount() {
108         // Create a query for number of items in DB
109         String sql = "select count(*) as count from operationshistory";
110         Query nq = em.createNativeQuery(sql);
111
112         int numEvents = -1;
113         try {
114             numEvents = ((Number) nq.getSingleResult()).intValue();
115         } catch (NoResultException | NonUniqueResultException ex) {
116             logger.error("getCountFromDb threw: ", ex);
117             fail(ex.getMessage());
118         }
119         return numEvents;
120     }
121
122
123     /**
124      * Set up test class.
125      */
126     @BeforeClass
127     public static void setUp() {
128
129         try {
130             org.onap.policy.simulators.Util.buildAaiSim();
131         } catch (Exception e) {
132             fail(e.getMessage());
133         }
134
135         // Set PU
136         System.setProperty("OperationsHistoryPU", "OperationsHistoryPUTest");
137
138         // Enter dummy props to avoid nullPointerException
139         PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_URL, "a");
140         PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_USER, "b");
141         PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_PASS, "c");
142
143         // Connect to in-mem db
144         emf = Persistence.createEntityManagerFactory("OperationsHistoryPUTest");
145         em = emf.createEntityManager();
146     }
147
148
149     /**
150      * Clean up test class.
151      */
152     @AfterClass
153     public static void tearDown() {
154         em.close();
155         emf.close();
156         HttpServletServer.factory.destroy();
157     }
158
159     @Test
160     public void testRetriesFail() {
161         //
162         // Load up the policy
163         //
164         final SupportUtil.Pair<ControlLoopPolicy, String> pair = SupportUtil.loadYaml("src/test/resources/test.yaml");
165         onset.setClosedLoopControlName(pair.key.getControlLoop().getControlLoopName());
166         try {
167             //
168             // Create a processor
169             //
170             final ControlLoopProcessor processor = new ControlLoopProcessor(pair.value);
171             //
172             // create the manager
173             //
174             ControlLoopEventManager eventManager =
175                     new ControlLoopEventManager(onset.getClosedLoopControlName(), onset.getRequestId());
176             VirtualControlLoopNotification notification = eventManager.activate(onset);
177
178             assertNotNull(notification);
179             assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
180
181             ControlLoopEventManager.NewEventStatus status = null;
182             try {
183                 status = eventManager.onNewEvent(onset);
184             } catch (AaiException e) {
185                 logger.warn(e.toString());
186                 fail("A&AI Query Failed");
187             }
188             assertNotNull(status);
189             assertEquals(ControlLoopEventManager.NewEventStatus.FIRST_ONSET, status);
190
191             ControlLoopOperationManager manager =
192                     new ControlLoopOperationManager(onset, processor.getCurrentPolicy(), eventManager);
193             logger.debug("{}", manager);
194             //
195             //
196             //
197             assertFalse(manager.isOperationComplete());
198             assertFalse(manager.isOperationRunning());
199             //
200             // Start
201             //
202             Object request = manager.startOperation(onset);
203             logger.debug("{}", manager);
204             assertNotNull(request);
205             assertTrue(request instanceof LcmRequestWrapper);
206             LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) request;
207             LcmRequest appcRequest = dmaapRequest.getBody();
208             assertTrue(appcRequest.getCommonHeader().getSubRequestId().contentEquals("1"));
209             assertFalse(manager.isOperationComplete());
210             assertTrue(manager.isOperationRunning());
211             //
212             // Accept
213             //
214             LcmResponseWrapper dmaapResponse = new LcmResponseWrapper();
215             LcmResponse appcResponse = new LcmResponse(appcRequest);
216             appcResponse.getStatus().setCode(100);
217             appcResponse.getStatus().setMessage("ACCEPT");
218             dmaapResponse.setBody(appcResponse);
219             //
220             //
221             //
222             PolicyResult result = manager.onResponse(dmaapResponse);
223             logger.debug("{}", manager);
224             assertTrue(result == null);
225             assertFalse(manager.isOperationComplete());
226             assertTrue(manager.isOperationRunning());
227             //
228             // Now we are going to Fail it
229             //
230             appcResponse = new LcmResponse(appcRequest);
231             appcResponse.getStatus().setCode(401);
232             appcResponse.getStatus().setMessage("AppC failed for some reason");
233             dmaapResponse.setBody(appcResponse);
234             result = manager.onResponse(dmaapResponse);
235             logger.debug("{}", manager);
236             assertTrue(result.equals(PolicyResult.FAILURE));
237             assertFalse(manager.isOperationComplete());
238             assertFalse(manager.isOperationRunning());
239             //
240             // Retry it
241             //
242             request = manager.startOperation(onset);
243             logger.debug("{}", manager);
244             assertNotNull(request);
245             assertTrue(request instanceof LcmRequestWrapper);
246             dmaapRequest = (LcmRequestWrapper) request;
247             appcRequest = dmaapRequest.getBody();
248             assertTrue(appcRequest.getCommonHeader().getSubRequestId().contentEquals("2"));
249             assertFalse(manager.isOperationComplete());
250             assertTrue(manager.isOperationRunning());
251             //
252             //
253             //
254             appcResponse = new LcmResponse(appcRequest);
255             logger.debug("{}", manager);
256             appcResponse.getStatus().setCode(100);
257             appcResponse.getStatus().setMessage("ACCEPT");
258             dmaapResponse.setBody(appcResponse);
259             //
260             //
261             //
262             result = manager.onResponse(dmaapResponse);
263             logger.debug("{}", manager);
264             assertTrue(result == null);
265             assertFalse(manager.isOperationComplete());
266             assertTrue(manager.isOperationRunning());
267             //
268             // Now we are going to Fail it
269             //
270             appcResponse = new LcmResponse(appcRequest);
271             appcResponse.getStatus().setCode(401);
272             appcResponse.getStatus().setMessage("AppC failed for some reason");
273             dmaapResponse.setBody(appcResponse);
274             result = manager.onResponse(dmaapResponse);
275             logger.debug("{}", manager);
276             assertTrue(result.equals(PolicyResult.FAILURE));
277             //
278             // Should be complete now
279             //
280             assertTrue(manager.isOperationComplete());
281             assertFalse(manager.isOperationRunning());
282             assertNotNull(manager.getOperationResult());
283             assertTrue(manager.getOperationResult().equals(PolicyResult.FAILURE_RETRIES));
284             assertTrue(manager.getHistory().size() == 2);
285         } catch (ControlLoopException | AaiException e) {
286             fail(e.getMessage());
287         }
288     }
289
290     @Test
291     public void testTimeout() {
292         //
293         // Load up the policy
294         //
295         final SupportUtil.Pair<ControlLoopPolicy, String> pair = SupportUtil.loadYaml("src/test/resources/test.yaml");
296         onset.setClosedLoopControlName(pair.key.getControlLoop().getControlLoopName());
297         try {
298             //
299             // Create a processor
300             //
301             final ControlLoopProcessor processor = new ControlLoopProcessor(pair.value);
302             //
303             // create the manager
304             //
305             ControlLoopEventManager eventManager =
306                     new ControlLoopEventManager(onset.getClosedLoopControlName(), onset.getRequestId());
307             VirtualControlLoopNotification notification = eventManager.activate(onset);
308
309             assertNotNull(notification);
310             assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
311
312             ControlLoopEventManager.NewEventStatus status = null;
313             try {
314                 status = eventManager.onNewEvent(onset);
315             } catch (AaiException e) {
316                 logger.warn(e.toString());
317                 fail("A&AI Query Failed");
318             }
319             assertNotNull(status);
320             assertEquals(ControlLoopEventManager.NewEventStatus.FIRST_ONSET, status);
321
322             ControlLoopOperationManager manager =
323                     new ControlLoopOperationManager(onset, processor.getCurrentPolicy(), eventManager);
324             //
325             //
326             //
327             logger.debug("{}", manager);
328             assertFalse(manager.isOperationComplete());
329             assertFalse(manager.isOperationRunning());
330             //
331             // Start
332             //
333             Object request = manager.startOperation(onset);
334             logger.debug("{}", manager);
335             assertNotNull(request);
336             assertTrue((request) instanceof LcmRequestWrapper);
337             LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) request;
338             LcmRequest appcRequest = dmaapRequest.getBody();
339             assertTrue((appcRequest).getCommonHeader().getSubRequestId().contentEquals("1"));
340             assertFalse(manager.isOperationComplete());
341             assertTrue(manager.isOperationRunning());
342             //
343             // Accept
344             //
345             LcmResponseWrapper dmaapResponse = new LcmResponseWrapper();
346             LcmResponse appcResponse = new LcmResponse(appcRequest);
347             dmaapResponse.setBody(appcResponse);
348             appcResponse.getStatus().setCode(100);
349             appcResponse.getStatus().setMessage("ACCEPT");
350             //
351             //
352             //
353             PolicyResult result = manager.onResponse(dmaapResponse);
354             logger.debug("{}", manager);
355             assertTrue(result == null);
356             assertFalse(manager.isOperationComplete());
357             assertTrue(manager.isOperationRunning());
358             //
359             // Now we are going to simulate Timeout
360             //
361             manager.setOperationHasTimedOut();
362             logger.debug("{}", manager);
363             assertTrue(manager.isOperationComplete());
364             assertFalse(manager.isOperationRunning());
365             assertTrue(manager.getHistory().size() == 1);
366             assertTrue(manager.getOperationResult().equals(PolicyResult.FAILURE_TIMEOUT));
367             //
368             // Now we are going to Fail the previous request
369             //
370             appcResponse = new LcmResponse(appcRequest);
371             appcResponse.getStatus().setCode(401);
372             appcResponse.getStatus().setMessage("AppC failed for some reason");
373             dmaapResponse.setBody(appcResponse);
374             result = manager.onResponse(dmaapResponse);
375             logger.debug("{}", manager);
376             //
377             //
378             //
379             assertTrue(manager.isOperationComplete());
380             assertFalse(manager.isOperationRunning());
381             assertTrue(manager.getHistory().size() == 1);
382             assertTrue(manager.getOperationResult().equals(PolicyResult.FAILURE_TIMEOUT));
383         } catch (ControlLoopException | AaiException e) {
384             fail(e.getMessage());
385         }
386     }
387
388     @Test
389     public void testMethods() throws IOException, ControlLoopException, AaiException {
390         InputStream is = new FileInputStream(new File("src/test/resources/testSOactor.yaml"));
391         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
392
393         UUID requestId = UUID.randomUUID();
394         VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
395         onsetEvent.setClosedLoopControlName("TwoOnsetTest");
396         onsetEvent.setRequestId(requestId);
397         onsetEvent.setTarget("generic-vnf.vnf-id");
398         onsetEvent.setClosedLoopAlarmStart(Instant.now());
399         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
400         onsetEvent.setAai(new HashMap<>());
401         onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne");
402
403         ControlLoopEventManager manager =
404                 new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId());
405         VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent);
406         assertNotNull(notification);
407         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
408
409         ControlLoopOperationManager clom = manager.processControlLoop();
410         assertNotNull(clom);
411         assertNull(clom.getOperationResult());
412
413         clom.setEventManager(manager);
414         assertEquals(manager, clom.getEventManager());
415
416         assertNull(clom.getTargetEntity());
417
418         clom.setGuardApprovalStatus("WizardOKedIt");
419         assertEquals("WizardOKedIt", clom.getGuardApprovalStatus());
420
421         assertNull(clom.getOperationResult());
422
423         Policy policy = manager.getProcessor().getCurrentPolicy();
424         clom.getTarget(policy);
425
426         final Target savedTarget = policy.getTarget();
427         policy.setTarget(null);
428         try {
429             clom.getTarget(policy);
430             fail("test should throw an exception here");
431         } catch (Exception e) {
432             assertEquals("The target is null", e.getMessage());
433         }
434
435         policy.setTarget(new Target());
436         try {
437             clom.getTarget(policy);
438             fail("test should throw an exception here");
439         } catch (Exception e) {
440             assertEquals("The target type is null", e.getMessage());
441         }
442
443         policy.setTarget(savedTarget);
444
445         policy.getTarget().setType(TargetType.PNF);
446         try {
447             clom.getTarget(policy);
448             fail("test should throw an exception here");
449         } catch (Exception e) {
450             assertEquals("PNF target is not supported", e.getMessage());
451         }
452
453         onsetEvent.setTarget("Oz");
454         onsetEvent.getAai().remove("generic-vnf.vnf-name");
455         onsetEvent.getAai().remove("generic-vnf.vnf-id");
456         onsetEvent.getAai().remove("vserver.vserver-name");
457
458         policy.getTarget().setType(TargetType.VNF);
459         try {
460             clom.getTarget(policy);
461             fail("test should throw an exception here");
462         } catch (Exception e) {
463             assertEquals("Target does not match target type", e.getMessage());
464         }
465
466         onsetEvent.setTarget("vserver.vserver-name");
467         onsetEvent.getAai().put("vserver.vserver-name", "OzVServer");
468         assertEquals("OzVServer", clom.getTarget(policy));
469
470         onsetEvent.getAai().remove("vserver.vserver-name");
471         onsetEvent.setTarget("generic-vnf.vnf-id");
472         onsetEvent.getAai().put("generic-vnf.vnf-id", "OzVNF");
473         assertEquals("OzVNF", clom.getTarget(policy));
474
475         onsetEvent.setTarget("generic-vnf.vnf-name");
476         assertEquals("OzVNF", clom.getTarget(policy));
477
478         manager.onNewEvent(onsetEvent);
479
480         onsetEvent.getAai().remove("generic-vnf.vnf-id");
481         manager.getVnfResponse();
482         if (!Boolean.valueOf(PolicyEngine.manager.getEnvironmentProperty("aai.customQuery"))) {
483             clom.getEventManager().getVnfResponse().setVnfId("generic-vnf.vnf-id");
484             assertEquals("generic-vnf.vnf-id", clom.getTarget(policy));
485         }
486
487
488         policy.getTarget().setType(TargetType.VFC);
489         try {
490             clom.getTarget(policy);
491             fail("test should throw an exception here");
492         } catch (Exception e) {
493             assertEquals("The target type is not supported", e.getMessage());
494         }
495
496         assertEquals(Integer.valueOf(20), clom.getOperationTimeout());
497
498         assertEquals("20s", clom.getOperationTimeoutString(100));
499
500         assertEquals(null, clom.getOperationMessage());
501         assertEquals(null, clom.getOperationMessage("The Wizard Escaped"));
502
503         clom.startOperation(onsetEvent);
504
505         assertEquals("actor=SO,operation=Restart,target=Target [type=VFC, resourceId=null],subRequestId=1",
506                 clom.getOperationMessage());
507         assertEquals(
508                 "actor=SO,operation=Restart,target=Target [type=VFC, resourceId=null],subRequestId=1, Guard result: "
509                         + "The Wizard Escaped",
510                 clom.getOperationMessage("The Wizard Escaped"));
511
512         assertEquals("actor=SO,operation=Restart,tar", clom.getOperationHistory().substring(0, 30));
513
514         clom.setOperationHasException("The Wizard is gone");
515         clom.setOperationHasGuardDeny();
516     }
517
518     @Test
519     public void testConstructor() throws IOException, ControlLoopException, AaiException {
520         InputStream is = new FileInputStream(new File("src/test/resources/test.yaml"));
521         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
522
523         UUID requestId = UUID.randomUUID();
524         VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
525         onsetEvent.setClosedLoopControlName("TwoOnsetTest");
526         onsetEvent.setRequestId(requestId);
527         onsetEvent.setTarget("generic-vnf.vnf-id");
528         onsetEvent.setClosedLoopAlarmStart(Instant.now());
529         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
530         onsetEvent.setAai(new HashMap<>());
531         onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne");
532
533         ControlLoopEventManager manager =
534                 new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId());
535         VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent);
536         assertNotNull(notification);
537         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
538
539         Policy policy = manager.getProcessor().getCurrentPolicy();
540         ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
541         assertNotNull(clom);
542
543         policy.setRecipe("ModifyConfig");
544         policy.getTarget().setResourceID(UUID.randomUUID().toString());
545         try {
546             new ControlLoopOperationManager(onsetEvent, policy, manager);
547             fail("test should throw an exception here");
548         } catch (Exception e) {
549             assertEquals("Target vnf-id could not be found", e.getMessage());
550         }
551
552         policy.getTarget().setResourceID("82194af1-3c2c-485a-8f44-420e22a9eaa4");
553         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
554         assertNotNull(clom);
555
556
557         policy.setActor("SO");
558         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
559         assertNotNull(clom);
560
561         policy.setActor("VFC");
562         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
563         assertNotNull(clom);
564
565         policy.setActor("Dorothy");
566         try {
567             new ControlLoopOperationManager(onsetEvent, policy, manager);
568             fail("test should throw an exception here");
569         } catch (Exception e) {
570             assertEquals("ControlLoopEventManager: policy has an unknown actor.", e.getMessage());
571         }
572     }
573
574     @Test
575     public void testStartOperation() throws IOException, ControlLoopException, AaiException {
576         InputStream is = new FileInputStream(new File("src/test/resources/test.yaml"));
577         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
578
579         UUID requestId = UUID.randomUUID();
580         VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
581         onsetEvent.setClosedLoopControlName("TwoOnsetTest");
582         onsetEvent.setRequestId(requestId);
583         onsetEvent.setTarget("generic-vnf.vnf-id");
584         onsetEvent.setClosedLoopAlarmStart(Instant.now());
585         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
586         onsetEvent.setAai(new HashMap<>());
587         onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne");
588
589         ControlLoopEventManager manager =
590                 new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId());
591         VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent);
592         assertNotNull(notification);
593         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
594
595         Policy policy = manager.getProcessor().getCurrentPolicy();
596         ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
597         assertNotNull(clom);
598
599         clom.startOperation(onsetEvent);
600
601         try {
602             clom.startOperation(onsetEvent);
603             fail("test should throw an exception here");
604         } catch (Exception e) {
605             assertEquals("current operation is not null (an operation is already running)", e.getMessage());
606         }
607
608         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
609         assertNotNull(clom);
610         final String savedRecipe = policy.getRecipe();
611         policy.setRecipe("ModifyConfig");
612         policy.getTarget().setResourceID(UUID.randomUUID().toString());
613         clom.startOperation(onsetEvent);
614         policy.setRecipe(savedRecipe);
615
616         policy.setRetry(null);
617         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
618         assertNotNull(clom);
619         clom.startOperation(onsetEvent);
620         clom.setOperationHasTimedOut();
621         assertTrue(clom.isOperationComplete());
622         try {
623             clom.startOperation(onsetEvent);
624             fail("test should throw an exception here");
625         } catch (Exception e) {
626             assertEquals("current operation failed and retries are not allowed", e.getMessage());
627         }
628
629         policy.setRetry(0);
630         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
631         assertNotNull(clom);
632         clom.startOperation(onsetEvent);
633         clom.setOperationHasTimedOut();
634         assertTrue(clom.isOperationComplete());
635         try {
636             clom.startOperation(onsetEvent);
637             fail("test should throw an exception here");
638         } catch (Exception e) {
639             assertEquals("current operation failed and retries are not allowed", e.getMessage());
640         }
641
642         policy.setRetry(1);
643         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
644         assertNotNull(clom);
645         clom.startOperation(onsetEvent);
646         clom.setOperationHasTimedOut();
647         clom.startOperation(onsetEvent);
648         clom.setOperationHasTimedOut();
649         assertTrue(clom.isOperationComplete());
650         try {
651             clom.startOperation(onsetEvent);
652             fail("test should throw an exception here");
653         } catch (Exception e) {
654             assertEquals("current oepration has failed after 2 retries", e.getMessage());
655         }
656
657         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
658         assertNotNull(clom);
659         policy.setActor("SO");
660         clom.startOperation(onsetEvent);
661
662         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
663         assertNotNull(clom);
664         policy.setActor("VFC");
665         clom.startOperation(onsetEvent);
666
667         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
668         assertNotNull(clom);
669         policy.setActor("Oz");
670         try {
671             clom.startOperation(onsetEvent);
672             fail("test should throw an exception here");
673         } catch (Exception e) {
674             assertEquals("invalid actor Oz on policy", e.getMessage());
675         }
676     }
677
678     @Test
679     public void testOnResponse() throws IOException, ControlLoopException, AaiException {
680         InputStream is = new FileInputStream(new File("src/test/resources/test.yaml"));
681         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
682
683         UUID requestId = UUID.randomUUID();
684         VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
685         onsetEvent.setClosedLoopControlName("TwoOnsetTest");
686         onsetEvent.setRequestId(requestId);
687         onsetEvent.setTarget("generic-vnf.vnf-id");
688         onsetEvent.setClosedLoopAlarmStart(Instant.now());
689         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
690         onsetEvent.setAai(new HashMap<>());
691         onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne");
692
693         ControlLoopEventManager manager =
694                 new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId());
695         VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent);
696         assertNotNull(notification);
697         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
698
699         Policy policy = manager.getProcessor().getCurrentPolicy();
700         ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
701         assertNotNull(clom);
702
703         assertNull(clom.onResponse(null));
704
705         Response appcResponse = new Response();
706         CommonHeader commonHeader = new CommonHeader();
707         appcResponse.setCommonHeader(commonHeader);
708         assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse));
709
710         commonHeader.setSubRequestId("12345");
711         appcResponse.setStatus(null);
712         assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse));
713
714         ResponseStatus responseStatus = new ResponseStatus();
715         appcResponse.setStatus(responseStatus);
716         assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse));
717
718         responseStatus.setCode(0);
719         assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse));
720
721         responseStatus.setCode(ResponseCode.ACCEPT.getValue());
722         assertEquals(null, clom.onResponse(appcResponse));
723
724         responseStatus.setCode(ResponseCode.ERROR.getValue());
725         assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse));
726
727         responseStatus.setCode(ResponseCode.FAILURE.getValue());
728         assertEquals(PolicyResult.FAILURE, clom.onResponse(appcResponse));
729
730         responseStatus.setCode(ResponseCode.REJECT.getValue());
731         assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse));
732
733         responseStatus.setCode(ResponseCode.SUCCESS.getValue());
734         assertEquals(PolicyResult.SUCCESS, clom.onResponse(appcResponse));
735
736         LcmResponseWrapper lrw = new LcmResponseWrapper();
737         LcmResponse body = new LcmResponse();
738         LcmCommonHeader lcmCh = new LcmCommonHeader();
739         body.setCommonHeader(lcmCh);
740         lrw.setBody(body);
741
742         lcmCh.setSubRequestId("NotANumber");
743         assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(lrw));
744
745         lcmCh.setSubRequestId("12345");
746         assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(lrw));
747
748         SoResponse soResponse = new SoResponse();
749         SoResponseWrapper soRw = new SoResponseWrapper(soResponse, null);
750
751         soResponse.setHttpResponseCode(200);
752         assertEquals(PolicyResult.SUCCESS, clom.onResponse(soRw));
753
754         soResponse.setHttpResponseCode(202);
755         assertEquals(PolicyResult.SUCCESS, clom.onResponse(soRw));
756
757         soResponse.setHttpResponseCode(500);
758         assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw));
759
760         VfcResponse vfcResponse = new VfcResponse();
761         VfcResponseDescriptor responseDescriptor = new VfcResponseDescriptor();
762         vfcResponse.setResponseDescriptor(responseDescriptor);
763
764         responseDescriptor.setStatus("finished");
765         assertEquals(PolicyResult.SUCCESS, clom.onResponse(vfcResponse));
766
767         responseDescriptor.setStatus("unfinished");
768         assertEquals(PolicyResult.FAILURE, clom.onResponse(vfcResponse));
769     }
770
771     @Test
772     public void testCompleteOperation() throws ControlLoopException, AaiException, IOException {
773         InputStream is = new FileInputStream(new File("src/test/resources/test.yaml"));
774         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
775
776         UUID requestId = UUID.randomUUID();
777         VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
778         onsetEvent.setClosedLoopControlName("TwoOnsetTest");
779         onsetEvent.setRequestId(requestId);
780         onsetEvent.setTarget("generic-vnf.vnf-id");
781         onsetEvent.setClosedLoopAlarmStart(Instant.now());
782         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
783         onsetEvent.setAai(new HashMap<>());
784         onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne");
785
786         ControlLoopEventManager manager =
787                 new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId());
788         VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent);
789         assertNotNull(notification);
790         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
791
792         Policy policy = manager.getProcessor().getCurrentPolicy();
793         ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
794         assertNotNull(clom);
795
796         clom.startOperation(onsetEvent);
797
798         SoResponse soResponse = new SoResponse();
799         final SoResponseWrapper soRw = new SoResponseWrapper(soResponse, null);
800
801         PolicyEngine.manager.setEnvironmentProperty("guard.disabled", "false");
802         PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_URL,
803                 "http://somewhere.over.the.rainbow");
804         PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_USER, "Dorothy");
805         PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_PASS, "Toto");
806
807         assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw));
808
809         System.setProperty("OperationsHistoryPU", "OperationsHistoryPUTest");
810         assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw));
811     }
812
813     @Test
814     public void testCommitAbatement() throws ControlLoopException, AaiException, IOException {
815
816         String yamlString = null;
817         try (InputStream is = new FileInputStream(new File("src/test/resources/test.yaml"))) {
818             yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
819         } catch (Exception e) {
820             fail(e.getMessage());
821         }
822
823         UUID requestId = UUID.randomUUID();
824         VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
825         onsetEvent.setClosedLoopControlName("TwoOnsetTest");
826         onsetEvent.setRequestId(requestId);
827         onsetEvent.setTarget("generic-vnf.vnf-id");
828         onsetEvent.setClosedLoopAlarmStart(Instant.now());
829         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
830         onsetEvent.setAai(new HashMap<>());
831         onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne");
832
833         ControlLoopEventManager manager =
834                 new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId());
835         VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent);
836         assertNotNull(notification);
837         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
838
839         Policy policy = manager.getProcessor().getCurrentPolicy();
840         ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
841         assertNotNull(clom);
842
843         clom.startOperation(onsetEvent);
844
845         int numEventsBefore = getCount();
846         logger.info("numEventsBefore={}", numEventsBefore);
847
848         clom.commitAbatement("Test message", "TEST_RESULT");
849
850         int numEventsAfter = getCount();
851         logger.info("numEventsAfter={}", numEventsAfter);
852
853         assertEquals(1, numEventsAfter - numEventsBefore);
854     }
855
856     @Test
857     public void testSerialization() throws Exception {
858         InputStream is = new FileInputStream(new File("src/test/resources/test.yaml"));
859         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
860
861         UUID requestId = UUID.randomUUID();
862         VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
863         onsetEvent.setClosedLoopControlName("TwoOnsetTest");
864         onsetEvent.setRequestId(requestId);
865         onsetEvent.setTarget("generic-vnf.vnf-id");
866         onsetEvent.setClosedLoopAlarmStart(Instant.now());
867         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
868         onsetEvent.setAai(new HashMap<>());
869         onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne");
870
871         ControlLoopEventManager manager =
872                 new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId());
873         VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent);
874         assertNotNull(notification);
875         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
876
877         Policy policy = manager.getProcessor().getCurrentPolicy();
878         ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
879         assertNotNull(clom);
880
881         clom.startOperation(onsetEvent);
882         assertTrue(clom.isOperationRunning());
883
884         clom = Serializer.roundTrip(clom);
885         assertNotNull(clom);
886         assertTrue(clom.isOperationRunning());
887
888         SoResponse soResponse = new SoResponse();
889         final SoResponseWrapper soRw = new SoResponseWrapper(soResponse, null);
890
891         PolicyEngine.manager.setEnvironmentProperty("guard.disabled", "false");
892         PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_URL,
893                 "http://somewhere.over.the.rainbow");
894         PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_USER, "Dorothy");
895         PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_PASS, "Toto");
896
897         assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw));
898         assertFalse(clom.isOperationRunning());
899         assertEquals(1, clom.getHistory().size());
900
901         clom = Serializer.roundTrip(clom);
902         assertNotNull(clom);
903         assertFalse(clom.isOperationRunning());
904         assertEquals(1, clom.getHistory().size());
905
906         System.setProperty("OperationsHistoryPU", "OperationsHistoryPUTest");
907         assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw));
908
909         clom = Serializer.roundTrip(clom);
910         assertNotNull(clom);
911         assertFalse(clom.isOperationRunning());
912         assertEquals(1, clom.getHistory().size());
913     }
914 }