2377cfb91578458f7b32ebe51a7dc7d1a143d755
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.testsuites.integration.uservice.engine;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertTrue;
26 import static org.junit.Assert.fail;
27
28 import java.io.ByteArrayOutputStream;
29 import java.io.IOException;
30 import java.util.Date;
31 import java.util.HashMap;
32 import java.util.Map;
33
34 import org.junit.After;
35 import org.junit.AfterClass;
36 import org.junit.Before;
37 import org.junit.BeforeClass;
38 import org.junit.Test;
39 import org.onap.policy.apex.context.parameters.ContextParameterConstants;
40 import org.onap.policy.apex.context.parameters.ContextParameters;
41 import org.onap.policy.apex.context.parameters.DistributorParameters;
42 import org.onap.policy.apex.context.parameters.LockManagerParameters;
43 import org.onap.policy.apex.context.parameters.PersistorParameters;
44 import org.onap.policy.apex.context.parameters.SchemaParameters;
45 import org.onap.policy.apex.core.engine.EngineParameterConstants;
46 import org.onap.policy.apex.core.engine.EngineParameters;
47 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
48 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
49 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
50 import org.onap.policy.apex.model.basicmodel.handling.ApexModelException;
51 import org.onap.policy.apex.model.basicmodel.handling.ApexModelWriter;
52 import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
53 import org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters;
54 import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters;
55 import org.onap.policy.apex.service.engine.event.ApexEvent;
56 import org.onap.policy.apex.service.engine.runtime.ApexEventListener;
57 import org.onap.policy.apex.service.engine.runtime.EngineService;
58 import org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface;
59 import org.onap.policy.apex.service.engine.runtime.impl.EngineServiceImpl;
60 import org.onap.policy.apex.service.parameters.ApexParameterConstants;
61 import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters;
62 import org.onap.policy.apex.testsuites.integration.common.model.SampleDomainModelFactory;
63 import org.onap.policy.common.parameters.ParameterService;
64 import org.slf4j.ext.XLogger;
65 import org.slf4j.ext.XLoggerFactory;
66
67 /**
68  * The Class ApexServiceTest.
69  *
70  * @author Liam Fallon (liam.fallon@ericsson.com)
71  */
72 public class ApexServiceTest {
73     // Logger for this class
74     private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexServiceTest.class);
75
76     private static final long MAX_STOP_WAIT = 5000; // 5 sec
77     private static final long MAX_START_WAIT = 5000; // 5 sec
78     private static final long MAX_RECV_WAIT = 5000; // 5 sec
79
80     private static final AxArtifactKey engineServiceKey = new AxArtifactKey("Machine-1_process-1_engine-1", "0.0.0");
81     private static final EngineServiceParameters parameters = new EngineServiceParameters();
82     private static EngineService service = null;
83     private static TestListener listener = null;
84     private static AxPolicyModel apexPolicyModel = null;
85     private static int actionEventsReceived = 0;
86
87     private static String apexModelString;
88
89     private boolean waitFlag = true;
90
91     /**
92      * Sets the up.
93      *
94      * @throws Exception the exception
95      */
96     @BeforeClass
97     public static void setUp() throws Exception {
98         // create engine with 3 threads
99         parameters.setInstanceCount(3);
100         parameters.setName(engineServiceKey.getName());
101         parameters.setVersion(engineServiceKey.getVersion());
102         parameters.setId(100);
103         parameters.getEngineParameters().getExecutorParameterMap().put("MVEL", new MvelExecutorParameters());
104         service = EngineServiceImpl.create(parameters);
105
106         LOGGER.debug("Running TestApexEngine. . .");
107
108         apexPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("JAVASCRIPT");
109         assertNotNull(apexPolicyModel);
110
111         apexModelString = getModelString(apexPolicyModel);
112
113         // create engine
114         listener = new TestListener();
115         service.registerActionListener("Listener", listener);
116     }
117
118     /**
119      * Set up parameters.
120      */
121     @Before
122     public void setupParameters() {
123         ParameterService.register(new SchemaParameters());
124         ParameterService.register(new ContextParameters());
125         ParameterService.register(new DistributorParameters());
126         ParameterService.register(new LockManagerParameters());
127         ParameterService.register(new PersistorParameters());
128         ParameterService.register(new EngineServiceParameters());
129
130         EngineParameters engineParameters = new EngineParameters();
131         engineParameters.getExecutorParameterMap().put("JAVASCRIPT", new JavascriptExecutorParameters());
132         ParameterService.register(engineParameters);
133     }
134
135     /**
136      * Clear down parameters.
137      */
138     @After
139     public void teardownParameters() {
140         ParameterService.deregister(EngineParameterConstants.MAIN_GROUP_NAME);
141         ParameterService.deregister(ApexParameterConstants.ENGINE_SERVICE_GROUP_NAME);
142         ParameterService.deregister(ContextParameterConstants.PERSISTENCE_GROUP_NAME);
143         ParameterService.deregister(ContextParameterConstants.LOCKING_GROUP_NAME);
144         ParameterService.deregister(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME);
145         ParameterService.deregister(ContextParameterConstants.MAIN_GROUP_NAME);
146         ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME);
147     }
148
149     /**
150      * Update the engine then test the engine with 2 sample events.
151      *
152      * @throws ApexException if there is a problem
153      */
154     @Test
155     public void testExecutionSet1() throws ApexException {
156         service.updateModel(parameters.getEngineKey(), apexModelString, true);
157
158         final long starttime = System.currentTimeMillis();
159         for (final AxArtifactKey engineKey : service.getEngineKeys()) {
160             LOGGER.debug("{}", service.getStatus(engineKey));
161         }
162         while (!service.isStarted() && System.currentTimeMillis() - starttime < MAX_START_WAIT) {
163             ThreadUtilities.sleep(200);
164         }
165         if (!service.isStarted()) {
166             fail("Apex Service " + service.getKey() + " failed to start after " + MAX_START_WAIT + " ms");
167         }
168
169         final EngineServiceEventInterface engineServiceEventInterface = service.getEngineServiceEventInterface();
170
171         // Send some events
172         final Date testStartTime = new Date();
173         final Map<String, Object> eventDataMap = new HashMap<String, Object>();
174         eventDataMap.put("TestSlogan", "This is a test slogan");
175         eventDataMap.put("TestMatchCase", (byte) 123);
176         eventDataMap.put("TestTimestamp", testStartTime.getTime());
177         eventDataMap.put("TestTemperature", 34.5445667);
178
179         final ApexEvent event = new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events",
180                         "test", "apex");
181         event.setExecutionId(System.nanoTime());
182         event.putAll(eventDataMap);
183         engineServiceEventInterface.sendEvent(event);
184
185         final ApexEvent event2 = new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events",
186                         "test", "apex");
187         event2.setExecutionId(System.nanoTime());
188         event2.putAll(eventDataMap);
189         engineServiceEventInterface.sendEvent(event2);
190
191         // Wait for results
192         final long recvtime = System.currentTimeMillis();
193         while (actionEventsReceived < 2 && System.currentTimeMillis() - recvtime < MAX_RECV_WAIT) {
194             ThreadUtilities.sleep(100);
195         }
196         ThreadUtilities.sleep(500);
197         assertEquals(2, actionEventsReceived);
198         actionEventsReceived = 0;
199
200         // Stop all engines on this engine service
201         final long stoptime = System.currentTimeMillis();
202         service.stop();
203         while (!service.isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT) {
204             ThreadUtilities.sleep(200);
205         }
206         if (!service.isStopped()) {
207             fail("Apex Service " + service.getKey() + " failed to stop after " + MAX_STOP_WAIT + " ms");
208         }
209     }
210
211     /**
212      * Update the engine then test the engine with 2 sample events.
213      *
214      * @throws ApexException if there is a problem
215      */
216     @Test
217     public void testExecutionSet1Sync() throws ApexException {
218         service.updateModel(parameters.getEngineKey(), apexModelString, true);
219
220         final long starttime = System.currentTimeMillis();
221         for (final AxArtifactKey engineKey : service.getEngineKeys()) {
222             LOGGER.debug("{}", service.getStatus(engineKey));
223         }
224         while (!service.isStarted() && System.currentTimeMillis() - starttime < MAX_START_WAIT) {
225             ThreadUtilities.sleep(200);
226         }
227         if (!service.isStarted()) {
228             fail("Apex Service " + service.getKey() + " failed to start after " + MAX_START_WAIT + " ms");
229         }
230
231         // Send some events
232         final Date testStartTime = new Date();
233         final Map<String, Object> eventDataMap = new HashMap<String, Object>();
234         eventDataMap.put("TestSlogan", "This is a test slogan");
235         eventDataMap.put("TestMatchCase", (byte) 123);
236         eventDataMap.put("TestTimestamp", testStartTime.getTime());
237         eventDataMap.put("TestTemperature", 34.5445667);
238
239         final ApexEvent event1 = new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events",
240                         "test", "apex");
241         event1.putAll(eventDataMap);
242         event1.setExecutionId(System.nanoTime());
243
244         final ApexEventListener myEventListener1 = new ApexEventListener() {
245             @Override
246             public void onApexEvent(final ApexEvent responseEvent) {
247                 assertNotNull("Synchronous sendEventWait failed", responseEvent);
248                 assertEquals(event1.getExecutionId(), responseEvent.getExecutionId());
249                 waitFlag = false;
250             }
251         };
252
253         waitFlag = true;
254         service.registerActionListener("Listener1", myEventListener1);
255         service.getEngineServiceEventInterface().sendEvent(event1);
256
257         while (waitFlag) {
258             ThreadUtilities.sleep(100);
259         }
260
261         final ApexEvent event2 = new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events",
262                         "test", "apex");
263         event2.setExecutionId(System.nanoTime());
264         event2.putAll(eventDataMap);
265
266         final ApexEventListener myEventListener2 = new ApexEventListener() {
267             @Override
268             public void onApexEvent(final ApexEvent responseEvent) {
269                 assertNotNull("Synchronous sendEventWait failed", responseEvent);
270                 assertEquals(event2.getExecutionId(), responseEvent.getExecutionId());
271                 assertEquals(2, actionEventsReceived);
272                 waitFlag = false;
273             }
274         };
275
276         waitFlag = true;
277         service.deregisterActionListener("Listener1");
278         service.registerActionListener("Listener2", myEventListener2);
279         service.getEngineServiceEventInterface().sendEvent(event2);
280
281         while (waitFlag) {
282             ThreadUtilities.sleep(100);
283         }
284         service.deregisterActionListener("Listener2");
285
286         actionEventsReceived = 0;
287
288         // Stop all engines on this engine service
289         final long stoptime = System.currentTimeMillis();
290         service.stop();
291         while (!service.isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT) {
292             ThreadUtilities.sleep(200);
293         }
294         if (!service.isStopped()) {
295             fail("Apex Service " + service.getKey() + " failed to stop after " + MAX_STOP_WAIT + " ms");
296         }
297     }
298
299     /**
300      * Update the engine then test the engine with 2 sample events - again.
301      *
302      * @throws ApexException if there is a problem
303      */
304     @Test
305     public void testExecutionSet2() throws ApexException {
306         service.updateModel(parameters.getEngineKey(), apexModelString, true);
307
308         final long starttime = System.currentTimeMillis();
309         for (final AxArtifactKey engineKey : service.getEngineKeys()) {
310             LOGGER.debug("{}", service.getStatus(engineKey));
311         }
312         while (!service.isStarted() && System.currentTimeMillis() - starttime < MAX_START_WAIT) {
313             ThreadUtilities.sleep(200);
314         }
315         if (!service.isStarted()) {
316             fail("Apex Service " + service.getKey() + " failed to start after " + MAX_START_WAIT + " ms");
317         }
318
319         final EngineServiceEventInterface engineServiceEventInterface = service.getEngineServiceEventInterface();
320
321         // Send some events
322         final Date testStartTime = new Date();
323         final Map<String, Object> eventDataMap = new HashMap<String, Object>();
324         eventDataMap.put("TestSlogan", "This is a test slogan");
325         eventDataMap.put("TestMatchCase", (byte) 123);
326         eventDataMap.put("TestTimestamp", testStartTime.getTime());
327         eventDataMap.put("TestTemperature", 34.5445667);
328
329         final ApexEvent event = new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events",
330                         "test", "apex");
331         event.setExecutionId(System.nanoTime());
332         event.putAll(eventDataMap);
333         engineServiceEventInterface.sendEvent(event);
334
335         final ApexEvent event2 = new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events",
336                         "test", "apex");
337         event2.setExecutionId(System.nanoTime());
338         event2.putAll(eventDataMap);
339         engineServiceEventInterface.sendEvent(event2);
340
341         // Wait for results
342         final long recvtime = System.currentTimeMillis();
343         while (actionEventsReceived < 2 && System.currentTimeMillis() - recvtime < MAX_RECV_WAIT) {
344             ThreadUtilities.sleep(100);
345         }
346         ThreadUtilities.sleep(500);
347         assertEquals(2, actionEventsReceived);
348         actionEventsReceived = 0;
349
350         // Stop all engines on this engine service
351         final long stoptime = System.currentTimeMillis();
352         service.stop();
353         while (!service.isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT) {
354             ThreadUtilities.sleep(200);
355         }
356         if (!service.isStopped()) {
357             fail("Apex Service " + service.getKey() + " failed to stop after " + MAX_STOP_WAIT + " ms");
358         }
359     }
360
361     /**
362      * Update the engine then test the engine with 2 sample events - again.
363      *
364      * @throws ApexException if there is a problem
365      */
366     @Test
367     public void testExecutionSet2Sync() throws ApexException {
368         service.updateModel(parameters.getEngineKey(), apexModelString, true);
369
370         final long starttime = System.currentTimeMillis();
371         for (final AxArtifactKey engineKey : service.getEngineKeys()) {
372             LOGGER.debug("{}", service.getStatus(engineKey));
373         }
374         while (!service.isStarted() && System.currentTimeMillis() - starttime < MAX_START_WAIT) {
375             ThreadUtilities.sleep(200);
376         }
377         if (!service.isStarted()) {
378             fail("Apex Service " + service.getKey() + " failed to start after " + MAX_START_WAIT + " ms");
379         }
380
381         // Send some events
382         final Date testStartTime = new Date();
383         final Map<String, Object> eventDataMap = new HashMap<String, Object>();
384         eventDataMap.put("TestSlogan", "This is a test slogan");
385         eventDataMap.put("TestMatchCase", (byte) 123);
386         eventDataMap.put("TestTimestamp", testStartTime.getTime());
387         eventDataMap.put("TestTemperature", 34.5445667);
388
389         final ApexEvent event1 = new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events",
390                         "test", "apex");
391         event1.putAll(eventDataMap);
392
393         final ApexEventListener myEventListener1 = new ApexEventListener() {
394             @Override
395             public void onApexEvent(final ApexEvent responseEvent) {
396                 assertNotNull("Synchronous sendEventWait failed", responseEvent);
397                 assertEquals(event1.getExecutionId(), responseEvent.getExecutionId());
398                 waitFlag = false;
399             }
400         };
401
402         waitFlag = true;
403         service.registerActionListener("Listener1", myEventListener1);
404         service.getEngineServiceEventInterface().sendEvent(event1);
405
406         while (waitFlag) {
407             ThreadUtilities.sleep(100);
408         }
409
410         final ApexEvent event2 = new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events",
411                         "test", "apex");
412         event2.putAll(eventDataMap);
413
414         final ApexEventListener myEventListener2 = new ApexEventListener() {
415             @Override
416             public void onApexEvent(final ApexEvent responseEvent) {
417                 assertNotNull("Synchronous sendEventWait failed", responseEvent);
418                 assertEquals(event2.getExecutionId(), responseEvent.getExecutionId());
419                 waitFlag = false;
420             }
421         };
422
423         waitFlag = true;
424         service.registerActionListener("Listener2", myEventListener2);
425         service.deregisterActionListener("Listener1");
426         service.getEngineServiceEventInterface().sendEvent(event2);
427
428         while (waitFlag) {
429             ThreadUtilities.sleep(100);
430         }
431
432         service.deregisterActionListener("Listener2");
433
434         assertEquals(2, actionEventsReceived);
435
436         actionEventsReceived = 0;
437
438         // Stop all engines on this engine service
439         final long stoptime = System.currentTimeMillis();
440         service.stop();
441         while (!service.isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT) {
442             ThreadUtilities.sleep(200);
443         }
444         if (!service.isStopped()) {
445             fail("Apex Service " + service.getKey() + " failed to stop after " + MAX_STOP_WAIT + " ms");
446         }
447     }
448
449     /**
450      * Tear down the the test infrastructure.
451      *
452      * @throws ApexException if there is an error
453      */
454     @AfterClass
455     public static void tearDown() throws Exception {
456         // Stop all engines on this engine service
457         final long stoptime = System.currentTimeMillis();
458         service.stop();
459         while (!service.isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT) {
460             ThreadUtilities.sleep(200);
461         }
462         if (!service.isStopped()) {
463             fail("Apex Service " + service.getKey() + " failed to stop after " + MAX_STOP_WAIT + " ms");
464         }
465         service = null;
466     }
467
468     /**
469      * The listener interface for receiving test events. The class that is interested in processing a test event
470      * implements this interface, and the object created with that class is registered with a component using the
471      * component's <code>addTestListener</code> method. When the test event occurs, that object's appropriate method is
472      * invoked.
473      *
474      * @see TestEvent
475      */
476     private static final class TestListener implements ApexEventListener {
477
478         /**
479          * {@inheritDoc}.
480          */
481         @Override
482         public synchronized void onApexEvent(final ApexEvent event) {
483             LOGGER.debug("result 1 is:" + event);
484             checkResult(event);
485             actionEventsReceived++;
486
487             final Date testStartTime = new Date((Long) event.get("TestTimestamp"));
488             final Date testEndTime = new Date();
489
490             LOGGER.debug("policy execution time: " + (testEndTime.getTime() - testStartTime.getTime()) + "ms");
491         }
492
493         /**
494          * Check result.
495          *
496          * @param result the result
497          */
498         private void checkResult(final ApexEvent result) {
499             assertTrue(result.getName().startsWith("Event0004") || result.getName().startsWith("Event0104"));
500
501             assertTrue(result.get("TestSlogan").equals("This is a test slogan"));
502             assertTrue(result.get("TestMatchCase").equals(new Byte((byte) 123)));
503             assertTrue(result.get("TestTemperature").equals(34.5445667));
504             assertTrue(((byte) result.get("TestMatchCaseSelected")) >= 0
505                             && ((byte) result.get("TestMatchCaseSelected") <= 3));
506             assertTrue(((byte) result.get("TestEstablishCaseSelected")) >= 0
507                             && ((byte) result.get("TestEstablishCaseSelected") <= 3));
508             assertTrue(((byte) result.get("TestDecideCaseSelected")) >= 0
509                             && ((byte) result.get("TestDecideCaseSelected") <= 3));
510             assertTrue(((byte) result.get("TestActCaseSelected")) >= 0
511                             && ((byte) result.get("TestActCaseSelected") <= 3));
512         }
513     }
514
515     /**
516      * Gets the model string.
517      *
518      * @param policyModel the eca policy model
519      * @return the model string
520      * @throws ApexModelException the apex model exception
521      * @throws IOException Signals that an I/O exception has occurred.
522      */
523     private static String getModelString(final AxPolicyModel policyModel) throws ApexModelException, IOException {
524         try (final ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream()) {
525             new ApexModelWriter<AxPolicyModel>(AxPolicyModel.class).write(policyModel, baOutputStream);
526             return baOutputStream.toString();
527         }
528     }
529 }