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.Test;
32 import org.kie.api.runtime.KieSession;
33 import org.kie.api.runtime.rule.FactHandle;
34 import org.onap.policy.appc.Request;
35 import org.onap.policy.appc.Response;
36 import org.onap.policy.appc.ResponseCode;
37 import org.onap.policy.controlloop.ControlLoopEventStatus;
38 import org.onap.policy.controlloop.ControlLoopNotificationType;
39 import org.onap.policy.controlloop.VirtualControlLoopEvent;
40 import org.onap.policy.controlloop.VirtualControlLoopNotification;
41 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
42 import org.onap.policy.controlloop.policy.TargetType;
43 import org.onap.policy.drools.impl.PolicyEngineJUnitImpl;
44 import org.onap.policy.guard.PolicyGuard;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
48 public class VFWControlLoopTest {
50 private static final Logger logger = LoggerFactory.getLogger(VFWControlLoopTest.class);
52 private KieSession kieSession;
53 private Util.Pair<ControlLoopPolicy, String> pair;
54 private PolicyEngineJUnitImpl engine;
57 public void successTest() {
60 * Start the kie session
63 kieSession = startSession("src/main/resources/ControlLoop_Template_xacml_guard.drl",
64 "src/test/resources/yaml/policy_ControlLoop_vFW.yaml",
65 "service=ServiceDemo;resource=Res1Demo;type=operational",
67 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
68 } catch (IOException e) {
70 logger.debug("Could not create kieSession");
71 fail("Could not create kieSession");
75 * Create a thread to continuously fire rules
76 * until main thread calls halt
78 new Thread( new Runnable() {
81 kieSession.fireUntilHalt();
86 * Create a unique requestId and a unique trigger source
88 UUID requestID = UUID.randomUUID();
89 String triggerSourceName = "foobartriggersource36";
92 * This will be the object returned from the PolicyEngine
97 * Simulate an onset event the policy engine will
98 * receive from DCAE to kick off processing through
102 sendOnset(pair.a, requestID, triggerSourceName);
103 } catch (InterruptedException e) {
105 logger.debug("Unable to send onset event");
106 fail("Unable to send onset event");
110 * Pull the object that was sent out to DMAAP and make
111 * sure it is a ControlLoopNoticiation of type active
113 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
115 assertTrue(obj instanceof VirtualControlLoopNotification);
116 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.ACTIVE));
119 * Give the control loop time to acquire a lock
123 } catch (InterruptedException e) {
125 logger.debug("An interrupt Exception was thrown");
126 fail("An interrupt Exception was thrown");
130 * The fact should be ready to query guard now to see
131 * if a ModifyConfig recipe is allowed
133 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
135 logger.debug("\n\n####################### GOING TO QUERY GUARD about ModifyConfig!!!!!!");
136 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
139 * Make sure the object is an instance of a ControlLoopNotification
140 * and is of type operation
142 assertTrue(obj instanceof VirtualControlLoopNotification);
143 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
147 } catch (InterruptedException e) {
149 logger.debug("An interrupt Exception was thrown");
150 fail("An interrupt Exception was thrown");
154 * The guard response should be received at this point
156 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
158 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
161 * The object should be a ControlLoopNotification with type operation
163 assertTrue(obj instanceof VirtualControlLoopNotification);
164 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
167 * See if Guard permits this action, if it does
168 * not then the test should fail
170 if (((VirtualControlLoopNotification)obj).message.contains("Guard result: Permit")) {
173 * Obtain the ControlLoopNoticiation, it should be of type operation
175 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
177 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
180 * A notification should be sent out of the Policy
181 * Engine at this point, it will be of type operation
183 assertTrue(obj instanceof VirtualControlLoopNotification);
184 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
188 } catch (InterruptedException e) {
190 logger.debug("An interrupt Exception was thrown");
191 fail("An interrupt Exception was thrown");
195 * Obtain the request sent from the Policy Engine
197 obj = engine.subscribe("UEB", "APPC-CL");
201 * The request should be of type Request
202 * and the subrequestid should be 1
204 assertTrue(obj instanceof Request);
205 assertTrue(((Request)obj).getCommonHeader().SubRequestID.equals("1"));
207 logger.debug("\n============ APPC received the request!!! ===========\n");
210 * Give some time for processing
214 } catch (InterruptedException e) {
216 logger.debug("An interrupt Exception was thrown");
217 fail("An interrupt Exception was thrown");
221 * Simulate a success response from APPC and insert
222 * the response into the working memory
224 Response appcResponse = new Response((Request)obj);
225 appcResponse.getStatus().Code = ResponseCode.SUCCESS.getValue();
226 appcResponse.getStatus().Description = "AppC success";
227 kieSession.insert(appcResponse);
230 * Give time for processing
234 } catch (InterruptedException e) {
236 logger.debug("An interrupt Exception was thrown");
237 fail("An interrupt Exception was thrown");
241 * Make sure the next notification is delivered
243 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
245 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
248 * The ControlLoopNotification should be
249 * an OPERATION_SUCCESS
251 assertTrue(obj instanceof VirtualControlLoopNotification);
252 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION_SUCCESS));
255 * Now simulate the abatement sent from DCAE
258 sendAbatement(pair.a, requestID, triggerSourceName);
259 } catch (InterruptedException e1) {
260 e1.printStackTrace();
261 logger.debug("Abatement could not be sent");
262 fail("Abatement could not be sent");
266 * Give time to finish processing
270 } catch (InterruptedException e) {
272 logger.debug("An interrupt Exception was thrown");
273 fail("An interrupt Exception was thrown");
277 * This should be the final notification from the Policy Engine
279 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
281 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
284 * The ControlLoopNotification should be of type FINAL_SUCCESS
286 assertTrue(obj instanceof VirtualControlLoopNotification);
287 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.FINAL_SUCCESS));
290 * One final check to make sure the lock is released
292 assertFalse(PolicyGuard.isLocked(TargetType.VNF, triggerSourceName, requestID));
295 fail("Operation Denied by Guard");
299 * This will stop the thread that is firing the rules
304 * The only fact in memory should be Params
306 assertEquals(1, kieSession.getFactCount());
309 * Print what's left in memory
311 dumpFacts(kieSession);
314 * Gracefully shut down the kie session
316 kieSession.dispose();
320 * This method will start a kie session and instantiate
323 * @param droolsTemplate
326 * the yaml file containing the policies
331 * @param policyVersion
332 * version of the policy
333 * @return the kieSession to be used to insert facts
334 * @throws IOException
336 private KieSession startSession(String droolsTemplate,
340 String policyVersion) throws IOException {
343 * Load policies from yaml
345 pair = Util.loadYaml(yamlFile);
347 assertNotNull(pair.a);
348 assertNotNull(pair.a.getControlLoop());
349 assertNotNull(pair.a.getControlLoop().getControlLoopName());
350 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
353 * Construct a kie session
355 final KieSession kieSession = Util.buildContainer(droolsTemplate,
356 pair.a.getControlLoop().getControlLoopName(),
360 URLEncoder.encode(pair.b, "UTF-8"));
363 * Retrieve the Policy Engine
365 engine = (PolicyEngineJUnitImpl) kieSession.getGlobal("Engine");
367 logger.debug("============");
368 logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
369 logger.debug("============");
375 * This method is used to simulate event messages from DCAE
376 * that start the control loop (onset message).
378 * @param policy the controlLoopName comes from the policy
379 * @param requestID the requestId for this event
380 * @param triggerSourceName
381 * @throws InterruptedException
383 protected void sendOnset(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
384 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
385 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
386 event.requestID = requestID;
387 event.target = "generic-vnf.vnf-id";
388 event.closedLoopAlarmStart = Instant.now();
389 event.AAI = new HashMap<>();
390 event.AAI.put("cloud-region.identity-url", "foo");
391 event.AAI.put("vserver.selflink", "bar");
392 event.AAI.put("vserver.is-closed-loop-disabled", "false");
393 event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
394 event.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
395 kieSession.insert(event);
400 * This method is used to simulate event messages from DCAE
401 * that end the control loop (abatement message).
403 * @param policy the controlLoopName comes from the policy
404 * @param requestID the requestId for this event
405 * @param triggerSourceName
406 * @throws InterruptedException
408 protected void sendAbatement(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
409 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
410 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
411 event.requestID = requestID;
412 event.target = "generic-vnf.vnf-id";
413 event.closedLoopAlarmStart = Instant.now().minusSeconds(5);
414 event.closedLoopAlarmEnd = Instant.now();
415 event.AAI = new HashMap<>();
416 event.AAI.put("cloud-region.identity-url", "foo");
417 event.AAI.put("vserver.selflink", "bar");
418 event.AAI.put("vserver.is-closed-loop-disabled", "false");
419 event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
420 event.closedLoopEventStatus = ControlLoopEventStatus.ABATED;
421 kieSession.insert(event);
425 * This method will dump all the facts in the working memory.
427 * @param kieSession the session containing the facts
429 public void dumpFacts(KieSession kieSession) {
430 logger.debug("Fact Count: {}", kieSession.getFactCount());
431 for (FactHandle handle : kieSession.getFactHandles()) {
432 logger.debug("FACT: {}", handle);