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