dc28e26aea8d484e9b850fa6d801043420e3c7d3
[lispflowmapping.git] / mappingservice / clusterdao / src / main / java / org / opendaylight / lispflowmapping / clusterdao / ClusterDAOService.java
1 /*
2  * Copyright (c) 2014 Contextream, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.lispflowmapping.clusterdao;
10
11 import java.util.EnumSet;
12 import java.util.HashMap;
13 import java.util.Map;
14 import java.util.concurrent.ConcurrentMap;
15 import java.util.concurrent.Executors;
16 import java.util.concurrent.ScheduledExecutorService;
17 import java.util.concurrent.TimeUnit;
18
19 import org.opendaylight.controller.clustering.services.CacheConfigException;
20 import org.opendaylight.controller.clustering.services.CacheExistException;
21 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
22 import org.opendaylight.controller.clustering.services.IClusterServices;
23 import org.opendaylight.lispflowmapping.interfaces.dao.ILispDAO;
24 import org.opendaylight.lispflowmapping.interfaces.dao.IQueryAll;
25 import org.opendaylight.lispflowmapping.interfaces.dao.IRowVisitor;
26 import org.opendaylight.lispflowmapping.interfaces.dao.MappingEntry;
27 import org.opendaylight.lispflowmapping.interfaces.dao.MappingServiceRLOCGroup;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 public class ClusterDAOService implements ILispDAO, IQueryAll {
32
33     protected static final Logger logger = LoggerFactory.getLogger(ClusterDAOService.class);
34     private IClusterContainerServices clusterContainerService = null;
35     private ConcurrentMap<Object, Map<String, Object>> data;
36     private final String CACHE_NAME = "mappingServiceCache";
37     private TimeUnit timeUnit = TimeUnit.SECONDS;
38     private int recordTimeOut = 240;
39     private int cleanInterval = 10;
40     private ScheduledExecutorService scheduler;
41
42     void setClusterContainerService(IClusterContainerServices s) {
43         this.clusterContainerService = s;
44         allocateCache();
45         retrieveCache();
46         scheduler = Executors.newScheduledThreadPool(1);
47         scheduler.scheduleAtFixedRate(new Runnable() {
48
49             public void run() {
50                 cleanOld();
51             }
52         }, 0, cleanInterval, timeUnit);
53     }
54
55     void unsetClusterContainerService(IClusterContainerServices s) {
56         logger.trace("Cluster Service unset");
57         if (this.clusterContainerService == s) {
58             this.clusterContainerService = null;
59         }
60         scheduler.shutdownNow();
61     }
62
63     @SuppressWarnings("deprecation")
64     private void allocateCache() {
65         if (this.clusterContainerService == null) {
66             logger.warn("un-initialized clusterContainerService, can't create cache");
67             return;
68         }
69         logger.trace("Creating Cache for ClusterDAOService");
70         try {
71             this.clusterContainerService.createCache(CACHE_NAME, EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
72         } catch (CacheConfigException cce) {
73             logger.warn("Cache couldn't be created for ClusterDAOService -  check cache mode");
74         } catch (CacheExistException cce) {
75             logger.warn("Cache for ClusterDAOService already exists, destroy and recreate");
76         }
77         logger.trace("Cache successfully created for ClusterDAOService");
78     }
79
80     @SuppressWarnings({ "unchecked", "deprecation" })
81     private void retrieveCache() {
82         if (this.clusterContainerService == null) {
83             logger.warn("un-initialized clusterContainerService, can't retrieve cache");
84             return;
85         }
86         logger.trace("Retrieving cache for ClusterDAOService");
87         data = (ConcurrentMap<Object, Map<String, Object>>) this.clusterContainerService.getCache(CACHE_NAME);
88         if (data == null) {
89             logger.warn("Cache couldn't be retrieved for ClusterDAOService");
90         }
91         logger.trace("Cache was successfully retrieved for ClusterDAOService");
92     }
93
94     public void getAll(IRowVisitor visitor) {
95         for (Map.Entry<Object, Map<String, Object>> keyEntry : data.entrySet()) {
96             for (Map.Entry<String, Object> valueEntry : keyEntry.getValue().entrySet()) {
97                 visitor.visitRow(keyEntry.getKey(), valueEntry.getKey(), valueEntry.getValue());
98             }
99         }
100     }
101
102     public void put(Object key, MappingEntry<?>... values) {
103         if (!data.containsKey(key)) {
104             data.put(key, new HashMap<String, Object>());
105         }
106         for (MappingEntry<?> entry : values) {
107             data.get(key).put(entry.getKey(), entry.getValue());
108         }
109     }
110
111     public void cleanOld() {
112         getAll(new IRowVisitor() {
113             public void visitRow(Object keyId, String valueKey, Object value) {
114                 if (value instanceof MappingServiceRLOCGroup) {
115                     MappingServiceRLOCGroup rloc = (MappingServiceRLOCGroup) value;
116                     if (isExpired(rloc)) {
117                         removeSpecific(keyId, valueKey);
118                     }
119                 }
120             }
121
122             private boolean isExpired(MappingServiceRLOCGroup rloc) {
123                 return System.currentTimeMillis() - rloc.getRegisterdDate().getTime() > TimeUnit.MILLISECONDS.convert(recordTimeOut, timeUnit);
124             }
125         });
126     }
127
128     public Object getSpecific(Object key, String valueKey) {
129         Map<String, Object> keyToValues = data.get(key);
130         if (keyToValues == null) {
131             return null;
132         }
133         return keyToValues.get(valueKey);
134     }
135
136     public <K> Map<String, Object> get(K key) {
137         return data.get(key);
138     }
139
140     public boolean remove(Object key) {
141         return data.remove(key) != null;
142     }
143
144     public boolean removeSpecific(Object key, String valueKey) {
145         if (!data.containsKey(key) || !data.get(key).containsKey(valueKey)) {
146             return false;
147         }
148         return data.get(key).remove(valueKey) != null;
149     }
150
151     public void clearAll() {
152         data.clear();
153     }
154
155     public TimeUnit getTimeUnit() {
156         return timeUnit;
157     }
158
159     public void setRecordTimeOut(int recordTimeOut) {
160         this.recordTimeOut = recordTimeOut;
161     }
162
163     public int getRecordTimeOut() {
164         return recordTimeOut;
165     }
166
167     public void setTimeUnit(TimeUnit timeUnit) {
168         this.timeUnit = timeUnit;
169     }
170 }