88908b965e8423b451bc08b9677c625726b7e9ad
[policy/apex-pdp.git] /
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      * (non-Javadoc)
56      *
57      * @see org.onap.policy.apex.context.LockManager#init(org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey)
58      */
59     @Override
60     public void init(final AxArtifactKey lockManagerKey) throws ContextException {
61         this.key = lockManagerKey;
62     }
63
64     /*
65      * (non-Javadoc)
66      *
67      * @see org.onap.policy.apex.context.LockManager#getKey()
68      */
69     @Override
70     public AxArtifactKey getKey() {
71         return key;
72     }
73
74     /*
75      * (non-Javadoc)
76      *
77      * @see org.onap.policy.apex.core.context.LockManager#lockForReading(org.onap.policy.apex.core.model.concepts.
78      * AxArtifactKey, java.lang.String)
79      */
80     @Override
81     public synchronized void lockForReading(final String lockTypeKey, final String lockKey) throws ContextException {
82         LOGGER.entry("lockForReading(" + lockTypeKey + "_" + lockKey + ")");
83
84         // Find the lock or create a new one
85         final ReadWriteLock lock = getLock(lockTypeKey, lockKey, true);
86
87         try {
88             lock.readLock().lock();
89             LOGGER.exit("lockForReading(" + lockTypeKey + "_" + lockKey + ")");
90         } catch (final Exception e) {
91             LOGGER.warn("error acquiring read lock on context map " + lockTypeKey + CONTEXT_ITEM + lockKey, e);
92             throw new ContextException(
93                             "error acquiring read lock on context map " + lockTypeKey + CONTEXT_ITEM + lockKey, e);
94         }
95     }
96
97     /*
98      * (non-Javadoc)
99      *
100      * @see org.onap.policy.apex.core.context.LockManager#lockForWriting(java.lang.String, java.lang.String)
101      */
102     @Override
103     public synchronized void lockForWriting(final String lockTypeKey, final String lockKey) throws ContextException {
104         LOGGER.entry("lockForWriting(" + lockTypeKey + "_" + lockKey + ")");
105
106         // Find the lock or create a new one
107         final ReadWriteLock lock = getLock(lockTypeKey, lockKey, true);
108
109         try {
110             lock.writeLock().lock();
111             LOGGER.exit("lockForWriting(" + lockTypeKey + "_" + lockKey + ")");
112         } catch (final Exception e) {
113             LOGGER.warn("error acquiring write lock on context map " + lockTypeKey + CONTEXT_ITEM + lockKey, e);
114             throw new ContextException(
115                             "error acquiring write lock on context map " + lockTypeKey + CONTEXT_ITEM + lockKey, e);
116         }
117     }
118
119     /*
120      * (non-Javadoc)
121      *
122      * @see org.onap.policy.apex.core.context.LockManager#unlockForReading(java.lang.String, java.lang.String)
123      */
124     @Override
125     public void unlockForReading(final String lockTypeKey, final String lockKey) throws ContextException {
126         LOGGER.entry("unlockForReading(" + lockTypeKey + "_" + lockKey + ")");
127
128         // Find the lock
129         final ReadWriteLock lock = getLock(lockTypeKey, lockKey, false);
130
131         try {
132             lock.readLock().unlock();
133             LOGGER.exit("unlockForReading(" + lockTypeKey + "_" + lockKey + ")");
134         } catch (final Exception e) {
135             LOGGER.warn("error releasing read lock on context map " + lockTypeKey + CONTEXT_ITEM + lockKey, e);
136             throw new ContextException(
137                             "error releasing read lock on context map " + lockTypeKey + CONTEXT_ITEM + lockKey, e);
138         }
139     }
140
141     /*
142      * (non-Javadoc)
143      *
144      * @see org.onap.policy.apex.core.context.LockManager#unlockForWriting(java.lang.String, java.lang.String)
145      */
146     @Override
147     public void unlockForWriting(final String lockTypeKey, final String lockKey) throws ContextException {
148         LOGGER.entry("unlockForWriting(" + lockTypeKey + "_" + lockKey + ")");
149
150         // Find the lock
151         final ReadWriteLock lock = getLock(lockTypeKey, lockKey, false);
152
153         try {
154             lock.writeLock().unlock();
155             LOGGER.exit("unlockForWriting(" + lockTypeKey + "_" + lockKey + ")");
156         } catch (final Exception e) {
157             LOGGER.warn("error releasing write lock on context map " + lockTypeKey + CONTEXT_ITEM + lockKey, e);
158             throw new ContextException(
159                             "error releasing write lock on context map " + lockTypeKey + CONTEXT_ITEM + lockKey, e);
160         }
161     }
162
163     /**
164      * Get a reentrant read write lock from whatever locking mechanism is in use.
165      *
166      * @param lockId The unique ID of the lock.
167      * @return The lock
168      * @throws ContextException On errors getting a lock
169      */
170     protected abstract ReadWriteLock getReentrantReadWriteLock(String lockId) throws ContextException;
171
172     /**
173      * Get a lock for a context item in a context map.
174      *
175      * @param lockTypeKey The key of the map where the context item to lock is
176      * @param lockKey The key on the map to lock
177      * @param createMode if true, create a lock if it does not exist
178      * @return The lock
179      * @throws ContextException On errors getting the lock
180      */
181     private ReadWriteLock getLock(final String lockTypeKey, final String lockKey, final boolean createMode)
182                     throws ContextException {
183         // Check if we have a lock type map for this lock type yet
184         if (!lockMaps.containsKey(lockTypeKey)) {
185             // Create a lock type map for the lock type
186             lockMaps.put(lockTypeKey, Collections.synchronizedMap(new HashMap<String, ReadWriteLock>()));
187         }
188
189         // Find or create a lock in the lock map
190         ReadWriteLock lock = lockMaps.get(lockTypeKey).get(lockKey);
191         if (lock != null) {
192             return lock;
193         }
194
195         // Should we create a lock?
196         String errorMessage = "error getting lock on context map " + lockTypeKey + CONTEXT_ITEM + lockKey;
197         if (!createMode) {
198             String message = errorMessage + ", lock does not exist";
199             LOGGER.warn(message);
200             throw new ContextException(message);
201         }
202
203         try {
204             // Create the lock using the specialization of this abstract class
205             lock = getReentrantReadWriteLock(lockTypeKey + "_" + lockKey);
206
207             // Add the lock to the lock map
208             lockMaps.get(lockTypeKey).put(lockKey, lock);
209
210             if (LOGGER.isTraceEnabled()) {
211                 LOGGER.trace("created lock {}_{}", lockTypeKey, lockKey);
212             }
213             return lock;
214         } catch (final Exception e) {
215             LOGGER.warn(errorMessage, e);
216             throw new ContextException(errorMessage, e);
217         }
218     }
219 }