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