summaryrefslogtreecommitdiffstats
path: root/policy-core/src/main/java/org/onap/policy/drools/core/lock/SimpleLockManager.java
blob: 14cffaaba989b47d0f3c69e46b806bc407dedb9d (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
/*
 * ============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 static org.onap.policy.drools.core.lock.LockRequestFuture.MSG_NULL_OWNER;
import static org.onap.policy.drools.core.lock.LockRequestFuture.MSG_NULL_RESOURCE_ID;
import static org.onap.policy.drools.core.lock.LockRequestFuture.makeNullArgException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import org.onap.policy.drools.core.lock.PolicyResourceLockFeatureAPI.Callback;
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);

    /**
     * Maps a resource to the owner that holds the lock on it.
     */
    private ConcurrentHashMap<String, String> resource2owner = new ConcurrentHashMap<>();

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

    // TODO: for ease of use by clients, should we always invoke the callback, even though
    // this is synchronous?

    /**
     * Attempts to lock a resource. This method ignores the callback and always returns a
     * {@link CompletedLockRequest}.
     * 
     * @param resourceId
     * @param owner
     * @param callback function to invoke, if the requester wishes to wait for the lock to
     *        be acquired, {@code null} to provide immediate replies
     * @return a future for the lock request. The future will be in one of three states:
     *         <dl>
     *         <dt>isDone()=true and get()=true</dt>
     *         <dd>the lock has been acquired; the callback may or may not have been
     *         invoked</dd>
     *         <dt>isDone()=true and get()=false</dt>
     *         <dd>the lock request has been denied; the callback may or may not have been
     *         invoked</dd>
     *         <dt>isDone()=false</dt>
     *         <dd>the lock was not immediately available and a callback was provided. The
     *         callback will be invoked once the lock is acquired (or denied). In this
     *         case, the future may be used to cancel the request</dd>
     *         </dl>
     * @throws IllegalArgumentException if the resourceId or owner is {@code null}
     * @throws IllegalStateException if the owner already holds the lock or is already in
     *         the queue to get the lock
     */
    public Future<Boolean> lock(String resourceId, String owner, Callback callback) {

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

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

        boolean locked = (resource2owner.putIfAbsent(resourceId, owner) == null);

        if (!locked && owner.equals(resource2owner.get(resourceId))) {
            throw new IllegalStateException("lock for resource " + resourceId + " already owned by " + owner);
        }

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

        return new LockRequestFuture(resourceId, owner, 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);
        }

        boolean unlocked = resource2owner.remove(resourceId, owner);
        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 = resource2owner.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);
        }

        boolean locked = owner.equals(resource2owner.get(resourceId));
        logger.debug("resource {} isLockedBy {} = {}", resourceId, owner, locked);

        return locked;
    }
}