4eb878b1cd8463f90721f86a8f82c6aeac498bb7
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.context.impl.locking;
23
24 import java.util.Collections;
25 import java.util.HashMap;
26 import java.util.Map;
27 import java.util.concurrent.locks.ReadWriteLock;
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         // Find or create a map for the lock type
171         Map<String, ReadWriteLock> lockTypeMap = lockMaps.computeIfAbsent(lockTypeKey,
172             unusedKey -> Collections.synchronizedMap(new HashMap<String, ReadWriteLock>()));
173
174         // Find or create a lock in the lock map
175         ReadWriteLock lock = lockTypeMap.get(lockKey);
176         if (lock != null) {
177             return lock;
178         }
179
180         // Should we create a lock?
181         String errorMessage = "error getting lock on context map " + lockTypeKey + CONTEXT_ITEM + lockKey;
182         if (!createMode) {
183             String message = errorMessage + ", lock does not exist";
184             LOGGER.warn(message);
185             throw new ContextException(message);
186         }
187
188         try {
189             // Create the lock using the specialization of this abstract class
190             lock = getReentrantReadWriteLock(lockTypeKey + "_" + lockKey);
191
192             // Add the lock to the lock map
193             lockTypeMap.put(lockKey, lock);
194
195             if (LOGGER.isTraceEnabled()) {
196                 LOGGER.trace("created lock {}_{}", lockTypeKey, lockKey);
197             }
198             return lock;
199         } catch (final Exception e) {
200             LOGGER.warn(errorMessage, e);
201             throw new ContextException(errorMessage, e);
202         }
203     }
204 }