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