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 */
68 public static void setUpSimulator() {
72 } catch (Exception e) {
78 public static void tearDownSimulator() {
79 HttpServletServer.factory.destroy();
83 public void successTest() {
86 * Start the kie session
89 kieSession = startSession("src/main/resources/ControlLoop_Template_xacml_guard.drl",
90 "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml",
91 "service=ServiceTest;resource=ResourceTest;type=operational",
93 "org.onap.closed_loop.ServiceTest:VNFS:1.0.0");
94 } catch (IOException e) {
96 logger.debug("Could not create kieSession");
97 fail("Could not create kieSession");
101 * Create a thread to continuously fire rules
102 * until main thread calls halt
104 new Thread( new Runnable() {
107 kieSession.fireUntilHalt();
112 * Create a unique requestId and a unique trigger source
114 UUID requestID = UUID.randomUUID();
115 String triggerSourceName = "foobartriggersource36";
118 * This will be the object returned from the PolicyEngine
123 * Simulate an onset event the policy engine will
124 * receive from DCAE to kick off processing through
128 sendOnset(pair.a, requestID, triggerSourceName);
129 } catch (InterruptedException e) {
131 logger.debug("Unable to send onset event");
132 fail("Unable to send onset event");
136 * Pull the object that was sent out to DMAAP and make
137 * sure it is a ControlLoopNoticiation of type active
139 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
141 assertTrue(obj instanceof VirtualControlLoopNotification);
142 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.ACTIVE));
145 * Give the control loop time to acquire a lock
149 } catch (InterruptedException e) {
151 logger.debug("An interrupt Exception was thrown");
152 fail("An interrupt Exception was thrown");
156 * The fact should be ready to query guard now to see
157 * if a ModifyConfig recipe is allowed
159 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
161 logger.debug("\n\n####################### GOING TO QUERY GUARD about Restart!!!!!!");
162 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
165 * Make sure the object is an instance of a ControlLoopNotification
166 * and is of type operation
168 assertTrue(obj instanceof VirtualControlLoopNotification);
169 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
173 } catch (InterruptedException e) {
175 logger.debug("An interrupt Exception was thrown");
176 fail("An interrupt Exception was thrown");
180 * The guard response should be received at this point
182 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
184 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
187 * The object should be a ControlLoopNotification with type operation
189 assertTrue(obj instanceof VirtualControlLoopNotification);
190 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
193 * See if Guard permits this action, if it does
194 * not then the test should fail
196 if (((VirtualControlLoopNotification)obj).message.contains("PERMIT")) {
199 * A notification should be sent out of the Policy
200 * Engine at this point, it will be of type operation
202 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
204 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
206 /* A notification should be sent out of the Policy
207 * Engine at this point, it will be of type operation
209 assertTrue(obj instanceof VirtualControlLoopNotification);
210 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
214 } catch (InterruptedException e) {
216 logger.debug("An interrupt Exception was thrown");
217 fail("An interrupt Exception was thrown");
221 * Obtain the request sent from the Policy Engine
223 obj = engine.subscribe("UEB", "APPC-LCM-READ");
227 * The request should be of type LCMRequestWrapper
228 * and the subrequestid should be 1
230 assertTrue(obj instanceof LCMRequestWrapper);
231 LCMRequestWrapper dmaapRequest = (LCMRequestWrapper) obj;
232 LCMRequest appcRequest = dmaapRequest.getBody();
233 assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
235 logger.debug("\n============ APPC received the request!!! ===========\n");
238 * Give some time for processing
242 } catch (InterruptedException e) {
244 logger.debug("An interrupt Exception was thrown");
245 fail("An interrupt Exception was thrown");
249 * Simulate a success response from APPC and insert
250 * the response into the working memory
252 LCMResponseWrapper dmaapResponse = new LCMResponseWrapper();
253 LCMResponse appcResponse = new LCMResponse(appcRequest);
254 appcResponse.getStatus().setCode(400);
255 appcResponse.getStatus().setMessage("AppC success");
256 dmaapResponse.setBody(appcResponse);
257 kieSession.insert(dmaapResponse);
260 * Give time for processing
264 } catch (InterruptedException e) {
266 logger.debug("An interrupt Exception was thrown");
267 fail("An interrupt Exception was thrown");
271 * Make sure the next notification is delivered
273 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
275 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
278 * The ControlLoopNotification should be
279 * an OPERATION_SUCCESS
281 assertTrue(obj instanceof VirtualControlLoopNotification);
282 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION_SUCCESS));
285 * Now simulate the abatement sent from DCAE
288 sendAbatement(pair.a, requestID, triggerSourceName);
289 } catch (InterruptedException e1) {
290 e1.printStackTrace();
291 logger.debug("Abatement could not be sent");
292 fail("Abatement could not be sent");
296 * Give time to finish processing
300 } catch (InterruptedException e) {
302 logger.debug("An interrupt Exception was thrown");
303 fail("An interrupt Exception was thrown");
307 * This should be the final notification from the Policy Engine
309 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
311 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
314 * The ControlLoopNotification should be of type FINAL_SUCCESS
316 assertTrue(obj instanceof VirtualControlLoopNotification);
317 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.FINAL_SUCCESS));
320 * One final check to make sure the lock is released
322 assertFalse(PolicyGuard.isLocked(TargetType.VNF, triggerSourceName, requestID));
325 fail("Operation Denied by Guard");
329 * This will stop the thread that is firing the rules
334 * The only fact in memory should be Params
336 //assertEquals(1, kieSession.getFactCount());
337 if (kieSession.getFactCount() != 1L) {
338 logger.error("FACT count mismatch: 1 expected but there are {}", kieSession.getFactCount());
342 * Print what's left in memory
344 dumpFacts(kieSession);
347 * Gracefully shut down the kie session
349 kieSession.dispose();
353 * This method will start a kie session and instantiate
356 * @param droolsTemplate
359 * the yaml file containing the policies
364 * @param policyVersion
365 * version of the policy
366 * @return the kieSession to be used to insert facts
367 * @throws IOException
369 private KieSession startSession(String droolsTemplate,
373 String policyVersion) throws IOException {
376 * Load policies from yaml
378 pair = Util.loadYaml(yamlFile);
380 assertNotNull(pair.a);
381 assertNotNull(pair.a.getControlLoop());
382 assertNotNull(pair.a.getControlLoop().getControlLoopName());
383 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
386 * Construct a kie session
388 final KieSession kieSession = Util.buildContainer(droolsTemplate,
389 pair.a.getControlLoop().getControlLoopName(),
393 URLEncoder.encode(pair.b, "UTF-8"));
396 * Retrieve the Policy Engine
398 engine = (PolicyEngineJUnitImpl) kieSession.getGlobal("Engine");
400 logger.debug("============");
401 logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
402 logger.debug("============");
408 * This method is used to simulate event messages from DCAE
409 * that start the control loop (onset message).
411 * @param policy the controlLoopName comes from the policy
412 * @param requestID the requestId for this event
413 * @param triggerSourceName
414 * @throws InterruptedException
416 protected void sendOnset(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
417 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
418 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
419 event.requestID = requestID;
420 event.target = "generic-vnf.vnf-id";
421 event.closedLoopAlarmStart = Instant.now();
422 event.AAI = new HashMap<>();
423 event.AAI.put("generic-vnf.vnf-id", "testGenericVnfId");
424 event.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
425 kieSession.insert(event);
430 * This method is used to simulate event messages from DCAE
431 * that end the control loop (abatement message).
433 * @param policy the controlLoopName comes from the policy
434 * @param requestID the requestId for this event
435 * @param triggerSourceName
436 * @throws InterruptedException
438 protected void sendAbatement(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
439 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
440 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
441 event.requestID = requestID;
442 event.target = "generic-vnf.vnf-id";
443 event.closedLoopAlarmStart = Instant.now().minusSeconds(5);
444 event.closedLoopAlarmEnd = Instant.now();
445 event.AAI = new HashMap<>();
446 event.AAI.put("generic-vnf.vnf-id", "testGenericVnfId");
447 event.closedLoopEventStatus = ControlLoopEventStatus.ABATED;
448 kieSession.insert(event);
452 * This method will dump all the facts in the working memory.
454 * @param kieSession the session containing the facts
456 public void dumpFacts(KieSession kieSession) {
457 logger.debug("Fact Count: {}", kieSession.getFactCount());
458 for (FactHandle handle : kieSession.getFactHandles()) {
459 logger.debug("FACT: {}", handle);