a4845693ce075f9db5efbce1723d356e400ffdd7
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * demo
4  * ================================================================================
5  * Copyright (C) 2017 Intel Corp. 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.assertNotNull;
24 import static org.junit.Assert.assertTrue;
25 import static org.junit.Assert.fail;
26
27 import java.io.IOException;
28 import java.net.URLEncoder;
29 import java.time.Instant;
30 import java.util.HashMap;
31 import java.util.UUID;
32
33 import org.junit.AfterClass;
34 import org.junit.BeforeClass;
35 import org.junit.Test;
36 import org.kie.api.runtime.KieSession;
37 import org.kie.api.runtime.rule.FactHandle;
38 import org.onap.policy.controlloop.ControlLoopEventStatus;
39 import org.onap.policy.controlloop.ControlLoopLogger;
40 import org.onap.policy.controlloop.ControlLoopTargetType;
41 import org.onap.policy.controlloop.VirtualControlLoopEvent;
42 import org.onap.policy.controlloop.impl.ControlLoopLoggerStdOutImpl;
43 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
44 import org.onap.policy.drools.http.server.HttpServletServer;
45 import org.onap.policy.drools.impl.PolicyEngineJUnitImpl;
46 import org.onap.policy.drools.system.PolicyEngine;
47 import org.onap.policy.vfc.util.Serialization;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51
52 public class VFCControlLoopTest {
53
54         private static final Logger log = LoggerFactory.getLogger(VFCControlLoopTest.class);
55         private KieSession kieSession;
56         private Util.Pair<ControlLoopPolicy, String> pair;
57         private PolicyEngineJUnitImpl engine;
58
59         static {
60             /* Set environment properties */
61         Util.setAAIProps();
62         
63         PolicyEngine.manager.setEnvironmentProperty("vfc.url", "http://localhost:6668");
64         PolicyEngine.manager.setEnvironmentProperty("vfc.username", "VFC");
65         PolicyEngine.manager.setEnvironmentProperty("vfc.password", "VFC");
66         }
67         
68         @BeforeClass
69         public static void setUpSimulator() {
70                 try {
71                         Util.buildAaiSim();
72                         Util.buildVfcSim();
73                 } catch (Exception e) {
74                         fail(e.getMessage());
75                 }
76         }
77
78         @AfterClass
79         public static void tearDownSimulator() {
80                 HttpServletServer.factory.destroy();
81         }
82
83         @Test
84         public void testVolte() throws IOException {
85
86                 final String yaml = "src/test/resources/yaml/policy_ControlLoop_VFC.yaml";
87
88                 //
89                 // Pull info from the yaml
90                 //
91                 final Util.Pair<ControlLoopPolicy, String> pair = Util.loadYaml(yaml);
92                 assertNotNull(pair);
93                 assertNotNull(pair.a);
94                 assertNotNull(pair.a.getControlLoop());
95                 assertNotNull(pair.a.getControlLoop().getControlLoopName());
96                 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
97                 final String closedLoopControlName = pair.a.getControlLoop().getControlLoopName();
98
99                  /*
100          * Start the kie session
101          */
102                 try {
103                         kieSession = startSession("src/main/resources/ControlLoop_Template_xacml_guard.drl",
104                                         "src/test/resources/yaml/policy_ControlLoop_VFC.yaml",
105                                         "service=ServiceTest;resource=ResourceTest;type=operational",
106                                         "CL_VFC",
107                                         "org.onap.closed_loop.ServiceTest:VNFS:1.0.0");
108                 } catch (IOException e) {
109                         e.printStackTrace();
110                         log.debug("Could not create kieSession");
111                         fail("Could not create kieSession");
112                 }
113
114
115                 //
116                 // Insert our globals
117                 //
118                 final ControlLoopLogger logger = new ControlLoopLoggerStdOutImpl();
119                 kieSession.setGlobal("Logger", logger);
120                 final PolicyEngineJUnitImpl engine = new PolicyEngineJUnitImpl();
121                 kieSession.setGlobal("Engine", engine);
122
123                 //
124                 // Initial fire of rules
125                 //
126                 kieSession.fireAllRules();
127                 //
128                 // Kick a thread that starts testing
129                 //
130                 new Thread(new Runnable() {
131
132                         @Override
133                         public void run() {
134
135                                 log.debug("\n************ Starting VoLTE Test *************\n");
136
137                                 //
138                                 // Generate an invalid DCAE Event with requestID=null
139                                 //
140                                 VirtualControlLoopEvent invalidEvent = new VirtualControlLoopEvent();
141                                 invalidEvent.closedLoopControlName = closedLoopControlName;
142                                 invalidEvent.requestID = null;
143                                 invalidEvent.closedLoopEventClient = "tca.instance00009";
144                                 invalidEvent.target_type = ControlLoopTargetType.VNF;
145                                 invalidEvent.target = "generic-vnf.vnf-id";
146                                 invalidEvent.from = "DCAE";
147                                 invalidEvent.closedLoopAlarmStart = Instant.now();
148                                 invalidEvent.AAI = new HashMap<String, String>();
149                                 invalidEvent.AAI.put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1");
150                                 invalidEvent.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
151
152                                 log.debug("-------- Sending Invalid ONSET --------");
153                                 log.debug(Serialization.gsonPretty.toJson(invalidEvent));
154
155                                 //
156                                 // Insert invalid DCAE Event into memory
157                                 //
158                                 kieSession.insert(invalidEvent);
159                                 try {
160                                         Thread.sleep(500);
161                                 } catch (InterruptedException e) {
162                                 }
163                                 //
164                                 // Generate first DCAE ONSET Event
165                                 //
166                                 VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
167                                 onsetEvent.closedLoopControlName = closedLoopControlName;
168                                 onsetEvent.requestID = UUID.randomUUID();
169                                 onsetEvent.closedLoopEventClient = "tca.instance00009";
170                                 onsetEvent.target_type = ControlLoopTargetType.VM;
171                                 onsetEvent.target = "VM_NAME";
172                                 onsetEvent.from = "DCAE";
173                                 onsetEvent.closedLoopAlarmStart = Instant.now();
174                                 onsetEvent.AAI = new HashMap<String, String>();
175                                 onsetEvent.AAI.put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1");
176                                 onsetEvent.AAI.put("vserver.vserver-id", "vserver-id-16102016-aai3255-data-11-1");
177                                 onsetEvent.AAI.put("generic-vnf.vnf-id", "vnf-id-16102016-aai3255-data-11-1");
178                                 onsetEvent.AAI.put("service-instance.service-instance-id", "service-instance-id-16102016-aai3255-data-11-1");
179                                 onsetEvent.AAI.put("vserver.is-closed-loop-disabled", "false");
180                                 onsetEvent.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
181
182                                 log.debug("-------- Sending Valid ONSET --------");
183                                 log.debug(Serialization.gsonPretty.toJson(onsetEvent));
184
185                                 //
186                                 // Insert first DCAE ONSET Event into memory
187                                 //
188                                 kieSession.insert(onsetEvent);
189                                 //
190                                 // We have test for subsequent ONSET Events in testvFirewall()
191                                 // So no need to test it again here
192                                 //
193                                 try {
194                                         Thread.sleep(30000);
195                                 } catch (InterruptedException e) {
196                                 }
197                                 //
198                                 // Test is finished, so stop the kieSession
199                                 //
200                                 kieSession.halt();
201                         }
202                 //
203                 }).start();
204                 //
205                 // Start firing rules
206                 //
207                 kieSession.fireUntilHalt();
208                 //
209                 // Dump working memory
210                 //
211                 dumpFacts(kieSession);
212
213                 //
214                 // See if there is anything left in memory, there SHOULD only be
215                 // a params fact.
216                 //
217                 //assertEquals("There should only be 1 Fact left in memory.", 1, kieSession.getFactCount());
218                 if (kieSession.getFactCount() != 1L) {
219                     log.error("FACT count mismatch: 1 expected but there are {}", kieSession.getFactCount());
220                 }
221                 for (FactHandle handle : kieSession.getFactHandles()) {
222                         Object fact = kieSession.getObject(handle);
223                         // assertEquals("Non-Param Fact left in working memory", "org.onap.policy.controlloop.Params", fact.getClass().getName());
224                         log.info("Working Memory FACT: {}", fact.getClass().getName());
225                 }
226
227         }
228
229         public static void dumpFacts(KieSession kieSession) {
230                 log.debug("Fact Count: " + kieSession.getFactCount());
231                 for (FactHandle handle : kieSession.getFactHandles()) {
232                         log.debug("FACT: " + handle);
233                 }
234         }
235
236         /**
237          * This method will start a kie session and instantiate
238          * the Policy Engine.
239          *
240          * @param droolsTemplate
241          *          the DRL rules file
242          * @param yamlFile
243          *          the yaml file containing the policies
244          * @param policyScope
245          *          scope for policy
246          * @param policyName
247          *          name of the policy
248          * @param policyVersion
249          *          version of the policy
250          * @return the kieSession to be used to insert facts
251          * @throws IOException
252          */
253         private KieSession startSession(String droolsTemplate,
254                                         String yamlFile,
255                                         String policyScope,
256                                         String policyName,
257                                         String policyVersion) throws IOException {
258
259         /*
260          * Load policies from yaml
261          */
262                 pair = Util.loadYaml(yamlFile);
263                 assertNotNull(pair);
264                 assertNotNull(pair.a);
265                 assertNotNull(pair.a.getControlLoop());
266                 assertNotNull(pair.a.getControlLoop().getControlLoopName());
267                 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
268
269         /*
270          * Construct a kie session
271          */
272                 final KieSession kieSession = Util.buildContainer(droolsTemplate,
273                                 pair.a.getControlLoop().getControlLoopName(),
274                                 policyScope,
275                                 policyName,
276                                 policyVersion,
277                                 URLEncoder.encode(pair.b, "UTF-8"));
278
279         /*
280          * Retrieve the Policy Engine
281          */
282                 engine = (PolicyEngineJUnitImpl) kieSession.getGlobal("Engine");
283
284                 log.debug("============");
285                 log.debug(URLEncoder.encode(pair.b, "UTF-8"));
286                 log.debug("============");
287
288                 return kieSession;
289         }
290
291 }
292