[POLICY-11] Sample Query with variable arguments
[policy/drools-applications.git] / template.demo / src / test / java / org / openecomp / policy / template / demo / TestFirewallDemo.java
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.openecomp.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.Ignore;
36 import org.junit.Test;
37 import org.kie.api.KieServices;
38 import org.kie.api.builder.KieBuilder;
39 import org.kie.api.builder.KieFileSystem;
40 import org.kie.api.builder.Message;
41 import org.kie.api.builder.ReleaseId;
42 import org.kie.api.builder.Results;
43 import org.kie.api.builder.model.KieModuleModel;
44 import org.kie.api.runtime.KieContainer;
45 import org.kie.api.runtime.KieSession;
46 import org.kie.api.runtime.rule.FactHandle;
47 import org.openecomp.policy.appc.CommonHeader;
48 import org.openecomp.policy.appc.Response;
49 import org.openecomp.policy.appc.ResponseStatus;
50 import org.openecomp.policy.controlloop.ControlLoopEventStatus;
51 import org.openecomp.policy.controlloop.ControlLoopTargetType;
52 import org.openecomp.policy.controlloop.VirtualControlLoopEvent;
53 import org.openecomp.policy.controlloop.util.Serialization;
54
55
56
57 public class TestFirewallDemo {
58
59         
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                                 "MSO",
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                                 System.out.println("----- Invalid ONSET -----");
110                                 System.out.println(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                                 System.out.println("----- ONSET -----");
136                                 System.out.println(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.openecomp.policy.controlloop.Params", fact.getClass().getName());
173                 }
174         }
175         
176         @Ignore
177         @Test
178         public void testvFirewall() throws IOException {
179                 //
180                 // Build a container
181                 //
182                 final String closedLoopControlName = "CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8";
183                 final KieSession kieSession = buildContainer("src/main/resources/archetype-resources/src/main/resources/ControlLoopDemo__closedLoopControlName__.drl", 
184                                 closedLoopControlName, 
185                                 "type=operational", 
186                                 "myFirewallDemoPolicy", 
187                                 "v1.0",
188                                 "APPC",
189                                 "http://localhost:8080/TestREST/Test",
190                                 "POLICY",
191                                 "POLICY",
192                                 null,
193                                 null,
194                                 null,
195                                 null,
196                                 1,
197                                 "POLICY-CL-MGT",
198                                 "APPC-CL"
199                                 );
200                 //
201                 // Initial fire of rules
202                 //
203                 kieSession.fireAllRules();
204                 //
205                 // Kick a thread that starts testing
206                 //
207                 new Thread(new Runnable() {
208
209                         @Override
210                         public void run() {
211                                 //
212                                 // Generate an invalid DCAE Event with requestID=null
213                                 //
214                                 VirtualControlLoopEvent invalidEvent = new VirtualControlLoopEvent();
215                                 invalidEvent.closedLoopControlName = closedLoopControlName;
216                                 invalidEvent.requestID = null;
217                                 invalidEvent.closedLoopEventClient = "tca.instance00001";
218                                 invalidEvent.target_type = ControlLoopTargetType.VF;
219                                 invalidEvent.target = "generic-vnf.vnf-id";
220                                 invalidEvent.from = "DCAE";
221                                 invalidEvent.closedLoopAlarmStart = Instant.now();
222                                 invalidEvent.AAI = new HashMap<String, String>();
223                                 invalidEvent.AAI.put("generic-vnf.vnf-id", "foo");
224                                 invalidEvent.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
225                                 
226                                 System.out.println("----- Invalid ONSET -----");
227                                 System.out.println(Serialization.gsonPretty.toJson(invalidEvent));
228                                 
229                                 //
230                                 // Insert invalid DCAE Event into memory
231                                 //
232                                 kieSession.insert(invalidEvent);        
233                                 try {
234                                         Thread.sleep(500);
235                                 } catch (InterruptedException e) {
236                                 }
237                                 //
238                                 // Generate first DCAE ONSET Event
239                                 //
240                                 VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
241                                 onsetEvent.closedLoopControlName = closedLoopControlName;
242                                 onsetEvent.requestID = UUID.randomUUID();
243                                 onsetEvent.closedLoopEventClient = "tca.instance00001";
244                                 onsetEvent.target_type = ControlLoopTargetType.VF;
245                                 onsetEvent.target = "generic-vnf.vnf-id";
246                                 onsetEvent.from = "DCAE";
247                                 onsetEvent.closedLoopAlarmStart = Instant.now();
248                                 onsetEvent.AAI = new HashMap<String, String>();
249                                 onsetEvent.AAI.put("generic-vnf.vnf-id", "fw0001vm001fw001");
250                                 //onsetEvent.AAI.put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1");
251                                 onsetEvent.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
252                                 
253                                 System.out.println("----- ONSET -----");
254                                 System.out.println(Serialization.gsonPretty.toJson(onsetEvent));
255                                 
256                                 //
257                                 // Insert first DCAE ONSET Event into memory
258                                 //
259                                 kieSession.insert(onsetEvent);
260                                 try {
261                                         Thread.sleep(500);
262                                 } catch (InterruptedException e) {
263                                 }
264                                 
265                                 
266                                 Thread thread = new Thread(new Runnable() {
267
268                                         @Override
269                                         public void run() {
270                                                 while (true) {
271                                                         //
272                                                         // Generate subsequent DCAE ONSET Event
273                                                         //
274                                                         VirtualControlLoopEvent subOnsetEvent = new VirtualControlLoopEvent();
275                                                         subOnsetEvent.closedLoopControlName = closedLoopControlName;
276                                                         subOnsetEvent.requestID = UUID.randomUUID();
277                                                         subOnsetEvent.closedLoopEventClient = "tca.instance00001";
278                                                         subOnsetEvent.target_type = ControlLoopTargetType.VF;
279                                                         subOnsetEvent.target = "generic-vnf.vnf-id";
280                                                         subOnsetEvent.from = "DCAE";
281                                                         subOnsetEvent.closedLoopAlarmStart = Instant.now();
282                                                         subOnsetEvent.AAI = new HashMap<String, String>();
283                                                         subOnsetEvent.AAI.put("generic-vnf.vnf-id", "fw0001vm001fw001");
284                                                         //subOnsetEvent.AAI.put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1");
285                                                         subOnsetEvent.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
286                                                         
287                                                         System.out.println("----- Subsequent ONSET -----");
288                                                         System.out.println(Serialization.gsonPretty.toJson(subOnsetEvent));
289                                                         
290                                                         //
291                                                         // Insert subsequent DCAE ONSET Event into memory
292                                                         //
293                                                         kieSession.insert(subOnsetEvent);
294                                                         try {
295                                                                 Thread.sleep(500);
296                                                         } catch (InterruptedException e) {
297                                                                 break;
298                                                         }
299                                                 }
300                                         }
301                                         
302                                 });
303                                 thread.start();
304                                 try {
305                                         Thread.sleep(3000);
306                                 } catch (InterruptedException e) {
307                                 }
308                                 //
309                                 // Stop the thread
310                                 //
311                                 thread.interrupt();
312                                 //
313                                 // Generate APPC ACCEPT Response
314                                 //
315                                 Response response1 = new Response();
316                                 // CommonHeader
317                                 CommonHeader commonHeader1 = new CommonHeader();
318                                 commonHeader1.RequestID = onsetEvent.requestID;
319                                 response1.CommonHeader = commonHeader1;
320                                 // ResponseStatus
321                                 ResponseStatus responseStatus1 = new ResponseStatus();
322                                 responseStatus1.Code = 100;
323                                 response1.Status = responseStatus1;
324                                 //
325                                 System.out.println("----- APP-C RESPONSE 100 -----");
326                                 System.out.println(Serialization.gsonPretty.toJson(response1));
327                                 //
328                                 // Insert APPC Response into memory
329                                 //
330                                 kieSession.insert(response1);
331                                 //
332                                 // Simulating APPC takes some time for processing the recipe 
333                                 // and then gives response
334                                 //
335                                 try {
336                                         Thread.sleep(1000);
337                                 } catch (InterruptedException e) {
338                                 }
339                                 //
340                                 // Generate APPC SUCCESS Response
341                                 //
342                                 Response response2 = new Response();
343                                 // CommonHeader
344                                 CommonHeader commonHeader2 = new CommonHeader();
345                                 commonHeader2.RequestID = onsetEvent.requestID;
346                                 response2.CommonHeader = commonHeader2;
347                                 // ResponseStatus
348                                 ResponseStatus responseStatus2 = new ResponseStatus();
349                                 responseStatus2.Code = 400;
350                                 response2.Status = responseStatus2;
351                                 //
352                                 System.out.println("----- APP-C RESPONSE 400 -----");
353                                 System.out.println(Serialization.gsonPretty.toJson(response2));
354                                 //
355                                 // Insert APPC Response into memory
356                                 //
357                                 kieSession.insert(response2);
358                                 //
359                                 try {
360                                         Thread.sleep(3000);
361                                 } catch (InterruptedException e) {
362                                 }
363                                 //
364                                 // Test is finished, so stop the kieSession
365                                 //
366                                 kieSession.halt();
367                         }
368                 //
369                 }).start();
370                 //
371                 // Start firing rules
372                 //
373                 kieSession.fireUntilHalt();
374                 //
375                 // Dump working memory
376                 //
377                 dumpFacts(kieSession);
378                 //
379                 // See if there is anything left in memory, there SHOULD only be
380                 // a params fact.
381                 //
382                 assertEquals("There should only be 1 Fact left in memory.", 1, kieSession.getFactCount());
383                 for (FactHandle handle : kieSession.getFactHandles()) {
384                         Object fact = kieSession.getObject(handle);
385                         assertEquals("Non-Param Fact left in working memory", "org.openecomp.policy.controlloop.Params", fact.getClass().getName());
386                 }
387         }
388         
389         public static void dumpFacts(KieSession kieSession) {
390                 System.out.println("Fact Count: " + kieSession.getFactCount());
391                 for (FactHandle handle : kieSession.getFactHandles()) {
392                         System.out.println("FACT: " + handle);
393                 }
394         }
395
396         public static KieSession buildContainer(String droolsTemplate, 
397                         String closedLoopControlName, 
398                         String policyScope, 
399                         String policyName, 
400                         String policyVersion, 
401                         String actor, 
402                         String aaiURL,
403                         String aaiUsername,
404                         String aaiPassword,
405                         String msoURL,
406                         String msoUsername,
407                         String msoPassword,
408                         String aaiNamedQuery,
409                         int aaiPatternMatch,
410                         String notificationTopic,
411                         String appcTopic ) throws IOException {
412                 //
413         // Get our Drools Kie factory
414         //
415         KieServices ks = KieServices.Factory.get();
416         
417         KieModuleModel kModule = ks.newKieModuleModel();
418         
419         System.out.println("KMODULE:" + System.lineSeparator() + kModule.toXML());
420         
421         //
422         // Generate our drools rule from our template
423         //
424         KieFileSystem kfs = ks.newKieFileSystem();
425         
426         kfs.writeKModuleXML(kModule.toXML());
427         {
428                 Path rule = Paths.get(droolsTemplate);
429                 String ruleTemplate = new String(Files.readAllBytes(rule));
430                 String drlContents = generatePolicy(ruleTemplate,
431                                                                 closedLoopControlName,
432                                                                 policyScope,
433                                                                         policyName,
434                                                                         policyVersion,
435                                                                         actor,
436                                                                         aaiURL,
437                                                                         aaiUsername,
438                                                                         aaiPassword,
439                                                                         msoURL,
440                                                                         msoUsername,
441                                                                         msoPassword,
442                                                                         aaiNamedQuery,
443                                                                         aaiPatternMatch,
444                                                                         notificationTopic,
445                                                                         appcTopic
446                                                                         );
447                 
448                 kfs.write("src/main/resources/" + policyName + ".drl", ks.getResources().newByteArrayResource(drlContents.getBytes()));
449         }
450         //
451         // Compile the rule
452         //
453         KieBuilder builder = ks.newKieBuilder(kfs).buildAll();
454         Results results = builder.getResults();
455         if (results.hasMessages(Message.Level.ERROR)) {
456                 for (Message msg : results.getMessages()) {
457                         System.err.println(msg.toString());
458                 }
459                 throw new RuntimeException("Drools Rule has Errors");
460         }
461         for (Message msg : results.getMessages()) {
462                 System.out.println(msg.toString());
463         }
464         //
465         // Create our kie Session and container
466         //
467         ReleaseId releaseId = ks.getRepository().getDefaultReleaseId();
468         System.out.println(releaseId);
469             KieContainer kContainer = ks.newKieContainer(releaseId);
470             
471             return kContainer.newKieSession();
472         }
473         public static String    generatePolicy(String ruleContents, 
474                         String closedLoopControlName, 
475                         String policyScope, 
476                         String policyName, 
477                         String policyVersion,
478                         String actor,
479                         String aaiURL,
480                         String aaiUsername,
481                         String aaiPassword,
482                         String msoURL,
483                         String msoUsername,
484                         String msoPassword,
485                         String aaiNamedQueryUUID,
486                         int aaiPatternMatch,
487                         String notificationTopic,
488                         String appcTopic) {
489
490                 Pattern p = Pattern.compile("\\$\\{closedLoopControlName\\}");
491                 Matcher m = p.matcher(ruleContents);
492                 ruleContents = m.replaceAll(closedLoopControlName);
493
494                 p = Pattern.compile("\\$\\{policyScope\\}");
495                 m = p.matcher(ruleContents);
496                 ruleContents = m.replaceAll(policyScope);
497
498                 p = Pattern.compile("\\$\\{policyName\\}");
499                 m = p.matcher(ruleContents);
500                 ruleContents = m.replaceAll(policyName);
501
502                 p = Pattern.compile("\\$\\{policyVersion\\}");
503                 m = p.matcher(ruleContents);
504                 ruleContents = m.replaceAll(policyVersion);
505                 
506                 p = Pattern.compile("\\$\\{actor\\}");
507                 m = p.matcher(ruleContents);
508                 ruleContents = m.replaceAll(actor);
509                 
510                 p = Pattern.compile("\\$\\{aaiURL\\}");
511                 m = p.matcher(ruleContents);
512                 if (aaiURL == null) {
513                         ruleContents = m.replaceAll("null");
514                 } else {
515                         ruleContents = m.replaceAll(aaiURL);
516                 }
517                 
518                 p = Pattern.compile("\\$\\{aaiUsername\\}");
519                 m = p.matcher(ruleContents);
520                 if (aaiUsername == null) {
521                         ruleContents = m.replaceAll("null");
522                 } else {
523                         ruleContents = m.replaceAll(aaiUsername);
524                 }
525
526                 p = Pattern.compile("\\$\\{aaiPassword\\}");
527                 m = p.matcher(ruleContents);
528                 if (aaiPassword == null) {
529                         ruleContents = m.replaceAll("null");
530                 } else {
531                         ruleContents = m.replaceAll(aaiPassword);
532                 }
533
534                 p = Pattern.compile("\\$\\{msoURL\\}");
535                 m = p.matcher(ruleContents);
536                 if (msoURL == null) {
537                         ruleContents = m.replaceAll("null");
538                 } else {
539                         ruleContents = m.replaceAll(msoURL);
540                 }
541
542                 p = Pattern.compile("\\$\\{msoUsername\\}");
543                 m = p.matcher(ruleContents);
544                 if (msoUsername == null) {
545                         ruleContents = m.replaceAll("null");
546                 } else {
547                         ruleContents = m.replaceAll(msoUsername);
548                 }
549
550                 p = Pattern.compile("\\$\\{msoPassword\\}");
551                 m = p.matcher(ruleContents);
552                 if (msoPassword == null) {
553                         ruleContents = m.replaceAll("null");
554                 } else {
555                         ruleContents = m.replaceAll(msoPassword);
556                 }
557
558                 p = Pattern.compile("\\$\\{aaiNamedQueryUUID\\}");
559                 m = p.matcher(ruleContents);
560                 if (aaiNamedQueryUUID == null) {
561                         ruleContents = m.replaceAll("null");
562                 } else {
563                         ruleContents = m.replaceAll(aaiNamedQueryUUID);
564                 }
565
566                 p = Pattern.compile("\\$\\{aaiPatternMatch\\}");
567                 m = p.matcher(ruleContents);
568                 if (aaiPatternMatch == 1) {
569                         ruleContents = m.replaceAll("1");
570                 } else {
571                         ruleContents = m.replaceAll("0");
572                 }
573                 
574                 p = Pattern.compile("\\$\\{notificationTopic\\}");
575                 m = p.matcher(ruleContents);
576                 if (notificationTopic == null) {
577                         ruleContents = m.replaceAll("null");
578                 } else {
579                         ruleContents = m.replaceAll(notificationTopic);
580                 }
581                 
582                 p = Pattern.compile("\\$\\{appcTopic\\}");
583                 m = p.matcher(ruleContents);
584                 if (appcTopic == null) {
585                         ruleContents = m.replaceAll("null");
586                 } else {
587                         ruleContents = m.replaceAll(appcTopic);
588                 }
589                 
590                 System.out.println(ruleContents);
591
592                 return ruleContents;
593         }
594
595 }