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