blob: 7124a1fc33e655e6db798b79551c48e7709fd2cb [file] [log] [blame]
alshabib7bb05012015-08-05 10:15:09 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
alshabib7bb05012015-08-05 10:15:09 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.incubator.store.meter.impl;
17
alshabibeadfc8e2015-08-18 15:40:46 -070018import com.google.common.collect.Collections2;
Charles Chan593acf92017-11-22 13:55:41 -080019import com.google.common.collect.Lists;
Pier Luigif094c612017-10-14 12:15:02 +020020import com.google.common.collect.Iterables;
alshabibeadfc8e2015-08-18 15:40:46 -070021import com.google.common.collect.Maps;
Pier Luigif094c612017-10-14 12:15:02 +020022import org.apache.commons.lang.math.RandomUtils;
alshabib7bb05012015-08-05 10:15:09 -070023import org.apache.felix.scr.annotations.Activate;
alshabib58fe6dc2015-08-19 17:16:13 -070024import org.apache.felix.scr.annotations.Component;
alshabib7bb05012015-08-05 10:15:09 -070025import org.apache.felix.scr.annotations.Deactivate;
alshabib7bb05012015-08-05 10:15:09 -070026import org.apache.felix.scr.annotations.Reference;
27import org.apache.felix.scr.annotations.ReferenceCardinality;
alshabib58fe6dc2015-08-19 17:16:13 -070028import org.apache.felix.scr.annotations.Service;
Charles Chan593acf92017-11-22 13:55:41 -080029import org.onlab.util.KryoNamespace;
alshabib7bb05012015-08-05 10:15:09 -070030import org.onosproject.cluster.ClusterService;
31import org.onosproject.cluster.NodeId;
alshabib58fe6dc2015-08-19 17:16:13 -070032import org.onosproject.mastership.MastershipService;
Jordi Ortizaa8de492016-12-01 00:21:36 +010033import org.onosproject.net.DeviceId;
Pier Luigif094c612017-10-14 12:15:02 +020034import org.onosproject.net.behaviour.MeterQuery;
35import org.onosproject.net.driver.DriverHandler;
36import org.onosproject.net.driver.DriverService;
alshabib58fe6dc2015-08-19 17:16:13 -070037import org.onosproject.net.meter.Band;
38import org.onosproject.net.meter.DefaultBand;
alshabib10c810b2015-08-18 16:59:04 -070039import org.onosproject.net.meter.DefaultMeter;
Jordi Ortiz6c847762017-01-30 17:13:05 +010040import org.onosproject.net.meter.DefaultMeterFeatures;
alshabib10c810b2015-08-18 16:59:04 -070041import org.onosproject.net.meter.Meter;
42import org.onosproject.net.meter.MeterEvent;
43import org.onosproject.net.meter.MeterFailReason;
Jordi Ortizaa8de492016-12-01 00:21:36 +010044import org.onosproject.net.meter.MeterFeatures;
cansu.toprak409289d2017-10-27 10:04:05 +030045import org.onosproject.net.meter.MeterFeaturesFlag;
Jordi Ortizaa8de492016-12-01 00:21:36 +010046import org.onosproject.net.meter.MeterFeaturesKey;
Jordi Ortiz6c847762017-01-30 17:13:05 +010047import org.onosproject.net.meter.MeterId;
alshabib70aaa1b2015-09-25 14:30:59 -070048import org.onosproject.net.meter.MeterKey;
alshabib10c810b2015-08-18 16:59:04 -070049import org.onosproject.net.meter.MeterOperation;
50import org.onosproject.net.meter.MeterState;
51import org.onosproject.net.meter.MeterStore;
52import org.onosproject.net.meter.MeterStoreDelegate;
53import org.onosproject.net.meter.MeterStoreResult;
alshabib7bb05012015-08-05 10:15:09 -070054import org.onosproject.store.AbstractStore;
Pier Luigif094c612017-10-14 12:15:02 +020055import org.onosproject.store.primitives.DefaultDistributedSet;
alshabibeadfc8e2015-08-18 15:40:46 -070056import org.onosproject.store.serializers.KryoNamespaces;
Pier Luigif094c612017-10-14 12:15:02 +020057import org.onosproject.store.service.AtomicCounterMap;
alshabib7bb05012015-08-05 10:15:09 -070058import org.onosproject.store.service.ConsistentMap;
Pier Luigif094c612017-10-14 12:15:02 +020059import org.onosproject.store.service.DistributedPrimitive;
60import org.onosproject.store.service.DistributedSet;
alshabibeadfc8e2015-08-18 15:40:46 -070061import org.onosproject.store.service.MapEvent;
62import org.onosproject.store.service.MapEventListener;
alshabib7bb05012015-08-05 10:15:09 -070063import org.onosproject.store.service.Serializer;
alshabibeadfc8e2015-08-18 15:40:46 -070064import org.onosproject.store.service.StorageException;
alshabib7bb05012015-08-05 10:15:09 -070065import org.onosproject.store.service.StorageService;
alshabibeadfc8e2015-08-18 15:40:46 -070066import org.onosproject.store.service.Versioned;
alshabib7bb05012015-08-05 10:15:09 -070067import org.slf4j.Logger;
68
69import java.util.Collection;
alshabibeadfc8e2015-08-18 15:40:46 -070070import java.util.Map;
Pier Luigif094c612017-10-14 12:15:02 +020071import java.util.Set;
alshabibeadfc8e2015-08-18 15:40:46 -070072import java.util.concurrent.CompletableFuture;
Pier Luigif094c612017-10-14 12:15:02 +020073import java.util.stream.Collectors;
alshabib7bb05012015-08-05 10:15:09 -070074
Pier Luigif094c612017-10-14 12:15:02 +020075import static org.onosproject.incubator.store.meter.impl.DistributedMeterStore.ReuseStrategy.FIRST_FIT;
Jordi Ortizaa8de492016-12-01 00:21:36 +010076import static org.onosproject.net.meter.MeterFailReason.TIMEOUT;
alshabib7bb05012015-08-05 10:15:09 -070077import static org.slf4j.LoggerFactory.getLogger;
78
79/**
80 * A distributed meter store implementation. Meters are stored consistently
81 * across the cluster.
82 */
alshabib58fe6dc2015-08-19 17:16:13 -070083@Component(immediate = true)
84@Service
alshabib7bb05012015-08-05 10:15:09 -070085public class DistributedMeterStore extends AbstractStore<MeterEvent, MeterStoreDelegate>
86 implements MeterStore {
87
88 private Logger log = getLogger(getClass());
89
90 private static final String METERSTORE = "onos-meter-store";
Jordi Ortizaa8de492016-12-01 00:21:36 +010091 private static final String METERFEATURESSTORE = "onos-meter-features-store";
Jordi Ortiz6c847762017-01-30 17:13:05 +010092 private static final String AVAILABLEMETERIDSTORE = "onos-meters-available-store";
Pier Luigif094c612017-10-14 12:15:02 +020093 private static final String METERIDSTORE = "onos-meters-id-store";
alshabib7bb05012015-08-05 10:15:09 -070094
Charles Chan593acf92017-11-22 13:55:41 -080095 private static final KryoNamespace.Builder APP_KRYO_BUILDER = KryoNamespace.newBuilder()
96 .register(KryoNamespaces.API)
97 .register(MeterKey.class)
98 .register(MeterData.class)
99 .register(DefaultMeter.class)
100 .register(DefaultBand.class)
101 .register(Band.Type.class)
102 .register(MeterState.class)
103 .register(Meter.Unit.class);
104
105 private Serializer serializer = Serializer.using(Lists.newArrayList(APP_KRYO_BUILDER.build()));
106
alshabib7bb05012015-08-05 10:15:09 -0700107 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
108 private StorageService storageService;
109
110 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
alshabib7bb05012015-08-05 10:15:09 -0700111 private MastershipService mastershipService;
112
113 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
114 private ClusterService clusterService;
115
Pier Luigif094c612017-10-14 12:15:02 +0200116 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
117 protected DriverService driverService;
118
alshabib70aaa1b2015-09-25 14:30:59 -0700119 private ConsistentMap<MeterKey, MeterData> meters;
alshabib7bb05012015-08-05 10:15:09 -0700120 private NodeId local;
alshabib7bb05012015-08-05 10:15:09 -0700121
Jordi Ortizaa8de492016-12-01 00:21:36 +0100122 private ConsistentMap<MeterFeaturesKey, MeterFeatures> meterFeatures;
123
HIGUCHI Yuta0574a552015-09-29 14:38:25 -0700124 private MapEventListener<MeterKey, MeterData> mapListener = new InternalMapEventListener();
alshabibeadfc8e2015-08-18 15:40:46 -0700125
alshabib70aaa1b2015-09-25 14:30:59 -0700126 private Map<MeterKey, CompletableFuture<MeterStoreResult>> futures =
alshabibeadfc8e2015-08-18 15:40:46 -0700127 Maps.newConcurrentMap();
alshabib7bb05012015-08-05 10:15:09 -0700128
Pier Luigif094c612017-10-14 12:15:02 +0200129 // Available meter identifiers
130 private DistributedSet<MeterKey> availableMeterIds;
131
132 // Atomic counter map for generation of new identifiers;
133 private AtomicCounterMap<DeviceId> meterIdGenerators;
134
135 /**
136 * Defines possible selection strategies to reuse meter ids.
137 */
138 enum ReuseStrategy {
139 /**
140 * Select randomly an available id.
141 */
142 RANDOM,
143 /**
144 * Select the first one.
145 */
146 FIRST_FIT
147 }
148
149 private ReuseStrategy reuseStrategy = FIRST_FIT;
Jordi Ortiz6c847762017-01-30 17:13:05 +0100150
alshabib7bb05012015-08-05 10:15:09 -0700151 @Activate
152 public void activate() {
alshabib7bb05012015-08-05 10:15:09 -0700153 local = clusterService.getLocalNode().id();
154
alshabib70aaa1b2015-09-25 14:30:59 -0700155 meters = storageService.<MeterKey, MeterData>consistentMapBuilder()
alshabib7bb05012015-08-05 10:15:09 -0700156 .withName(METERSTORE)
Charles Chan593acf92017-11-22 13:55:41 -0800157 .withSerializer(serializer).build();
alshabib7bb05012015-08-05 10:15:09 -0700158
alshabibeadfc8e2015-08-18 15:40:46 -0700159 meters.addListener(mapListener);
alshabib7bb05012015-08-05 10:15:09 -0700160
Jordi Ortizaa8de492016-12-01 00:21:36 +0100161 meterFeatures = storageService.<MeterFeaturesKey, MeterFeatures>consistentMapBuilder()
162 .withName(METERFEATURESSTORE)
Pier Luigif094c612017-10-14 12:15:02 +0200163 .withSerializer(Serializer.using(KryoNamespaces.API,
164 MeterFeaturesKey.class,
165 MeterFeatures.class,
166 DefaultMeterFeatures.class,
167 Band.Type.class,
168 Meter.Unit.class,
cansu.toprak409289d2017-10-27 10:04:05 +0300169 MeterFailReason.class,
170 MeterFeaturesFlag.class)).build();
Jordi Ortizaa8de492016-12-01 00:21:36 +0100171
Pier Luigif094c612017-10-14 12:15:02 +0200172 // Init the set of the available ids
173 availableMeterIds = new DefaultDistributedSet<>(storageService.<MeterKey>setBuilder()
Jordi Ortiz6c847762017-01-30 17:13:05 +0100174 .withName(AVAILABLEMETERIDSTORE)
Pier Luigif094c612017-10-14 12:15:02 +0200175 .withSerializer(Serializer.using(KryoNamespaces.API,
176 MeterKey.class)).build(),
177 DistributedPrimitive.DEFAULT_OPERATION_TIMEOUT_MILLIS);
178
179 // Init atomic map counters
180 meterIdGenerators = storageService.<DeviceId>atomicCounterMapBuilder()
181 .withName(METERIDSTORE)
Yuta HIGUCHI872c9822017-05-25 09:35:14 -0700182 .withSerializer(Serializer.using(KryoNamespaces.API)).build();
Jordi Ortiz6c847762017-01-30 17:13:05 +0100183
alshabib7bb05012015-08-05 10:15:09 -0700184 log.info("Started");
185 }
186
187 @Deactivate
188 public void deactivate() {
alshabibeadfc8e2015-08-18 15:40:46 -0700189 meters.removeListener(mapListener);
alshabib7bb05012015-08-05 10:15:09 -0700190 log.info("Stopped");
191 }
192
alshabib7bb05012015-08-05 10:15:09 -0700193 @Override
alshabibeadfc8e2015-08-18 15:40:46 -0700194 public CompletableFuture<MeterStoreResult> storeMeter(Meter meter) {
Pier Luigif094c612017-10-14 12:15:02 +0200195 // Init steps
alshabibeadfc8e2015-08-18 15:40:46 -0700196 CompletableFuture<MeterStoreResult> future = new CompletableFuture<>();
alshabib70aaa1b2015-09-25 14:30:59 -0700197 MeterKey key = MeterKey.key(meter.deviceId(), meter.id());
Pier Luigif094c612017-10-14 12:15:02 +0200198 // Store the future related to the operation
alshabib70aaa1b2015-09-25 14:30:59 -0700199 futures.put(key, future);
Pier Luigif094c612017-10-14 12:15:02 +0200200 // Store the meter data
alshabibeadfc8e2015-08-18 15:40:46 -0700201 MeterData data = new MeterData(meter, null, local);
alshabibeadfc8e2015-08-18 15:40:46 -0700202 try {
alshabib70aaa1b2015-09-25 14:30:59 -0700203 meters.put(key, data);
alshabibeadfc8e2015-08-18 15:40:46 -0700204 } catch (StorageException e) {
Hwanwook Lee8206ad92018-01-02 18:03:50 +0900205 futures.remove(key);
alshabibeadfc8e2015-08-18 15:40:46 -0700206 future.completeExceptionally(e);
alshabib7bb05012015-08-05 10:15:09 -0700207 }
Pier Luigif094c612017-10-14 12:15:02 +0200208 // Done, return the future
alshabibeadfc8e2015-08-18 15:40:46 -0700209 return future;
alshabib7bb05012015-08-05 10:15:09 -0700210 }
211
212 @Override
alshabibeadfc8e2015-08-18 15:40:46 -0700213 public CompletableFuture<MeterStoreResult> deleteMeter(Meter meter) {
Pier Luigif094c612017-10-14 12:15:02 +0200214 // Init steps
alshabibeadfc8e2015-08-18 15:40:46 -0700215 CompletableFuture<MeterStoreResult> future = new CompletableFuture<>();
alshabib70aaa1b2015-09-25 14:30:59 -0700216 MeterKey key = MeterKey.key(meter.deviceId(), meter.id());
Pier Luigif094c612017-10-14 12:15:02 +0200217 // Store the future related to the operation
alshabib70aaa1b2015-09-25 14:30:59 -0700218 futures.put(key, future);
Pier Luigif094c612017-10-14 12:15:02 +0200219 // Create the meter data
alshabibeadfc8e2015-08-18 15:40:46 -0700220 MeterData data = new MeterData(meter, null, local);
Pier Luigif094c612017-10-14 12:15:02 +0200221 // Update the state of the meter. It will be pruned by observing
alshabib7bb05012015-08-05 10:15:09 -0700222 // that it has been removed from the dataplane.
alshabibeadfc8e2015-08-18 15:40:46 -0700223 try {
Pier Luigif094c612017-10-14 12:15:02 +0200224 // If it does not exist in the system
alshabib70aaa1b2015-09-25 14:30:59 -0700225 if (meters.computeIfPresent(key, (k, v) -> data) == null) {
Pier Luigif094c612017-10-14 12:15:02 +0200226 // Complete immediately
alshabibe1248b62015-08-20 17:21:55 -0700227 future.complete(MeterStoreResult.success());
228 }
alshabibeadfc8e2015-08-18 15:40:46 -0700229 } catch (StorageException e) {
Hwanwook Lee8206ad92018-01-02 18:03:50 +0900230 futures.remove(key);
alshabibeadfc8e2015-08-18 15:40:46 -0700231 future.completeExceptionally(e);
alshabib7bb05012015-08-05 10:15:09 -0700232 }
Pier Luigif094c612017-10-14 12:15:02 +0200233 // Done, return the future
alshabibeadfc8e2015-08-18 15:40:46 -0700234 return future;
alshabib7bb05012015-08-05 10:15:09 -0700235 }
236
237 @Override
Jordi Ortizaa8de492016-12-01 00:21:36 +0100238 public MeterStoreResult storeMeterFeatures(MeterFeatures meterfeatures) {
239 MeterStoreResult result = MeterStoreResult.success();
240 MeterFeaturesKey key = MeterFeaturesKey.key(meterfeatures.deviceId());
241 try {
242 meterFeatures.putIfAbsent(key, meterfeatures);
243 } catch (StorageException e) {
244 result = MeterStoreResult.fail(TIMEOUT);
245 }
246 return result;
247 }
248
249 @Override
250 public MeterStoreResult deleteMeterFeatures(DeviceId deviceId) {
251 MeterStoreResult result = MeterStoreResult.success();
252 MeterFeaturesKey key = MeterFeaturesKey.key(deviceId);
253 try {
254 meterFeatures.remove(key);
255 } catch (StorageException e) {
256 result = MeterStoreResult.fail(TIMEOUT);
257 }
258 return result;
259 }
260
261 @Override
alshabibeadfc8e2015-08-18 15:40:46 -0700262 public CompletableFuture<MeterStoreResult> updateMeter(Meter meter) {
263 CompletableFuture<MeterStoreResult> future = new CompletableFuture<>();
alshabib70aaa1b2015-09-25 14:30:59 -0700264 MeterKey key = MeterKey.key(meter.deviceId(), meter.id());
265 futures.put(key, future);
alshabib7bb05012015-08-05 10:15:09 -0700266
alshabibeadfc8e2015-08-18 15:40:46 -0700267 MeterData data = new MeterData(meter, null, local);
268 try {
alshabib70aaa1b2015-09-25 14:30:59 -0700269 if (meters.computeIfPresent(key, (k, v) -> data) == null) {
alshabibe1248b62015-08-20 17:21:55 -0700270 future.complete(MeterStoreResult.fail(MeterFailReason.INVALID_METER));
271 }
alshabibeadfc8e2015-08-18 15:40:46 -0700272 } catch (StorageException e) {
Hwanwook Lee8206ad92018-01-02 18:03:50 +0900273 futures.remove(key);
alshabibeadfc8e2015-08-18 15:40:46 -0700274 future.completeExceptionally(e);
alshabib7bb05012015-08-05 10:15:09 -0700275 }
alshabibeadfc8e2015-08-18 15:40:46 -0700276 return future;
alshabib7bb05012015-08-05 10:15:09 -0700277 }
278
279 @Override
280 public void updateMeterState(Meter meter) {
alshabib70aaa1b2015-09-25 14:30:59 -0700281 MeterKey key = MeterKey.key(meter.deviceId(), meter.id());
282 meters.computeIfPresent(key, (k, v) -> {
alshabibeadfc8e2015-08-18 15:40:46 -0700283 DefaultMeter m = (DefaultMeter) v.meter();
alshabib7bb05012015-08-05 10:15:09 -0700284 m.setState(meter.state());
285 m.setProcessedPackets(meter.packetsSeen());
286 m.setProcessedBytes(meter.bytesSeen());
287 m.setLife(meter.life());
alshabibeadfc8e2015-08-18 15:40:46 -0700288 // TODO: Prune if drops to zero.
alshabib7bb05012015-08-05 10:15:09 -0700289 m.setReferenceCount(meter.referenceCount());
alshabibeadfc8e2015-08-18 15:40:46 -0700290 return new MeterData(m, null, v.origin());
alshabib7bb05012015-08-05 10:15:09 -0700291 });
292 }
293
294 @Override
alshabib70aaa1b2015-09-25 14:30:59 -0700295 public Meter getMeter(MeterKey key) {
296 MeterData data = Versioned.valueOrElse(meters.get(key), null);
alshabibeadfc8e2015-08-18 15:40:46 -0700297 return data == null ? null : data.meter();
alshabib7bb05012015-08-05 10:15:09 -0700298 }
299
300 @Override
301 public Collection<Meter> getAllMeters() {
alshabibeadfc8e2015-08-18 15:40:46 -0700302 return Collections2.transform(meters.asJavaMap().values(),
303 MeterData::meter);
alshabib7bb05012015-08-05 10:15:09 -0700304 }
305
306 @Override
Jordi Ortiz9287b632017-06-22 11:01:37 +0200307 public Collection<Meter> getAllMeters(DeviceId deviceId) {
308 return Collections2.transform(
309 Collections2.filter(meters.asJavaMap().values(),
310 (MeterData m) -> m.meter().deviceId().equals(deviceId)),
311 MeterData::meter);
312 }
313
314 @Override
alshabib7bb05012015-08-05 10:15:09 -0700315 public void failedMeter(MeterOperation op, MeterFailReason reason) {
alshabib70aaa1b2015-09-25 14:30:59 -0700316 MeterKey key = MeterKey.key(op.meter().deviceId(), op.meter().id());
317 meters.computeIfPresent(key, (k, v) ->
alshabibeadfc8e2015-08-18 15:40:46 -0700318 new MeterData(v.meter(), reason, v.origin()));
alshabib7bb05012015-08-05 10:15:09 -0700319 }
320
alshabib5eb79392015-08-19 18:09:55 -0700321 @Override
322 public void deleteMeterNow(Meter m) {
Pier Luigif094c612017-10-14 12:15:02 +0200323 // Create the key
alshabib70aaa1b2015-09-25 14:30:59 -0700324 MeterKey key = MeterKey.key(m.deviceId(), m.id());
Pier Luigif094c612017-10-14 12:15:02 +0200325 // Remove the future
alshabib70aaa1b2015-09-25 14:30:59 -0700326 futures.remove(key);
Pier Luigif094c612017-10-14 12:15:02 +0200327 // Remove the meter
alshabib70aaa1b2015-09-25 14:30:59 -0700328 meters.remove(key);
Pier Luigif094c612017-10-14 12:15:02 +0200329 // Free the id
330 freeMeterId(m.deviceId(), m.id());
331 // Finally notify the delegate
Jordi Ortizdf28ecd2017-03-25 19:22:36 +0100332 notifyDelegate(new MeterEvent(MeterEvent.Type.METER_REMOVED, m));
alshabib5eb79392015-08-19 18:09:55 -0700333 }
334
Jordi Ortizaa8de492016-12-01 00:21:36 +0100335 @Override
336 public long getMaxMeters(MeterFeaturesKey key) {
337 MeterFeatures features = Versioned.valueOrElse(meterFeatures.get(key), null);
338 return features == null ? 0L : features.maxMeter();
339 }
340
Pier Luigif094c612017-10-14 12:15:02 +0200341 // queryMaxMeters is implemented in FullMetersAvailable behaviour.
342 private long queryMaxMeters(DeviceId device) {
343 // Get driver handler for this device
344 DriverHandler handler = driverService.createHandler(device);
345 // If creation failed or the device does not have this behavior
346 if (handler == null || !handler.hasBehaviour(MeterQuery.class)) {
347 // We cannot know max meter
348 return 0L;
349 }
350 // Get the behavior
351 MeterQuery query = handler.behaviour(MeterQuery.class);
352 // Return as max meter the result of the query
353 return query.getMaxMeters();
354 }
355
356 private boolean updateMeterIdAvailability(DeviceId deviceId, MeterId id,
357 boolean available) {
358 // According to available, make available or unavailable a meter key
359 return available ? availableMeterIds.add(MeterKey.key(deviceId, id)) :
360 availableMeterIds.remove(MeterKey.key(deviceId, id));
361 }
362
363 private MeterId getNextAvailableId(Set<MeterId> availableIds) {
364 // If there are no available ids
365 if (availableIds.isEmpty()) {
366 // Just end the cycle
367 return null;
368 }
369 // If it is the first fit
370 if (reuseStrategy == FIRST_FIT || availableIds.size() == 1) {
371 return availableIds.iterator().next();
372 }
373 // If it is random, get the size
374 int size = availableIds.size();
375 // Return a random element
376 return Iterables.get(availableIds, RandomUtils.nextInt(size));
377 }
378
379 // Implements reuse strategy
380 private MeterId firstReusableMeterId(DeviceId deviceId) {
381 // Filter key related to device id, and reduce to meter ids
382 Set<MeterId> localAvailableMeterIds = availableMeterIds.stream()
383 .filter(meterKey -> meterKey.deviceId().equals(deviceId))
384 .map(MeterKey::meterId)
385 .collect(Collectors.toSet());
386 // Get next available id
387 MeterId meterId = getNextAvailableId(localAvailableMeterIds);
388 // Iterate until there are items
389 while (meterId != null) {
390 // If we are able to reserve the id
391 if (updateMeterIdAvailability(deviceId, meterId, false)) {
392 // Just end
393 return meterId;
394 }
395 // Update the set
396 localAvailableMeterIds.remove(meterId);
397 // Try another time
398 meterId = getNextAvailableId(localAvailableMeterIds);
399 }
400 // No reusable ids
401 return null;
402 }
403
404 @Override
405 public MeterId allocateMeterId(DeviceId deviceId) {
406 // Init steps
407 MeterId meterId;
408 long id;
409 // Try to reuse meter id
410 meterId = firstReusableMeterId(deviceId);
411 // We found a reusable id, return
412 if (meterId != null) {
413 return meterId;
414 }
415 // If there was no reusable MeterId we have to generate a new value
416 // using maxMeters as upper limit.
417 long maxMeters = getMaxMeters(MeterFeaturesKey.key(deviceId));
418 // If the device does not give us MeterFeatures
419 if (maxMeters == 0L) {
420 // MeterFeatures couldn't be retrieved, fallback to queryMeters.
421 maxMeters = queryMaxMeters(deviceId);
422 }
423 // If we don't know the max, cannot proceed
424 if (maxMeters == 0L) {
425 return null;
426 }
427 // Get a new value
428 id = meterIdGenerators.incrementAndGet(deviceId);
429 // Check with the max, and if the value is bigger, cannot proceed
430 if (id >= maxMeters) {
431 return null;
432 }
433 // Done, return the value
434 return MeterId.meterId(id);
435 }
436
437 @Override
438 public void freeMeterId(DeviceId deviceId, MeterId meterId) {
Pier Luigibdcd9672017-10-13 13:54:48 +0200439 // Avoid to free meter not allocated
440 if (meterIdGenerators.get(deviceId) < meterId.id()) {
441 return;
442 }
Pier Luigif094c612017-10-14 12:15:02 +0200443 // Update the availability
444 updateMeterIdAvailability(deviceId, meterId, true);
445 }
446
HIGUCHI Yuta0574a552015-09-29 14:38:25 -0700447 private class InternalMapEventListener implements MapEventListener<MeterKey, MeterData> {
alshabibeadfc8e2015-08-18 15:40:46 -0700448 @Override
HIGUCHI Yuta0574a552015-09-29 14:38:25 -0700449 public void event(MapEvent<MeterKey, MeterData> event) {
450 MeterKey key = event.key();
alshabibeadfc8e2015-08-18 15:40:46 -0700451 MeterData data = event.value().value();
452 NodeId master = mastershipService.getMasterFor(data.meter().deviceId());
453 switch (event.type()) {
454 case INSERT:
455 case UPDATE:
456 switch (data.meter().state()) {
457 case PENDING_ADD:
458 case PENDING_REMOVE:
459 if (!data.reason().isPresent() && local.equals(master)) {
460 notifyDelegate(
461 new MeterEvent(data.meter().state() == MeterState.PENDING_ADD ?
462 MeterEvent.Type.METER_ADD_REQ : MeterEvent.Type.METER_REM_REQ,
463 data.meter()));
464 } else if (data.reason().isPresent() && local.equals(data.origin())) {
465 MeterStoreResult msr = MeterStoreResult.fail(data.reason().get());
466 //TODO: No future -> no friend
HIGUCHI Yuta0574a552015-09-29 14:38:25 -0700467 futures.get(key).complete(msr);
alshabibeadfc8e2015-08-18 15:40:46 -0700468 }
469 break;
470 case ADDED:
Jordi Ortizdf28ecd2017-03-25 19:22:36 +0100471 if (local.equals(data.origin()) &&
472 (data.meter().state() == MeterState.PENDING_ADD
473 || data.meter().state() == MeterState.ADDED)) {
474 futures.computeIfPresent(key, (k, v) -> {
475 notifyDelegate(
476 new MeterEvent(MeterEvent.Type.METER_ADDED, data.meter()));
477 return null;
478 });
alshabibe1248b62015-08-20 17:21:55 -0700479 }
480 break;
alshabibeadfc8e2015-08-18 15:40:46 -0700481 case REMOVED:
alshabib5eb79392015-08-19 18:09:55 -0700482 if (local.equals(data.origin()) && data.meter().state() == MeterState.PENDING_REMOVE) {
HIGUCHI Yuta0574a552015-09-29 14:38:25 -0700483 futures.remove(key).complete(MeterStoreResult.success());
alshabibeadfc8e2015-08-18 15:40:46 -0700484 }
485 break;
486 default:
487 log.warn("Unknown meter state type {}", data.meter().state());
488 }
489 break;
490 case REMOVE:
491 //Only happens at origin so we do not need to care.
492 break;
493 default:
494 log.warn("Unknown Map event type {}", event.type());
495 }
496
497 }
498 }
499
500
alshabib7bb05012015-08-05 10:15:09 -0700501}