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.appclcm.LCMRequest;
37 import org.onap.policy.appclcm.LCMRequestWrapper;
38 import org.onap.policy.appclcm.LCMResponse;
39 import org.onap.policy.appclcm.LCMResponseWrapper;
40 import org.onap.policy.controlloop.ControlLoopEventStatus;
41 import org.onap.policy.controlloop.ControlLoopNotificationType;
42 import org.onap.policy.controlloop.VirtualControlLoopEvent;
43 import org.onap.policy.controlloop.VirtualControlLoopNotification;
44 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
45 import org.onap.policy.controlloop.policy.TargetType;
46 import org.onap.policy.drools.http.server.HttpServletServer;
47 import org.onap.policy.drools.impl.PolicyEngineJUnitImpl;
48 import org.onap.policy.drools.system.PolicyEngine;
49 import org.onap.policy.guard.PolicyGuard;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
53 public class VCPEControlLoopTest {
55 private static final Logger logger = LoggerFactory.getLogger(VCPEControlLoopTest.class);
57 private KieSession kieSession;
58 private Util.Pair<ControlLoopPolicy, String> pair;
59 private PolicyEngineJUnitImpl engine;
62 /* Set environment properties */
63 PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666");
64 PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI");
65 PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI");
67 PolicyEngine.manager.setEnvironmentProperty("guard.url", "http://localhost:6669/pdp/api/getDecision");
68 PolicyEngine.manager.setEnvironmentProperty("guard.username", "GUARD");
69 PolicyEngine.manager.setEnvironmentProperty("guard.password", "GUARD");
73 public static void setUpSimulator() {
77 } catch (Exception e) {
83 public static void tearDownSimulator() {
84 HttpServletServer.factory.destroy();
88 public void successTest() {
91 * Start the kie session
94 kieSession = startSession("src/main/resources/ControlLoop_Template_xacml_guard.drl",
95 "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml",
96 "service=ServiceTest;resource=ResourceTest;type=operational",
98 "org.onap.closed_loop.ServiceTest:VNFS:1.0.0");
99 } catch (IOException e) {
101 logger.debug("Could not create kieSession");
102 fail("Could not create kieSession");
106 * Create a thread to continuously fire rules
107 * until main thread calls halt
109 new Thread( new Runnable() {
112 kieSession.fireUntilHalt();
117 * Create a unique requestId and a unique trigger source
119 UUID requestID = UUID.randomUUID();
120 String triggerSourceName = "foobartriggersource36";
123 * This will be the object returned from the PolicyEngine
128 * Simulate an onset event the policy engine will
129 * receive from DCAE to kick off processing through
133 sendOnset(pair.a, requestID, triggerSourceName);
134 } catch (InterruptedException e) {
136 logger.debug("Unable to send onset event");
137 fail("Unable to send onset event");
141 * Pull the object that was sent out to DMAAP and make
142 * sure it is a ControlLoopNoticiation of type active
144 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
146 assertTrue(obj instanceof VirtualControlLoopNotification);
147 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.ACTIVE));
150 * Give the control loop time to acquire a lock
154 } catch (InterruptedException e) {
156 logger.debug("An interrupt Exception was thrown");
157 fail("An interrupt Exception was thrown");
161 * The fact should be ready to query guard now to see
162 * if a ModifyConfig recipe is allowed
164 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
166 logger.debug("\n\n####################### GOING TO QUERY GUARD about Restart!!!!!!");
167 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
170 * Make sure the object is an instance of a ControlLoopNotification
171 * and is of type operation
173 assertTrue(obj instanceof VirtualControlLoopNotification);
174 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
178 } catch (InterruptedException e) {
180 logger.debug("An interrupt Exception was thrown");
181 fail("An interrupt Exception was thrown");
185 * The guard response should be received at this point
187 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
189 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
192 * The object should be a ControlLoopNotification with type operation
194 assertTrue(obj instanceof VirtualControlLoopNotification);
195 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
198 * See if Guard permits this action, if it does
199 * not then the test should fail
201 if (((VirtualControlLoopNotification)obj).message.contains("Guard result: PERMIT")) {
204 * A notification should be sent out of the Policy
205 * Engine at this point, it will be of type operation
207 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
209 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
211 /* A notification should be sent out of the Policy
212 * Engine at this point, it will be of type operation
214 assertTrue(obj instanceof VirtualControlLoopNotification);
215 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
219 } catch (InterruptedException e) {
221 logger.debug("An interrupt Exception was thrown");
222 fail("An interrupt Exception was thrown");
226 * Obtain the request sent from the Policy Engine
228 obj = engine.subscribe("UEB", "APPC-LCM-READ");
232 * The request should be of type LCMRequestWrapper
233 * and the subrequestid should be 1
235 assertTrue(obj instanceof LCMRequestWrapper);
236 LCMRequestWrapper dmaapRequest = (LCMRequestWrapper) obj;
237 LCMRequest appcRequest = dmaapRequest.getBody();
238 assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
240 logger.debug("\n============ APPC received the request!!! ===========\n");
243 * Give some time for processing
247 } catch (InterruptedException e) {
249 logger.debug("An interrupt Exception was thrown");
250 fail("An interrupt Exception was thrown");
254 * Simulate a success response from APPC and insert
255 * the response into the working memory
257 LCMResponseWrapper dmaapResponse = new LCMResponseWrapper();
258 LCMResponse appcResponse = new LCMResponse(appcRequest);
259 appcResponse.getStatus().setCode(400);
260 appcResponse.getStatus().setMessage("AppC success");
261 dmaapResponse.setBody(appcResponse);
262 kieSession.insert(dmaapResponse);
265 * Give time for processing
269 } catch (InterruptedException e) {
271 logger.debug("An interrupt Exception was thrown");
272 fail("An interrupt Exception was thrown");
276 * Make sure the next notification is delivered
278 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
280 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
283 * The ControlLoopNotification should be
284 * an OPERATION_SUCCESS
286 assertTrue(obj instanceof VirtualControlLoopNotification);
287 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION_SUCCESS));
290 * Now simulate the abatement sent from DCAE
293 sendAbatement(pair.a, requestID, triggerSourceName);
294 } catch (InterruptedException e1) {
295 e1.printStackTrace();
296 logger.debug("Abatement could not be sent");
297 fail("Abatement could not be sent");
301 * Give time to finish processing
305 } catch (InterruptedException e) {
307 logger.debug("An interrupt Exception was thrown");
308 fail("An interrupt Exception was thrown");
312 * This should be the final notification from the Policy Engine
314 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
316 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
319 * The ControlLoopNotification should be of type FINAL_SUCCESS
321 assertTrue(obj instanceof VirtualControlLoopNotification);
322 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.FINAL_SUCCESS));
325 * One final check to make sure the lock is released
327 assertFalse(PolicyGuard.isLocked(TargetType.VNF, triggerSourceName, requestID));
330 fail("Operation Denied by Guard");
334 * This will stop the thread that is firing the rules
339 * The only fact in memory should be Params
341 //assertEquals(1, kieSession.getFactCount());
342 if (kieSession.getFactCount() != 1L) {
343 logger.error("FACT count mismatch: 1 expected but there are {}", kieSession.getFactCount());
347 * Print what's left in memory
349 dumpFacts(kieSession);
352 * Gracefully shut down the kie session
354 kieSession.dispose();
358 * This method will start a kie session and instantiate
361 * @param droolsTemplate
364 * the yaml file containing the policies
369 * @param policyVersion
370 * version of the policy
371 * @return the kieSession to be used to insert facts
372 * @throws IOException
374 private KieSession startSession(String droolsTemplate,
378 String policyVersion) throws IOException {
381 * Load policies from yaml
383 pair = Util.loadYaml(yamlFile);
385 assertNotNull(pair.a);
386 assertNotNull(pair.a.getControlLoop());
387 assertNotNull(pair.a.getControlLoop().getControlLoopName());
388 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
391 * Construct a kie session
393 final KieSession kieSession = Util.buildContainer(droolsTemplate,
394 pair.a.getControlLoop().getControlLoopName(),
398 URLEncoder.encode(pair.b, "UTF-8"));
401 * Retrieve the Policy Engine
403 engine = (PolicyEngineJUnitImpl) kieSession.getGlobal("Engine");
405 logger.debug("============");
406 logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
407 logger.debug("============");
413 * This method is used to simulate event messages from DCAE
414 * that start the control loop (onset message).
416 * @param policy the controlLoopName comes from the policy
417 * @param requestID the requestId for this event
418 * @param triggerSourceName
419 * @throws InterruptedException
421 protected void sendOnset(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
422 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
423 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
424 event.requestID = requestID;
425 event.target = "generic-vnf.vnf-id";
426 event.closedLoopAlarmStart = Instant.now();
427 event.AAI = new HashMap<>();
428 event.AAI.put("generic-vnf.vnf-id", "testGenericVnfId");
429 event.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
430 kieSession.insert(event);
435 * This method is used to simulate event messages from DCAE
436 * that end the control loop (abatement message).
438 * @param policy the controlLoopName comes from the policy
439 * @param requestID the requestId for this event
440 * @param triggerSourceName
441 * @throws InterruptedException
443 protected void sendAbatement(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
444 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
445 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
446 event.requestID = requestID;
447 event.target = "generic-vnf.vnf-id";
448 event.closedLoopAlarmStart = Instant.now().minusSeconds(5);
449 event.closedLoopAlarmEnd = Instant.now();
450 event.AAI = new HashMap<>();
451 event.AAI.put("generic-vnf.vnf-id", "testGenericVnfId");
452 event.closedLoopEventStatus = ControlLoopEventStatus.ABATED;
453 kieSession.insert(event);
457 * This method will dump all the facts in the working memory.
459 * @param kieSession the session containing the facts
461 public void dumpFacts(KieSession kieSession) {
462 logger.debug("Fact Count: {}", kieSession.getFactCount());
463 for (FactHandle handle : kieSession.getFactHandles()) {
464 logger.debug("FACT: {}", handle);