2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.template.demo;
23 import static org.junit.Assert.*;
25 import java.io.IOException;
26 import java.net.URLEncoder;
27 import java.time.Instant;
28 import java.util.HashMap;
29 import java.util.UUID;
31 import org.junit.AfterClass;
32 import org.junit.BeforeClass;
33 import org.junit.Test;
34 import org.kie.api.runtime.KieSession;
35 import org.kie.api.runtime.rule.FactHandle;
36 import org.onap.policy.appc.Request;
37 import org.onap.policy.appc.Response;
38 import org.onap.policy.appc.ResponseCode;
39 import org.onap.policy.controlloop.ControlLoopEventStatus;
40 import org.onap.policy.controlloop.ControlLoopNotificationType;
41 import org.onap.policy.controlloop.VirtualControlLoopEvent;
42 import org.onap.policy.controlloop.VirtualControlLoopNotification;
43 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
44 import org.onap.policy.controlloop.policy.TargetType;
45 import org.onap.policy.drools.http.server.HttpServletServer;
46 import org.onap.policy.drools.impl.PolicyEngineJUnitImpl;
47 import org.onap.policy.guard.PolicyGuard;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
51 public class VFWControlLoopTest {
53 private static final Logger logger = LoggerFactory.getLogger(VFWControlLoopTest.class);
55 private KieSession kieSession;
56 private Util.Pair<ControlLoopPolicy, String> pair;
57 private PolicyEngineJUnitImpl engine;
60 public static void setUpSimulator() {
63 } catch (InterruptedException e) {
69 public static void tearDownSimulator() {
70 HttpServletServer.factory.destroy();
74 public void successTest() {
77 * Start the kie session
80 kieSession = startSession("src/main/resources/ControlLoop_Template_xacml_guard.drl",
81 "src/test/resources/yaml/policy_ControlLoop_vFW.yaml",
82 "service=ServiceDemo;resource=Res1Demo;type=operational",
84 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
85 } catch (IOException e) {
87 logger.debug("Could not create kieSession");
88 fail("Could not create kieSession");
92 * Create a thread to continuously fire rules
93 * until main thread calls halt
95 new Thread( new Runnable() {
98 kieSession.fireUntilHalt();
103 * Create a unique requestId and a unique trigger source
105 UUID requestID = UUID.randomUUID();
106 String triggerSourceName = "foobartriggersource36";
109 * This will be the object returned from the PolicyEngine
114 * Simulate an onset event the policy engine will
115 * receive from DCAE to kick off processing through
119 sendOnset(pair.a, requestID, triggerSourceName);
120 } catch (InterruptedException e) {
122 logger.debug("Unable to send onset event");
123 fail("Unable to send onset event");
127 * Pull the object that was sent out to DMAAP and make
128 * sure it is a ControlLoopNoticiation of type active
130 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
132 assertTrue(obj instanceof VirtualControlLoopNotification);
133 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.ACTIVE));
136 * Give the control loop time to acquire a lock
140 } catch (InterruptedException e) {
142 logger.debug("An interrupt Exception was thrown");
143 fail("An interrupt Exception was thrown");
147 * The fact should be ready to query guard now to see
148 * if a ModifyConfig recipe is allowed
150 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
152 logger.debug("\n\n####################### GOING TO QUERY GUARD about ModifyConfig!!!!!!");
153 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
156 * Make sure the object is an instance of a ControlLoopNotification
157 * and is of type operation
159 assertTrue(obj instanceof VirtualControlLoopNotification);
160 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
164 } catch (InterruptedException e) {
166 logger.debug("An interrupt Exception was thrown");
167 fail("An interrupt Exception was thrown");
171 * The guard response should be received at this point
173 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
175 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
178 * The object should be a ControlLoopNotification with type operation
180 assertTrue(obj instanceof VirtualControlLoopNotification);
181 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
184 * See if Guard permits this action, if it does
185 * not then the test should fail
187 if (((VirtualControlLoopNotification)obj).message.contains("Guard result: Permit")) {
190 * Obtain the ControlLoopNoticiation, it should be of type operation
192 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
194 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
197 * A notification should be sent out of the Policy
198 * Engine at this point, it will be of type operation
200 assertTrue(obj instanceof VirtualControlLoopNotification);
201 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
205 } catch (InterruptedException e) {
207 logger.debug("An interrupt Exception was thrown");
208 fail("An interrupt Exception was thrown");
212 * Obtain the request sent from the Policy Engine
214 obj = engine.subscribe("UEB", "APPC-CL");
218 * The request should be of type Request
219 * and the subrequestid should be 1
221 assertTrue(obj instanceof Request);
222 assertTrue(((Request)obj).getCommonHeader().SubRequestID.equals("1"));
224 logger.debug("\n============ APPC received the request!!! ===========\n");
227 * Give some time for processing
231 } catch (InterruptedException e) {
233 logger.debug("An interrupt Exception was thrown");
234 fail("An interrupt Exception was thrown");
238 * Simulate a success response from APPC and insert
239 * the response into the working memory
241 Response appcResponse = new Response((Request)obj);
242 appcResponse.getStatus().Code = ResponseCode.SUCCESS.getValue();
243 appcResponse.getStatus().Description = "AppC success";
244 kieSession.insert(appcResponse);
247 * Give time for processing
251 } catch (InterruptedException e) {
253 logger.debug("An interrupt Exception was thrown");
254 fail("An interrupt Exception was thrown");
258 * Make sure the next notification is delivered
260 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
262 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
265 * The ControlLoopNotification should be
266 * an OPERATION_SUCCESS
268 assertTrue(obj instanceof VirtualControlLoopNotification);
269 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION_SUCCESS));
272 * Now simulate the abatement sent from DCAE
275 sendAbatement(pair.a, requestID, triggerSourceName);
276 } catch (InterruptedException e1) {
277 e1.printStackTrace();
278 logger.debug("Abatement could not be sent");
279 fail("Abatement could not be sent");
283 * Give time to finish processing
287 } catch (InterruptedException e) {
289 logger.debug("An interrupt Exception was thrown");
290 fail("An interrupt Exception was thrown");
294 * This should be the final notification from the Policy Engine
296 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
298 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
301 * The ControlLoopNotification should be of type FINAL_SUCCESS
303 assertTrue(obj instanceof VirtualControlLoopNotification);
304 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.FINAL_SUCCESS));
307 * One final check to make sure the lock is released
309 assertFalse(PolicyGuard.isLocked(TargetType.VNF, triggerSourceName, requestID));
312 fail("Operation Denied by Guard");
316 * This will stop the thread that is firing the rules
321 * The only fact in memory should be Params
323 assertEquals(1, kieSession.getFactCount());
326 * Print what's left in memory
328 dumpFacts(kieSession);
331 * Gracefully shut down the kie session
333 kieSession.dispose();
337 * This method will start a kie session and instantiate
340 * @param droolsTemplate
343 * the yaml file containing the policies
348 * @param policyVersion
349 * version of the policy
350 * @return the kieSession to be used to insert facts
351 * @throws IOException
353 private KieSession startSession(String droolsTemplate,
357 String policyVersion) throws IOException {
360 * Load policies from yaml
362 pair = Util.loadYaml(yamlFile);
364 assertNotNull(pair.a);
365 assertNotNull(pair.a.getControlLoop());
366 assertNotNull(pair.a.getControlLoop().getControlLoopName());
367 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
370 * Construct a kie session
372 final KieSession kieSession = Util.buildContainer(droolsTemplate,
373 pair.a.getControlLoop().getControlLoopName(),
377 URLEncoder.encode(pair.b, "UTF-8"));
380 * Retrieve the Policy Engine
382 engine = (PolicyEngineJUnitImpl) kieSession.getGlobal("Engine");
384 logger.debug("============");
385 logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
386 logger.debug("============");
392 * This method is used to simulate event messages from DCAE
393 * that start the control loop (onset message).
395 * @param policy the controlLoopName comes from the policy
396 * @param requestID the requestId for this event
397 * @param triggerSourceName
398 * @throws InterruptedException
400 protected void sendOnset(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
401 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
402 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
403 event.requestID = requestID;
404 event.target = "generic-vnf.vnf-id";
405 event.closedLoopAlarmStart = Instant.now();
406 event.AAI = new HashMap<>();
407 event.AAI.put("cloud-region.identity-url", "foo");
408 event.AAI.put("vserver.selflink", "bar");
409 event.AAI.put("vserver.is-closed-loop-disabled", "false");
410 event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
411 event.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
412 kieSession.insert(event);
417 * This method is used to simulate event messages from DCAE
418 * that end the control loop (abatement message).
420 * @param policy the controlLoopName comes from the policy
421 * @param requestID the requestId for this event
422 * @param triggerSourceName
423 * @throws InterruptedException
425 protected void sendAbatement(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
426 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
427 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
428 event.requestID = requestID;
429 event.target = "generic-vnf.vnf-id";
430 event.closedLoopAlarmStart = Instant.now().minusSeconds(5);
431 event.closedLoopAlarmEnd = Instant.now();
432 event.AAI = new HashMap<>();
433 event.AAI.put("cloud-region.identity-url", "foo");
434 event.AAI.put("vserver.selflink", "bar");
435 event.AAI.put("vserver.is-closed-loop-disabled", "false");
436 event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
437 event.closedLoopEventStatus = ControlLoopEventStatus.ABATED;
438 kieSession.insert(event);
442 * This method will dump all the facts in the working memory.
444 * @param kieSession the session containing the facts
446 public void dumpFacts(KieSession kieSession) {
447 logger.debug("Fact Count: {}", kieSession.getFactCount());
448 for (FactHandle handle : kieSession.getFactHandles()) {
449 logger.debug("FACT: {}", handle);