blob: 2acf10e3d4023b769425e589522d9d537b29be48 [file] [log] [blame]
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001/*
2 * Copyright 2016-present Open Networking Foundation
3 *
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.opencord.olt.impl;
17
Saurav Dasf62cea82020-08-26 17:43:04 -070018import static java.util.stream.Collectors.collectingAndThen;
19import static java.util.stream.Collectors.groupingBy;
20import static java.util.stream.Collectors.mapping;
21import static java.util.stream.Collectors.toSet;
22import static org.onlab.util.Tools.groupedThreads;
23import static org.opencord.olt.impl.OsgiPropertyConstants.DELETE_METERS;
24import static org.opencord.olt.impl.OsgiPropertyConstants.DELETE_METERS_DEFAULT;
25import static org.slf4j.LoggerFactory.getLogger;
26
27import java.util.ArrayList;
28import java.util.Collection;
29import java.util.Dictionary;
30import java.util.HashMap;
31import java.util.HashSet;
32import java.util.List;
33import java.util.Map;
34import java.util.Optional;
35import java.util.Properties;
36import java.util.Set;
37import java.util.concurrent.CompletableFuture;
38import java.util.concurrent.ExecutorService;
39import java.util.concurrent.Executors;
40import java.util.concurrent.atomic.AtomicInteger;
41import java.util.concurrent.atomic.AtomicReference;
42import java.util.stream.Collectors;
43
Jonathan Hart4f178fa2020-02-03 10:46:01 -080044import org.onlab.util.KryoNamespace;
Andrea Campanellacbbb7952019-11-25 06:38:41 +000045import org.onlab.util.Tools;
46import org.onosproject.cfg.ComponentConfigService;
47import org.onosproject.core.ApplicationId;
48import org.onosproject.core.CoreService;
49import org.onosproject.net.DeviceId;
50import org.onosproject.net.flowobjective.ObjectiveError;
51import org.onosproject.net.meter.Band;
52import org.onosproject.net.meter.DefaultBand;
53import org.onosproject.net.meter.DefaultMeterRequest;
54import org.onosproject.net.meter.Meter;
55import org.onosproject.net.meter.MeterContext;
56import org.onosproject.net.meter.MeterEvent;
57import org.onosproject.net.meter.MeterFailReason;
58import org.onosproject.net.meter.MeterId;
59import org.onosproject.net.meter.MeterKey;
60import org.onosproject.net.meter.MeterListener;
61import org.onosproject.net.meter.MeterRequest;
62import org.onosproject.net.meter.MeterService;
Jonathan Hart4f178fa2020-02-03 10:46:01 -080063import org.onosproject.store.serializers.KryoNamespaces;
64import org.onosproject.store.service.ConsistentMultimap;
65import org.onosproject.store.service.Serializer;
66import org.onosproject.store.service.StorageService;
Andrea Campanellacbbb7952019-11-25 06:38:41 +000067import org.opencord.olt.internalapi.AccessDeviceMeterService;
68import org.opencord.sadis.BandwidthProfileInformation;
69import org.osgi.service.component.ComponentContext;
70import org.osgi.service.component.annotations.Activate;
71import org.osgi.service.component.annotations.Component;
72import org.osgi.service.component.annotations.Deactivate;
73import org.osgi.service.component.annotations.Modified;
74import org.osgi.service.component.annotations.Reference;
75import org.osgi.service.component.annotations.ReferenceCardinality;
76import org.slf4j.Logger;
77
Saurav Dasf62cea82020-08-26 17:43:04 -070078import com.google.common.collect.ImmutableMap;
79import com.google.common.collect.ImmutableSet;
Andrea Campanellacbbb7952019-11-25 06:38:41 +000080
81/**
82 * Provisions Meters on access devices.
83 */
84@Component(immediate = true, property = {
85 DELETE_METERS + ":Boolean=" + DELETE_METERS_DEFAULT,
86 })
87public class OltMeterService implements AccessDeviceMeterService {
88
89 @Reference(cardinality = ReferenceCardinality.MANDATORY)
90 protected MeterService meterService;
91
92 @Reference(cardinality = ReferenceCardinality.MANDATORY)
93 protected CoreService coreService;
94
95 @Reference(cardinality = ReferenceCardinality.MANDATORY)
96 protected ComponentConfigService componentConfigService;
97
Jonathan Hart4f178fa2020-02-03 10:46:01 -080098 @Reference(cardinality = ReferenceCardinality.MANDATORY)
99 protected StorageService storageService;
100
Saurav Dasf62cea82020-08-26 17:43:04 -0700101 /**
102 * Delete meters when reference count drops to zero.
103 */
104 protected boolean deleteMeters = DELETE_METERS_DEFAULT;
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000105
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000106 private ApplicationId appId;
107 private static final String APP_NAME = "org.opencord.olt";
108
109 private final MeterListener meterListener = new InternalMeterListener();
110
111 private final Logger log = getLogger(getClass());
112
113 protected ExecutorService eventExecutor;
114
Ilayda Ozdemir90a93622021-02-25 09:40:58 +0000115 protected Map<DeviceId, Set<BandwidthProfileInformation>> pendingMeters;
116 protected Map<DeviceId, Map<MeterKey, AtomicInteger>> pendingRemoveMeters;
117 protected ConsistentMultimap<String, MeterKey> bpInfoToMeter;
Andrea Campanella3ce4d282020-06-09 13:46:58 +0200118
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000119 @Activate
120 public void activate(ComponentContext context) {
121 eventExecutor = Executors.newFixedThreadPool(5, groupedThreads("onos/olt",
122 "events-%d", log));
123 appId = coreService.registerApplication(APP_NAME);
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800124 modified(context);
125
126 KryoNamespace serializer = KryoNamespace.newBuilder()
127 .register(KryoNamespaces.API)
128 .register(MeterKey.class)
Ilayda Ozdemir90a93622021-02-25 09:40:58 +0000129 .register(BandwidthProfileInformation.class)
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800130 .build();
131
132 bpInfoToMeter = storageService.<String, MeterKey>consistentMultimapBuilder()
133 .withName("volt-bp-info-to-meter")
134 .withSerializer(Serializer.using(serializer))
135 .withApplicationId(appId)
136 .build();
137
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000138 meterService.addListener(meterListener);
139 componentConfigService.registerProperties(getClass());
Ilayda Ozdemir90a93622021-02-25 09:40:58 +0000140 pendingMeters = storageService.<DeviceId, Set<BandwidthProfileInformation>>consistentMapBuilder()
141 .withName("volt-pending-meters")
142 .withSerializer(Serializer.using(serializer))
143 .withApplicationId(appId)
144 .build().asJavaMap();
145 pendingRemoveMeters = storageService.<DeviceId, Map<MeterKey, AtomicInteger>>consistentMapBuilder()
146 .withName("volt-pending-remove-meters")
147 .withSerializer(Serializer.using(serializer))
148 .withApplicationId(appId)
149 .build().asJavaMap();
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000150 log.info("Olt Meter service started");
151 }
152
153 @Deactivate
154 public void deactivate() {
155 meterService.removeListener(meterListener);
156 }
157
158
159 @Modified
160 public void modified(ComponentContext context) {
161 Dictionary<?, ?> properties = context != null ? context.getProperties() : new Properties();
162
163 Boolean d = Tools.isPropertyEnabled(properties, "deleteMeters");
164 if (d != null) {
165 deleteMeters = d;
166 }
167 }
168
169 @Override
170 public ImmutableMap<String, Collection<MeterKey>> getBpMeterMappings() {
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800171 return bpInfoToMeter.stream()
172 .collect(collectingAndThen(
173 groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toSet())),
174 ImmutableMap::copyOf));
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000175 }
176
Matteo Scandolo19b56f62020-10-29 13:29:21 -0700177 boolean addMeterIdToBpMapping(DeviceId deviceId, MeterId meterId, String bandwidthProfile) {
Andrea Campanella0c3309d2020-05-29 01:51:18 -0700178 log.debug("adding bp {} to meter {} mapping for device {}",
179 bandwidthProfile, meterId, deviceId);
Matteo Scandolo19b56f62020-10-29 13:29:21 -0700180 return bpInfoToMeter.put(bandwidthProfile, MeterKey.key(deviceId, meterId));
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000181 }
182
183 @Override
184 public MeterId getMeterIdFromBpMapping(DeviceId deviceId, String bandwidthProfile) {
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800185 if (bpInfoToMeter.get(bandwidthProfile).value().isEmpty()) {
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000186 log.warn("Bandwidth Profile '{}' is not currently mapped to a meter",
187 bandwidthProfile);
188 return null;
189 }
190
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800191 Optional<? extends MeterKey> meterKeyForDevice = bpInfoToMeter.get(bandwidthProfile).value()
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000192 .stream()
193 .filter(meterKey -> meterKey.deviceId().equals(deviceId))
194 .findFirst();
195 if (meterKeyForDevice.isPresent()) {
Matteo Scandolo19b56f62020-10-29 13:29:21 -0700196 log.debug("Found meter {} for bandwidth profile {} on {}",
197 meterKeyForDevice.get().meterId(), bandwidthProfile, deviceId);
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000198 return meterKeyForDevice.get().meterId();
199 } else {
Matteo Scandolo19b56f62020-10-29 13:29:21 -0700200 log.warn("Bandwidth Profile '{}' is not currently mapped to a meter on {} , {}",
201 bandwidthProfile, deviceId, bpInfoToMeter.get(bandwidthProfile).value());
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000202 return null;
203 }
204 }
205
206 @Override
207 public ImmutableSet<MeterKey> getProgMeters() {
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800208 return bpInfoToMeter.stream()
209 .map(Map.Entry::getValue)
210 .collect(ImmutableSet.toImmutableSet());
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000211 }
212
213 @Override
214 public MeterId createMeter(DeviceId deviceId, BandwidthProfileInformation bpInfo,
215 CompletableFuture<Object> meterFuture) {
Saurav Dasf62cea82020-08-26 17:43:04 -0700216 log.debug("Creating meter on {} for {}", deviceId, bpInfo);
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000217 if (bpInfo == null) {
Matteo Scandolo19b56f62020-10-29 13:29:21 -0700218 log.warn("Requested bandwidth profile on {} information is NULL", deviceId);
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000219 meterFuture.complete(ObjectiveError.BADPARAMS);
220 return null;
221 }
222
223 MeterId meterId = getMeterIdFromBpMapping(deviceId, bpInfo.id());
224 if (meterId != null) {
225 log.debug("Meter {} was previously created for bp {}", meterId, bpInfo.id());
226 meterFuture.complete(null);
227 return meterId;
228 }
229
230 List<Band> meterBands = createMeterBands(bpInfo);
231
232 final AtomicReference<MeterId> meterIdRef = new AtomicReference<>();
233 MeterRequest meterRequest = DefaultMeterRequest.builder()
234 .withBands(meterBands)
235 .withUnit(Meter.Unit.KB_PER_SEC)
236 .withContext(new MeterContext() {
237 @Override
238 public void onSuccess(MeterRequest op) {
Matteo Scandolo19b56f62020-10-29 13:29:21 -0700239 log.debug("Meter {} for {} is installed on the device {}",
240 meterIdRef.get(), bpInfo.id(), deviceId);
241 boolean added = addMeterIdToBpMapping(deviceId, meterIdRef.get(), bpInfo.id());
242 if (added) {
243 meterFuture.complete(null);
244 } else {
245 log.error("Failed to add Meter {} for {} on {} to the meter-bandwidth mapping",
246 meterIdRef.get(), bpInfo.id(), deviceId);
247 meterFuture.complete(ObjectiveError.UNKNOWN);
248 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000249 }
250
251 @Override
252 public void onError(MeterRequest op, MeterFailReason reason) {
Andrea Campanellac727a372020-06-09 17:34:38 +0200253 log.error("Failed installing meter {} on {} for {}",
254 meterIdRef.get(), deviceId, bpInfo.id());
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000255 bpInfoToMeter.remove(bpInfo.id(),
256 MeterKey.key(deviceId, meterIdRef.get()));
257 meterFuture.complete(reason);
258 }
259 })
260 .forDevice(deviceId)
261 .fromApp(appId)
262 .burst()
263 .add();
264
265 Meter meter = meterService.submit(meterRequest);
266 meterIdRef.set(meter.id());
Saurav Dasf62cea82020-08-26 17:43:04 -0700267 log.info("Meter {} created and sent for installation on {} for {}",
268 meter.id(), deviceId, bpInfo);
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000269 return meter.id();
270 }
271
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800272 @Override
Andrea Campanella600d2e22020-06-22 11:00:31 +0200273 public void removeFromPendingMeters(DeviceId deviceId, BandwidthProfileInformation bwpInfo) {
274 if (deviceId == null) {
275 return;
276 }
277 pendingMeters.computeIfPresent(deviceId, (id, bwps) -> {
278 bwps.remove(bwpInfo);
279 return bwps;
280 });
Andrea Campanella3ce4d282020-06-09 13:46:58 +0200281 }
282
283 @Override
Andrea Campanellad1e26642020-10-23 12:08:32 +0200284 public synchronized boolean checkAndAddPendingMeter(DeviceId deviceId, BandwidthProfileInformation bwpInfo) {
285 if (pendingMeters.containsKey(deviceId)
286 && pendingMeters.get(deviceId).contains(bwpInfo)) {
Matteo Scandolo19b56f62020-10-29 13:29:21 -0700287 log.debug("Meter is already pending on {} with bp {}",
Andrea Campanellad1e26642020-10-23 12:08:32 +0200288 deviceId, bwpInfo);
Andrea Campanella600d2e22020-06-22 11:00:31 +0200289 return false;
290 }
Andrea Campanellad1e26642020-10-23 12:08:32 +0200291 log.debug("Adding bandwidth profile {} to pending on {}",
292 bwpInfo, deviceId);
293 pendingMeters.compute(deviceId, (id, bwps) -> {
294 if (bwps == null) {
295 bwps = new HashSet<>();
296 }
297 bwps.add(bwpInfo);
298 return bwps;
299 });
300
301 return true;
Andrea Campanella3ce4d282020-06-09 13:46:58 +0200302 }
303
304 @Override
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800305 public void clearMeters(DeviceId deviceId) {
Andrea Campanella65487ba2020-06-17 11:31:30 +0200306 log.debug("Removing all meters for device {}", deviceId);
Andrea Campanella600d2e22020-06-22 11:00:31 +0200307 clearDeviceState(deviceId);
Andrea Campanella65487ba2020-06-17 11:31:30 +0200308 meterService.purgeMeters(deviceId);
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800309 }
310
Andrea Campanella600d2e22020-06-22 11:00:31 +0200311 @Override
312 public void clearDeviceState(DeviceId deviceId) {
313 log.info("Clearing local device state for {}", deviceId);
314 pendingRemoveMeters.remove(deviceId);
315 removeMetersFromBpMapping(deviceId);
316 //Following call handles cornercase of OLT delete during meter provisioning
317 pendingMeters.remove(deviceId);
318 }
319
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000320 private List<Band> createMeterBands(BandwidthProfileInformation bpInfo) {
321 List<Band> meterBands = new ArrayList<>();
322
323 meterBands.add(createMeterBand(bpInfo.committedInformationRate(), bpInfo.committedBurstSize()));
324 meterBands.add(createMeterBand(bpInfo.exceededInformationRate(), bpInfo.exceededBurstSize()));
325 meterBands.add(createMeterBand(bpInfo.assuredInformationRate(), 0L));
326
327 return meterBands;
328 }
329
330 private Band createMeterBand(long rate, Long burst) {
331 return DefaultBand.builder()
332 .withRate(rate) //already Kbps
333 .burstSize(burst) // already Kbits
334 .ofType(Band.Type.DROP) // no matter
335 .build();
336 }
337
Andrea Campanella600d2e22020-06-22 11:00:31 +0200338 private void removeMeterFromBpMapping(MeterKey meterKey) {
339 List<Map.Entry<String, MeterKey>> meters = bpInfoToMeter.stream()
340 .filter(e -> e.getValue().equals(meterKey))
341 .collect(Collectors.toList());
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000342
Andrea Campanella600d2e22020-06-22 11:00:31 +0200343 meters.forEach(e -> bpInfoToMeter.remove(e.getKey(), e.getValue()));
344 }
345
346 private void removeMetersFromBpMapping(DeviceId deviceId) {
347 List<Map.Entry<String, MeterKey>> meters = bpInfoToMeter.stream()
348 .filter(e -> e.getValue().deviceId().equals(deviceId))
349 .collect(Collectors.toList());
350
351 meters.forEach(e -> bpInfoToMeter.remove(e.getKey(), e.getValue()));
352 }
353
354 private class InternalMeterListener implements MeterListener {
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000355
356 @Override
357 public void event(MeterEvent meterEvent) {
358 eventExecutor.execute(() -> {
359 Meter meter = meterEvent.subject();
360 if (meter == null) {
361 log.error("Meter in event {} is null", meterEvent);
362 return;
363 }
364 MeterKey key = MeterKey.key(meter.deviceId(), meter.id());
365 if (deleteMeters && MeterEvent.Type.METER_REFERENCE_COUNT_ZERO.equals(meterEvent.type())) {
Andrea Campanella600d2e22020-06-22 11:00:31 +0200366 log.info("Zero Count Meter Event is received. Meter is {} on {}",
367 meter.id(), meter.deviceId());
368 incrementMeterCount(meter.deviceId(), key);
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000369
Andrea Campanella600d2e22020-06-22 11:00:31 +0200370 if (appId.equals(meter.appId()) && pendingRemoveMeters.get(meter.deviceId())
371 .get(key).get() == 3) {
372 log.info("Deleting unreferenced, no longer programmed Meter {} on {}",
373 meter.id(), meter.deviceId());
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000374 deleteMeter(meter.deviceId(), meter.id());
375 }
376 }
377 if (MeterEvent.Type.METER_REMOVED.equals(meterEvent.type())) {
Andrea Campanella600d2e22020-06-22 11:00:31 +0200378 log.info("Meter Removed Event is received for {} on {}",
379 meter.id(), meter.deviceId());
380 pendingRemoveMeters.computeIfPresent(meter.deviceId(),
381 (id, meters) -> {
382 if (meters.get(key) == null) {
383 log.info("Meters is not pending " +
384 "{} on {}", key, id);
385 return meters;
386 }
387 meters.remove(key);
388 return meters;
389 });
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000390 removeMeterFromBpMapping(key);
391 }
392 });
393 }
394
Andrea Campanella600d2e22020-06-22 11:00:31 +0200395 private void incrementMeterCount(DeviceId deviceId, MeterKey key) {
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000396 if (key == null) {
397 return;
398 }
Andrea Campanella600d2e22020-06-22 11:00:31 +0200399 pendingRemoveMeters.compute(deviceId,
400 (id, meters) -> {
401 if (meters == null) {
402 meters = new HashMap<>();
403
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000404 }
Andrea Campanella600d2e22020-06-22 11:00:31 +0200405 if (meters.get(key) == null) {
406 meters.put(key, new AtomicInteger(1));
407 }
408 meters.get(key).addAndGet(1);
409 return meters;
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000410 });
411 }
412
413 private void deleteMeter(DeviceId deviceId, MeterId meterId) {
414 Meter meter = meterService.getMeter(deviceId, meterId);
415 if (meter != null) {
416 MeterRequest meterRequest = DefaultMeterRequest.builder()
417 .withBands(meter.bands())
418 .withUnit(meter.unit())
419 .forDevice(deviceId)
420 .fromApp(appId)
421 .burst()
422 .remove();
423
424 meterService.withdraw(meterRequest, meterId);
425 }
426 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000427 }
428}