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