blob: 478e2804f32768273b4094584b40b7cf63b3b729 [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;
80import com.google.common.collect.Maps;
Andrea Campanellacbbb7952019-11-25 06:38:41 +000081
82/**
83 * Provisions Meters on access devices.
84 */
85@Component(immediate = true, property = {
86 DELETE_METERS + ":Boolean=" + DELETE_METERS_DEFAULT,
87 })
88public class OltMeterService implements AccessDeviceMeterService {
89
90 @Reference(cardinality = ReferenceCardinality.MANDATORY)
91 protected MeterService meterService;
92
93 @Reference(cardinality = ReferenceCardinality.MANDATORY)
94 protected CoreService coreService;
95
96 @Reference(cardinality = ReferenceCardinality.MANDATORY)
97 protected ComponentConfigService componentConfigService;
98
Jonathan Hart4f178fa2020-02-03 10:46:01 -080099 @Reference(cardinality = ReferenceCardinality.MANDATORY)
100 protected StorageService storageService;
101
Saurav Dasf62cea82020-08-26 17:43:04 -0700102 /**
103 * Delete meters when reference count drops to zero.
104 */
105 protected boolean deleteMeters = DELETE_METERS_DEFAULT;
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000106
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000107 private ApplicationId appId;
108 private static final String APP_NAME = "org.opencord.olt";
109
110 private final MeterListener meterListener = new InternalMeterListener();
111
112 private final Logger log = getLogger(getClass());
113
114 protected ExecutorService eventExecutor;
115
Andrea Campanella600d2e22020-06-22 11:00:31 +0200116 private Map<DeviceId, Set<BandwidthProfileInformation>> pendingMeters;
117 private Map<DeviceId, Map<MeterKey, AtomicInteger>> pendingRemoveMeters;
118 ConsistentMultimap<String, MeterKey> bpInfoToMeter;
Andrea Campanella3ce4d282020-06-09 13:46:58 +0200119
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000120 @Activate
121 public void activate(ComponentContext context) {
122 eventExecutor = Executors.newFixedThreadPool(5, groupedThreads("onos/olt",
123 "events-%d", log));
124 appId = coreService.registerApplication(APP_NAME);
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800125 modified(context);
126
127 KryoNamespace serializer = KryoNamespace.newBuilder()
128 .register(KryoNamespaces.API)
129 .register(MeterKey.class)
130 .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());
Andrea Campanella600d2e22020-06-22 11:00:31 +0200140 pendingMeters = Maps.newConcurrentMap();
141 pendingRemoveMeters = Maps.newConcurrentMap();
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000142 log.info("Olt Meter service started");
143 }
144
145 @Deactivate
146 public void deactivate() {
147 meterService.removeListener(meterListener);
148 }
149
150
151 @Modified
152 public void modified(ComponentContext context) {
153 Dictionary<?, ?> properties = context != null ? context.getProperties() : new Properties();
154
155 Boolean d = Tools.isPropertyEnabled(properties, "deleteMeters");
156 if (d != null) {
157 deleteMeters = d;
158 }
159 }
160
161 @Override
162 public ImmutableMap<String, Collection<MeterKey>> getBpMeterMappings() {
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800163 return bpInfoToMeter.stream()
164 .collect(collectingAndThen(
165 groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toSet())),
166 ImmutableMap::copyOf));
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000167 }
168
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800169 void addMeterIdToBpMapping(DeviceId deviceId, MeterId meterId, String bandwidthProfile) {
Andrea Campanella0c3309d2020-05-29 01:51:18 -0700170 log.debug("adding bp {} to meter {} mapping for device {}",
171 bandwidthProfile, meterId, deviceId);
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000172 bpInfoToMeter.put(bandwidthProfile, MeterKey.key(deviceId, meterId));
173 }
174
175 @Override
176 public MeterId getMeterIdFromBpMapping(DeviceId deviceId, String bandwidthProfile) {
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800177 if (bpInfoToMeter.get(bandwidthProfile).value().isEmpty()) {
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000178 log.warn("Bandwidth Profile '{}' is not currently mapped to a meter",
179 bandwidthProfile);
180 return null;
181 }
182
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800183 Optional<? extends MeterKey> meterKeyForDevice = bpInfoToMeter.get(bandwidthProfile).value()
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000184 .stream()
185 .filter(meterKey -> meterKey.deviceId().equals(deviceId))
186 .findFirst();
187 if (meterKeyForDevice.isPresent()) {
188 log.debug("Found meter {} for bandwidth profile {}",
189 meterKeyForDevice.get().meterId(), bandwidthProfile);
190 return meterKeyForDevice.get().meterId();
191 } else {
Andrea Campanella0c3309d2020-05-29 01:51:18 -0700192 log.warn("Bandwidth Profile '{}' is not currently mapped to a meter in {}",
193 bandwidthProfile, bpInfoToMeter.get(bandwidthProfile).value());
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000194 return null;
195 }
196 }
197
198 @Override
199 public ImmutableSet<MeterKey> getProgMeters() {
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800200 return bpInfoToMeter.stream()
201 .map(Map.Entry::getValue)
202 .collect(ImmutableSet.toImmutableSet());
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000203 }
204
205 @Override
206 public MeterId createMeter(DeviceId deviceId, BandwidthProfileInformation bpInfo,
207 CompletableFuture<Object> meterFuture) {
Saurav Dasf62cea82020-08-26 17:43:04 -0700208 log.debug("Creating meter on {} for {}", deviceId, bpInfo);
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000209 if (bpInfo == null) {
210 log.warn("Requested bandwidth profile information is NULL");
211 meterFuture.complete(ObjectiveError.BADPARAMS);
212 return null;
213 }
214
215 MeterId meterId = getMeterIdFromBpMapping(deviceId, bpInfo.id());
216 if (meterId != null) {
217 log.debug("Meter {} was previously created for bp {}", meterId, bpInfo.id());
218 meterFuture.complete(null);
219 return meterId;
220 }
221
222 List<Band> meterBands = createMeterBands(bpInfo);
223
224 final AtomicReference<MeterId> meterIdRef = new AtomicReference<>();
225 MeterRequest meterRequest = DefaultMeterRequest.builder()
226 .withBands(meterBands)
227 .withUnit(Meter.Unit.KB_PER_SEC)
228 .withContext(new MeterContext() {
229 @Override
230 public void onSuccess(MeterRequest op) {
Andrea Campanella0c3309d2020-05-29 01:51:18 -0700231 log.debug("Meter {} is installed on the device {}",
Andrea Campanella3ce4d282020-06-09 13:46:58 +0200232 meterIdRef.get(), deviceId);
Andrea Campanella0c3309d2020-05-29 01:51:18 -0700233 addMeterIdToBpMapping(deviceId, meterIdRef.get(), bpInfo.id());
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000234 meterFuture.complete(null);
235 }
236
237 @Override
238 public void onError(MeterRequest op, MeterFailReason reason) {
Andrea Campanellac727a372020-06-09 17:34:38 +0200239 log.error("Failed installing meter {} on {} for {}",
240 meterIdRef.get(), deviceId, bpInfo.id());
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000241 bpInfoToMeter.remove(bpInfo.id(),
242 MeterKey.key(deviceId, meterIdRef.get()));
243 meterFuture.complete(reason);
244 }
245 })
246 .forDevice(deviceId)
247 .fromApp(appId)
248 .burst()
249 .add();
250
251 Meter meter = meterService.submit(meterRequest);
252 meterIdRef.set(meter.id());
Saurav Dasf62cea82020-08-26 17:43:04 -0700253 log.info("Meter {} created and sent for installation on {} for {}",
254 meter.id(), deviceId, bpInfo);
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000255 return meter.id();
256 }
257
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800258 @Override
Andrea Campanella600d2e22020-06-22 11:00:31 +0200259 public void removeFromPendingMeters(DeviceId deviceId, BandwidthProfileInformation bwpInfo) {
260 if (deviceId == null) {
261 return;
262 }
263 pendingMeters.computeIfPresent(deviceId, (id, bwps) -> {
264 bwps.remove(bwpInfo);
265 return bwps;
266 });
Andrea Campanella3ce4d282020-06-09 13:46:58 +0200267 }
268
269 @Override
Andrea Campanellad1e26642020-10-23 12:08:32 +0200270 public synchronized boolean checkAndAddPendingMeter(DeviceId deviceId, BandwidthProfileInformation bwpInfo) {
271 if (pendingMeters.containsKey(deviceId)
272 && pendingMeters.get(deviceId).contains(bwpInfo)) {
273 log.debug("Meter is already pending for EAPOL on {} with bp {}",
274 deviceId, bwpInfo);
Andrea Campanella600d2e22020-06-22 11:00:31 +0200275 return false;
276 }
Andrea Campanellad1e26642020-10-23 12:08:32 +0200277 log.debug("Adding bandwidth profile {} to pending on {}",
278 bwpInfo, deviceId);
279 pendingMeters.compute(deviceId, (id, bwps) -> {
280 if (bwps == null) {
281 bwps = new HashSet<>();
282 }
283 bwps.add(bwpInfo);
284 return bwps;
285 });
286
287 return true;
Andrea Campanella3ce4d282020-06-09 13:46:58 +0200288 }
289
290 @Override
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800291 public void clearMeters(DeviceId deviceId) {
Andrea Campanella65487ba2020-06-17 11:31:30 +0200292 log.debug("Removing all meters for device {}", deviceId);
Andrea Campanella600d2e22020-06-22 11:00:31 +0200293 clearDeviceState(deviceId);
Andrea Campanella65487ba2020-06-17 11:31:30 +0200294 meterService.purgeMeters(deviceId);
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800295 }
296
Andrea Campanella600d2e22020-06-22 11:00:31 +0200297 @Override
298 public void clearDeviceState(DeviceId deviceId) {
299 log.info("Clearing local device state for {}", deviceId);
300 pendingRemoveMeters.remove(deviceId);
301 removeMetersFromBpMapping(deviceId);
302 //Following call handles cornercase of OLT delete during meter provisioning
303 pendingMeters.remove(deviceId);
304 }
305
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000306 private List<Band> createMeterBands(BandwidthProfileInformation bpInfo) {
307 List<Band> meterBands = new ArrayList<>();
308
309 meterBands.add(createMeterBand(bpInfo.committedInformationRate(), bpInfo.committedBurstSize()));
310 meterBands.add(createMeterBand(bpInfo.exceededInformationRate(), bpInfo.exceededBurstSize()));
311 meterBands.add(createMeterBand(bpInfo.assuredInformationRate(), 0L));
312
313 return meterBands;
314 }
315
316 private Band createMeterBand(long rate, Long burst) {
317 return DefaultBand.builder()
318 .withRate(rate) //already Kbps
319 .burstSize(burst) // already Kbits
320 .ofType(Band.Type.DROP) // no matter
321 .build();
322 }
323
Andrea Campanella600d2e22020-06-22 11:00:31 +0200324 private void removeMeterFromBpMapping(MeterKey meterKey) {
325 List<Map.Entry<String, MeterKey>> meters = bpInfoToMeter.stream()
326 .filter(e -> e.getValue().equals(meterKey))
327 .collect(Collectors.toList());
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000328
Andrea Campanella600d2e22020-06-22 11:00:31 +0200329 meters.forEach(e -> bpInfoToMeter.remove(e.getKey(), e.getValue()));
330 }
331
332 private void removeMetersFromBpMapping(DeviceId deviceId) {
333 List<Map.Entry<String, MeterKey>> meters = bpInfoToMeter.stream()
334 .filter(e -> e.getValue().deviceId().equals(deviceId))
335 .collect(Collectors.toList());
336
337 meters.forEach(e -> bpInfoToMeter.remove(e.getKey(), e.getValue()));
338 }
339
340 private class InternalMeterListener implements MeterListener {
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000341
342 @Override
343 public void event(MeterEvent meterEvent) {
344 eventExecutor.execute(() -> {
345 Meter meter = meterEvent.subject();
346 if (meter == null) {
347 log.error("Meter in event {} is null", meterEvent);
348 return;
349 }
350 MeterKey key = MeterKey.key(meter.deviceId(), meter.id());
351 if (deleteMeters && MeterEvent.Type.METER_REFERENCE_COUNT_ZERO.equals(meterEvent.type())) {
Andrea Campanella600d2e22020-06-22 11:00:31 +0200352 log.info("Zero Count Meter Event is received. Meter is {} on {}",
353 meter.id(), meter.deviceId());
354 incrementMeterCount(meter.deviceId(), key);
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000355
Andrea Campanella600d2e22020-06-22 11:00:31 +0200356 if (appId.equals(meter.appId()) && pendingRemoveMeters.get(meter.deviceId())
357 .get(key).get() == 3) {
358 log.info("Deleting unreferenced, no longer programmed Meter {} on {}",
359 meter.id(), meter.deviceId());
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000360 deleteMeter(meter.deviceId(), meter.id());
361 }
362 }
363 if (MeterEvent.Type.METER_REMOVED.equals(meterEvent.type())) {
Andrea Campanella600d2e22020-06-22 11:00:31 +0200364 log.info("Meter Removed Event is received for {} on {}",
365 meter.id(), meter.deviceId());
366 pendingRemoveMeters.computeIfPresent(meter.deviceId(),
367 (id, meters) -> {
368 if (meters.get(key) == null) {
369 log.info("Meters is not pending " +
370 "{} on {}", key, id);
371 return meters;
372 }
373 meters.remove(key);
374 return meters;
375 });
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000376 removeMeterFromBpMapping(key);
377 }
378 });
379 }
380
Andrea Campanella600d2e22020-06-22 11:00:31 +0200381 private void incrementMeterCount(DeviceId deviceId, MeterKey key) {
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000382 if (key == null) {
383 return;
384 }
Andrea Campanella600d2e22020-06-22 11:00:31 +0200385 pendingRemoveMeters.compute(deviceId,
386 (id, meters) -> {
387 if (meters == null) {
388 meters = new HashMap<>();
389
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000390 }
Andrea Campanella600d2e22020-06-22 11:00:31 +0200391 if (meters.get(key) == null) {
392 meters.put(key, new AtomicInteger(1));
393 }
394 meters.get(key).addAndGet(1);
395 return meters;
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000396 });
397 }
398
399 private void deleteMeter(DeviceId deviceId, MeterId meterId) {
400 Meter meter = meterService.getMeter(deviceId, meterId);
401 if (meter != null) {
402 MeterRequest meterRequest = DefaultMeterRequest.builder()
403 .withBands(meter.bands())
404 .withUnit(meter.unit())
405 .forDevice(deviceId)
406 .fromApp(appId)
407 .burst()
408 .remove();
409
410 meterService.withdraw(meterRequest, meterId);
411 }
412 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000413 }
414}