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.assertEquals;
25 import java.io.IOException;
26 import java.nio.file.Files;
27 import java.nio.file.Path;
28 import java.nio.file.Paths;
29 import java.time.Instant;
30 import java.util.HashMap;
31 import java.util.UUID;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
35 import org.junit.Test;
36 import org.kie.api.KieServices;
37 import org.kie.api.builder.KieBuilder;
38 import org.kie.api.builder.KieFileSystem;
39 import org.kie.api.builder.Message;
40 import org.kie.api.builder.ReleaseId;
41 import org.kie.api.builder.Results;
42 import org.kie.api.builder.model.KieModuleModel;
43 import org.kie.api.runtime.KieContainer;
44 import org.kie.api.runtime.KieSession;
45 import org.kie.api.runtime.rule.FactHandle;
46 import org.onap.policy.appc.CommonHeader;
47 import org.onap.policy.appc.Response;
48 import org.onap.policy.appc.ResponseStatus;
49 import org.onap.policy.controlloop.ControlLoopEventStatus;
50 import org.onap.policy.controlloop.ControlLoopTargetType;
51 import org.onap.policy.controlloop.VirtualControlLoopEvent;
52 import org.onap.policy.appc.util.Serialization;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
57 public class TestFirewallDemo {
59 private static final Logger logger = LoggerFactory.getLogger(TestFirewallDemo.class);
61 public void testvDNS() throws IOException {
65 final String closedLoopControlName = "CL-DNS-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8";
66 final KieSession kieSession = buildContainer("src/main/resources/archetype-resources/src/main/resources/ControlLoopDemo__closedLoopControlName__.drl",
67 closedLoopControlName,
69 "myFirewallDemoPolicy",
72 "http://localhost:8080/TestREST/Test",
75 "http://localhost:8080/TestREST/Test",
78 "4ff56a54-9e3f-46b7-a337-07a1d3c6b469",
84 // Initial fire of rules
86 kieSession.fireAllRules();
88 // Kick a thread that starts testing
90 new Thread(new Runnable() {
95 // Generate an invalid DCAE Event with requestID=null
97 VirtualControlLoopEvent invalidEvent = new VirtualControlLoopEvent();
98 invalidEvent.closedLoopControlName = closedLoopControlName;
99 invalidEvent.requestID = null;
100 invalidEvent.closedLoopEventClient = "tca.instance00001";
101 invalidEvent.target_type = ControlLoopTargetType.VF;
102 invalidEvent.target = "generic-vnf.vnf-id";
103 invalidEvent.from = "DCAE";
104 invalidEvent.closedLoopAlarmStart = Instant.now();
105 invalidEvent.AAI = new HashMap<String, String>();
106 invalidEvent.AAI.put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1");
107 invalidEvent.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
109 logger.debug("----- Invalid ONSET -----");
110 logger.debug(Serialization.gsonPretty.toJson(invalidEvent));
113 // Insert invalid DCAE Event into memory
115 kieSession.insert(invalidEvent);
118 } catch (InterruptedException e) {
121 // Generate first DCAE ONSET Event
123 VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
124 onsetEvent.closedLoopControlName = closedLoopControlName;
125 onsetEvent.requestID = UUID.randomUUID();
126 onsetEvent.closedLoopEventClient = "tca.instance00001";
127 onsetEvent.target_type = ControlLoopTargetType.VF;
128 onsetEvent.target = "generic-vnf.vnf-id";
129 onsetEvent.from = "DCAE";
130 onsetEvent.closedLoopAlarmStart = Instant.now();
131 onsetEvent.AAI = new HashMap<String, String>();
132 onsetEvent.AAI.put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1");
133 onsetEvent.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
135 logger.debug("----- ONSET -----");
136 logger.debug(Serialization.gsonPretty.toJson(onsetEvent));
139 // Insert first DCAE ONSET Event into memory
141 kieSession.insert(onsetEvent);
143 // We have test for subsequent ONSET Events in testvFirewall()
144 // So no need to test it again here
148 } catch (InterruptedException e) {
151 // Test is finished, so stop the kieSession
158 // Start firing rules
160 kieSession.fireUntilHalt();
162 // Dump working memory
164 dumpFacts(kieSession);
166 // See if there is anything left in memory, there SHOULD only be
169 assertEquals("There should only be 1 Fact left in memory.", 1, kieSession.getFactCount());
170 for (FactHandle handle : kieSession.getFactHandles()) {
171 Object fact = kieSession.getObject(handle);
172 assertEquals("Non-Param Fact left in working memory", "org.onap.policy.controlloop.Params", fact.getClass().getName());
177 public void testvFirewall() throws IOException {
181 final String closedLoopControlName = "CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8";
182 final KieSession kieSession = buildContainer("src/main/resources/archetype-resources/src/main/resources/ControlLoopDemo__closedLoopControlName__.drl",
183 closedLoopControlName,
185 "myFirewallDemoPolicy",
188 "http://localhost:8080/TestREST/Test",
200 // Initial fire of rules
202 kieSession.fireAllRules();
204 // Kick a thread that starts testing
206 new Thread(new Runnable() {
211 // Generate an invalid DCAE Event with requestID=null
213 VirtualControlLoopEvent invalidEvent = new VirtualControlLoopEvent();
214 invalidEvent.closedLoopControlName = closedLoopControlName;
215 invalidEvent.requestID = null;
216 invalidEvent.closedLoopEventClient = "tca.instance00001";
217 invalidEvent.target_type = ControlLoopTargetType.VF;
218 invalidEvent.target = "generic-vnf.vnf-id";
219 invalidEvent.from = "DCAE";
220 invalidEvent.closedLoopAlarmStart = Instant.now();
221 invalidEvent.AAI = new HashMap<String, String>();
222 invalidEvent.AAI.put("generic-vnf.vnf-id", "foo");
223 invalidEvent.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
225 logger.debug("----- Invalid ONSET -----");
226 logger.debug(Serialization.gsonPretty.toJson(invalidEvent));
229 // Insert invalid DCAE Event into memory
231 kieSession.insert(invalidEvent);
234 } catch (InterruptedException e) {
237 // Generate first DCAE ONSET Event
239 VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
240 onsetEvent.closedLoopControlName = closedLoopControlName;
241 onsetEvent.requestID = UUID.randomUUID();
242 onsetEvent.closedLoopEventClient = "tca.instance00001";
243 onsetEvent.target_type = ControlLoopTargetType.VF;
244 onsetEvent.target = "generic-vnf.vnf-id";
245 onsetEvent.from = "DCAE";
246 onsetEvent.closedLoopAlarmStart = Instant.now();
247 onsetEvent.AAI = new HashMap<String, String>();
248 onsetEvent.AAI.put("generic-vnf.vnf-id", "fw0001vm001fw001");
249 //onsetEvent.AAI.put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1");
250 onsetEvent.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
252 logger.debug("----- ONSET -----");
253 logger.debug(Serialization.gsonPretty.toJson(onsetEvent));
256 // Insert first DCAE ONSET Event into memory
258 kieSession.insert(onsetEvent);
261 } catch (InterruptedException e) {
265 Thread thread = new Thread(new Runnable() {
271 // Generate subsequent DCAE ONSET Event
273 VirtualControlLoopEvent subOnsetEvent = new VirtualControlLoopEvent();
274 subOnsetEvent.closedLoopControlName = closedLoopControlName;
275 subOnsetEvent.requestID = UUID.randomUUID();
276 subOnsetEvent.closedLoopEventClient = "tca.instance00001";
277 subOnsetEvent.target_type = ControlLoopTargetType.VF;
278 subOnsetEvent.target = "generic-vnf.vnf-id";
279 subOnsetEvent.from = "DCAE";
280 subOnsetEvent.closedLoopAlarmStart = Instant.now();
281 subOnsetEvent.AAI = new HashMap<String, String>();
282 subOnsetEvent.AAI.put("generic-vnf.vnf-id", "fw0001vm001fw001");
283 //subOnsetEvent.AAI.put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1");
284 subOnsetEvent.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
286 logger.debug("----- Subsequent ONSET -----");
287 logger.debug(Serialization.gsonPretty.toJson(subOnsetEvent));
290 // Insert subsequent DCAE ONSET Event into memory
292 kieSession.insert(subOnsetEvent);
295 } catch (InterruptedException e) {
305 } catch (InterruptedException e) {
312 // Generate APPC ACCEPT Response
314 Response response1 = new Response();
316 CommonHeader commonHeader1 = new CommonHeader();
317 commonHeader1.RequestID = onsetEvent.requestID;
318 response1.CommonHeader = commonHeader1;
320 ResponseStatus responseStatus1 = new ResponseStatus();
321 responseStatus1.Code = 100;
322 response1.Status = responseStatus1;
324 logger.debug("----- APP-C RESPONSE 100 -----");
325 logger.debug(Serialization.gsonPretty.toJson(response1));
327 // Insert APPC Response into memory
329 kieSession.insert(response1);
331 // Simulating APPC takes some time for processing the recipe
332 // and then gives response
336 } catch (InterruptedException e) {
339 // Generate APPC SUCCESS Response
341 Response response2 = new Response();
343 CommonHeader commonHeader2 = new CommonHeader();
344 commonHeader2.RequestID = onsetEvent.requestID;
345 response2.CommonHeader = commonHeader2;
347 ResponseStatus responseStatus2 = new ResponseStatus();
348 responseStatus2.Code = 400;
349 response2.Status = responseStatus2;
351 logger.debug("----- APP-C RESPONSE 400 -----");
352 logger.debug(Serialization.gsonPretty.toJson(response2));
354 // Insert APPC Response into memory
356 kieSession.insert(response2);
360 } catch (InterruptedException e) {
363 // Test is finished, so stop the kieSession
370 // Start firing rules
372 kieSession.fireUntilHalt();
374 // Dump working memory
376 dumpFacts(kieSession);
378 // See if there is anything left in memory, there SHOULD only be
381 assertEquals("There should only be 1 Fact left in memory.", 1, kieSession.getFactCount());
382 for (FactHandle handle : kieSession.getFactHandles()) {
383 Object fact = kieSession.getObject(handle);
384 assertEquals("Non-Param Fact left in working memory", "org.onap.policy.controlloop.Params", fact.getClass().getName());
388 public static void dumpFacts(KieSession kieSession) {
389 logger.debug("Fact Count: {}", kieSession.getFactCount());
390 for (FactHandle handle : kieSession.getFactHandles()) {
391 logger.debug("FACT: {}", handle);
395 public static KieSession buildContainer(String droolsTemplate,
396 String closedLoopControlName,
399 String policyVersion,
407 String aaiNamedQuery,
409 String notificationTopic,
410 String appcTopic ) throws IOException {
412 // Get our Drools Kie factory
414 KieServices ks = KieServices.Factory.get();
416 KieModuleModel kModule = ks.newKieModuleModel();
418 logger.debug("KMODULE: {} {}", System.lineSeparator(), kModule.toXML());
421 // Generate our drools rule from our template
423 KieFileSystem kfs = ks.newKieFileSystem();
425 kfs.writeKModuleXML(kModule.toXML());
427 Path rule = Paths.get(droolsTemplate);
428 String ruleTemplate = new String(Files.readAllBytes(rule));
429 String drlContents = generatePolicy(ruleTemplate,
430 closedLoopControlName,
447 kfs.write("src/main/resources/" + policyName + ".drl", ks.getResources().newByteArrayResource(drlContents.getBytes()));
452 KieBuilder builder = ks.newKieBuilder(kfs).buildAll();
453 Results results = builder.getResults();
454 if (results.hasMessages(Message.Level.ERROR)) {
455 for (Message msg : results.getMessages()) {
456 logger.error("{}", msg);
458 throw new RuntimeException("Drools Rule has Errors");
460 for (Message msg : results.getMessages()) {
461 logger.debug("{}", msg);
464 // Create our kie Session and container
466 ReleaseId releaseId = ks.getRepository().getDefaultReleaseId();
467 logger.debug("{}", releaseId);
468 KieContainer kContainer = ks.newKieContainer(releaseId);
470 return kContainer.newKieSession();
472 public static String generatePolicy(String ruleContents,
473 String closedLoopControlName,
476 String policyVersion,
484 String aaiNamedQueryUUID,
486 String notificationTopic,
489 Pattern p = Pattern.compile("\\$\\{closedLoopControlName\\}");
490 Matcher m = p.matcher(ruleContents);
491 ruleContents = m.replaceAll(closedLoopControlName);
493 p = Pattern.compile("\\$\\{policyScope\\}");
494 m = p.matcher(ruleContents);
495 ruleContents = m.replaceAll(policyScope);
497 p = Pattern.compile("\\$\\{policyName\\}");
498 m = p.matcher(ruleContents);
499 ruleContents = m.replaceAll(policyName);
501 p = Pattern.compile("\\$\\{policyVersion\\}");
502 m = p.matcher(ruleContents);
503 ruleContents = m.replaceAll(policyVersion);
505 p = Pattern.compile("\\$\\{actor\\}");
506 m = p.matcher(ruleContents);
507 ruleContents = m.replaceAll(actor);
509 p = Pattern.compile("\\$\\{aaiURL\\}");
510 m = p.matcher(ruleContents);
511 if (aaiURL == null) {
512 ruleContents = m.replaceAll("null");
514 ruleContents = m.replaceAll(aaiURL);
517 p = Pattern.compile("\\$\\{aaiUsername\\}");
518 m = p.matcher(ruleContents);
519 if (aaiUsername == null) {
520 ruleContents = m.replaceAll("null");
522 ruleContents = m.replaceAll(aaiUsername);
525 p = Pattern.compile("\\$\\{aaiPassword\\}");
526 m = p.matcher(ruleContents);
527 if (aaiPassword == null) {
528 ruleContents = m.replaceAll("null");
530 ruleContents = m.replaceAll(aaiPassword);
533 p = Pattern.compile("\\$\\{msoURL\\}");
534 m = p.matcher(ruleContents);
535 if (msoURL == null) {
536 ruleContents = m.replaceAll("null");
538 ruleContents = m.replaceAll(msoURL);
541 p = Pattern.compile("\\$\\{msoUsername\\}");
542 m = p.matcher(ruleContents);
543 if (msoUsername == null) {
544 ruleContents = m.replaceAll("null");
546 ruleContents = m.replaceAll(msoUsername);
549 p = Pattern.compile("\\$\\{msoPassword\\}");
550 m = p.matcher(ruleContents);
551 if (msoPassword == null) {
552 ruleContents = m.replaceAll("null");
554 ruleContents = m.replaceAll(msoPassword);
557 p = Pattern.compile("\\$\\{aaiNamedQueryUUID\\}");
558 m = p.matcher(ruleContents);
559 if (aaiNamedQueryUUID == null) {
560 ruleContents = m.replaceAll("null");
562 ruleContents = m.replaceAll(aaiNamedQueryUUID);
565 p = Pattern.compile("\\$\\{aaiPatternMatch\\}");
566 m = p.matcher(ruleContents);
567 if (aaiPatternMatch == 1) {
568 ruleContents = m.replaceAll("1");
570 ruleContents = m.replaceAll("0");
573 p = Pattern.compile("\\$\\{notificationTopic\\}");
574 m = p.matcher(ruleContents);
575 if (notificationTopic == null) {
576 ruleContents = m.replaceAll("null");
578 ruleContents = m.replaceAll(notificationTopic);
581 p = Pattern.compile("\\$\\{appcTopic\\}");
582 m = p.matcher(ruleContents);
583 if (appcTopic == null) {
584 ruleContents = m.replaceAll("null");
586 ruleContents = m.replaceAll(appcTopic);
589 logger.debug(ruleContents);