4cb365a76ac2a4646b975f3347ecaddd89546b95
[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     private static final Logger logger =
98         LoggerFactory.getLogger(ControlLoopOperationManagerTest.class);
99
100     private static VirtualControlLoopEvent onset;
101
102     static {
103         onset = new VirtualControlLoopEvent();
104         onset.setRequestId(UUID.randomUUID());
105         onset.setTarget(VNF_NAME);
106         onset.setTargetType(ControlLoopTargetType.VNF);
107         onset.setClosedLoopAlarmStart(Instant.now());
108         onset.setAai(new HashMap<>());
109         onset.getAai().put(VNF_NAME, "testTriggerSource");
110         onset.getAai().put(VSERVER_NAME, "testVserverName");
111         onset.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
112         onset.setTargetType(ControlLoopTargetType.VNF);
113
114         /* Set environment properties */
115         PolicyEngineConstants.getManager().setEnvironmentProperty("aai.url",
116             "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     private static int getCount() {
126         // Create a query for number of items in DB
127         String sql = "select count(*) as count from operationshistory";
128         Query nq = em.createNativeQuery(sql);
129
130         return ((Number) nq.getSingleResult()).intValue();
131     }
132
133     /**
134      * Set up test class.
135      */
136     @BeforeClass
137     public static void setUp() throws Exception {
138
139         org.onap.policy.simulators.Util.buildAaiSim();
140
141         // Set PU
142         System.setProperty(OPERATIONS_HISTORY_PU, OPERATIONS_HISTORY_PU_TEST);
143
144         // Enter dummy props to avoid nullPointerException
145         PolicyEngineConstants.getManager()
146             .setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_URL, "a");
147         PolicyEngineConstants.getManager()
148             .setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_USER, "b");
149         PolicyEngineConstants.getManager()
150             .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      * 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         onset.getAai().put(VSERVER_NAME, "testVserverName");
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         onset.getAai().put(VSERVER_NAME, "OzVServer");
303
304         //
305         // Create a processor
306         //
307         final ControlLoopProcessor processor = new ControlLoopProcessor(pair.value);
308         //
309         // create the manager
310         //
311         ControlLoopEventManager eventManager =
312             new ControlLoopEventManager(onset.getClosedLoopControlName(), onset.getRequestId());
313         VirtualControlLoopNotification notification = eventManager.activate(onset);
314
315         assertNotNull(notification);
316         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
317
318         ControlLoopEventManager.NewEventStatus status = eventManager.onNewEvent(onset);
319         assertNotNull(status);
320         assertEquals(ControlLoopEventManager.NewEventStatus.FIRST_ONSET, status);
321
322         ControlLoopOperationManager manager =
323             new ControlLoopOperationManager(onset, processor.getCurrentPolicy(), eventManager);
324         //
325         //
326         //
327         logger.debug("{}", manager);
328         assertFalse(manager.isOperationComplete());
329         assertFalse(manager.isOperationRunning());
330         //
331         // Start
332         //
333         Object request = manager.startOperation(onset);
334         logger.debug("{}", manager);
335         assertNotNull(request);
336         assertTrue((request) instanceof AppcLcmDmaapWrapper);
337         AppcLcmDmaapWrapper dmaapRequest = (AppcLcmDmaapWrapper) request;
338         AppcLcmInput appcRequest = dmaapRequest.getBody().getInput();
339         assertTrue((appcRequest).getCommonHeader().getSubRequestId().contentEquals("1"));
340         assertFalse(manager.isOperationComplete());
341         assertTrue(manager.isOperationRunning());
342         //
343         // Accept
344         //
345         AppcLcmDmaapWrapper dmaapResponse = new AppcLcmDmaapWrapper();
346         AppcLcmOutput appcResponse = new AppcLcmOutput(appcRequest);
347         AppcLcmBody outputBody = new AppcLcmBody();
348         outputBody.setOutput(appcResponse);
349         dmaapResponse.setBody(outputBody);
350         appcResponse.getStatus().setCode(100);
351         appcResponse.getStatus().setMessage(ACCEPT);
352         //
353         //
354         //
355         PolicyResult result = manager.onResponse(dmaapResponse);
356         logger.debug("{}", manager);
357         assertTrue(result == null);
358         assertFalse(manager.isOperationComplete());
359         assertTrue(manager.isOperationRunning());
360         //
361         // Now we are going to simulate Timeout
362         //
363         manager.setOperationHasTimedOut();
364         logger.debug("{}", manager);
365         assertTrue(manager.isOperationComplete());
366         assertFalse(manager.isOperationRunning());
367         assertTrue(manager.getHistory().size() == 1);
368         assertTrue(manager.getOperationResult().equals(PolicyResult.FAILURE_TIMEOUT));
369         //
370         // Now we are going to Fail the previous request
371         //
372         appcResponse = new AppcLcmOutput(appcRequest);
373         appcResponse.getStatus().setCode(401);
374         appcResponse.getStatus().setMessage(APPC_FAILURE_REASON);
375         outputBody.setOutput(appcResponse);
376         dmaapResponse.setBody(outputBody);
377         manager.onResponse(dmaapResponse);
378         logger.debug("{}", manager);
379         //
380         //
381         //
382         assertTrue(manager.isOperationComplete());
383         assertFalse(manager.isOperationRunning());
384         assertTrue(manager.getHistory().size() == 1);
385         assertTrue(manager.getOperationResult().equals(PolicyResult.FAILURE_TIMEOUT));
386     }
387
388     @Test
389     public void testMethods() throws IOException, ControlLoopException, AaiException {
390         InputStream is = new FileInputStream(new File("src/test/resources/testSOactor.yaml"));
391         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
392
393         UUID requestId = UUID.randomUUID();
394         VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
395         onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST);
396         onsetEvent.setRequestId(requestId);
397         onsetEvent.setTarget(VNF_ID);
398         onsetEvent.setTargetType(ControlLoopTargetType.VNF);
399         onsetEvent.setClosedLoopAlarmStart(Instant.now());
400         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
401         onsetEvent.setAai(new HashMap<>());
402         onsetEvent.getAai().put(VNF_NAME, ONSET_ONE);
403         onsetEvent.getAai().put(VSERVER_NAME, "testVserverName");
404
405         ControlLoopEventManager manager = new ControlLoopEventManager(
406             onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId());
407         VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent);
408         assertNotNull(notification);
409         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
410
411         ControlLoopOperationManager clom = manager.processControlLoop();
412         assertNotNull(clom);
413         assertNull(clom.getOperationResult());
414
415         clom.setEventManager(manager);
416         assertEquals(manager, clom.getEventManager());
417
418         assertNull(clom.getTargetEntity());
419
420         clom.setGuardApprovalStatus("WizardOKedIt");
421         assertEquals("WizardOKedIt", clom.getGuardApprovalStatus());
422
423         assertNull(clom.getOperationResult());
424
425         Policy policy = manager.getProcessor().getCurrentPolicy();
426         clom.getTarget(policy);
427
428         final Target savedTarget = policy.getTarget();
429         policy.setTarget(null);
430         assertThatThrownBy(() -> clom.getTarget(policy)).hasMessage("The target is null");
431
432         policy.setTarget(new Target());
433         assertThatThrownBy(() -> clom.getTarget(policy)).hasMessage("The target type is null");
434
435         policy.setTarget(savedTarget);
436
437         policy.getTarget().setType(TargetType.PNF);
438         assertThatThrownBy(() -> clom.getTarget(policy)).hasMessage(
439             "Target in the onset event is either null or does not match target key expected in AAI section.");
440
441         onsetEvent.setTarget("Oz");
442         onsetEvent.getAai().remove(VNF_NAME);
443         onsetEvent.getAai().remove(VNF_ID);
444         onsetEvent.getAai().remove(VSERVER_NAME);
445
446         policy.getTarget().setType(TargetType.VNF);
447         assertThatThrownBy(() -> clom.getTarget(policy))
448             .hasMessage("Target does not match target type");
449
450         onsetEvent.setTarget(VSERVER_NAME);
451         onsetEvent.getAai().put(VSERVER_NAME, "OzVServer");
452         assertEquals("OzVServer", clom.getTarget(policy));
453
454         onsetEvent.getAai().remove(VSERVER_NAME);
455         onsetEvent.setTarget(VNF_ID);
456         onsetEvent.getAai().put(VNF_ID, OZ_VNF);
457         assertEquals(OZ_VNF, clom.getTarget(policy));
458
459         onsetEvent.setTarget(VNF_NAME);
460         assertEquals(OZ_VNF, clom.getTarget(policy));
461
462         manager.onNewEvent(onsetEvent);
463
464         policy.getTarget().setType(TargetType.VFC);
465         assertThatThrownBy(() -> clom.getTarget(policy))
466             .hasMessage("The target type is not supported");
467
468         assertEquals(Integer.valueOf(20), clom.getOperationTimeout());
469
470         assertEquals("20s", clom.getOperationTimeoutString(100));
471
472         assertEquals(null, clom.getOperationMessage());
473         assertEquals(null, clom.getOperationMessage(OPER_MSG));
474
475         clom.startOperation(onsetEvent);
476
477         assertEquals(
478             "actor=SO,operation=Restart,target=Target [type=VFC, resourceId=null],subRequestId=1",
479             clom.getOperationMessage());
480         assertEquals(
481             "actor=SO,operation=Restart,target=Target [type=VFC, resourceId=null],subRequestId=1, Guard result: "
482                 + OPER_MSG,
483             clom.getOperationMessage(OPER_MSG));
484
485         assertEquals("actor=SO,operation=Restart,tar", clom.getOperationHistory().substring(0, 30));
486
487         clom.setOperationHasException("The Wizard is gone");
488         clom.setOperationHasGuardDeny();
489     }
490
491     @Test
492     public void testConstructor() throws IOException, ControlLoopException, AaiException {
493         InputStream is = new FileInputStream(new File(TEST_YAML));
494         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
495
496         UUID requestId = UUID.randomUUID();
497         VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
498         onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST);
499         onsetEvent.setRequestId(requestId);
500         onsetEvent.setTarget(VNF_ID);
501         onsetEvent.setTargetType(ControlLoopTargetType.VNF);
502         onsetEvent.setClosedLoopAlarmStart(Instant.now());
503         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
504         onsetEvent.setAai(new HashMap<>());
505         onsetEvent.getAai().put(VNF_NAME, ONSET_ONE);
506         onsetEvent.getAai().put(VSERVER_NAME, "OzVServer");
507
508         ControlLoopEventManager manager = new ControlLoopEventManager(
509             onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId());
510         VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent);
511         assertNotNull(notification);
512         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
513
514         Policy policy = manager.getProcessor().getCurrentPolicy();
515         ControlLoopOperationManager clom =
516             new ControlLoopOperationManager(onsetEvent, policy, manager);
517         assertNotNull(clom);
518
519         policy.setRecipe("ModifyConfig");
520         onsetEvent.getAai().put(VSERVER_NAME, "NonExistentVserver");
521         policy.getTarget().setResourceID(UUID.randomUUID().toString());
522         assertThatThrownBy(() -> new ControlLoopOperationManager(onsetEvent, policy, manager))
523             .hasMessage("Target vnf-id could not be found");
524
525         onsetEvent.getAai().put(VSERVER_NAME, "testVserverName");
526         policy.getTarget().setResourceID("bbb3cefd-01c8-413c-9bdd-2b92f9ca3d38");
527         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
528         assertNotNull(clom);
529
530         policy.setActor("SO");
531         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
532         assertNotNull(clom);
533
534         policy.setActor("VFC");
535         clom = new ControlLoopOperationManager(onsetEvent, policy, manager);
536         assertNotNull(clom);
537
538         policy.setActor(DOROTHY);
539         assertThatThrownBy(() -> new ControlLoopOperationManager(onsetEvent, policy, manager))
540             .hasMessage("ControlLoopEventManager: policy has an unknown actor.");
541     }
542
543     @Test
544     public void testStartOperation() throws IOException, ControlLoopException, AaiException {
545         InputStream is = new FileInputStream(new File(TEST_YAML));
546         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
547
548         UUID requestId = UUID.randomUUID();
549         VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
550         onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST);
551         onsetEvent.setRequestId(requestId);
552         onsetEvent.setTarget(VNF_ID);
553         onsetEvent.setTargetType(ControlLoopTargetType.VNF);
554         onsetEvent.setClosedLoopAlarmStart(Instant.now());
555         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
556         onsetEvent.setAai(new HashMap<>());
557         onsetEvent.getAai().put(VNF_NAME, ONSET_ONE);
558         onsetEvent.getAai().put(VSERVER_NAME, "testVserverName");
559
560         ControlLoopEventManager manager = new ControlLoopEventManager(
561             onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId());
562         VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent);
563         assertNotNull(notification);
564         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
565
566         Policy policy = manager.getProcessor().getCurrentPolicy();
567         ControlLoopOperationManager clom =
568             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 = new ControlLoopEventManager(
652             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 =
659             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 = new ControlLoopEventManager(
750             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 =
757             new ControlLoopOperationManager(onsetEvent, policy, manager);
758         assertNotNull(clom);
759
760         clom.startOperation(onsetEvent);
761
762         SoResponse soResponse = new SoResponse();
763         final SoResponseWrapper soRw = new SoResponseWrapper(soResponse, null);
764
765         PolicyEngineConstants.getManager().setEnvironmentProperty("guard.disabled", "false");
766         PolicyEngineConstants.getManager().setEnvironmentProperty(
767             org.onap.policy.guard.Util.ONAP_KEY_URL, "http://somewhere.over.the.rainbow");
768         PolicyEngineConstants.getManager()
769             .setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_USER, DOROTHY);
770         PolicyEngineConstants.getManager()
771             .setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_PASS, "Toto");
772
773         assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw));
774
775         System.setProperty(OPERATIONS_HISTORY_PU, OPERATIONS_HISTORY_PU_TEST);
776         assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw));
777     }
778
779     @Test
780     public void testStartCdsOperation() throws ControlLoopException, IOException {
781
782         // Prepare
783         String yamlString;
784         try (InputStream is = new FileInputStream(new File(TEST_CDS_YAML))) {
785             yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
786         }
787
788         UUID requestId = UUID.randomUUID();
789         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
790         event.setClosedLoopControlName(TWO_ONSET_TEST);
791         event.setRequestId(requestId);
792         event.setTarget(VNF_ID);
793         event.setTargetType(ControlLoopTargetType.VNF);
794         event.setClosedLoopAlarmStart(Instant.now());
795         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
796         event.setAai(new HashMap<>());
797         event.getAai().put(VNF_NAME, ONSET_ONE);
798         event.getAai().put(VSERVER_NAME, "OzVServer");
799
800         ControlLoopEventManager eventManager =
801             new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestId());
802         VirtualControlLoopNotification notification = eventManager.activate(yamlString, event);
803         assertNotNull(notification);
804         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
805
806         Policy policy = eventManager.getProcessor().getCurrentPolicy();
807         ControlLoopOperationManager operationManager =
808             new ControlLoopOperationManager(event, policy, eventManager);
809
810         // Run
811         Object result = operationManager.startOperation(event);
812
813         // Verify
814         assertNotNull(result);
815         assertTrue(result instanceof ExecutionServiceInput);
816         ExecutionServiceInput request = (ExecutionServiceInput) result;
817         logger.debug("request: " + request);
818
819     }
820
821     @Test
822     public void testCommitAbatement() throws Exception {
823
824         String yamlString;
825         try (InputStream is = new FileInputStream(new File(TEST_YAML))) {
826             yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
827         }
828
829         UUID requestId = UUID.randomUUID();
830         VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
831         onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST);
832         onsetEvent.setRequestId(requestId);
833         onsetEvent.setTarget(VNF_ID);
834         onsetEvent.setTargetType(ControlLoopTargetType.VNF);
835         onsetEvent.setClosedLoopAlarmStart(Instant.now());
836         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
837         onsetEvent.setAai(new HashMap<>());
838         onsetEvent.getAai().put(VNF_NAME, ONSET_ONE);
839         onsetEvent.getAai().put(VSERVER_NAME, "testVserverName");
840
841         ControlLoopEventManager manager = new ControlLoopEventManager(
842             onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId());
843         VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent);
844         assertNotNull(notification);
845         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
846
847         Policy policy = manager.getProcessor().getCurrentPolicy();
848         ControlLoopOperationManager clom =
849             new ControlLoopOperationManager(onsetEvent, policy, manager);
850         assertNotNull(clom);
851
852         clom.startOperation(onsetEvent);
853
854         int numEventsBefore = getCount();
855         logger.info("numEventsBefore={}", numEventsBefore);
856
857         clom.commitAbatement("Test message", "TEST_RESULT");
858
859         int numEventsAfter = getCount();
860         logger.info("numEventsAfter={}", numEventsAfter);
861
862         int diff = numEventsAfter - numEventsBefore;
863         assertEquals(1, diff);
864     }
865
866     @Test
867     public void testSerialization() throws Exception {
868         InputStream is = new FileInputStream(new File(TEST_YAML));
869         final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
870
871         UUID requestId = UUID.randomUUID();
872         VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
873         onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST);
874         onsetEvent.setRequestId(requestId);
875         onsetEvent.setTarget(VNF_ID);
876         onsetEvent.setTargetType(ControlLoopTargetType.VNF);
877         onsetEvent.setClosedLoopAlarmStart(Instant.now());
878         onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
879         onsetEvent.setAai(new HashMap<>());
880         onsetEvent.getAai().put(VNF_NAME, ONSET_ONE);
881         onsetEvent.getAai().put(VSERVER_NAME, "testVserverName");
882
883         ControlLoopEventManager manager = new ControlLoopEventManager(
884             onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId());
885         VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent);
886         assertNotNull(notification);
887         assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
888
889         Policy policy = manager.getProcessor().getCurrentPolicy();
890         ControlLoopOperationManager clom =
891             new ControlLoopOperationManager(onsetEvent, policy, manager);
892         assertNotNull(clom);
893
894         clom.startOperation(onsetEvent);
895         assertTrue(clom.isOperationRunning());
896
897         clom = Serializer.roundTrip(clom);
898         assertNotNull(clom);
899         assertTrue(clom.isOperationRunning());
900
901         SoResponse soResponse = new SoResponse();
902         final SoResponseWrapper soRw = new SoResponseWrapper(soResponse, null);
903
904         PolicyEngineConstants.getManager().setEnvironmentProperty("guard.disabled", "false");
905         PolicyEngineConstants.getManager().setEnvironmentProperty(
906             org.onap.policy.guard.Util.ONAP_KEY_URL, "http://somewhere.over.the.rainbow");
907         PolicyEngineConstants.getManager()
908             .setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_USER, DOROTHY);
909         PolicyEngineConstants.getManager()
910             .setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_PASS, "Toto");
911
912         assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw));
913         assertFalse(clom.isOperationRunning());
914         assertEquals(1, clom.getHistory().size());
915
916         clom = Serializer.roundTrip(clom);
917         assertNotNull(clom);
918         assertFalse(clom.isOperationRunning());
919         assertEquals(1, clom.getHistory().size());
920
921         System.setProperty(OPERATIONS_HISTORY_PU, OPERATIONS_HISTORY_PU_TEST);
922         assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw));
923
924         clom = Serializer.roundTrip(clom);
925         assertNotNull(clom);
926         assertFalse(clom.isOperationRunning());
927         assertEquals(1, clom.getHistory().size());
928     }
929 }