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