03872e1ee3b2206a29cffaf98c12dcf45694d995
[policy/drools-pdp.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * feature-distributed-locking
4  * ================================================================================
5  * Copyright (C) 2018 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 package org.onap.policy.distributed.locking;
21
22 import java.sql.Connection;
23 import java.sql.PreparedStatement;
24 import java.sql.SQLException;
25 import java.util.Properties;
26 import java.util.UUID;
27 import org.apache.commons.dbcp2.BasicDataSource;
28 import org.apache.commons.dbcp2.BasicDataSourceFactory;
29 import org.onap.policy.common.utils.properties.exception.PropertyException;
30 import org.onap.policy.drools.core.lock.PolicyResourceLockFeatureAPI;
31 import org.onap.policy.drools.features.PolicyEngineFeatureAPI;
32 import org.onap.policy.drools.persistence.SystemPersistence;
33 import org.onap.policy.drools.system.PolicyEngine;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 public class DistributedLockingFeature implements PolicyEngineFeatureAPI, PolicyResourceLockFeatureAPI {
38         
39         /**
40          * Logger instance
41          */
42         private static final Logger logger = LoggerFactory.getLogger(DistributedLockingFeature.class);
43         
44         /**
45          * Properties Configuration Name
46          */
47         public static final String CONFIGURATION_PROPERTIES_NAME = "feature-distributed-locking";
48         
49         /**
50          * Properties for locking feature
51          */
52         private DistributedLockingProperties lockProps;
53         
54         /**
55          * Data source used to connect to the DB containing locks.
56          */
57         private BasicDataSource dataSource;
58         
59         /**
60          * UUID 
61          */
62         private static final UUID uuid = UUID.randomUUID();
63         
64         @Override
65         public int getSequenceNumber() {
66         return 1000;
67         }
68         
69         @Override
70     public OperResult beforeLock(String resourceId, String owner, int holdSec) {
71                 
72                 TargetLock tLock = new TargetLock(resourceId, uuid, owner, dataSource);
73
74         return(tLock.lock(holdSec) ? OperResult.OPER_ACCEPTED : OperResult.OPER_DENIED);                                
75         }
76
77         @Override
78         public OperResult beforeUnlock(String resourceId, String owner) {
79                 TargetLock tLock = new TargetLock(resourceId, uuid, owner, dataSource);
80                 
81                 return(tLock.unlock() ? OperResult.OPER_ACCEPTED : OperResult.OPER_DENIED);
82         }
83         
84         @Override
85         public OperResult beforeIsLockedBy(String resourceId, String owner) {
86                 TargetLock tLock = new TargetLock(resourceId, uuid, owner, dataSource);
87
88         return(tLock.isActive() ? OperResult.OPER_ACCEPTED : OperResult.OPER_DENIED);
89         }
90         
91         @Override
92         public OperResult beforeIsLocked(String resourceId) {
93                 TargetLock tLock = new TargetLock(resourceId, uuid, "dummyOwner", dataSource);
94
95         return(tLock.isLocked() ? OperResult.OPER_ACCEPTED : OperResult.OPER_DENIED);
96         }
97         
98         @Override
99         public boolean afterStart(PolicyEngine engine) {
100
101                 try {
102                         this.lockProps = new DistributedLockingProperties(SystemPersistence.manager.getProperties(DistributedLockingFeature.CONFIGURATION_PROPERTIES_NAME));
103                         this.dataSource = makeDataSource();
104                 } catch (PropertyException e) {
105                         logger.error("DistributedLockingFeature feature properies have not been loaded", e);
106                         throw new DistributedLockingFeatureException(e);
107                 } catch(InterruptedException e) {
108             logger.error("DistributedLockingFeature failed to create data source", e);
109                     Thread.currentThread().interrupt();
110             throw new DistributedLockingFeatureException(e);
111         } catch(Exception e) {
112             logger.error("DistributedLockingFeature failed to create data source", e);
113             throw new DistributedLockingFeatureException(e);
114                 }
115                 
116                 cleanLockTable();
117                 
118                 return false;
119         }
120         
121         /**
122          * @return a new, pooled data source
123          * @throws Exception
124          */
125         private BasicDataSource makeDataSource() throws Exception {
126         Properties props = new Properties();
127         props.put("driverClassName", lockProps.getDbDriver());
128         props.put("url", lockProps.getDbUrl());
129         props.put("username", lockProps.getDbUser());
130         props.put("password", lockProps.getDbPwd());
131         props.put("testOnBorrow", "true");
132         props.put("poolPreparedStatements", "true");
133
134         // additional properties are listed in the GenericObjectPool API
135         
136         return BasicDataSourceFactory.createDataSource(props);
137     }
138
139     /**
140          * This method kills the heartbeat thread and calls refreshLockTable which removes
141          * any records from the db where the current host is the owner.
142          */
143         @Override
144         public boolean beforeShutdown(PolicyEngine engine) {
145                 cleanLockTable();
146                 return false;
147         }
148
149         /**
150          * This method removes all records owned by the current host from the db.
151          */
152         private void cleanLockTable() {
153                 
154             try (Connection conn = dataSource.getConnection();
155                 PreparedStatement statement = conn.prepareStatement("DELETE FROM pooling.locks WHERE host = ? OR expirationTime < ?");
156                 ){
157                         
158                                 statement.setString(1, uuid.toString());
159                                 statement.setLong(2, System.currentTimeMillis());
160                                 statement.executeUpdate();
161                         
162                 } catch (SQLException e) {
163                         logger.error("error in refreshLockTable()", e);
164                 }
165                 
166         }       
167 }