a27dbd026743431fd6022d47644c63015e72e7df
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * demo
4  * ================================================================================
5  * Copyright (C) 2017-2018 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.template.demo;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertTrue;
26 import static org.junit.Assert.fail;
27
28 import java.io.IOException;
29 import java.net.URLEncoder;
30 import java.time.Instant;
31 import java.util.HashMap;
32 import java.util.List;
33 import java.util.Properties;
34 import java.util.UUID;
35
36 import org.junit.AfterClass;
37 import org.junit.BeforeClass;
38 import org.junit.Test;
39 import org.kie.api.runtime.KieSession;
40 import org.kie.api.runtime.rule.FactHandle;
41 import org.onap.policy.appclcm.LcmRequest;
42 import org.onap.policy.appclcm.LcmRequestWrapper;
43 import org.onap.policy.appclcm.LcmResponse;
44 import org.onap.policy.appclcm.LcmResponseWrapper;
45 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
46 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
47 import org.onap.policy.common.endpoints.event.comm.TopicListener;
48 import org.onap.policy.common.endpoints.event.comm.TopicSink;
49 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
50 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
51 import org.onap.policy.controlloop.ControlLoopEventStatus;
52 import org.onap.policy.controlloop.ControlLoopNotificationType;
53 import org.onap.policy.controlloop.ControlLoopTargetType;
54 import org.onap.policy.controlloop.VirtualControlLoopEvent;
55 import org.onap.policy.controlloop.VirtualControlLoopNotification;
56 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
57 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
58 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
59 import org.onap.policy.drools.system.PolicyController;
60 import org.onap.policy.drools.system.PolicyEngine;
61 import org.onap.policy.drools.utils.logging.LoggerUtil;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64
65 public class VcpeControlLoopTest implements TopicListener {
66
67     private static final Logger logger = LoggerFactory.getLogger(VcpeControlLoopTest.class);
68
69     private static List<? extends TopicSink> noopTopics;
70
71     private static KieSession kieSession;
72     private static Util.Pair<ControlLoopPolicy, String> pair;
73     private UUID requestId;
74
75     static {
76         /* Set environment properties */
77         Util.setAaiProps();
78         Util.setGuardProps();
79         Util.setPuProp();
80         LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
81     }
82
83     /**
84      * Setup the simulator.
85      */
86     @BeforeClass
87     public static void setUpSimulator() {
88         PolicyEngine.manager.configure(new Properties());
89         assertTrue(PolicyEngine.manager.start());
90         Properties noopSinkProperties = new Properties();
91         noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-LCM-READ,POLICY-CL-MGT");
92         noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events", "org.onap.policy.appclcm.LcmRequestWrapper");
93         noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events.custom.gson",
94                 "org.onap.policy.appclcm.util.Serialization,gson");
95         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
96                 "org.onap.policy.controlloop.VirtualControlLoopNotification");
97         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
98                 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
99         noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
100
101         EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT",
102                 "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null,
103                 1111);
104         EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-LCM-READ",
105                 "org.onap.policy.appclcm.LcmRequestWrapper", new JsonProtocolFilter(), null, null, 1111);
106         try {
107             Util.buildAaiSim();
108             Util.buildGuardSim();
109         } catch (Exception e) {
110             fail(e.getMessage());
111         }
112         /*
113          * Start the kie session
114          */
115         try {
116             kieSession = startSession(
117                     "../archetype-cl-amsterdam/src/main/resources/archetype-resources"
118                     + "/src/main/resources/__closedLoopControlName__.drl",
119                     "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml",
120                     "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vCPE",
121                     "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
122         } catch (IOException e) {
123             e.printStackTrace();
124             logger.debug("Could not create kieSession");
125             fail("Could not create kieSession");
126         }
127     }
128
129     /**
130      * Tear down the simulator.
131      */
132     @AfterClass
133     public static void tearDownSimulator() {
134         /*
135          * Gracefully shut down the kie session
136          */
137         kieSession.dispose();
138
139         PolicyEngine.manager.stop();
140         HttpServletServer.factory.destroy();
141         PolicyController.factory.shutdown();
142         TopicEndpoint.manager.shutdown();
143     }
144
145     @Test
146     public void successTest() {
147
148         /*
149          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
150          * to be pulled from the queue
151          */
152         for (TopicSink sink : noopTopics) {
153             assertTrue(sink.start());
154             sink.register(this);
155         }
156
157         /*
158          * Create a unique requestId
159          */
160         requestId = UUID.randomUUID();
161
162         /*
163          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
164          * through the rules
165          */
166         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "vCPEInfraVNF13", true);
167
168         kieSession.fireUntilHalt();
169         
170         // allow object clean-up
171         kieSession.fireAllRules();
172
173         /*
174          * The only fact in memory should be Params
175          */
176         assertEquals(1, kieSession.getFactCount());
177
178         /*
179          * Print what's left in memory
180          */
181         dumpFacts(kieSession);
182     }
183
184     @Test
185     public void aaiGetFailTest() {
186
187         /*
188          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
189          * to be pulled from the queue
190          */
191         for (TopicSink sink : noopTopics) {
192             assertTrue(sink.start());
193             sink.register(this);
194         }
195
196         /*
197          * Create a unique requestId
198          */
199         requestId = UUID.randomUUID();
200
201         /*
202          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
203          * through the rules
204          */
205         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail", false);
206
207
208         kieSession.fireUntilHalt();
209         
210         // allow object clean-up
211         kieSession.fireAllRules();
212
213         /*
214          * The only fact in memory should be Params
215          */
216         assertEquals(1, kieSession.getFactCount());
217
218         /*
219          * Print what's left in memory
220          */
221         dumpFacts(kieSession);
222
223     }
224
225     /**
226      * This method will start a kie session and instantiate the Policy Engine.
227      * 
228      * @param droolsTemplate the DRL rules file
229      * @param yamlFile the yaml file containing the policies
230      * @param policyScope scope for policy
231      * @param policyName name of the policy
232      * @param policyVersion version of the policy
233      * @return the kieSession to be used to insert facts
234      * @throws IOException IO exception
235      */
236     private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
237             String policyName, String policyVersion) throws IOException {
238
239         /*
240          * Load policies from yaml
241          */
242         pair = Util.loadYaml(yamlFile);
243         assertNotNull(pair);
244         assertNotNull(pair.first);
245         assertNotNull(pair.first.getControlLoop());
246         assertNotNull(pair.first.getControlLoop().getControlLoopName());
247         assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
248
249         /*
250          * Construct a kie session
251          */
252         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
253                 pair.first.getControlLoop().getControlLoopName(),
254                 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
255
256         /*
257          * Retrieve the Policy Engine
258          */
259
260         logger.debug("============");
261         logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
262         logger.debug("============");
263
264         return kieSession;
265     }
266
267     /*
268      * (non-Javadoc)
269      * 
270      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
271      */
272     @Override
273     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
274         /*
275          * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
276          * of type active
277          */
278         Object obj = null;
279         if ("POLICY-CL-MGT".equals(topic)) {
280             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
281                     org.onap.policy.controlloop.VirtualControlLoopNotification.class);
282         } else if ("APPC-LCM-READ".equals(topic)) {
283             obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event,
284                     org.onap.policy.appclcm.LcmRequestWrapper.class);
285         }
286         assertNotNull(obj);
287         if (obj instanceof VirtualControlLoopNotification) {
288             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
289             String policyName = notification.getPolicyName();
290             if (policyName.endsWith("EVENT")) {
291                 logger.debug("Rule Fired: " + notification.getPolicyName());
292                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
293             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
294                 logger.debug("Rule Fired: " + notification.getPolicyName());
295                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
296                 assertNotNull(notification.getMessage());
297                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
298             } else if (policyName.endsWith("GUARD.RESPONSE")) {
299                 logger.debug("Rule Fired: " + notification.getPolicyName());
300                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
301                 assertNotNull(notification.getMessage());
302                 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
303             } else if (policyName.endsWith("GUARD_PERMITTED")) {
304                 logger.debug("Rule Fired: " + notification.getPolicyName());
305                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
306                 assertNotNull(notification.getMessage());
307                 assertTrue(notification.getMessage().startsWith("actor=APPC"));
308             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
309                 logger.debug("Rule Fired: " + notification.getPolicyName());
310                 kieSession.halt();
311                 logger.debug("The operation timed out");
312                 fail("Operation Timed Out");
313             } else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
314                 logger.debug("Rule Fired: " + notification.getPolicyName());
315                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
316                 assertNotNull(notification.getMessage());
317                 assertTrue(notification.getMessage().startsWith("actor=APPC"));
318                 sendEvent(pair.first, requestId, ControlLoopEventStatus.ABATED);
319             } else if (policyName.endsWith("EVENT.MANAGER")) {
320                 logger.debug("Rule Fired: " + notification.getPolicyName());
321                 if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-name"))) {
322                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
323                     kieSession.halt();
324                 } else {
325                     assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
326                     kieSession.halt();
327                 }
328             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
329                 logger.debug("Rule Fired: " + notification.getPolicyName());
330                 kieSession.halt();
331                 logger.debug("The control loop timed out");
332                 fail("Control Loop Timed Out");
333             }
334         } else if (obj instanceof LcmRequestWrapper) {
335             /*
336              * The request should be of type LcmRequestWrapper and the subrequestid should be 1
337              */
338             LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) obj;
339             LcmRequest appcRequest = dmaapRequest.getBody();
340             assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
341             assertNotNull(appcRequest.getActionIdentifiers().get("vnf-id"));
342
343             logger.debug("\n============ APPC received the request!!! ===========\n");
344
345             /*
346              * Simulate a success response from APPC and insert the response into the working memory
347              */
348             LcmResponseWrapper dmaapResponse = new LcmResponseWrapper();
349             LcmResponse appcResponse = new LcmResponse(appcRequest);
350             appcResponse.getStatus().setCode(400);
351             appcResponse.getStatus().setMessage("AppC success");
352             dmaapResponse.setBody(appcResponse);
353             kieSession.insert(dmaapResponse);
354         }
355     }
356
357     /**
358      * This method is used to simulate event messages from DCAE that start the control loop (onset
359      * message) or end the control loop (abatement message).
360      * 
361      * @param policy the controlLoopName comes from the policy
362      * @param requestID the requestId for this event
363      * @param status could be onset or abated
364      */
365     protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
366         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
367         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
368         event.setRequestId(requestId);
369         event.setTarget("generic-vnf.vnf-name");
370         event.setClosedLoopAlarmStart(Instant.now());
371         event.setAai(new HashMap<>());
372         event.getAai().put("generic-vnf.vnf-name", "testGenericVnfName");
373         event.setClosedLoopEventStatus(status);
374         kieSession.insert(event);
375     }
376
377     protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status, String vnfName,
378             boolean isEnriched) {
379         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
380         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
381         event.setRequestId(requestId);
382         event.setTarget("generic-vnf.vnf-name");
383         event.setTargetType(ControlLoopTargetType.VNF);
384         event.setClosedLoopAlarmStart(Instant.now());
385         event.setAai(new HashMap<>());
386         event.getAai().put("generic-vnf.vnf-name", vnfName);
387         if (isEnriched) {
388             event.getAai().put("generic-vnf.in-maint", "false");
389             event.getAai().put("generic-vnf.is-closed-loop-disabled", "false");
390             event.getAai().put("generic-vnf.orchestration-status", "Created");
391             event.getAai().put("generic-vnf.prov-status", "ACTIVE");
392             event.getAai().put("generic-vnf.resource-version", "1");
393             event.getAai().put("generic-vnf.service-id", "e8cb8968-5411-478b-906a-f28747de72cd");
394             event.getAai().put("generic-vnf.vnf-id", "63b31229-9a3a-444f-9159-04ce2dca3be9");
395             event.getAai().put("generic-vnf.vnf-type", "vCPEInfraService10/vCPEInfraService10 0");
396         }
397         event.setClosedLoopEventStatus(status);
398         kieSession.insert(event);
399     }
400
401     /**
402      * This method will dump all the facts in the working memory.
403      * 
404      * @param kieSession the session containing the facts
405      */
406     public void dumpFacts(KieSession kieSession) {
407         logger.debug("Fact Count: {}", kieSession.getFactCount());
408         for (FactHandle handle : kieSession.getFactHandles()) {
409             logger.debug("FACT: {}", handle);
410         }
411     }
412
413 }