Merge "Removed useless parentheses"
[policy/drools-pdp.git] / feature-active-standby-management / src / main / java / org / onap / policy / drools / activestandby / ActiveStandbyFeature.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * feature-active-standby-management
4  * ================================================================================
5  * Copyright (C) 2017 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.Date;
25 import java.util.HashMap;
26 import java.util.Map;
27 import java.util.Properties;
28
29 import javax.persistence.EntityManagerFactory;
30 import javax.persistence.Persistence;
31
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import org.onap.policy.drools.core.PolicySessionFeatureAPI;
35 import org.onap.policy.drools.features.PolicyEngineFeatureAPI;
36 import org.onap.policy.drools.statemanagement.StateManagementFeatureAPI;
37 import org.onap.policy.drools.system.PolicyEngine;
38 import org.onap.policy.drools.utils.PropertyUtil;
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  * 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 {
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         {
76                 return(SEQ_NUM);
77         }
78
79         /**
80          * {@inheritDoc}
81          */
82         @Override
83         public void globalInit(String args[], String configDir)
84         {
85                 // This must come first since it initializes myPdp
86                 initializePersistence(configDir);
87                 
88                 for (StateManagementFeatureAPI feature : StateManagementFeatureAPI.impl.getList())
89                 {
90                         if (feature.getResourceName().equals(myPdp.getPdpId()))
91                         {
92                                 if(logger.isDebugEnabled()){
93                                         logger.debug("ActiveStandbyFeature.globalInit: Found StateManagementFeature"
94                                                 + " with resourceName: {}", myPdp.getPdpId());
95                                 }
96                                 stateManagementFeature = feature;
97                                 break;
98                         }
99                 }
100                 if(stateManagementFeature == null){
101                         if(logger.isDebugEnabled()){
102                                 logger.debug("ActiveStandbyFeature failed to initialize.  "
103                                         + "Unable to get instance of StateManagementFeatureAPI "
104                                         + "with resourceID: {}", myPdp.getPdpId());
105                         }
106                         logger.error("ActiveStandbyFeature failed to initialize.  "
107                                         + "Unable to get instance of StateManagementFeatureAPI "
108                                         + "with resourceID: {}", myPdp.getPdpId());
109                 }
110
111
112
113                 //Create an instance of the Observer
114                 PMStandbyStateChangeNotifier pmNotifier = new PMStandbyStateChangeNotifier();
115
116                 //Register the PMStandbyStateChangeNotifier Observer
117                 stateManagementFeature.addObserver(pmNotifier);
118                 if(logger.isDebugEnabled()){
119                         logger.debug("ActiveStandbyFeature.globalInit() exit");
120                 }
121         }
122
123
124         /**
125          * {@inheritDoc}
126          */
127         @Override
128         public boolean afterStart(PolicyEngine engine) 
129         {
130                 // ASSERTION: engine == PolicyEngine.manager
131                 PolicyEngine.manager.lock();
132                 return false;
133         }
134
135         /**
136          * Read in the persistence properties, determine whether persistence is
137          * enabled or disabled, and initialize persistence if enabled.
138          */
139         private static void initializePersistence(String configDir)
140         {
141                 //Get the Active Standby properties
142                 try {
143                                 Properties activeStandbyProperties = 
144                                                 PropertyUtil.getProperties(configDir + "/feature-active-standby-management.properties");
145                                 ActiveStandbyProperties.initProperties(activeStandbyProperties);
146                                 logger.info("initializePersistence: ActiveStandbyProperties success");
147                 } catch (IOException e) {
148                         logger.error("ActiveStandbyFeature: initializePersistence ActiveStandbyProperties", e);
149                 }
150                 
151                 DroolsPdpsConnector conn = getDroolsPdpsConnector("activeStandbyPU");
152                 String resourceName = ActiveStandbyProperties.getProperty(ActiveStandbyProperties.NODE_NAME);
153                 if(resourceName == null){
154                         throw new NullPointerException();
155                 }
156
157                 /*
158                  * In a JUnit test environment, one or more PDPs may already have been
159                  * inserted in the DB, so we need to check for this.
160                  */
161                 DroolsPdp existingPdp = conn.getPdp(resourceName);
162                 if (existingPdp != null) {
163                         System.out.println("Found existing PDP record, pdpId="
164                                         + existingPdp.getPdpId() + ", isDesignated="
165                                         + existingPdp.isDesignated() + ", updatedDate="
166                                         + existingPdp.getUpdatedDate());
167                         myPdp = existingPdp;
168                 }
169
170                 synchronized(myPdpSync){
171                         if(myPdp == null){
172
173                                 myPdp = new DroolsPdpImpl(resourceName,false,4,new Date());     
174                         }
175                         if(myPdp != null){
176                                 String site_name = ActiveStandbyProperties.getProperty(ActiveStandbyProperties.SITE_NAME);
177                                 if (site_name == null) {
178                                         site_name = "";
179                                 }else{
180                                         site_name = site_name.trim();
181                                 }
182                                 myPdp.setSiteName(site_name);
183                         }
184                         if(electionHandler == null){
185                                 electionHandler = new DroolsPdpsElectionHandler(conn,myPdp);
186                         }
187                 }
188                 System.out.println("\n\nThis controller is a standby, waiting to be chosen as primary...\n\n");
189                 logger.info("\n\nThis controller is a standby, waiting to be chosen as primary...\n\n");
190         }
191
192
193         /*
194          * Moved code to instantiate a JpaDroolsPdpsConnector object from main() to
195          * this method, so it can also be accessed from StandbyStateChangeNotifier
196          * class.
197          */
198         public static DroolsPdpsConnector getDroolsPdpsConnector(String pu) {
199
200                 Map<String, Object> propMap = new HashMap<String, Object>();
201                 propMap.put("javax.persistence.jdbc.driver", ActiveStandbyProperties
202                                 .getProperty(ActiveStandbyProperties.DB_DRIVER));
203                 propMap.put("javax.persistence.jdbc.url",
204                                 ActiveStandbyProperties.getProperty(ActiveStandbyProperties.DB_URL));
205                 propMap.put("javax.persistence.jdbc.user", ActiveStandbyProperties
206                                 .getProperty(ActiveStandbyProperties.DB_USER));
207                 propMap.put("javax.persistence.jdbc.password",
208                                 ActiveStandbyProperties.getProperty(ActiveStandbyProperties.DB_PWD));
209
210                 EntityManagerFactory emf = Persistence.createEntityManagerFactory(
211                                 pu, propMap);
212                 DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emf);
213
214                 return conn;
215         }
216
217         /**
218          * {@inheritDoc}
219          */
220         @Override
221         public String getPdpdNowActive(){
222                 return electionHandler.getPdpdNowActive();
223         }
224
225         /**
226          * {@inheritDoc}
227          */
228         @Override
229         public String getPdpdLastActive(){
230                 return electionHandler.getPdpdLastActive();
231         }
232
233         /**
234          * {@inheritDoc}
235          */
236         @Override
237         public String getResourceName() {
238                 return myPdp.getPdpId();
239         }
240 }