cc7a7a12988917a83b327f5eca9ae3272fa326a8
[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.DriverManager;
24 import java.sql.PreparedStatement;
25 import java.sql.SQLException;
26 import java.util.UUID;
27 import java.util.concurrent.Executors;
28 import java.util.concurrent.Future;
29 import java.util.concurrent.ScheduledExecutorService;
30 import java.util.concurrent.TimeUnit;
31
32 import org.onap.policy.common.utils.properties.exception.PropertyException;
33 import org.onap.policy.drools.core.lock.LockRequestFuture;
34 import org.onap.policy.drools.core.lock.PolicyResourceLockFeatureAPI;
35 import org.onap.policy.drools.features.PolicyEngineFeatureAPI;
36 import org.onap.policy.drools.persistence.SystemPersistence;
37 import org.onap.policy.drools.system.PolicyEngine;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 public class DistributedLockingFeature implements PolicyEngineFeatureAPI, PolicyResourceLockFeatureAPI {
42         
43         /**
44          * Logger instance
45          */
46         private static final Logger logger = LoggerFactory.getLogger(DistributedLockingFeature.class);
47         
48         /**
49          * Properties Configuration Name
50          */
51         public static final String CONFIGURATION_PROPERTIES_NAME = "feature-distributed-locking";
52         
53         /**
54          * Properties for locking feature
55          */
56         private DistributedLockingProperties lockProps;
57         
58         /**
59          *ScheduledExecutorService for LockHeartbeat 
60          */
61         private ScheduledExecutorService scheduledExecutorService;
62         
63         /**
64          * UUID 
65          */
66         private static final UUID uuid = UUID.randomUUID();
67         
68         /**
69          * Config directory
70          */
71         @Override
72         public int getSequenceNumber() {
73         return 1000;
74         }
75         
76         @Override
77         public Future<Boolean> beforeLock(String resourceId, String owner, Callback callback) {
78                 
79                 TargetLock tLock = new TargetLock(resourceId, this.uuid, owner, lockProps);
80                 
81                 return new LockRequestFuture(resourceId, owner, tLock.lock());
82                                 
83         }
84
85         @Override
86         public Boolean beforeUnlock(String resourceId, String owner) {
87                 TargetLock tLock = new TargetLock(resourceId, this.uuid, owner, lockProps);
88                 
89                 return tLock.unlock();
90         }
91         
92         @Override
93         public Boolean beforeIsLockedBy(String resourceId, String owner) {
94                 TargetLock tLock = new TargetLock(resourceId, this.uuid, owner, lockProps);
95                 
96                 return tLock.isActive();
97         }
98         
99         @Override
100         public Boolean beforeIsLocked(String resourceId) {
101                 TargetLock tLock = new TargetLock(resourceId, this.uuid, "dummyOwner", lockProps);
102                 
103                 return tLock.isLocked();
104         }
105         
106         @Override
107         public boolean afterStart(PolicyEngine engine) {
108
109                 try {
110                         this.lockProps = new DistributedLockingProperties(SystemPersistence.manager.getProperties(DistributedLockingFeature.CONFIGURATION_PROPERTIES_NAME));
111                 } catch (PropertyException e) {
112                         logger.error("DistributedLockingFeature feature properies have not been loaded", e);
113                         throw new DistributedLockingFeatureException(e);
114                 }
115                 
116                 long heartbeatInterval = this.lockProps.getHeartBeatIntervalProperty();
117                 
118                 cleanLockTable();
119                 Heartbeat heartbeat = new Heartbeat(this.uuid, lockProps);
120                 
121                 this.scheduledExecutorService = Executors.newScheduledThreadPool(1);
122                 this.scheduledExecutorService.scheduleAtFixedRate(heartbeat, heartbeatInterval, heartbeatInterval, TimeUnit.MILLISECONDS);
123                 return false;
124         }
125         
126         /**
127          * This method kills the heartbeat thread and calls refreshLockTable which removes
128          * any records from the db where the current host is the owner.
129          */
130         @Override
131         public boolean beforeShutdown(PolicyEngine engine) {
132                 scheduledExecutorService.shutdown();
133                 cleanLockTable();
134                 return false;
135         }
136
137         /**
138          * This method removes all records owned by the current host from the db.
139          */
140         private void cleanLockTable() {
141                 
142             try (Connection conn = DriverManager.getConnection(lockProps.getDbUrl(), 
143                         lockProps.getDbUser(),
144                         lockProps.getDbPwd());
145                 PreparedStatement statement = conn.prepareStatement("DELETE FROM pooling.locks WHERE host = ? OR expirationTime < ?");
146                 ){
147                         
148                                 statement.setString(1, this.uuid.toString());
149                                 statement.setLong(2, System.currentTimeMillis());
150                                 statement.executeUpdate();
151                         
152                 } catch (SQLException e) {
153                         logger.error("error in refreshLockTable()", e);
154                 }
155                 
156         }
157         
158 }