e5a45b2033b29e200683560dc6cb516fe8519e1a
[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.distribution;
22
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.Map;
26 import java.util.Map.Entry;
27
28 import org.onap.policy.apex.context.ContextAlbum;
29 import org.onap.policy.apex.context.ContextException;
30 import org.onap.policy.apex.context.Distributor;
31 import org.onap.policy.apex.context.LockManager;
32 import org.onap.policy.apex.context.Persistor;
33 import org.onap.policy.apex.context.impl.ContextAlbumImpl;
34 import org.onap.policy.apex.context.impl.locking.LockManagerFactory;
35 import org.onap.policy.apex.context.impl.persistence.PersistorFactory;
36 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
37 import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation;
38 import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult;
39 import org.onap.policy.apex.model.basicmodel.service.ModelService;
40 import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum;
41 import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums;
42 import org.onap.policy.apex.model.contextmodel.concepts.AxContextModel;
43 import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema;
44 import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas;
45 import org.slf4j.ext.XLogger;
46 import org.slf4j.ext.XLoggerFactory;
47
48 /**
49  * This context distributor implements the mechanism-neutral parts of a context distributor.
50  *
51  * @author Liam Fallon (liam.fallon@ericsson.com)
52  */
53 public abstract class AbstractDistributor implements Distributor {
54
55     // Logger for this class
56     private static final XLogger LOGGER = XLoggerFactory.getXLogger(AbstractDistributor.class);
57
58     // The key of this distributor
59     private AxArtifactKey key = null;
60
61     // The context albums for this context set indexed by their keys
62     private static Map<AxArtifactKey, ContextAlbum> albumMaps =
63             Collections.synchronizedMap(new HashMap<AxArtifactKey, ContextAlbum>());
64
65     // Lock manager for this distributor
66     private static LockManager lockManager = null;
67
68     // Hold a persistor for this distributor
69     private Persistor persistor = null;
70
71     // Hold a flush timer for this context distributor
72     private static DistributorFlushTimerTask flushTimer = null;
73
74     /**
75      * Create an instance of an abstract Context Distributor.
76      */
77     public AbstractDistributor() {
78         LOGGER.entry("AbstractContextDistributor()");
79         LOGGER.exit("AbstractContextDistributor()");
80     }
81
82     /*
83      * (non-Javadoc)
84      *
85      * @see org.onap.policy.apex.context.ContextDistributor#init(org.onap.policy.apex.model.basicmodel.concepts.
86      * AxArtifactKey)
87      */
88     @Override
89     public void init(final AxArtifactKey distributorKey) throws ContextException {
90         LOGGER.entry("init(" + distributorKey + ")");
91
92         // Record parameters and key
93         this.key = distributorKey;
94
95         // Create the lock manager if it doesn't already exist
96         if (lockManager == null) {
97             lockManager = new LockManagerFactory().createLockManager(key);
98         }
99
100         // Set up flushing on the context distributor if its not set up already
101         if (flushTimer == null) {
102             flushTimer = new DistributorFlushTimerTask(this);
103         }
104
105         // Create a new persistor for this key
106         persistor = new PersistorFactory().createPersistor(key);
107         LOGGER.exit("init(" + key + ")");
108     }
109
110     /*
111      * (non-Javadoc)
112      *
113      * @see org.onap.policy.apex.context.ContextDistributor#shutdown()
114      */
115     @Override
116     public abstract void shutdown();
117
118     /*
119      * (non-Javadoc)
120      *
121      * @see org.onap.policy.apex.context.ContextDistributor#getKey()
122      */
123     @Override
124     public AxArtifactKey getKey() {
125         return key;
126     }
127
128     /**
129      * Create a context album using whatever underlying mechanism we are using for albums.
130      *
131      * @param contextAlbumKey The key of the album
132      * @return The album as a string-object map
133      */
134     public abstract Map<String, Object> getContextAlbumMap(AxArtifactKey contextAlbumKey);
135
136
137     /*
138      * (non-Javadoc)
139      *
140      * @see org.onap.policy.apex.context.Distributor#registerModel(org.onap.policy.apex.model.contextmodel.concepts.
141      * AxContextModel)
142      */
143     @Override
144     public void registerModel(final AxContextModel contextModel) throws ContextException {
145         ModelService.registerModel(AxKeyInformation.class, contextModel.getKeyInformation());
146         ModelService.registerModel(AxContextSchemas.class, contextModel.getSchemas());
147         ModelService.registerModel(AxContextAlbums.class, contextModel.getAlbums());
148     }
149
150     /*
151      * (non-Javadoc)
152      *
153      * @see
154      * org.onap.policy.apex.core.context.ContextDistributor#createContextAlbum(org.onap.policy.apex.core.basicmodel.
155      * concepts. AxArtifactKey)
156      */
157     @Override
158     public synchronized ContextAlbum createContextAlbum(final AxArtifactKey axContextAlbumKey) throws ContextException {
159         // Get the context album definition
160         final AxContextAlbum album = ModelService.getModel(AxContextAlbums.class).get(axContextAlbumKey);
161         if (album == null) {
162             final String resultString = "context album " + axContextAlbumKey.getID() + " does not exist";
163             LOGGER.warn(resultString);
164             throw new ContextException(resultString);
165         }
166
167         // Check if the context album is valid
168         final AxValidationResult result = album.validate(new AxValidationResult());
169         if (!result.isValid()) {
170             final String resultString =
171                     "context album definition for " + album.getKey().getID() + " is invalid" + result;
172             LOGGER.warn(resultString);
173             throw new ContextException(resultString);
174         }
175
176         // Get the schema of the context album
177         final AxContextSchema schema = ModelService.getModel(AxContextSchemas.class).get(album.getItemSchema());
178         if (schema == null) {
179             final String resultString = "schema \"" + album.getItemSchema().getID() + "\" for context album "
180                     + album.getKey().getID() + " does not exist";
181             LOGGER.warn(resultString);
182             throw new ContextException(resultString);
183         }
184
185         // Check if the map has already been instantiated
186         if (!albumMaps.containsKey(album.getKey())) {
187             // Instantiate the album map for this context album that we'll distribute using the distribution mechanism
188             final Map<String, Object> newContextAlbumMap = getContextAlbumMap(album.getKey());
189
190             // The distributed context album will have content from another process instance if the album exists in
191             // another process,
192             // if not, we have to try to read the content from persistence
193             if (newContextAlbumMap.isEmpty()) {
194                 // Read entries from persistence
195                 // TODO: READ ITEMS FROM PRESISTENCE!!!!
196             }
197
198             // Create the context album and put the context album object onto the distributor
199             albumMaps.put(album.getKey(), new ContextAlbumImpl(album, this, newContextAlbumMap));
200         }
201
202         return albumMaps.get(album.getKey());
203     }
204
205     /*
206      * (non-Javadoc)
207      *
208      * @see
209      * org.onap.policy.apex.core.context.ContextDistributor#removeContextAlbum(org.onap.policy.apex.core.basicmodel.
210      * concepts. AxArtifactKey)
211      */
212     @Override
213     public void removeContextAlbum(final AxContextAlbum contextAlbum) throws ContextException {
214         // Check if the map already exists, if not return
215         if (!albumMaps.containsKey(contextAlbum.getKey())) {
216             LOGGER.warn("map remove failed, supplied map is null");
217             throw new ContextException("map update failed, supplied map is null");
218         }
219
220         // Remove the map from the distributor
221         albumMaps.remove(contextAlbum.getKey());
222     }
223
224     /*
225      * (non-Javadoc)
226      *
227      * @see org.onap.policy.apex.core.context.ContextDistributor#flush()
228      */
229     @Override
230     public void flush() throws ContextException {
231         // Flush all the maps
232         for (final Entry<AxArtifactKey, ContextAlbum> distributorMapEntry : albumMaps.entrySet()) {
233             // Let the persistor write each of the entries
234             for (final Object contextItem : distributorMapEntry.getValue().values()) {
235                 LOGGER.debug(contextItem.toString());
236                 // persistor.writeContextItem((AxContextSchema) contextItem);
237             }
238         }
239     }
240
241     /*
242      * (non-Javadoc)
243      *
244      * @see org.onap.policy.apex.core.context.ContextDistributor#flushContextAlbum(org.onap.policy.apex.core.context.
245      * ContextAlbum)
246      */
247     @Override
248     public void flushContextAlbum(final ContextAlbum contextAlbum) throws ContextException {
249         // Check if the map already exists, if not return
250         if (!albumMaps.containsKey(contextAlbum.getKey())) {
251             LOGGER.warn("map flush failed, supplied map is null");
252             throw new ContextException("map flush failed, supplied map is null");
253         }
254
255         // Let the persistor flush the items on the map
256         for (final Object contextItem : albumMaps.get(contextAlbum.getKey()).values()) {
257             persistor.writeContextItem(contextItem);
258         }
259     }
260
261     /*
262      * (non-Javadoc)
263      *
264      * @see org.onap.policy.apex.core.context.ContextDistributor#lockForReading(java.lang.String)
265      */
266     @Override
267     public synchronized void lockForReading(final AxArtifactKey mapKey, final String itemKey) throws ContextException {
268         // Lock using the lock manager
269         lockManager.lockForReading(mapKey.getID(), itemKey);
270     }
271
272     /*
273      * (non-Javadoc)
274      *
275      * @see org.onap.policy.apex.core.context.ContextDistributor#lockForWriting(java.lang.String)
276      */
277     @Override
278     public synchronized void lockForWriting(final AxArtifactKey mapKey, final String itemKey) throws ContextException {
279         // Lock using the lock manager
280         lockManager.lockForWriting(mapKey.getID(), itemKey);
281     }
282
283     /*
284      * (non-Javadoc)
285      *
286      * @see org.onap.policy.apex.core.context.ContextDistributor#unlockForReading(java.lang.String)
287      */
288     @Override
289     public void unlockForReading(final AxArtifactKey mapKey, final String itemKey) throws ContextException {
290         // Unlock using the lock manager
291         lockManager.unlockForReading(mapKey.getID(), itemKey);
292     }
293
294     /*
295      * (non-Javadoc)
296      *
297      * @see org.onap.policy.apex.core.context.ContextDistributor#unlockForWriting(java.lang.String)
298      */
299     @Override
300     public void unlockForWriting(final AxArtifactKey mapKey, final String itemKey) throws ContextException {
301         // Unlock using the lock manager
302         lockManager.unlockForWriting(mapKey.getID(), itemKey);
303     }
304
305     /*
306      * (non-Javadoc)
307      *
308      * @see org.onap.policy.apex.core.context.ContextDistributor#clear()
309      */
310     @Override
311     public void clear() {
312         // Shut down the lock manager
313         if (lockManager != null) {
314             lockManager.shutdown();
315             lockManager = null;
316         }
317
318         albumMaps.clear();
319
320         // Turn off the flush timer
321         flushTimer.cancel();
322
323         // Shut down the specialization of the context distributor
324         shutdown();
325     }
326 }