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.drools.system.PolicyEngine;
48 import org.onap.policy.guard.PolicyGuard;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
52 public class VFWControlLoopTest {
54 private static final Logger logger = LoggerFactory.getLogger(VFWControlLoopTest.class);
56 private KieSession kieSession;
57 private Util.Pair<ControlLoopPolicy, String> pair;
58 private PolicyEngineJUnitImpl engine;
61 /* Set environment properties */
66 public static void setUpSimulator() {
69 } catch (Exception e) {
75 public static void tearDownSimulator() {
76 HttpServletServer.factory.destroy();
80 public void successTest() {
83 * Start the kie session
86 kieSession = startSession("src/main/resources/ControlLoop_Template_xacml_guard.drl",
87 "src/test/resources/yaml/policy_ControlLoop_vFW.yaml",
88 "service=ServiceDemo;resource=Res1Demo;type=operational",
90 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
91 } catch (IOException e) {
93 logger.debug("Could not create kieSession");
94 fail("Could not create kieSession");
98 * Create a thread to continuously fire rules
99 * until main thread calls halt
101 new Thread( new Runnable() {
104 kieSession.fireUntilHalt();
109 * Create a unique requestId and a unique trigger source
111 UUID requestID = UUID.randomUUID();
112 String triggerSourceName = "foobartriggersource36";
115 * This will be the object returned from the PolicyEngine
120 * Simulate an onset event the policy engine will
121 * receive from DCAE to kick off processing through
125 sendOnset(pair.a, requestID, triggerSourceName);
126 } catch (InterruptedException e) {
128 logger.debug("Unable to send onset event");
129 fail("Unable to send onset event");
133 * Pull the object that was sent out to DMAAP and make
134 * sure it is a ControlLoopNoticiation of type active
136 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
138 assertTrue(obj instanceof VirtualControlLoopNotification);
139 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.ACTIVE));
142 * Give the control loop time to acquire a lock
146 } catch (InterruptedException e) {
148 logger.debug("An interrupt Exception was thrown");
149 fail("An interrupt Exception was thrown");
153 * The fact should be ready to query guard now to see
154 * if a ModifyConfig recipe is allowed
156 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
158 logger.debug("\n\n####################### GOING TO QUERY GUARD about ModifyConfig!!!!!!");
159 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
162 * Make sure the object is an instance of a ControlLoopNotification
163 * and is of type operation
165 assertTrue(obj instanceof VirtualControlLoopNotification);
166 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
170 } catch (InterruptedException e) {
172 logger.debug("An interrupt Exception was thrown");
173 fail("An interrupt Exception was thrown");
177 * The guard response should be received at this point
179 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
181 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
184 * The object should be a ControlLoopNotification with type operation
186 assertTrue(obj instanceof VirtualControlLoopNotification);
187 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
190 * See if Guard permits this action, if it does
191 * not then the test should fail
193 if (((VirtualControlLoopNotification)obj).message.contains("Guard result: Permit")) {
196 * Obtain the ControlLoopNoticiation, it should be of type operation
198 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
200 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
203 * A notification should be sent out of the Policy
204 * Engine at this point, it will be of type operation
206 assertTrue(obj instanceof VirtualControlLoopNotification);
207 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
211 } catch (InterruptedException e) {
213 logger.debug("An interrupt Exception was thrown");
214 fail("An interrupt Exception was thrown");
218 * Obtain the request sent from the Policy Engine
220 obj = engine.subscribe("UEB", "APPC-CL");
224 * The request should be of type Request
225 * and the subrequestid should be 1
227 assertTrue(obj instanceof Request);
228 assertTrue(((Request)obj).getCommonHeader().SubRequestID.equals("1"));
230 logger.debug("\n============ APPC received the request!!! ===========\n");
233 * Give some time for processing
237 } catch (InterruptedException e) {
239 logger.debug("An interrupt Exception was thrown");
240 fail("An interrupt Exception was thrown");
244 * Simulate a success response from APPC and insert
245 * the response into the working memory
247 Response appcResponse = new Response((Request)obj);
248 appcResponse.getStatus().Code = ResponseCode.SUCCESS.getValue();
249 appcResponse.getStatus().Value = "SUCCESS";
250 kieSession.insert(appcResponse);
253 * Give time for processing
257 } catch (InterruptedException e) {
259 logger.debug("An interrupt Exception was thrown");
260 fail("An interrupt Exception was thrown");
264 * Make sure the next notification is delivered
266 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
268 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
271 * The ControlLoopNotification should be
272 * an OPERATION_SUCCESS
274 assertTrue(obj instanceof VirtualControlLoopNotification);
275 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION_SUCCESS));
278 * Now simulate the abatement sent from DCAE
281 sendAbatement(pair.a, requestID, triggerSourceName);
282 } catch (InterruptedException e1) {
283 e1.printStackTrace();
284 logger.debug("Abatement could not be sent");
285 fail("Abatement could not be sent");
289 * Give time to finish processing
293 } catch (InterruptedException e) {
295 logger.debug("An interrupt Exception was thrown");
296 fail("An interrupt Exception was thrown");
300 * This should be the final notification from the Policy Engine
302 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
304 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
307 * The ControlLoopNotification should be of type FINAL_SUCCESS
309 assertTrue(obj instanceof VirtualControlLoopNotification);
310 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.FINAL_SUCCESS));
313 * One final check to make sure the lock is released
315 assertFalse(PolicyGuard.isLocked(TargetType.VNF, triggerSourceName, requestID));
318 fail("Operation Denied by Guard");
322 * This will stop the thread that is firing the rules
327 * The only fact in memory should be Params
329 assertEquals(1, kieSession.getFactCount());
332 * Print what's left in memory
334 dumpFacts(kieSession);
337 * Gracefully shut down the kie session
339 kieSession.dispose();
343 * This method will start a kie session and instantiate
346 * @param droolsTemplate
349 * the yaml file containing the policies
354 * @param policyVersion
355 * version of the policy
356 * @return the kieSession to be used to insert facts
357 * @throws IOException
359 private KieSession startSession(String droolsTemplate,
363 String policyVersion) throws IOException {
366 * Load policies from yaml
368 pair = Util.loadYaml(yamlFile);
370 assertNotNull(pair.a);
371 assertNotNull(pair.a.getControlLoop());
372 assertNotNull(pair.a.getControlLoop().getControlLoopName());
373 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
376 * Construct a kie session
378 final KieSession kieSession = Util.buildContainer(droolsTemplate,
379 pair.a.getControlLoop().getControlLoopName(),
383 URLEncoder.encode(pair.b, "UTF-8"));
386 * Retrieve the Policy Engine
388 engine = (PolicyEngineJUnitImpl) kieSession.getGlobal("Engine");
390 logger.debug("============");
391 logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
392 logger.debug("============");
398 * This method is used to simulate event messages from DCAE
399 * that start the control loop (onset message).
401 * @param policy the controlLoopName comes from the policy
402 * @param requestID the requestId for this event
403 * @param triggerSourceName
404 * @throws InterruptedException
406 protected void sendOnset(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
407 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
408 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
409 event.requestID = requestID;
410 event.target = "generic-vnf.vnf-id";
411 event.closedLoopAlarmStart = Instant.now();
412 event.AAI = new HashMap<>();
413 event.AAI.put("cloud-region.identity-url", "foo");
414 event.AAI.put("vserver.selflink", "bar");
415 event.AAI.put("vserver.is-closed-loop-disabled", "false");
416 event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
417 event.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
418 kieSession.insert(event);
423 * This method is used to simulate event messages from DCAE
424 * that end the control loop (abatement message).
426 * @param policy the controlLoopName comes from the policy
427 * @param requestID the requestId for this event
428 * @param triggerSourceName
429 * @throws InterruptedException
431 protected void sendAbatement(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
432 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
433 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
434 event.requestID = requestID;
435 event.target = "generic-vnf.vnf-id";
436 event.closedLoopAlarmStart = Instant.now().minusSeconds(5);
437 event.closedLoopAlarmEnd = Instant.now();
438 event.AAI = new HashMap<>();
439 event.AAI.put("cloud-region.identity-url", "foo");
440 event.AAI.put("vserver.selflink", "bar");
441 event.AAI.put("vserver.is-closed-loop-disabled", "false");
442 event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
443 event.closedLoopEventStatus = ControlLoopEventStatus.ABATED;
444 kieSession.insert(event);
448 * This method will dump all the facts in the working memory.
450 * @param kieSession the session containing the facts
452 public void dumpFacts(KieSession kieSession) {
453 logger.debug("Fact Count: {}", kieSession.getFactCount());
454 for (FactHandle handle : kieSession.getFactHandles()) {
455 logger.debug("FACT: {}", handle);