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