Merge "Remove model-impl/vfc checkstyle suppressions"
[policy/drools-applications.git] / controlloop / common / eventmanager / src / test / java / org / onap / policy / controlloop / eventmanager / ControlLoopOperationManagerTest.java
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 operationshistory10";
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", "TestOperationsHistoryPU");
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("TestOperationsHistoryPU");
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.NEW_EVENT_STATUS 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.NEW_EVENT_STATUS.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.NEW_EVENT_STATUS 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.NEW_EVENT_STATUS.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         clom.getEventManager().getVnfResponse().setVnfId("generic-vnf.vnf-id");
483         assertEquals("generic-vnf.vnf-id", clom.getTarget(policy));
484
485         policy.getTarget().setType(TargetType.VFC);
486         try {
487             clom.getTarget(policy);
488             fail("test should throw an exception here");
489         } catch (Exception e) {
490             assertEquals("The target type is not supported", e.getMessage());
491         }
492
493         assertEquals(Integer.valueOf(20), clom.getOperationTimeout());
494
495         assertEquals("20s", clom.getOperationTimeoutString(100));
496
497         assertEquals(null, clom.getOperationMessage());
498         assertEquals(null, clom.getOperationMessage("The Wizard Escaped"));
499
500         clom.startOperation(onsetEvent);
501
502         assertEquals("actor=SO,operation=Restart,target=Target [type=VFC, resourceId=null],subRequestId=1",
503                 clom.getOperationMessage());
504         assertEquals(
505                 "actor=SO,operation=Restart,target=Target [type=VFC, resourceId=null],subRequestId=1, Guard result: "
506                         + "The Wizard Escaped",
507                 clom.getOperationMessage("The Wizard Escaped"));
508
509         assertEquals("actor=SO,operation=Restart,tar", clom.getOperationHistory().substring(0, 30));
510
511         clom.setOperationHasException("The Wizard is gone");
512         clom.setOperationHasGuardDeny();
513     }
514
515     @Test
516     public void testConstructor() throws IOException, ControlLoopException, AaiException {
517         InputStream is = new FileInputStream(new File("src/test/resources/test.yaml"));
518         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
519
520         UUID requestId = UUID.randomUUID();
521         VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
522         onsetEvent.setClosedLoopControlName("TwoOnsetTest");
523         onsetEvent.setRequestId(requestId);
524         onsetEvent.setTarget("generic-vnf.vnf-id");
525         onsetEvent.setClosedLoopAlarmStart(Instant.now());
526         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
527         onsetEvent.setAai(new HashMap<>());
528         onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne");
529
530         ControlLoopEventManager manager =
531                 new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId());
532         VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent);
533         assertNotNull(notification);
534         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
535
536         Policy policy = manager.getProcessor().getCurrentPolicy();
537         ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
538         assertNotNull(clom);
539
540         policy.setRecipe("ModifyConfig");
541         policy.getTarget().setResourceID(UUID.randomUUID().toString());
542         try {
543             new ControlLoopOperationManager(onsetEvent, policy, manager);
544             fail("test should throw an exception here");
545         } catch (Exception e) {
546             assertEquals("Target vnf-id could not be found", e.getMessage());
547         }
548
549         policy.getTarget().setResourceID("82194af1-3c2c-485a-8f44-420e22a9eaa4");
550         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
551         assertNotNull(clom);
552
553         policy.setActor("SO");
554         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
555         assertNotNull(clom);
556
557         policy.setActor("VFC");
558         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
559         assertNotNull(clom);
560
561         policy.setActor("Dorothy");
562         try {
563             new ControlLoopOperationManager(onsetEvent, policy, manager);
564             fail("test should throw an exception here");
565         } catch (Exception e) {
566             assertEquals("ControlLoopEventManager: policy has an unknown actor.", e.getMessage());
567         }
568     }
569
570     @Test
571     public void testStartOperation() throws IOException, ControlLoopException, AaiException {
572         InputStream is = new FileInputStream(new File("src/test/resources/test.yaml"));
573         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
574
575         UUID requestId = UUID.randomUUID();
576         VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
577         onsetEvent.setClosedLoopControlName("TwoOnsetTest");
578         onsetEvent.setRequestId(requestId);
579         onsetEvent.setTarget("generic-vnf.vnf-id");
580         onsetEvent.setClosedLoopAlarmStart(Instant.now());
581         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
582         onsetEvent.setAai(new HashMap<>());
583         onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne");
584
585         ControlLoopEventManager manager =
586                 new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId());
587         VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent);
588         assertNotNull(notification);
589         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
590
591         Policy policy = manager.getProcessor().getCurrentPolicy();
592         ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
593         assertNotNull(clom);
594
595         clom.startOperation(onsetEvent);
596
597         try {
598             clom.startOperation(onsetEvent);
599             fail("test should throw an exception here");
600         } catch (Exception e) {
601             assertEquals("current operation is not null (an operation is already running)", e.getMessage());
602         }
603
604         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
605         assertNotNull(clom);
606         final String savedRecipe = policy.getRecipe();
607         policy.setRecipe("ModifyConfig");
608         policy.getTarget().setResourceID(UUID.randomUUID().toString());
609         clom.startOperation(onsetEvent);
610         policy.setRecipe(savedRecipe);
611
612         policy.setRetry(null);
613         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
614         assertNotNull(clom);
615         clom.startOperation(onsetEvent);
616         clom.setOperationHasTimedOut();
617         assertTrue(clom.isOperationComplete());
618         try {
619             clom.startOperation(onsetEvent);
620             fail("test should throw an exception here");
621         } catch (Exception e) {
622             assertEquals("current operation failed and retries are not allowed", e.getMessage());
623         }
624
625         policy.setRetry(0);
626         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
627         assertNotNull(clom);
628         clom.startOperation(onsetEvent);
629         clom.setOperationHasTimedOut();
630         assertTrue(clom.isOperationComplete());
631         try {
632             clom.startOperation(onsetEvent);
633             fail("test should throw an exception here");
634         } catch (Exception e) {
635             assertEquals("current operation failed and retries are not allowed", e.getMessage());
636         }
637
638         policy.setRetry(1);
639         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
640         assertNotNull(clom);
641         clom.startOperation(onsetEvent);
642         clom.setOperationHasTimedOut();
643         clom.startOperation(onsetEvent);
644         clom.setOperationHasTimedOut();
645         assertTrue(clom.isOperationComplete());
646         try {
647             clom.startOperation(onsetEvent);
648             fail("test should throw an exception here");
649         } catch (Exception e) {
650             assertEquals("current oepration has failed after 2 retries", e.getMessage());
651         }
652
653         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
654         assertNotNull(clom);
655         policy.setActor("SO");
656         clom.startOperation(onsetEvent);
657
658         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
659         assertNotNull(clom);
660         policy.setActor("VFC");
661         clom.startOperation(onsetEvent);
662
663         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
664         assertNotNull(clom);
665         policy.setActor("Oz");
666         try {
667             clom.startOperation(onsetEvent);
668             fail("test should throw an exception here");
669         } catch (Exception e) {
670             assertEquals("invalid actor Oz on policy", e.getMessage());
671         }
672     }
673
674     @Test
675     public void testOnResponse() throws IOException, ControlLoopException, AaiException {
676         InputStream is = new FileInputStream(new File("src/test/resources/test.yaml"));
677         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
678
679         UUID requestId = UUID.randomUUID();
680         VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
681         onsetEvent.setClosedLoopControlName("TwoOnsetTest");
682         onsetEvent.setRequestId(requestId);
683         onsetEvent.setTarget("generic-vnf.vnf-id");
684         onsetEvent.setClosedLoopAlarmStart(Instant.now());
685         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
686         onsetEvent.setAai(new HashMap<>());
687         onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne");
688
689         ControlLoopEventManager manager =
690                 new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId());
691         VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent);
692         assertNotNull(notification);
693         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
694
695         Policy policy = manager.getProcessor().getCurrentPolicy();
696         ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
697         assertNotNull(clom);
698
699         assertNull(clom.onResponse(null));
700
701         Response appcResponse = new Response();
702         CommonHeader commonHeader = new CommonHeader();
703         appcResponse.setCommonHeader(commonHeader);
704         assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse));
705
706         commonHeader.setSubRequestId("12345");
707         appcResponse.setStatus(null);
708         assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse));
709
710         ResponseStatus responseStatus = new ResponseStatus();
711         appcResponse.setStatus(responseStatus);
712         assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse));
713
714         responseStatus.setCode(0);
715         assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse));
716
717         responseStatus.setCode(ResponseCode.ACCEPT.getValue());
718         assertEquals(null, clom.onResponse(appcResponse));
719
720         responseStatus.setCode(ResponseCode.ERROR.getValue());
721         assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse));
722
723         responseStatus.setCode(ResponseCode.FAILURE.getValue());
724         assertEquals(PolicyResult.FAILURE, clom.onResponse(appcResponse));
725
726         responseStatus.setCode(ResponseCode.REJECT.getValue());
727         assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse));
728
729         responseStatus.setCode(ResponseCode.SUCCESS.getValue());
730         assertEquals(PolicyResult.SUCCESS, clom.onResponse(appcResponse));
731
732         LcmResponseWrapper lrw = new LcmResponseWrapper();
733         LcmResponse body = new LcmResponse();
734         LcmCommonHeader lcmCh = new LcmCommonHeader();
735         body.setCommonHeader(lcmCh);
736         lrw.setBody(body);
737
738         lcmCh.setSubRequestId("NotANumber");
739         assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(lrw));
740
741         lcmCh.setSubRequestId("12345");
742         assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(lrw));
743
744         SOResponse soResponse = new SOResponse();
745         SOResponseWrapper soRw = new SOResponseWrapper(soResponse, null);
746
747         soResponse.setHttpResponseCode(200);
748         assertEquals(PolicyResult.SUCCESS, clom.onResponse(soRw));
749
750         soResponse.setHttpResponseCode(202);
751         assertEquals(PolicyResult.SUCCESS, clom.onResponse(soRw));
752
753         soResponse.setHttpResponseCode(500);
754         assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw));
755
756         VfcResponse vfcResponse = new VfcResponse();
757         VfcResponseDescriptor responseDescriptor = new VfcResponseDescriptor();
758         vfcResponse.setResponseDescriptor(responseDescriptor);
759
760         responseDescriptor.setStatus("finished");
761         assertEquals(PolicyResult.SUCCESS, clom.onResponse(vfcResponse));
762
763         responseDescriptor.setStatus("unfinished");
764         assertEquals(PolicyResult.FAILURE, clom.onResponse(vfcResponse));
765     }
766
767     @Test
768     public void testCompleteOperation() throws ControlLoopException, AaiException, IOException {
769         InputStream is = new FileInputStream(new File("src/test/resources/test.yaml"));
770         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
771
772         UUID requestId = UUID.randomUUID();
773         VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
774         onsetEvent.setClosedLoopControlName("TwoOnsetTest");
775         onsetEvent.setRequestId(requestId);
776         onsetEvent.setTarget("generic-vnf.vnf-id");
777         onsetEvent.setClosedLoopAlarmStart(Instant.now());
778         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
779         onsetEvent.setAai(new HashMap<>());
780         onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne");
781
782         ControlLoopEventManager manager =
783                 new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId());
784         VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent);
785         assertNotNull(notification);
786         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
787
788         Policy policy = manager.getProcessor().getCurrentPolicy();
789         ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
790         assertNotNull(clom);
791
792         clom.startOperation(onsetEvent);
793
794         SOResponse soResponse = new SOResponse();
795         final SOResponseWrapper soRw = new SOResponseWrapper(soResponse, null);
796
797         PolicyEngine.manager.setEnvironmentProperty("guard.disabled", "false");
798         PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_URL,
799                 "http://somewhere.over.the.rainbow");
800         PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_USER, "Dorothy");
801         PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_PASS, "Toto");
802
803         assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw));
804
805         System.setProperty("OperationsHistoryPU", "TestOperationsHistoryPU");
806         assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw));
807     }    
808
809     @Test
810     public void testCommitAbatement() throws ControlLoopException, AaiException, IOException {
811
812         String yamlString = null;
813         try ( InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")) ) {
814             yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
815         } catch (Exception e) {
816             fail(e.getMessage());
817         }
818
819         UUID requestId = UUID.randomUUID();
820         VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
821         onsetEvent.setClosedLoopControlName("TwoOnsetTest");
822         onsetEvent.setRequestId(requestId);
823         onsetEvent.setTarget("generic-vnf.vnf-id");
824         onsetEvent.setClosedLoopAlarmStart(Instant.now());
825         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
826         onsetEvent.setAai(new HashMap<>());
827         onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne");
828
829         ControlLoopEventManager manager =
830                 new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId());
831         VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent);
832         assertNotNull(notification);
833         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
834
835         Policy policy = manager.getProcessor().getCurrentPolicy();
836         ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
837         assertNotNull(clom);
838         
839         clom.startOperation(onsetEvent);
840
841         int numEventsBefore = getCount();
842         logger.info("numEventsBefore={}", numEventsBefore); 
843         
844         clom.commitAbatement("Test message","TEST_RESULT");
845
846         int numEventsAfter = getCount();
847         logger.info("numEventsAfter={}", numEventsAfter); 
848         
849         assertEquals(1, numEventsAfter - numEventsBefore);        
850     }    
851
852     @Test
853     public void testSerialization() throws Exception {
854         InputStream is = new FileInputStream(new File("src/test/resources/test.yaml"));
855         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
856
857         UUID requestId = UUID.randomUUID();
858         VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
859         onsetEvent.setClosedLoopControlName("TwoOnsetTest");
860         onsetEvent.setRequestId(requestId);
861         onsetEvent.setTarget("generic-vnf.vnf-id");
862         onsetEvent.setClosedLoopAlarmStart(Instant.now());
863         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
864         onsetEvent.setAai(new HashMap<>());
865         onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne");
866
867         ControlLoopEventManager manager =
868                 new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId());
869         VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent);
870         assertNotNull(notification);
871         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
872
873         Policy policy = manager.getProcessor().getCurrentPolicy();
874         ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
875         assertNotNull(clom);
876
877         clom.startOperation(onsetEvent);
878         assertTrue(clom.isOperationRunning());
879         
880         clom = Serializer.roundTrip(clom);
881         assertNotNull(clom);
882         assertTrue(clom.isOperationRunning());
883
884         SOResponse soResponse = new SOResponse();
885         final SOResponseWrapper soRw = new SOResponseWrapper(soResponse, null);
886
887         PolicyEngine.manager.setEnvironmentProperty("guard.disabled", "false");
888         PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_URL,
889                 "http://somewhere.over.the.rainbow");
890         PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_USER, "Dorothy");
891         PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_PASS, "Toto");
892
893         assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw));
894         assertFalse(clom.isOperationRunning());
895         assertEquals(1, clom.getHistory().size());
896         
897         clom = Serializer.roundTrip(clom);
898         assertNotNull(clom);
899         assertFalse(clom.isOperationRunning());
900         assertEquals(1, clom.getHistory().size());
901
902         System.setProperty("OperationsHistoryPU", "TestOperationsHistoryPU");
903         assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw));
904         
905         clom = Serializer.roundTrip(clom);
906         assertNotNull(clom);
907         assertFalse(clom.isOperationRunning());
908         assertEquals(1, clom.getHistory().size());
909     }
910 }