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.guard.PolicyGuard;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
52 public class VCPEControlLoopTest {
54 private static final Logger logger = LoggerFactory.getLogger(VCPEControlLoopTest.class);
56 private KieSession kieSession;
57 private Util.Pair<ControlLoopPolicy, String> pair;
58 private PolicyEngineJUnitImpl engine;
61 /* Set environment properties */
67 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_vCPE.yaml",
90 "service=ServiceTest;resource=ResourceTest;type=operational",
92 "org.onap.closed_loop.ServiceTest: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 Restart!!!!!!");
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("PERMIT")) {
198 * A notification should be sent out of the Policy
199 * Engine at this point, it will be of type operation
201 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
203 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-LCM-READ");
226 * The request should be of type LCMRequestWrapper
227 * and the subrequestid should be 1
229 assertTrue(obj instanceof LCMRequestWrapper);
230 LCMRequestWrapper dmaapRequest = (LCMRequestWrapper) obj;
231 LCMRequest appcRequest = dmaapRequest.getBody();
232 assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
234 logger.debug("\n============ APPC received the request!!! ===========\n");
237 * Give some time for processing
241 } catch (InterruptedException e) {
243 logger.debug("An interrupt Exception was thrown");
244 fail("An interrupt Exception was thrown");
248 * Simulate a success response from APPC and insert
249 * the response into the working memory
251 LCMResponseWrapper dmaapResponse = new LCMResponseWrapper();
252 LCMResponse appcResponse = new LCMResponse(appcRequest);
253 appcResponse.getStatus().setCode(400);
254 appcResponse.getStatus().setMessage("AppC success");
255 dmaapResponse.setBody(appcResponse);
256 kieSession.insert(dmaapResponse);
259 * Give time for processing
263 } catch (InterruptedException e) {
265 logger.debug("An interrupt Exception was thrown");
266 fail("An interrupt Exception was thrown");
270 * Make sure the next notification is delivered
272 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
274 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
277 * The ControlLoopNotification should be
278 * an OPERATION_SUCCESS
280 assertTrue(obj instanceof VirtualControlLoopNotification);
281 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION_SUCCESS));
284 * Now simulate the abatement sent from DCAE
287 sendAbatement(pair.a, requestID, triggerSourceName);
288 } catch (InterruptedException e1) {
289 e1.printStackTrace();
290 logger.debug("Abatement could not be sent");
291 fail("Abatement could not be sent");
295 * Give time to finish processing
299 } catch (InterruptedException e) {
301 logger.debug("An interrupt Exception was thrown");
302 fail("An interrupt Exception was thrown");
306 * This should be the final notification from the Policy Engine
308 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
310 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
313 * The ControlLoopNotification should be of type FINAL_SUCCESS
315 assertTrue(obj instanceof VirtualControlLoopNotification);
316 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.FINAL_SUCCESS));
319 * One final check to make sure the lock is released
321 assertFalse(PolicyGuard.isLocked(TargetType.VNF, triggerSourceName, requestID));
324 fail("Operation Denied by Guard");
328 * This will stop the thread that is firing the rules
333 * The only fact in memory should be Params
335 //assertEquals(1, kieSession.getFactCount());
336 if (kieSession.getFactCount() != 1L) {
337 logger.error("FACT count mismatch: 1 expected but there are {}", kieSession.getFactCount());
341 * Print what's left in memory
343 dumpFacts(kieSession);
346 * Gracefully shut down the kie session
348 kieSession.dispose();
352 * This method will start a kie session and instantiate
355 * @param droolsTemplate
358 * the yaml file containing the policies
363 * @param policyVersion
364 * version of the policy
365 * @return the kieSession to be used to insert facts
366 * @throws IOException
368 private KieSession startSession(String droolsTemplate,
372 String policyVersion) throws IOException {
375 * Load policies from yaml
377 pair = Util.loadYaml(yamlFile);
379 assertNotNull(pair.a);
380 assertNotNull(pair.a.getControlLoop());
381 assertNotNull(pair.a.getControlLoop().getControlLoopName());
382 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
385 * Construct a kie session
387 final KieSession kieSession = Util.buildContainer(droolsTemplate,
388 pair.a.getControlLoop().getControlLoopName(),
392 URLEncoder.encode(pair.b, "UTF-8"));
395 * Retrieve the Policy Engine
397 engine = (PolicyEngineJUnitImpl) kieSession.getGlobal("Engine");
399 logger.debug("============");
400 logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
401 logger.debug("============");
407 * This method is used to simulate event messages from DCAE
408 * that start the control loop (onset message).
410 * @param policy the controlLoopName comes from the policy
411 * @param requestID the requestId for this event
412 * @param triggerSourceName
413 * @throws InterruptedException
415 protected void sendOnset(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
416 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
417 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
418 event.requestID = requestID;
419 event.target = "generic-vnf.vnf-id";
420 event.closedLoopAlarmStart = Instant.now();
421 event.AAI = new HashMap<>();
422 event.AAI.put("generic-vnf.vnf-id", "testGenericVnfId");
423 event.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
424 kieSession.insert(event);
429 * This method is used to simulate event messages from DCAE
430 * that end the control loop (abatement message).
432 * @param policy the controlLoopName comes from the policy
433 * @param requestID the requestId for this event
434 * @param triggerSourceName
435 * @throws InterruptedException
437 protected void sendAbatement(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
438 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
439 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
440 event.requestID = requestID;
441 event.target = "generic-vnf.vnf-id";
442 event.closedLoopAlarmStart = Instant.now().minusSeconds(5);
443 event.closedLoopAlarmEnd = Instant.now();
444 event.AAI = new HashMap<>();
445 event.AAI.put("generic-vnf.vnf-id", "testGenericVnfId");
446 event.closedLoopEventStatus = ControlLoopEventStatus.ABATED;
447 kieSession.insert(event);
451 * This method will dump all the facts in the working memory.
453 * @param kieSession the session containing the facts
455 public void dumpFacts(KieSession kieSession) {
456 logger.debug("Fact Count: {}", kieSession.getFactCount());
457 for (FactHandle handle : kieSession.getFactHandles()) {
458 logger.debug("FACT: {}", handle);