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