2 * ============LICENSE_START=======================================================
3 * feature-session-persistence
4 * ================================================================================
5 * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.drools.persistence;
23 import java.io.IOException;
24 import java.sql.Connection;
25 import java.sql.PreparedStatement;
26 import java.sql.SQLException;
27 import java.util.HashMap;
29 import java.util.Properties;
30 import java.util.concurrent.CountDownLatch;
31 import java.util.concurrent.TimeUnit;
33 import javax.persistence.EntityManagerFactory;
34 import javax.persistence.Persistence;
35 import javax.transaction.TransactionManager;
36 import javax.transaction.TransactionSynchronizationRegistry;
37 import javax.transaction.UserTransaction;
39 import org.apache.commons.dbcp2.BasicDataSource;
40 import org.apache.commons.dbcp2.BasicDataSourceFactory;
41 import org.hibernate.cfg.AvailableSettings;
42 import org.kie.api.KieServices;
43 import org.kie.api.runtime.Environment;
44 import org.kie.api.runtime.EnvironmentName;
45 import org.kie.api.runtime.KieSession;
46 import org.kie.api.runtime.KieSessionConfiguration;
47 import org.onap.policy.drools.core.PolicyContainer;
48 import org.onap.policy.drools.core.PolicySession;
49 import org.onap.policy.drools.core.PolicySessionFeatureApi;
50 import org.onap.policy.drools.features.PolicyEngineFeatureApi;
51 import org.onap.policy.drools.system.PolicyController;
52 import org.onap.policy.drools.system.PolicyControllerConstants;
53 import org.onap.policy.drools.system.PolicyEngine;
54 import org.onap.policy.drools.utils.PropertyUtil;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
59 * If this feature is supported, there is a single instance of it. It adds persistence to Drools
60 * sessions. In addition, if an active-standby feature exists, then that is used to determine the
61 * active and last-active PDP. If it does not exist, then the current host name is used as the PDP
64 * <p>The bulk of the code here was once in other classes, such as 'PolicyContainer' and 'Main'. It
65 * was moved here as part of making this a separate optional feature.
67 public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngineFeatureApi {
69 private static final Logger logger = LoggerFactory.getLogger(PersistenceFeature.class);
71 /** KieService factory. */
72 private KieServices kieSvcFact;
74 /** Persistence properties. */
75 private Properties persistProps;
77 /** Whether or not the SessionInfo records should be cleaned out. */
78 private boolean sessInfoCleaned;
80 /** SessionInfo timeout, in milli-seconds, as read from
81 * {@link #persistProps}. */
82 private long sessionInfoTimeoutMs;
84 /** Object used to serialize cleanup of sessioninfo table. */
85 private Object cleanupLock = new Object();
88 * Lookup the adjunct for this feature that is associated with the specified PolicyContainer. If
89 * not found, create one.
91 * @param policyContainer the container whose adjunct we are looking up, and possibly creating
92 * @return the associated 'ContainerAdjunct' instance, which may be new
94 private ContainerAdjunct getContainerAdjunct(PolicyContainer policyContainer) {
96 Object rval = policyContainer.getAdjunct(this);
98 if (!(rval instanceof ContainerAdjunct)) {
99 // adjunct does not exist, or has the wrong type (should never
101 rval = new ContainerAdjunct(policyContainer);
102 policyContainer.setAdjunct(this, rval);
105 return (ContainerAdjunct) rval;
112 public int getSequenceNumber() {
120 public void globalInit(String[] args, String configDir) {
122 kieSvcFact = getKieServices();
125 persistProps = loadProperties(configDir + "/feature-session-persistence.properties");
127 } catch (IOException e1) {
128 logger.error("initializePersistence: ", e1);
131 sessionInfoTimeoutMs = getPersistenceTimeout();
135 * Creates a persistent KieSession, loading it from the persistent store, or creating one, if it
136 * does not exist yet.
139 public KieSession activatePolicySession(
140 PolicyContainer policyContainer, String name, String kieBaseName) {
142 if (isPersistenceEnabled(policyContainer, name)) {
143 cleanUpSessionInfo();
145 return getContainerAdjunct(policyContainer).newPersistentKieSession(name, kieBaseName);
155 public PolicySession.ThreadModel selectThreadModel(PolicySession session) {
157 PolicyContainer policyContainer = session.getPolicyContainer();
158 if (isPersistenceEnabled(policyContainer, session.getName())) {
159 return new PersistentThreadModel(session, getProperties(policyContainer));
168 public void disposeKieSession(PolicySession policySession) {
170 ContainerAdjunct contAdj =
171 (ContainerAdjunct) policySession.getPolicyContainer().getAdjunct(this);
172 if (contAdj != null) {
173 contAdj.disposeKieSession(policySession.getName());
181 public void destroyKieSession(PolicySession policySession) {
183 ContainerAdjunct contAdj =
184 (ContainerAdjunct) policySession.getPolicyContainer().getAdjunct(this);
185 if (contAdj != null) {
186 contAdj.destroyKieSession(policySession.getName());
194 public boolean afterStart(PolicyEngine engine) {
202 public boolean beforeStart(PolicyEngine engine) {
210 public boolean beforeActivate(PolicyEngine engine) {
214 private boolean cleanup() {
215 synchronized (cleanupLock) {
216 sessInfoCleaned = false;
226 public boolean afterActivate(PolicyEngine engine) {
230 /* ============================================================ */
233 * Gets the persistence timeout value for sessioninfo records.
235 * @return the timeout value, in milli-seconds, or {@code -1} if it is unspecified or invalid
237 private long getPersistenceTimeout() {
238 String timeoutString = null;
241 timeoutString = persistProps.getProperty(DroolsPersistenceProperties.DB_SESSIONINFO_TIMEOUT);
243 if (timeoutString != null) {
244 // timeout parameter is specified
245 return Long.valueOf(timeoutString) * 1000;
248 } catch (NumberFormatException e) {
250 "Invalid value for Drools persistence property persistence.sessioninfo.timeout: {}",
258 /* ============================================================ */
261 * Each instance of this class is a logical extension of a 'PolicyContainer' instance. Its
262 * reference is stored in the 'adjuncts' table within the 'PolicyContainer', and will be
263 * garbage-collected with the container.
265 protected class ContainerAdjunct {
266 /** 'PolicyContainer' instance that this adjunct is extending. */
267 private PolicyContainer policyContainer;
269 /** Maps a KIE session name to its data source. */
270 private Map<String, DsEmf> name2ds = new HashMap<>();
273 * Constructor - initialize a new 'ContainerAdjunct'.
275 * @param policyContainer the 'PolicyContainer' instance this adjunct is extending
277 private ContainerAdjunct(PolicyContainer policyContainer) {
278 this.policyContainer = policyContainer;
282 * Create a new persistent KieSession. If there is already a corresponding entry in the
283 * database, it is used to initialize the KieSession. If not, a completely new session is
286 * @param name the name of the KieSession (which is also the name of the associated
288 * @param kieBaseName the name of the 'KieBase' instance containing this session
289 * @return a new KieSession with persistence enabled
291 private KieSession newPersistentKieSession(String name, String kieBaseName) {
295 BasicDataSource ds = makeDataSource(getDataSourceProperties());
296 DsEmf dsemf = new DsEmf(ds);
299 EntityManagerFactory emf = dsemf.emf;
300 DroolsSessionConnector conn = makeJpaConnector(emf);
302 long desiredSessionId = getSessionId(conn, name);
305 "\n\nThis controller is primary... coming up with session {} \n\n", desiredSessionId);
307 // session does not exist -- attempt to create one
309 "getPolicySession:session does not exist -- attempt to create one with name {}", name);
311 Environment env = kieSvcFact.newEnvironment();
313 configureKieEnv(env, emf);
315 KieSessionConfiguration kieConf = kieSvcFact.newKieSessionConfiguration();
317 KieSession kieSession =
318 (desiredSessionId >= 0
319 ? loadKieSession(kieBaseName, desiredSessionId, env, kieConf)
322 if (kieSession == null) {
323 // loadKieSession() returned null or desiredSessionId < 0
325 "LOADING We cannot load session {}. Going to create a new one", desiredSessionId);
327 kieSession = newKieSession(kieBaseName, env);
330 replaceSession(conn, name, kieSession);
332 name2ds.put(name, dsemf);
336 } catch (RuntimeException e) {
343 * Loads an existing KieSession from the persistent store.
345 * @param kieBaseName the name of the 'KieBase' instance containing this session
346 * @param desiredSessionId id of the desired KieSession
347 * @param env Kie Environment for the session
348 * @param kConf Kie Configuration for the session
349 * @return the persistent session, or {@code null} if it could not be loaded
351 private KieSession loadKieSession(
352 String kieBaseName, long desiredSessionId, Environment env, KieSessionConfiguration kieConf) {
354 KieSession kieSession =
359 policyContainer.getKieContainer().getKieBase(kieBaseName),
363 logger.info("LOADING Loaded session {}", desiredSessionId);
367 } catch (Exception e) {
368 logger.error("loadKieSession error: ", e);
374 * Creates a new, persistent KieSession.
376 * @param kieBaseName the name of the 'KieBase' instance containing this session
377 * @param env Kie Environment for the session
378 * @return a new, persistent session
380 private KieSession newKieSession(String kieBaseName, Environment env) {
381 KieSession kieSession =
384 .newKieSession(policyContainer.getKieContainer().getKieBase(kieBaseName), null, env);
386 logger.info("LOADING CREATED {}", kieSession.getIdentifier());
392 * Closes the data source associated with a session.
394 * @param name name of the session being destroyed
396 private void destroyKieSession(String name) {
397 closeDataSource(name);
401 * Closes the data source associated with a session.
403 * @param name name of the session being disposed of
405 private void disposeKieSession(String name) {
406 closeDataSource(name);
410 * Closes the data source associated with a session.
412 * @param name name of the session whose data source is to be closed
414 private void closeDataSource(String name) {
415 DsEmf ds = name2ds.remove(name);
421 /** Configures java system properties for JPA/JTA. */
422 private void configureSysProps() {
423 System.setProperty("com.arjuna.ats.arjuna.coordinator.defaultTimeout", "60");
425 "com.arjuna.ats.arjuna.objectstore.objectStoreDir",
426 persistProps.getProperty(DroolsPersistenceProperties.JTA_OBJECTSTORE_DIR));
428 "ObjectStoreEnvironmentBean.objectStoreDir",
429 persistProps.getProperty(DroolsPersistenceProperties.JTA_OBJECTSTORE_DIR));
433 * Configures a Kie Environment.
435 * @param env environment to be configured
436 * @param emf entity manager factory
438 private void configureKieEnv(Environment env, EntityManagerFactory emf) {
439 env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf);
440 env.set(EnvironmentName.TRANSACTION, getUserTrans());
441 env.set(EnvironmentName.TRANSACTION_SYNCHRONIZATION_REGISTRY, getTransSyncReg());
442 env.set(EnvironmentName.TRANSACTION_MANAGER, getTransMgr());
446 * Gets a session's ID from the persistent store.
448 * @param conn persistence connector
449 * @param sessnm name of the session
450 * @return the session's id, or {@code -1} if the session is not found
452 private long getSessionId(DroolsSessionConnector conn, String sessnm) {
453 DroolsSession sess = conn.get(sessnm);
454 return sess != null ? sess.getSessionId() : -1;
458 * Replaces a session within the persistent store, if it exists. Adds it otherwise.
460 * @param conn persistence connector
461 * @param sessnm name of session to be updated
462 * @param kieSession new session information
464 private void replaceSession(DroolsSessionConnector conn, String sessnm, KieSession kieSession) {
466 DroolsSessionEntity sess = new DroolsSessionEntity();
468 sess.setSessionName(sessnm);
469 sess.setSessionId(kieSession.getIdentifier());
475 /* ============================================================ */
478 * Gets the data source properties.
480 * @return the data source properties
482 private Properties getDataSourceProperties() {
483 Properties props = new Properties();
484 props.put("driverClassName", persistProps.getProperty(DroolsPersistenceProperties.DB_DRIVER));
485 props.put("url", persistProps.getProperty(DroolsPersistenceProperties.DB_URL));
486 props.put("username", persistProps.getProperty(DroolsPersistenceProperties.DB_USER));
487 props.put("password", persistProps.getProperty(DroolsPersistenceProperties.DB_PWD));
488 props.put("maxActive", "3");
489 props.put("maxIdle", "1");
490 props.put("maxWait", "120000");
491 props.put("whenExhaustedAction", "2");
492 props.put("testOnBorrow", "false");
493 props.put("poolPreparedStatements", "true");
499 * Removes "old" Drools 'sessioninfo' records, so they aren't used to restore data to Drools
500 * sessions. This also has the useful side-effect of removing abandoned records as well.
502 private void cleanUpSessionInfo() {
504 synchronized (cleanupLock) {
505 if (sessInfoCleaned) {
506 logger.info("Clean up of sessioninfo table: already done");
510 if (sessionInfoTimeoutMs < 0) {
511 logger.info("Clean up of sessioninfo table: no timeout specified");
515 // now do the record deletion
516 try (BasicDataSource ds = makeDataSource(getDataSourceProperties());
517 Connection connection = ds.getConnection();
518 PreparedStatement statement =
519 connection.prepareStatement(
520 "DELETE FROM sessioninfo WHERE timestampdiff(second,lastmodificationdate,now()) > ?")) {
522 connection.setAutoCommit(true);
524 statement.setLong(1, sessionInfoTimeoutMs / 1000);
526 int count = statement.executeUpdate();
527 logger.info("Cleaning up sessioninfo table -- {} records removed", count);
529 } catch (SQLException e) {
530 logger.error("Clean up of sessioninfo table failed", e);
533 // delete DroolsSessionEntity where sessionId not in (sessinfo.xxx)?
535 sessInfoCleaned = true;
540 * Determine whether persistence is enabled for a specific container.
542 * @param container container to be checked
543 * @param sessionName name of the session to be checked
544 * @return {@code true} if persistence is enabled for this container, and {@code false} if not
546 private boolean isPersistenceEnabled(PolicyContainer container, String sessionName) {
547 Properties properties = getProperties(container);
548 boolean rval = false;
550 if (properties != null) {
551 // fetch the 'type' property
552 String type = getProperty(properties, sessionName, "type");
553 rval = "auto".equals(type) || "native".equals(type);
560 * Determine the controller properties associated with the policy container.
562 * @param container container whose properties are to be retrieved
563 * @return the container's properties, or {@code null} if not found
565 private Properties getProperties(PolicyContainer container) {
567 return getPolicyController(container).getProperties();
568 } catch (IllegalArgumentException e) {
569 logger.error("getProperties exception: ", e);
575 * Fetch the persistence property associated with a session. The name may have the form:
578 * <li>persistence.SESSION-NAME.PROPERTY
579 * <li>persistence.PROPERTY
582 * @param properties properties from which the value is to be retrieved
583 * @param sessionName session name of interest
584 * @param property property name of interest
585 * @return the property value, or {@code null} if not found
587 private String getProperty(Properties properties, String sessionName, String property) {
588 String value = properties.getProperty("persistence." + sessionName + "." + property);
590 value = properties.getProperty("persistence." + property);
596 /* ============================================================ */
599 * This 'ThreadModel' variant periodically calls 'KieSession.fireAllRules()', because the
600 * 'fireUntilHalt' method isn't compatible with persistence.
602 public class PersistentThreadModel implements Runnable, PolicySession.ThreadModel {
604 /** Session associated with this persistent thread. */
605 private final PolicySession session;
607 /** The session thread. */
608 private final Thread thread;
610 /** Used to indicate that processing should stop. */
611 private final CountDownLatch stopped = new CountDownLatch(1);
613 /** Minimum time, in milli-seconds, that the thread should sleep before firing rules again. */
614 long minSleepTime = 100;
617 * Maximum time, in milli-seconds, that the thread should sleep before firing rules again. This
618 * is a "half" time, so that we can multiply it by two without overflowing the word size.
620 long halfMaxSleepTime = 5000L / 2L;
623 * Constructor - initialize variables and create thread.
625 * @param session the 'PolicySession' instance
626 * @param properties may contain additional session properties
628 public PersistentThreadModel(PolicySession session, Properties properties) {
629 this.session = session;
630 this.thread = new Thread(this, getThreadName());
632 if (properties == null) {
636 // extract 'minSleepTime' and/or 'maxSleepTime'
637 String name = session.getName();
639 // fetch 'minSleepTime' value, and update if defined
640 String sleepTimeString = getProperty(properties, name, "minSleepTime");
641 if (sleepTimeString != null) {
643 minSleepTime = Math.max(1, Integer.valueOf(sleepTimeString));
644 } catch (Exception e) {
645 logger.error("{}: Illegal value for 'minSleepTime'", sleepTimeString, e);
649 // fetch 'maxSleepTime' value, and update if defined
650 long maxSleepTime = 2 * halfMaxSleepTime;
651 sleepTimeString = getProperty(properties, name, "maxSleepTime");
652 if (sleepTimeString != null) {
654 maxSleepTime = Math.max(1, Integer.valueOf(sleepTimeString));
655 } catch (Exception e) {
656 logger.error("{}: Illegal value for 'maxSleepTime'", sleepTimeString, e);
660 // swap values if needed
661 if (minSleepTime > maxSleepTime) {
662 logger.error("minSleepTime({}) is greater than maxSleepTime({}) -- swapping", minSleepTime,
664 long tmp = minSleepTime;
665 minSleepTime = maxSleepTime;
669 halfMaxSleepTime = Math.max(1, maxSleepTime / 2);
675 * @return the String to use as the thread name */
676 private String getThreadName() {
677 return "Session " + session.getFullName() + " (persistent)";
680 /*=========================*/
681 /* 'ThreadModel' interface */
682 /*=========================*/
688 public void start() {
697 // tell the thread to stop
700 // wait up to 10 seconds for the thread to stop
704 } catch (InterruptedException e) {
705 logger.error("stopThread exception: ", e);
706 Thread.currentThread().interrupt();
709 // verify that it's done
710 if (thread.isAlive()) {
711 logger.error("stopThread: still running");
719 public void updated() {
720 // the container artifact has been updated -- adjust the thread name
721 thread.setName(getThreadName());
724 /*======================*/
725 /* 'Runnable' interface */
726 /*======================*/
733 logger.info("PersistentThreadModel running");
735 // set thread local variable
736 session.setPolicySession();
738 KieSession kieSession = session.getKieSession();
739 long sleepTime = 2 * halfMaxSleepTime;
741 // We want to continue, despite any exceptions that occur
742 // while rules are fired.
748 if (kieSession.fireAllRules() > 0) {
749 // some rules fired -- reduce poll delay
750 sleepTime = Math.max(minSleepTime, sleepTime / 2);
752 // no rules fired -- increase poll delay
753 sleepTime = 2 * Math.min(halfMaxSleepTime, sleepTime);
756 } catch (Exception | LinkageError e) {
757 logger.error("Exception during kieSession.fireAllRules", e);
761 if (stopped.await(sleepTime, TimeUnit.MILLISECONDS)) {
765 } catch (InterruptedException e) {
766 logger.error("startThread exception: ", e);
767 Thread.currentThread().interrupt();
772 logger.info("PersistentThreadModel completed");
776 /* ============================================================ */
778 /** DataSource-EntityManagerFactory pair. */
779 private class DsEmf {
780 private BasicDataSource bds;
781 private EntityManagerFactory emf;
784 * Makes an entity manager factory for the given data source.
786 * @param bds pooled data source
788 public DsEmf(BasicDataSource bds) {
790 Map<String, Object> props = new HashMap<>();
791 props.put(AvailableSettings.JPA_JTA_DATASOURCE, bds);
794 this.emf = makeEntMgrFact(props);
796 } catch (RuntimeException e) {
802 /** Closes the entity manager factory and the data source. */
803 public void close() {
807 } catch (RuntimeException e) {
815 /** Closes the data source only. */
816 private void closeDataSource() {
820 } catch (SQLException e) {
821 throw new PersistenceFeatureException(e);
826 private static class SingletonRegistry {
827 private static final TransactionSynchronizationRegistry transreg =
828 new com.arjuna.ats.internal.jta.transaction.arjunacore
829 .TransactionSynchronizationRegistryImple();
831 private SingletonRegistry() {
836 /** Factory for various items. Methods can be overridden for junit testing. */
839 * Gets the transaction manager.
841 * @return the transaction manager
843 protected TransactionManager getTransMgr() {
844 return com.arjuna.ats.jta.TransactionManager.transactionManager();
848 * Gets the user transaction.
850 * @return the user transaction
852 protected UserTransaction getUserTrans() {
853 return com.arjuna.ats.jta.UserTransaction.userTransaction();
857 * Gets the transaction synchronization registry.
859 * @return the transaction synchronization registry
861 protected TransactionSynchronizationRegistry getTransSyncReg() {
862 return SingletonRegistry.transreg;
866 * Gets the KIE services.
868 * @return the KIE services
870 protected KieServices getKieServices() {
871 return KieServices.Factory.get();
875 * Loads properties from a file.
877 * @param filenm name of the file to load
878 * @return properties, as loaded from the file
879 * @throws IOException if an error occurs reading from the file
881 protected Properties loadProperties(String filenm) throws IOException {
882 return PropertyUtil.getProperties(filenm);
886 * Makes a Data Source.
888 * @param dsProps data source properties
889 * @return a new data source
891 protected BasicDataSource makeDataSource(Properties dsProps) {
893 return BasicDataSourceFactory.createDataSource(dsProps);
895 } catch (Exception e) {
896 throw new PersistenceFeatureException(e);
901 * Makes a new JPA connector for drools sessions.
903 * @param emf entity manager factory
904 * @return a new JPA connector for drools sessions
906 protected DroolsSessionConnector makeJpaConnector(EntityManagerFactory emf) {
907 return new JpaDroolsSessionConnector(emf);
911 * Makes a new entity manager factory.
913 * @param props properties with which the factory should be configured
914 * @return a new entity manager factory
916 protected EntityManagerFactory makeEntMgrFact(Map<String, Object> props) {
917 return Persistence.createEntityManagerFactory("onapsessionsPU", props);
921 * Gets the policy controller associated with a given policy container.
923 * @param container container whose controller is to be retrieved
924 * @return the container's controller
926 protected PolicyController getPolicyController(PolicyContainer container) {
927 return PolicyControllerConstants.getFactory().get(container.getGroupId(), container.getArtifactId());
931 * Runtime exceptions generated by this class. Wraps exceptions generated by delegated operations,
932 * particularly when they are not, themselves, Runtime exceptions.
934 public static class PersistenceFeatureException extends RuntimeException {
935 private static final long serialVersionUID = 1L;
940 public PersistenceFeatureException(Exception ex) {