aboutsummaryrefslogtreecommitdiffstats
path: root/policy-core/src/main/java/org/onap/policy/drools/core/lock/SimpleLockManager.java
blob: 79fa0a7d0b4bd27783a7eb5f3256eb90fb42aefd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
/*
 * ============LICENSE_START=======================================================
 * ONAP
 * ================================================================================
 * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.drools.core.lock;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import org.onap.policy.common.utils.time.CurrentTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Simple lock manager. Callbacks are ignored. Does not redirect to lock feature
 * implementers.
 */
public class SimpleLockManager {

    protected static Logger logger = LoggerFactory.getLogger(SimpleLockManager.class);

    // messages used in exceptions
    public static final String MSG_NULL_RESOURCE_ID = "null resourceId";
    public static final String MSG_NULL_OWNER = "null owner";
    
    /**
     * Used to access the current time.  May be overridden by junit tests.
     */
    private static CurrentTime currentTime = new CurrentTime();

    /**
     * Used to synchronize updates to {@link #resource2data} and {@link #locks}.
     */
    private final Object locker = new Object();

    /**
     * Maps a resource to its lock data. Lock data is stored in both this and in
     * {@link #locks}.
     */
    private final Map<String, Data> resource2data = new HashMap<>();

    /**
     * Lock data, sorted by expiration time. Lock data is stored in both this and in
     * {@link #resource2data}. Whenever a lock operation is performed, this structure is
     * examined and any expired locks are removed; thus no timer threads are needed to
     * remove expired locks.
     */
    private final SortedSet<Data> locks = new TreeSet<>();

    /**
     * 
     */
    public SimpleLockManager() {
        super();
    }

    /**
     * Attempts to lock a resource, extending the lock if the owner already holds it.
     * 
     * @param resourceId
     * @param owner
     * @param holdSec the amount of time, in seconds, that the lock should be held
     * @return {@code true} if locked, {@code false} if the resource is already locked by
     *         a different owner
     * @throws IllegalArgumentException if the resourceId or owner is {@code null}
     */
    public boolean lock(String resourceId, String owner, int holdSec) {

        if (resourceId == null) {
            throw makeNullArgException(MSG_NULL_RESOURCE_ID);
        }

        if (owner == null) {
            throw makeNullArgException(MSG_NULL_OWNER);
        }

        Data existingLock;
        
        synchronized(locker) {
            cleanUpLocks();

            if ((existingLock = resource2data.get(resourceId)) != null && existingLock.getOwner().equals(owner)) {
                // replace the existing lock with an extended lock
                locks.remove(existingLock);
                existingLock = null;
            }

            if (existingLock == null) {
                Data data = new Data(owner, resourceId, currentTime.getMillis() + TimeUnit.SECONDS.toMillis(holdSec));
                resource2data.put(resourceId, data);
                locks.add(data);
            }
        }

        boolean locked = (existingLock == null);
        logger.info("lock {} for resource {} owner {}", locked, resourceId, owner);

        return locked;
    }

    /**
     * Unlocks a resource.
     * 
     * @param resourceId
     * @param owner
     * @return {@code true} if unlocked, {@code false} if the given owner does not
     *         currently hold a lock on the resource
     * @throws IllegalArgumentException if the resourceId or owner is {@code null}
     */
    public boolean unlock(String resourceId, String owner) {
        if (resourceId == null) {
            throw makeNullArgException(MSG_NULL_RESOURCE_ID);
        }

        if (owner == null) {
            throw makeNullArgException(MSG_NULL_OWNER);
        }
        
        Data data;
        
        synchronized(locker) {
            cleanUpLocks();
            
            if((data = resource2data.get(resourceId)) != null) {
                if(owner.equals(data.getOwner())) {
                    resource2data.remove(resourceId);
                    locks.remove(data);
                    
                } else {
                    data = null;
                }
            }
        }

        boolean unlocked = (data != null);
        logger.info("unlock resource {} owner {} = {}", resourceId, owner, unlocked);

        return unlocked;
    }

