7a7b237d68ccedadf7d75b22a15d6150f2e3b6f3
[policy/apex-pdp.git] / context / context-management / src / main / java / org / onap / policy / apex / context / impl / locking / AbstractLockManager.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.context.impl.locking;
22
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.Map;
26 import java.util.concurrent.locks.ReadWriteLock;
27
28 import org.onap.policy.apex.context.ContextException;
29 import org.onap.policy.apex.context.LockManager;
30 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
31 import org.slf4j.ext.XLogger;
32 import org.slf4j.ext.XLoggerFactory;
33
34 /**
35  * This class implements the {@link LockManager} functionality that is common across all implementations. Lock managers
36  * for specific lock mechanisms specialize this class.
37  *
38  * @author Liam Fallon (liam.fallon@ericsson.com)
39  */
40 public abstract class AbstractLockManager implements LockManager {
41     // Logger for this class
42     private static final XLogger LOGGER = XLoggerFactory.getXLogger(AbstractLockManager.class);
43
44     // Recurring string constants
45     private static final String CONTEXT_ITEM = " context item ";
46
47     // The key of this lock manager
48     private AxArtifactKey key = null;
49
50     // Map of locks in use on this distributor for each context map
51     private final Map<String, Map<String, ReadWriteLock>> lockMaps = Collections
52                     .synchronizedMap(new HashMap<String, Map<String, ReadWriteLock>>());
53
54     /**
55      * {@inheritDoc}.
56      */
57     @Override
58     public void init(final AxArtifactKey lockManagerKey) throws ContextException {
59         this.key = lockManagerKey;
60     }
61
62     /**
63      * {@inheritDoc}.
64      */
65     @Override
66     public AxArtifactKey getKey() {
67         return key;
68     }
69
70     /**
71      * {@inheritDoc}.
72      */
73     @Override
74     public synchronized void lockForReading(final String lockTypeKey, final String lockKey) throws ContextException {
75         LOGGER.entry("lockForReading(" + lockTypeKey + "_" + lockKey + ")");
76
77         // Find the lock or create a new one
78         final ReadWriteLock lock = getLock(lockTypeKey, lockKey, true);
79
80         try {
81             lock.readLock().lock();
82             LOGGER.exit("lockForReading(" + lockTypeKey + "_" + lockKey + ")");
83         } catch (final Exception e) {
84             LOGGER.warn("error acquiring read lock on context map " + lockTypeKey + CONTEXT_ITEM + lockKey, e);
85             throw new ContextException(
86                             "error acquiring read lock on context map " + lockTypeKey + CONTEXT_ITEM + lockKey, e);
87         }
88     }
89
90     /**
91      * {@inheritDoc}.
92      */
93     @Override
94     public synchronized void lockForWriting(final String lockTypeKey, final String lockKey) throws ContextException {
95         LOGGER.entry("lockForWriting(" + lockTypeKey + "_" + lockKey + ")");
96
97         // Find the lock or create a new one
98         final ReadWriteLock lock = getLock(lockTypeKey, lockKey, true);
99
100         try {
101             lock.writeLock().lock();
102             LOGGER.exit("lockForWriting(" + lockTypeKey + "_" + lockKey + ")");
103         } catch (final Exception e) {
104             LOGGER.warn("error acquiring write lock on context map " + lockTypeKey + CONTEXT_ITEM + lockKey, e);
105             throw new ContextException(
106                             "error acquiring write lock on context map " + lockTypeKey + CONTEXT_ITEM + lockKey, e);
107         }
108     }
109
110     /**
111      * {@inheritDoc}.
112      */
113     @Override
114     public void unlockForReading(final String lockTypeKey, final String lockKey) throws ContextException {
115         LOGGER.entry("unlockForReading(" + lockTypeKey + "_" + lockKey + ")");
116
117         // Find the lock
118         final ReadWriteLock lock = getLock(lockTypeKey, lockKey, false);
119
120         try {
121             lock.readLock().unlock();
122             LOGGER.exit("unlockForReading(" + lockTypeKey + "_" + lockKey + ")");
123         } catch (final Exception e) {
124             LOGGER.warn("error releasing read lock on context map " + lockTypeKey + CONTEXT_ITEM + lockKey, e);
125             throw new ContextException(
126                             "error releasing read lock on context map " + lockTypeKey + CONTEXT_ITEM + lockKey, e);
127         }
128     }
129
130     /**
131      * {@inheritDoc}.
132      */
133     @Override
134     public void unlockForWriting(final String lockTypeKey, final String lockKey) throws ContextException {
135         LOGGER.entry("unlockForWriting(" + lockTypeKey + "_" + lockKey + ")");
136
137         // Find the lock
138         final ReadWriteLock lock = getLock(lockTypeKey, lockKey, false);
139
140         try {
141             lock.writeLock().unlock();
142             LOGGER.exit("unlockForWriting(" + lockTypeKey + "_" + lockKey + ")");
143         } catch (final Exception e) {
144             LOGGER.warn("error releasing write lock on context map " + lockTypeKey + CONTEXT_ITEM + lockKey, e);
145             throw new ContextException(
146                             "error releasing write lock on context map " + lockTypeKey + CONTEXT_ITEM + lockKey, e);
147         }
148     }
149
150     /**
151      * Get a reentrant read write lock from whatever locking mechanism is in use.
152      *
153      * @param lockId The unique ID of the lock.
154      * @return The lock
155      * @throws ContextException On errors getting a lock
156      */
157     protected abstract ReadWriteLock getReentrantReadWriteLock(String lockId) throws ContextException;
158
159     /**
160      * Get a lock for a context item in a context map.
161      *
162      * @param lockTypeKey The key of the map where the context item to lock is
163      * @param lockKey The key on the map to lock
164      * @param createMode if true, create a lock if it does not exist
165      * @return The lock
166      * @throws ContextException On errors getting the lock
167      */
168     private ReadWriteLock getLock(final String lockTypeKey, final String lockKey, final boolean createMode)
169                     throws ContextException {
170         // Check if we have a lock type map for this lock type yet
171         if (!lockMaps.containsKey(lockTypeKey)) {
172             // Create a lock type map for the lock type
173             lockMaps.put(lockTypeKey, Collections.synchronizedMap(new HashMap<String, ReadWriteLock>()));
174         }
175
176         // Find or create a lock in the lock map
177         ReadWriteLock lock = lockMaps.get(lockTypeKey).get(lockKey);
178         if (lock != null) {
179             return lock;
180         }
181
182         // Should we create a lock?
183         String errorMessage = "error getting lock on context map " + lockTypeKey + CONTEXT_ITEM + lockKey;
184         if (!createMode) {
185             String message = errorMessage + ", lock does not exist";
186             LOGGER.warn(message);
187             throw new ContextException(message);
188         }
189
190         try {
191             // Create the lock using the specialization of this abstract class
192             lock = getReentrantReadWriteLock(lockTypeKey + "_" + lockKey);
193
194             // Add the lock to the lock map
195             lockMaps.get(lockTypeKey).put(lockKey, lock);
196
197             if (LOGGER.isTraceEnabled()) {
198                 LOGGER.trace("created lock {}_{}", lockTypeKey, lockKey);
199             }
200             return lock;
201         } catch (final Exception e) {
202             LOGGER.warn(errorMessage, e);
203             throw new ContextException(errorMessage, e);
204         }
205     }
206 }