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.assertFalse;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertTrue;
26 import static org.junit.Assert.fail;
28 import java.io.IOException;
29 import java.net.URLEncoder;
30 import java.time.Instant;
31 import java.util.HashMap;
32 import java.util.UUID;
34 import org.junit.AfterClass;
35 import org.junit.BeforeClass;
36 import org.junit.Test;
37 import org.kie.api.runtime.KieSession;
38 import org.kie.api.runtime.rule.FactHandle;
39 import org.onap.policy.appc.Request;
40 import org.onap.policy.appc.Response;
41 import org.onap.policy.appc.ResponseCode;
42 import org.onap.policy.controlloop.ControlLoopEventStatus;
43 import org.onap.policy.controlloop.ControlLoopNotificationType;
44 import org.onap.policy.controlloop.VirtualControlLoopEvent;
45 import org.onap.policy.controlloop.VirtualControlLoopNotification;
46 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
47 import org.onap.policy.controlloop.policy.TargetType;
48 import org.onap.policy.drools.http.server.HttpServletServer;
49 import org.onap.policy.drools.impl.PolicyEngineJUnitImpl;
50 import org.onap.policy.guard.PolicyGuard;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
54 public class VFWControlLoopTest {
56 private static final Logger logger = LoggerFactory.getLogger(VFWControlLoopTest.class);
58 private KieSession kieSession;
59 private Util.Pair<ControlLoopPolicy, String> pair;
60 private PolicyEngineJUnitImpl engine;
63 /* Set environment properties */
68 public static void setUpSimulator() {
71 } catch (Exception e) {
77 public static void tearDownSimulator() {
78 HttpServletServer.factory.destroy();
82 public void successTest() {
85 * Start the kie session
88 kieSession = startSession("src/main/resources/ControlLoop_Template_xacml_guard.drl",
89 "src/test/resources/yaml/policy_ControlLoop_vFW.yaml",
90 "service=ServiceDemo;resource=Res1Demo;type=operational",
92 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
93 } catch (IOException e) {
95 logger.debug("Could not create kieSession");
96 fail("Could not create kieSession");
100 * Create a thread to continuously fire rules
101 * until main thread calls halt
103 new Thread( new Runnable() {
106 kieSession.fireUntilHalt();
111 * Create a unique requestId and a unique trigger source
113 UUID requestID = UUID.randomUUID();
114 String triggerSourceName = "foobartriggersource36";
117 * This will be the object returned from the PolicyEngine
122 * Simulate an onset event the policy engine will
123 * receive from DCAE to kick off processing through
127 sendOnset(pair.a, requestID, triggerSourceName);
128 } catch (InterruptedException e) {
130 logger.debug("Unable to send onset event");
131 fail("Unable to send onset event");
135 * Pull the object that was sent out to DMAAP and make
136 * sure it is a ControlLoopNoticiation of type active
138 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
140 assertTrue(obj instanceof VirtualControlLoopNotification);
141 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.ACTIVE));
144 * Give the control loop time to acquire a lock
148 } catch (InterruptedException e) {
150 logger.debug("An interrupt Exception was thrown");
151 fail("An interrupt Exception was thrown");
155 * The fact should be ready to query guard now to see
156 * if a ModifyConfig recipe is allowed
158 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
160 logger.debug("\n\n####################### GOING TO QUERY GUARD about ModifyConfig!!!!!!");
161 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
164 * Make sure the object is an instance of a ControlLoopNotification
165 * and is of type operation
167 assertTrue(obj instanceof VirtualControlLoopNotification);
168 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
172 } catch (InterruptedException e) {
174 logger.debug("An interrupt Exception was thrown");
175 fail("An interrupt Exception was thrown");
179 * The guard response should be received at this point
181 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
183 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
186 * The object should be a ControlLoopNotification with type operation
188 assertTrue(obj instanceof VirtualControlLoopNotification);
189 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
192 * See if Guard permits this action, if it does
193 * not then the test should fail
195 if (((VirtualControlLoopNotification)obj).message.contains("Guard result: Permit")) {
198 * Obtain the ControlLoopNoticiation, it should be of type operation
200 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
202 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
205 * A notification should be sent out of the Policy
206 * Engine at this point, it will be of type operation
208 assertTrue(obj instanceof VirtualControlLoopNotification);
209 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
213 } catch (InterruptedException e) {
215 logger.debug("An interrupt Exception was thrown");
216 fail("An interrupt Exception was thrown");
220 * Obtain the request sent from the Policy Engine
222 obj = engine.subscribe("UEB", "APPC-CL");
226 * The request should be of type Request
227 * and the subrequestid should be 1
229 assertTrue(obj instanceof Request);
230 assertTrue(((Request)obj).getCommonHeader().SubRequestID.equals("1"));
232 logger.debug("\n============ APPC received the request!!! ===========\n");
235 * Give some time for processing
239 } catch (InterruptedException e) {
241 logger.debug("An interrupt Exception was thrown");
242 fail("An interrupt Exception was thrown");
246 * Simulate a success response from APPC and insert
247 * the response into the working memory
249 Response appcResponse = new Response((Request)obj);
250 appcResponse.getStatus().Code = ResponseCode.SUCCESS.getValue();
251 appcResponse.getStatus().Value = "SUCCESS";
252 kieSession.insert(appcResponse);
255 * Give time for processing
259 } catch (InterruptedException e) {
261 logger.debug("An interrupt Exception was thrown");
262 fail("An interrupt Exception was thrown");
266 * Make sure the next notification is delivered
268 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
270 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
273 * The ControlLoopNotification should be
274 * an OPERATION_SUCCESS
276 assertTrue(obj instanceof VirtualControlLoopNotification);
277 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION_SUCCESS));
280 * Now simulate the abatement sent from DCAE
283 sendAbatement(pair.a, requestID, triggerSourceName);
284 } catch (InterruptedException e1) {
285 e1.printStackTrace();
286 logger.debug("Abatement could not be sent");
287 fail("Abatement could not be sent");
291 * Give time to finish processing
295 } catch (InterruptedException e) {
297 logger.debug("An interrupt Exception was thrown");
298 fail("An interrupt Exception was thrown");
302 * This should be the final notification from the Policy Engine
304 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
306 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
309 * The ControlLoopNotification should be of type FINAL_SUCCESS
311 assertTrue(obj instanceof VirtualControlLoopNotification);
312 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.FINAL_SUCCESS));
315 * One final check to make sure the lock is released
317 assertFalse(PolicyGuard.isLocked(TargetType.VNF, triggerSourceName, requestID));
320 fail("Operation Denied by Guard");
324 * This will stop the thread that is firing the rules
329 * The only fact in memory should be Params
331 // assertEquals(1, kieSession.getFactCount());
332 if (kieSession.getFactCount() != 1L) {
333 logger.error("FACT count mismatch: 1 expected but there are {}", kieSession.getFactCount());
337 * Print what's left in memory
339 dumpFacts(kieSession);
342 * Gracefully shut down the kie session
344 kieSession.dispose();
348 * This method will start a kie session and instantiate
351 * @param droolsTemplate
354 * the yaml file containing the policies
359 * @param policyVersion
360 * version of the policy
361 * @return the kieSession to be used to insert facts
362 * @throws IOException
364 private KieSession startSession(String droolsTemplate,
368 String policyVersion) throws IOException {
371 * Load policies from yaml
373 pair = Util.loadYaml(yamlFile);
375 assertNotNull(pair.a);
376 assertNotNull(pair.a.getControlLoop());
377 assertNotNull(pair.a.getControlLoop().getControlLoopName());
378 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
381 * Construct a kie session
383 final KieSession kieSession = Util.buildContainer(droolsTemplate,
384 pair.a.getControlLoop().getControlLoopName(),
388 URLEncoder.encode(pair.b, "UTF-8"));
391 * Retrieve the Policy Engine
393 engine = (PolicyEngineJUnitImpl) kieSession.getGlobal("Engine");
395 logger.debug("============");
396 logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
397 logger.debug("============");
403 * This method is used to simulate event messages from DCAE
404 * that start the control loop (onset message).
406 * @param policy the controlLoopName comes from the policy
407 * @param requestID the requestId for this event
408 * @param triggerSourceName
409 * @throws InterruptedException
411 protected void sendOnset(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
412 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
413 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
414 event.requestID = requestID;
415 event.target = "generic-vnf.vnf-id";
416 event.closedLoopAlarmStart = Instant.now();
417 event.AAI = new HashMap<>();
418 event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
419 event.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
420 kieSession.insert(event);
425 * This method is used to simulate event messages from DCAE
426 * that end the control loop (abatement message).
428 * @param policy the controlLoopName comes from the policy
429 * @param requestID the requestId for this event
430 * @param triggerSourceName
431 * @throws InterruptedException
433 protected void sendAbatement(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
434 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
435 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
436 event.requestID = requestID;
437 event.target = "generic-vnf.vnf-id";
438 event.closedLoopAlarmStart = Instant.now().minusSeconds(5);
439 event.closedLoopAlarmEnd = Instant.now();
440 event.AAI = new HashMap<>();
441 event.AAI.put("cloud-region.identity-url", "foo");
442 event.AAI.put("vserver.selflink", "bar");
443 event.AAI.put("vserver.is-closed-loop-disabled", "false");
444 event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
445 event.closedLoopEventStatus = ControlLoopEventStatus.ABATED;
446 kieSession.insert(event);
450 * This method will dump all the facts in the working memory.
452 * @param kieSession the session containing the facts
454 public void dumpFacts(KieSession kieSession) {
455 logger.debug("Fact Count: {}", kieSession.getFactCount());
456 for (FactHandle handle : kieSession.getFactHandles()) {
457 logger.debug("FACT: {}", handle);