bd3f0215501e66d46ea5d5e4454e331430a85cfc
[policy/drools-pdp.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * feature-active-standby-management
4  * ================================================================================
5  * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.drools.activestandby;
22
23 import java.io.IOException;
24 import java.util.HashMap;
25 import java.util.Map;
26 import java.util.Properties;
27 import javax.persistence.EntityManagerFactory;
28 import javax.persistence.Persistence;
29 import org.eclipse.persistence.config.PersistenceUnitProperties;
30 import org.onap.policy.common.im.MonitorTime;
31 import org.onap.policy.drools.core.PolicySessionFeatureApi;
32 import org.onap.policy.drools.features.PolicyEngineFeatureApi;
33 import org.onap.policy.drools.statemanagement.StateManagementFeatureApi;
34 import org.onap.policy.drools.statemanagement.StateManagementFeatureApiConstants;
35 import org.onap.policy.drools.system.PolicyEngine;
36 import org.onap.policy.drools.system.PolicyEngineConstants;
37 import org.onap.policy.drools.utils.PropertyUtil;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 /**
42  * If this feature is supported, there is a single instance of it.
43  * It adds persistence to Drools sessions, but it is also intertwined with
44  * active/standby state management and IntegrityMonitor. For now, they are
45  * all treated as a single feature, but it would be nice to separate them.
46  *
47  * <p>The bulk of the code here was once in other classes, such as
48  * 'PolicyContainer' and 'Main'. It was moved here as part of making this
49  * a separate optional feature.
50  */
51 public class ActiveStandbyFeature implements ActiveStandbyFeatureApi,
52     PolicySessionFeatureApi, PolicyEngineFeatureApi {
53     // get an instance of logger
54     private static final Logger logger =
55             LoggerFactory.getLogger(ActiveStandbyFeature.class);
56
57     private static DroolsPdp myPdp;
58     private static Object myPdpSync = new Object();
59     private static DroolsPdpsElectionHandler electionHandler;
60
61     private StateManagementFeatureApi stateManagementFeature;
62
63     public static final int SEQ_NUM = 1;
64
65
66     /*========================*/
67     /* 'FeatureAPI' interface */
68     /*========================*/
69
70     /**
71      * {@inheritDoc}.
72      */
73     @Override
74     public int getSequenceNumber() {
75         return SEQ_NUM;
76     }
77
78     /**
79      * {@inheritDoc}.
80      */
81     @Override
82     public void globalInit(String[] args, String configDir) {
83         // This must come first since it initializes myPdp
84         initializePersistence(configDir);
85
86         for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) {
87             if (feature.getResourceName().equals(myPdp.getPdpId())) {
88                 logger.debug("ActiveStandbyFeature.globalInit: Found StateManagementFeature"
89                                 + " with resourceName: {}", myPdp.getPdpId());
90                 stateManagementFeature = feature;
91                 break;
92             }
93         }
94         if (stateManagementFeature == null) {
95             logger.debug("ActiveStandbyFeature failed to initialize.  "
96                             + "Unable to get instance of StateManagementFeatureApi "
97                             + "with resourceID: {}", myPdp.getPdpId());
98             logger.error("ActiveStandbyFeature failed to initialize.  "
99                     + "Unable to get instance of StateManagementFeatureApi "
100                     + "with resourceID: {}", myPdp.getPdpId());
101             //
102             // Cannot add observer since stateManagementFeature is null
103             //
104             return;
105         }
106
107
108
109         //Create an instance of the Observer
110         PmStandbyStateChangeNotifier pmNotifier = new PmStandbyStateChangeNotifier();
111
112         //Register the PMStandbyStateChangeNotifier Observer
113         stateManagementFeature.addObserver(pmNotifier);
114         logger.debug("ActiveStandbyFeature.globalInit() exit");
115     }
116
117
118     /**
119      * {@inheritDoc}.
120      */
121     @Override
122     public boolean afterStart(PolicyEngine engine) {
123         // ASSERTION: engine == PolicyEngine.manager
124         PolicyEngineConstants.getManager().lock();
125         return false;
126     }
127
128     /**
129      * Read in the persistence properties, determine whether persistence is
130      * enabled or disabled, and initialize persistence if enabled.
131      */
132     private static void initializePersistence(String configDir) {
133         //Get the Active Standby properties
134         try {
135             Properties activeStandbyProperties =
136                     PropertyUtil.getProperties(configDir + "/feature-active-standby-management.properties");
137             ActiveStandbyProperties.initProperties(activeStandbyProperties);
138             logger.info("initializePersistence: ActiveStandbyProperties success");
139         } catch (IOException e) {
140             logger.error("ActiveStandbyFeature: initializePersistence ActiveStandbyProperties", e);
141         }
142
143         DroolsPdpsConnector conn = getDroolsPdpsConnector("activeStandbyPU");
144         String resourceName = ActiveStandbyProperties.getProperty(ActiveStandbyProperties.NODE_NAME);
145         if (resourceName == null) {
146             throw new NullPointerException();
147         }
148
149         /*
150          * In a JUnit test environment, one or more PDPs may already have been
151          * inserted in the DB, so we need to check for this.
152          */
153         DroolsPdp existingPdp = conn.getPdp(resourceName);
154         if (existingPdp != null) {
155             logger.info("Found existing PDP record, pdpId={} isDesignated={}, updatedDate={}",
156                      existingPdp.getPdpId(), existingPdp.isDesignated(), existingPdp.getUpdatedDate());
157             myPdp = existingPdp;
158         }
159
160         synchronized (myPdpSync) {
161             if (myPdp == null) {
162
163                 myPdp = new DroolsPdpImpl(resourceName, false, 4, MonitorTime.getInstance().getDate());
164             }
165             String siteName = ActiveStandbyProperties.getProperty(ActiveStandbyProperties.SITE_NAME);
166             if (siteName == null) {
167                 siteName = "";
168             } else {
169                 siteName = siteName.trim();
170             }
171             myPdp.setSite(siteName);
172             if (electionHandler == null) {
173                 electionHandler = new DroolsPdpsElectionHandler(conn, myPdp);
174             }
175         }
176         logger.info("\n\nThis controller is a standby, waiting to be chosen as primary...\n\n");
177     }
178
179
180     /**
181      * Moved code to instantiate a JpaDroolsPdpsConnector object from main() to
182      * this method, so it can also be accessed from StandbyStateChangeNotifier
183      * class.
184      *
185      * @param pu string
186      * @return connector object
187      */
188     public static DroolsPdpsConnector getDroolsPdpsConnector(String pu) {
189
190         Map<String, Object> propMap = new HashMap<>();
191         propMap.put(PersistenceUnitProperties.JDBC_DRIVER,
192                         ActiveStandbyProperties.getProperty(ActiveStandbyProperties.DB_DRIVER));
193         propMap.put(PersistenceUnitProperties.JDBC_URL,
194                         ActiveStandbyProperties.getProperty(ActiveStandbyProperties.DB_URL));
195         propMap.put(PersistenceUnitProperties.JDBC_USER,
196                         ActiveStandbyProperties.getProperty(ActiveStandbyProperties.DB_USER));
197         propMap.put(PersistenceUnitProperties.JDBC_PASSWORD,
198                         ActiveStandbyProperties.getProperty(ActiveStandbyProperties.DB_PWD));
199         propMap.put(PersistenceUnitProperties.TARGET_DATABASE,
200                         ActiveStandbyProperties.getProperty(ActiveStandbyProperties.DB_TYPE));
201
202         EntityManagerFactory emf = Persistence.createEntityManagerFactory(
203                 pu, propMap);
204         return new JpaDroolsPdpsConnector(emf);
205     }
206
207     /**
208      * {@inheritDoc}.
209      */
210     @Override
211     public String getPdpdNowActive() {
212         return electionHandler.getPdpdNowActive();
213     }
214
215     /**
216      * {@inheritDoc}.
217      */
218     @Override
219     public String getPdpdLastActive() {
220         return electionHandler.getPdpdLastActive();
221     }
222
223     /**
224      * {@inheritDoc}.
225      */
226     @Override
227     public String getResourceName() {
228         return myPdp.getPdpId();
229     }
230 }