825c69b5055083f2707cbf7cbe5c95c5b9050676
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * demo
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.onap.policy.template.demo;
22
23 import static org.junit.Assert.assertEquals;
24
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;
34
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;
55
56
57 public class TestFirewallDemo {
58
59         private static final Logger logger = LoggerFactory.getLogger(TestFirewallDemo.class);
60         @Test
61         public void testvDNS() throws IOException {
62                 //
63                 // Build a container
64                 //
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, 
68                                 "type=operational", 
69                                 "myFirewallDemoPolicy", 
70                                 "v1.0",
71                                 "SO",
72                                 "http://localhost:8080/TestREST/Test",
73                                 "POLICY",
74                                 "POLICY",
75                                 "http://localhost:8080/TestREST/Test",
76                                 "POLICY",
77                                 "POLICY",
78                                 "4ff56a54-9e3f-46b7-a337-07a1d3c6b469",
79                                 0,
80                                 "POLICY-CL-MGT",
81                                 "APPC-CL"
82                                 );
83                 //
84                 // Initial fire of rules
85                 //
86                 kieSession.fireAllRules();
87                 //
88                 // Kick a thread that starts testing
89                 //
90                 new Thread(new Runnable() {
91
92                         @Override
93                         public void run() {
94                                 //
95                                 // Generate an invalid DCAE Event with requestID=null
96                                 //
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;
108                                 
109                                 logger.debug("----- Invalid ONSET -----");
110                                 logger.debug(Serialization.gsonPretty.toJson(invalidEvent));
111                                 
112                                 //
113                                 // Insert invalid DCAE Event into memory
114                                 //
115                                 kieSession.insert(invalidEvent);        
116                                 try {
117                                         Thread.sleep(500);
118                                 } catch (InterruptedException e) {
119                                 }
120                                 //
121                                 // Generate first DCAE ONSET Event
122                                 //
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;
134                                 
135                                 logger.debug("----- ONSET -----");
136                                 logger.debug(Serialization.gsonPretty.toJson(onsetEvent));
137                                 
138                                 //
139                                 // Insert first DCAE ONSET Event into memory
140                                 //
141                                 kieSession.insert(onsetEvent);
142                                 //
143                                 // We have test for subsequent ONSET Events in testvFirewall()
144                                 // So no need to test it again here
145                                 //
146                                 try {
147                                         Thread.sleep(3000);
148                                 } catch (InterruptedException e) {
149                                 }
150                                 //
151                                 // Test is finished, so stop the kieSession
152                                 //
153                                 kieSession.halt();
154                         }
155                 //
156                 }).start();
157                 //
158                 // Start firing rules
159                 //
160                 kieSession.fireUntilHalt();
161                 //
162                 // Dump working memory
163                 //
164                 dumpFacts(kieSession);
165                 //
166                 // See if there is anything left in memory, there SHOULD only be
167                 // a params fact.
168                 //
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());
173                 }
174         }
175         
176         @Test
177         public void testvFirewall() throws IOException {
178                 //
179                 // Build a container
180                 //
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, 
184                                 "type=operational", 
185                                 "myFirewallDemoPolicy", 
186                                 "v1.0",
187                                 "APPC",
188                                 "http://localhost:8080/TestREST/Test",
189                                 "POLICY",
190                                 "POLICY",
191                                 null,
192                                 null,
193                                 null,
194                                 null,
195                                 1,
196                                 "POLICY-CL-MGT",
197                                 "APPC-CL"
198                                 );
199                 //
200                 // Initial fire of rules
201                 //
202                 kieSession.fireAllRules();
203                 //
204                 // Kick a thread that starts testing
205                 //
206                 new Thread(new Runnable() {
207
208                         @Override
209                         public void run() {
210                                 //
211                                 // Generate an invalid DCAE Event with requestID=null
212                                 //
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;
224                                 
225                                 logger.debug("----- Invalid ONSET -----");
226                                 logger.debug(Serialization.gsonPretty.toJson(invalidEvent));
227                                 
228                                 //
229                                 // Insert invalid DCAE Event into memory
230                                 //
231                                 kieSession.insert(invalidEvent);        
232                                 try {
233                                         Thread.sleep(500);
234                                 } catch (InterruptedException e) {
235                                 }
236                                 //
237                                 // Generate first DCAE ONSET Event
238                                 //
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;
251                                 
252                                 logger.debug("----- ONSET -----");
253                                 logger.debug(Serialization.gsonPretty.toJson(onsetEvent));
254                                 
255                                 //
256                                 // Insert first DCAE ONSET Event into memory
257                                 //
258                                 kieSession.insert(onsetEvent);
259                                 try {
260                                         Thread.sleep(500);
261                                 } catch (InterruptedException e) {
262                                 }
263                                 
264                                 
265                                 Thread thread = new Thread(new Runnable() {
266
267                                         @Override
268                                         public void run() {
269                                                 while (true) {
270                                                         //
271                                                         // Generate subsequent DCAE ONSET Event
272                                                         //
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;
285                                                         
286                                                         logger.debug("----- Subsequent ONSET -----");
287                                                         logger.debug(Serialization.gsonPretty.toJson(subOnsetEvent));
288                                                         
289                                                         //
290                                                         // Insert subsequent DCAE ONSET Event into memory
291                                                         //
292                                                         kieSession.insert(subOnsetEvent);
293                                                         try {
294                                                                 Thread.sleep(500);
295                                                         } catch (InterruptedException e) {
296                                                                 break;
297                                                         }
298                                                 }
299                                         }
300                                         
301                                 });
302                                 thread.start();
303                                 try {
304                                         Thread.sleep(3000);
305                                 } catch (InterruptedException e) {
306                                 }
307                                 //
308                                 // Stop the thread
309                                 //
310                                 thread.interrupt();
311                                 //
312                                 // Generate APPC ACCEPT Response
313                                 //
314                                 Response response1 = new Response();
315                                 // CommonHeader
316                                 CommonHeader commonHeader1 = new CommonHeader();
317                                 commonHeader1.RequestID = onsetEvent.requestID;
318                                 response1.CommonHeader = commonHeader1;
319                                 // ResponseStatus
320                                 ResponseStatus responseStatus1 = new ResponseStatus();
321                                 responseStatus1.Code = 100;
322                                 response1.Status = responseStatus1;
323                                 //
324                                 logger.debug("----- APP-C RESPONSE 100 -----");
325                                 logger.debug(Serialization.gsonPretty.toJson(response1));
326                                 //
327                                 // Insert APPC Response into memory
328                                 //
329                                 kieSession.insert(response1);
330                                 //
331                                 // Simulating APPC takes some time for processing the recipe 
332                                 // and then gives response
333                                 //
334                                 try {
335                                         Thread.sleep(1000);
336                                 } catch (InterruptedException e) {
337                                 }
338                                 //
339                                 // Generate APPC SUCCESS Response
340                                 //
341                                 Response response2 = new Response();
342                                 // CommonHeader
343                                 CommonHeader commonHeader2 = new CommonHeader();
344                                 commonHeader2.RequestID = onsetEvent.requestID;
345                                 response2.CommonHeader = commonHeader2;
346                                 // ResponseStatus
347                                 ResponseStatus responseStatus2 = new ResponseStatus();
348                                 responseStatus2.Code = 400;
349                                 response2.Status = responseStatus2;
350                                 //
351                                 logger.debug("----- APP-C RESPONSE 400 -----");
352                                 logger.debug(Serialization.gsonPretty.toJson(response2));
353                                 //
354                                 // Insert APPC Response into memory
355                                 //
356                                 kieSession.insert(response2);
357                                 //
358                                 try {
359                                         Thread.sleep(3000);
360                                 } catch (InterruptedException e) {
361                                 }
362                                 //
363                                 // Test is finished, so stop the kieSession
364                                 //
365                                 kieSession.halt();
366                         }
367                 //
368                 }).start();
369                 //
370                 // Start firing rules
371                 //
372                 kieSession.fireUntilHalt();
373                 //
374                 // Dump working memory
375                 //
376                 dumpFacts(kieSession);
377                 //
378                 // See if there is anything left in memory, there SHOULD only be
379                 // a params fact.
380                 //
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());
385                 }
386         }
387         
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);
392                 }
393         }
394
395         public static KieSession buildContainer(String droolsTemplate, 
396                         String closedLoopControlName, 
397                         String policyScope, 
398                         String policyName, 
399                         String policyVersion, 
400                         String actor, 
401                         String aaiURL,
402                         String aaiUsername,
403                         String aaiPassword,
404                         String msoURL,
405                         String msoUsername,
406                         String msoPassword,
407                         String aaiNamedQuery,
408                         int aaiPatternMatch,
409                         String notificationTopic,
410                         String appcTopic ) throws IOException {
411                 //
412         // Get our Drools Kie factory
413         //
414         KieServices ks = KieServices.Factory.get();
415         
416         KieModuleModel kModule = ks.newKieModuleModel();
417         
418         logger.debug("KMODULE: {} {}", System.lineSeparator(), kModule.toXML());
419         
420         //
421         // Generate our drools rule from our template
422         //
423         KieFileSystem kfs = ks.newKieFileSystem();
424         
425         kfs.writeKModuleXML(kModule.toXML());
426         {
427                 Path rule = Paths.get(droolsTemplate);
428                 String ruleTemplate = new String(Files.readAllBytes(rule));
429                 String drlContents = generatePolicy(ruleTemplate,
430                                                                 closedLoopControlName,
431                                                                 policyScope,
432                                                                         policyName,
433                                                                         policyVersion,
434                                                                         actor,
435                                                                         aaiURL,
436                                                                         aaiUsername,
437                                                                         aaiPassword,
438                                                                         msoURL,
439                                                                         msoUsername,
440                                                                         msoPassword,
441                                                                         aaiNamedQuery,
442                                                                         aaiPatternMatch,
443                                                                         notificationTopic,
444                                                                         appcTopic
445                                                                         );
446                 
447                 kfs.write("src/main/resources/" + policyName + ".drl", ks.getResources().newByteArrayResource(drlContents.getBytes()));
448         }
449         //
450         // Compile the rule
451         //
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);
457                 }
458                 throw new RuntimeException("Drools Rule has Errors");
459         }
460         for (Message msg : results.getMessages()) {
461                 logger.debug("{}", msg);
462         }
463         //
464         // Create our kie Session and container
465         //
466         ReleaseId releaseId = ks.getRepository().getDefaultReleaseId();
467         logger.debug("{}", releaseId);
468             KieContainer kContainer = ks.newKieContainer(releaseId);
469             
470             return kContainer.newKieSession();
471         }
472         public static String    generatePolicy(String ruleContents, 
473                         String closedLoopControlName, 
474                         String policyScope, 
475                         String policyName, 
476                         String policyVersion,
477                         String actor,
478                         String aaiURL,
479                         String aaiUsername,
480                         String aaiPassword,
481                         String msoURL,
482                         String msoUsername,
483                         String msoPassword,
484                         String aaiNamedQueryUUID,
485                         int aaiPatternMatch,
486                         String notificationTopic,
487                         String appcTopic) {
488
489                 Pattern p = Pattern.compile("\\$\\{closedLoopControlName\\}");
490                 Matcher m = p.matcher(ruleContents);
491                 ruleContents = m.replaceAll(closedLoopControlName);
492
493                 p = Pattern.compile("\\$\\{policyScope\\}");
494                 m = p.matcher(ruleContents);
495                 ruleContents = m.replaceAll(policyScope);
496
497                 p = Pattern.compile("\\$\\{policyName\\}");
498                 m = p.matcher(ruleContents);
499                 ruleContents = m.replaceAll(policyName);
500
501                 p = Pattern.compile("\\$\\{policyVersion\\}");
502                 m = p.matcher(ruleContents);
503                 ruleContents = m.replaceAll(policyVersion);
504                 
505                 p = Pattern.compile("\\$\\{actor\\}");
506                 m = p.matcher(ruleContents);
507                 ruleContents = m.replaceAll(actor);
508                 
509                 p = Pattern.compile("\\$\\{aaiURL\\}");
510                 m = p.matcher(ruleContents);
511                 if (aaiURL == null) {
512                         ruleContents = m.replaceAll("null");
513                 } else {
514                         ruleContents = m.replaceAll(aaiURL);
515                 }
516                 
517                 p = Pattern.compile("\\$\\{aaiUsername\\}");
518                 m = p.matcher(ruleContents);
519                 if (aaiUsername == null) {
520                         ruleContents = m.replaceAll("null");
521                 } else {
522                         ruleContents = m.replaceAll(aaiUsername);
523                 }
524
525                 p = Pattern.compile("\\$\\{aaiPassword\\}");
526                 m = p.matcher(ruleContents);
527                 if (aaiPassword == null) {
528                         ruleContents = m.replaceAll("null");
529                 } else {
530                         ruleContents = m.replaceAll(aaiPassword);
531                 }
532
533                 p = Pattern.compile("\\$\\{msoURL\\}");
534                 m = p.matcher(ruleContents);
535                 if (msoURL == null) {
536                         ruleContents = m.replaceAll("null");
537                 } else {
538                         ruleContents = m.replaceAll(msoURL);
539                 }
540
541                 p = Pattern.compile("\\$\\{msoUsername\\}");
542                 m = p.matcher(ruleContents);
543                 if (msoUsername == null) {
544                         ruleContents = m.replaceAll("null");
545                 } else {
546                         ruleContents = m.replaceAll(msoUsername);
547                 }
548
549                 p = Pattern.compile("\\$\\{msoPassword\\}");
550                 m = p.matcher(ruleContents);
551                 if (msoPassword == null) {
552                         ruleContents = m.replaceAll("null");
553                 } else {
554                         ruleContents = m.replaceAll(msoPassword);
555                 }
556
557                 p = Pattern.compile("\\$\\{aaiNamedQueryUUID\\}");
558                 m = p.matcher(ruleContents);
559                 if (aaiNamedQueryUUID == null) {
560                         ruleContents = m.replaceAll("null");
561                 } else {
562                         ruleContents = m.replaceAll(aaiNamedQueryUUID);
563                 }
564
565                 p = Pattern.compile("\\$\\{aaiPatternMatch\\}");
566                 m = p.matcher(ruleContents);
567                 if (aaiPatternMatch == 1) {
568                         ruleContents = m.replaceAll("1");
569                 } else {
570                         ruleContents = m.replaceAll("0");
571                 }
572                 
573                 p = Pattern.compile("\\$\\{notificationTopic\\}");
574                 m = p.matcher(ruleContents);
575                 if (notificationTopic == null) {
576                         ruleContents = m.replaceAll("null");
577                 } else {
578                         ruleContents = m.replaceAll(notificationTopic);
579                 }
580                 
581                 p = Pattern.compile("\\$\\{appcTopic\\}");
582                 m = p.matcher(ruleContents);
583                 if (appcTopic == null) {
584                         ruleContents = m.replaceAll("null");
585                 } else {
586                         ruleContents = m.replaceAll(appcTopic);
587                 }
588                 
589                 logger.debug(ruleContents);
590
591                 return ruleContents;
592         }
593
594 }