    /**
     * Determines if a resource is locked by anyone.
     * 
     * @param resourceId
     * @return {@code true} if the resource is locked, {@code false} otherwise
     * @throws IllegalArgumentException if the resourceId is {@code null}
     */
    public boolean isLocked(String resourceId) {

        if (resourceId == null) {
            throw makeNullArgException(MSG_NULL_RESOURCE_ID);
        }

        boolean locked;
        
        synchronized(locker) {
            cleanUpLocks();
            
            locked = resource2data.containsKey(resourceId);
        }

        logger.debug("resource {} isLocked = {}", resourceId, locked);

        return locked;
    }

    /**
     * Determines if a resource is locked by a particular owner.
     * 
     * @param resourceId
     * @param owner
     * @return {@code true} if the resource is locked, {@code false} otherwise
     * @throws IllegalArgumentException if the resourceId or owner is {@code null}
     */
    public boolean isLockedBy(String resourceId, String owner) {

        if (resourceId == null) {
            throw makeNullArgException(MSG_NULL_RESOURCE_ID);
        }

        if (owner == null) {
            throw makeNullArgException(MSG_NULL_OWNER);
        }

        Data data;
        
        synchronized(locker) {
            cleanUpLocks();
            
            data = resource2data.get(resourceId);
        }

        boolean locked = (data != null && owner.equals(data.getOwner()));
        logger.debug("resource {} isLockedBy {} = {}", resourceId, owner, locked);

        return locked;
    }

    /**
     * Releases expired locks.
     */
    private void cleanUpLocks() {
        long tcur = currentTime.getMillis();
        
        synchronized(locker) {
            Iterator<Data> it = locks.iterator();
            while(it.hasNext()) {
                Data d = it.next();
                if(d.getExpirationMs() <= tcur) {
                    it.remove();
                    resource2data.remove(d.getResource());
                    
                } else {
                    break;
                }
            }
        }
    }

    /**
     * Makes an exception for when an argument is {@code null}.
     * 
     * @param msg exception message
     * @return a new Exception
     */
    public static IllegalArgumentException makeNullArgException(String msg) {
        return new IllegalArgumentException(msg);
    }
    
    /**
     * Data for a single Lock.  Sorts by expiration time, then resource, and
     * then owner.
     */
    protected static class Data implements Comparable<Data> {
        
        /**
         * Owner of the lock.
         */
        private final String owner;
        
        /**
         * Resource that is locked.
         */
        private final String resource;
        
        /**
         * Time when the lock will expire, in milliseconds.
         */
        private final long texpireMs;
        
        /**
         * 
         * @param resource
         * @param owner
         * @param texpireMs
         */
        public Data(String owner, String resource, long texpireMs) {
            this.owner = owner;
            this.resource = resource;
            this.texpireMs = texpireMs;
        }

        public String getOwner() {
            return owner;
        }

        public String getResource() {
            return resource;
        }

        public long getExpirationMs() {
            return texpireMs;
        }

        @Override
        public int compareTo(Data o) {
            int diff = Long.compare(texpireMs, o.texpireMs);
            if(diff == 0)
                diff = resource.compareTo(o.resource);
            if(diff == 0)
                diff = owner.compareTo(o.owner);
            return diff;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((owner == null) ? 0 : owner.hashCode());
            result = prime * result + ((resource == null) ? 0 : resource.hashCode());
            result = prime * result + (int) (texpireMs ^ (texpireMs >>> 32));
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Data other = (Data) obj;
            if (owner == null) {
                if (other.owner != null)
                    return false;
            } else if (!owner.equals(other.owner))
                return false;
            if (resource == null) {
                if (other.resource != null)
                    return false;
            } else if (!resource.equals(other.resource))
                return false;
            if (texpireMs != other.texpireMs)
                return false;
            return true;
        }
    }
}