blob: 3e3962cb7aaa88382413bfb0e8672141ceaa0507 [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
Andrea Campanellaaf39b4c2020-05-13 14:07:44 +020018import com.google.common.collect.ImmutableList;
Andrea Campanellacbbb7952019-11-25 06:38:41 +000019import com.google.common.collect.ImmutableMap;
20import com.google.common.collect.ImmutableSet;
21import com.google.common.collect.Maps;
Jonathan Hart4f178fa2020-02-03 10:46:01 -080022import org.onlab.util.KryoNamespace;
Andrea Campanellacbbb7952019-11-25 06:38:41 +000023import org.onlab.util.Tools;
24import org.onosproject.cfg.ComponentConfigService;
25import org.onosproject.core.ApplicationId;
26import org.onosproject.core.CoreService;
27import org.onosproject.net.DeviceId;
28import org.onosproject.net.flowobjective.ObjectiveError;
29import org.onosproject.net.meter.Band;
30import org.onosproject.net.meter.DefaultBand;
31import org.onosproject.net.meter.DefaultMeterRequest;
32import org.onosproject.net.meter.Meter;
33import org.onosproject.net.meter.MeterContext;
34import org.onosproject.net.meter.MeterEvent;
35import org.onosproject.net.meter.MeterFailReason;
36import org.onosproject.net.meter.MeterId;
37import org.onosproject.net.meter.MeterKey;
38import org.onosproject.net.meter.MeterListener;
39import org.onosproject.net.meter.MeterRequest;
40import org.onosproject.net.meter.MeterService;
Jonathan Hart4f178fa2020-02-03 10:46:01 -080041import org.onosproject.store.serializers.KryoNamespaces;
42import org.onosproject.store.service.ConsistentMultimap;
43import org.onosproject.store.service.Serializer;
44import org.onosproject.store.service.StorageService;
Andrea Campanellacbbb7952019-11-25 06:38:41 +000045import org.opencord.olt.internalapi.AccessDeviceMeterService;
46import org.opencord.sadis.BandwidthProfileInformation;
47import org.osgi.service.component.ComponentContext;
48import org.osgi.service.component.annotations.Activate;
49import org.osgi.service.component.annotations.Component;
50import org.osgi.service.component.annotations.Deactivate;
51import org.osgi.service.component.annotations.Modified;
52import org.osgi.service.component.annotations.Reference;
53import org.osgi.service.component.annotations.ReferenceCardinality;
54import org.slf4j.Logger;
55
56import java.util.ArrayList;
57import java.util.Collection;
58import java.util.Dictionary;
Andrea Campanellacbbb7952019-11-25 06:38:41 +000059import java.util.List;
60import java.util.Map;
61import java.util.Optional;
62import java.util.Properties;
Andrea Campanellacbbb7952019-11-25 06:38:41 +000063import java.util.concurrent.CompletableFuture;
64import java.util.concurrent.ExecutorService;
65import java.util.concurrent.Executors;
66import java.util.concurrent.atomic.AtomicInteger;
67import java.util.concurrent.atomic.AtomicReference;
Jonathan Hart4f178fa2020-02-03 10:46:01 -080068import java.util.stream.Collectors;
Andrea Campanellacbbb7952019-11-25 06:38:41 +000069
Jonathan Hart4f178fa2020-02-03 10:46:01 -080070import static java.util.stream.Collectors.collectingAndThen;
71import static java.util.stream.Collectors.groupingBy;
72import static java.util.stream.Collectors.mapping;
73import static java.util.stream.Collectors.toSet;
Andrea Campanellacbbb7952019-11-25 06:38:41 +000074import static org.onlab.util.Tools.groupedThreads;
75import static org.opencord.olt.impl.OsgiPropertyConstants.DELETE_METERS;
76import static org.opencord.olt.impl.OsgiPropertyConstants.DELETE_METERS_DEFAULT;
77import static org.slf4j.LoggerFactory.getLogger;
78
79/**
80 * Provisions Meters on access devices.
81 */
82@Component(immediate = true, property = {
83 DELETE_METERS + ":Boolean=" + DELETE_METERS_DEFAULT,
84 })
85public class OltMeterService implements AccessDeviceMeterService {
86
87 @Reference(cardinality = ReferenceCardinality.MANDATORY)
88 protected MeterService meterService;
89
90 @Reference(cardinality = ReferenceCardinality.MANDATORY)
91 protected CoreService coreService;
92
93 @Reference(cardinality = ReferenceCardinality.MANDATORY)
94 protected ComponentConfigService componentConfigService;
95
Jonathan Hart4f178fa2020-02-03 10:46:01 -080096 @Reference(cardinality = ReferenceCardinality.MANDATORY)
97 protected StorageService storageService;
98
Andrea Campanellacbbb7952019-11-25 06:38:41 +000099 protected boolean deleteMeters = true;
100
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800101 ConsistentMultimap<String, MeterKey> bpInfoToMeter;
102
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000103 private ApplicationId appId;
104 private static final String APP_NAME = "org.opencord.olt";
105
106 private final MeterListener meterListener = new InternalMeterListener();
107
108 private final Logger log = getLogger(getClass());
109
110 protected ExecutorService eventExecutor;
111
112 @Activate
113 public void activate(ComponentContext context) {
114 eventExecutor = Executors.newFixedThreadPool(5, groupedThreads("onos/olt",
115 "events-%d", log));
116 appId = coreService.registerApplication(APP_NAME);
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800117 modified(context);
118
119 KryoNamespace serializer = KryoNamespace.newBuilder()
120 .register(KryoNamespaces.API)
121 .register(MeterKey.class)
122 .build();
123
124 bpInfoToMeter = storageService.<String, MeterKey>consistentMultimapBuilder()
125 .withName("volt-bp-info-to-meter")
126 .withSerializer(Serializer.using(serializer))
127 .withApplicationId(appId)
128 .build();
129
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000130 meterService.addListener(meterListener);
131 componentConfigService.registerProperties(getClass());
132 log.info("Olt Meter service started");
133 }
134
135 @Deactivate
136 public void deactivate() {
137 meterService.removeListener(meterListener);
138 }
139
140
141 @Modified
142 public void modified(ComponentContext context) {
143 Dictionary<?, ?> properties = context != null ? context.getProperties() : new Properties();
144
145 Boolean d = Tools.isPropertyEnabled(properties, "deleteMeters");
146 if (d != null) {
147 deleteMeters = d;
148 }
149 }
150
151 @Override
152 public ImmutableMap<String, Collection<MeterKey>> getBpMeterMappings() {
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800153 return bpInfoToMeter.stream()
154 .collect(collectingAndThen(
155 groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toSet())),
156 ImmutableMap::copyOf));
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000157 }
158
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800159 void addMeterIdToBpMapping(DeviceId deviceId, MeterId meterId, String bandwidthProfile) {
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000160 bpInfoToMeter.put(bandwidthProfile, MeterKey.key(deviceId, meterId));
161 }
162
163 @Override
164 public MeterId getMeterIdFromBpMapping(DeviceId deviceId, String bandwidthProfile) {
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800165 if (bpInfoToMeter.get(bandwidthProfile).value().isEmpty()) {
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000166 log.warn("Bandwidth Profile '{}' is not currently mapped to a meter",
167 bandwidthProfile);
168 return null;
169 }
170
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800171 Optional<? extends MeterKey> meterKeyForDevice = bpInfoToMeter.get(bandwidthProfile).value()
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000172 .stream()
173 .filter(meterKey -> meterKey.deviceId().equals(deviceId))
174 .findFirst();
175 if (meterKeyForDevice.isPresent()) {
176 log.debug("Found meter {} for bandwidth profile {}",
177 meterKeyForDevice.get().meterId(), bandwidthProfile);
178 return meterKeyForDevice.get().meterId();
179 } else {
180 log.warn("Bandwidth profile '{}' is not currently mapped to a meter",
181 bandwidthProfile);
182 return null;
183 }
184 }
185
186 @Override
187 public ImmutableSet<MeterKey> getProgMeters() {
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800188 return bpInfoToMeter.stream()
189 .map(Map.Entry::getValue)
190 .collect(ImmutableSet.toImmutableSet());
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000191 }
192
193 @Override
194 public MeterId createMeter(DeviceId deviceId, BandwidthProfileInformation bpInfo,
195 CompletableFuture<Object> meterFuture) {
196 if (bpInfo == null) {
197 log.warn("Requested bandwidth profile information is NULL");
198 meterFuture.complete(ObjectiveError.BADPARAMS);
199 return null;
200 }
201
202 MeterId meterId = getMeterIdFromBpMapping(deviceId, bpInfo.id());
203 if (meterId != null) {
204 log.debug("Meter {} was previously created for bp {}", meterId, bpInfo.id());
205 meterFuture.complete(null);
206 return meterId;
207 }
208
209 List<Band> meterBands = createMeterBands(bpInfo);
210
211 final AtomicReference<MeterId> meterIdRef = new AtomicReference<>();
212 MeterRequest meterRequest = DefaultMeterRequest.builder()
213 .withBands(meterBands)
214 .withUnit(Meter.Unit.KB_PER_SEC)
215 .withContext(new MeterContext() {
216 @Override
217 public void onSuccess(MeterRequest op) {
218 meterFuture.complete(null);
219 }
220
221 @Override
222 public void onError(MeterRequest op, MeterFailReason reason) {
223 bpInfoToMeter.remove(bpInfo.id(),
224 MeterKey.key(deviceId, meterIdRef.get()));
225 meterFuture.complete(reason);
226 }
227 })
228 .forDevice(deviceId)
229 .fromApp(appId)
230 .burst()
231 .add();
232
233 Meter meter = meterService.submit(meterRequest);
234 meterIdRef.set(meter.id());
235 addMeterIdToBpMapping(deviceId, meterIdRef.get(), bpInfo.id());
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000236 log.info("Meter is created. Meter Id {}", meter.id());
237 return meter.id();
238 }
239
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800240 @Override
241 public void clearMeters(DeviceId deviceId) {
242 List<Map.Entry<String, MeterKey>> meters = bpInfoToMeter.stream()
243 .filter(e -> e.getValue().deviceId().equals(deviceId))
244 .collect(Collectors.toList());
245
246 meters.forEach(e -> bpInfoToMeter.remove(e.getKey(), e.getValue()));
Andrea Campanellaaf39b4c2020-05-13 14:07:44 +0200247 List<Meter> metersToRemove = ImmutableList.copyOf(meterService.getMeters(deviceId));
248 metersToRemove.forEach(meter -> {
249 MeterRequest mq = DefaultMeterRequest.builder().fromApp(appId)
250 .forDevice(deviceId).withBands(meter.bands())
251 .withUnit(meter.unit()).remove();
252 meterService.withdraw(mq, meter.id());
253 });
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800254 }
255
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000256 private List<Band> createMeterBands(BandwidthProfileInformation bpInfo) {
257 List<Band> meterBands = new ArrayList<>();
258
259 meterBands.add(createMeterBand(bpInfo.committedInformationRate(), bpInfo.committedBurstSize()));
260 meterBands.add(createMeterBand(bpInfo.exceededInformationRate(), bpInfo.exceededBurstSize()));
261 meterBands.add(createMeterBand(bpInfo.assuredInformationRate(), 0L));
262
263 return meterBands;
264 }
265
266 private Band createMeterBand(long rate, Long burst) {
267 return DefaultBand.builder()
268 .withRate(rate) //already Kbps
269 .burstSize(burst) // already Kbits
270 .ofType(Band.Type.DROP) // no matter
271 .build();
272 }
273
274 private class InternalMeterListener implements MeterListener {
275
276 Map<MeterKey, AtomicInteger> pendingRemoveMeters = Maps.newConcurrentMap();
277
278 @Override
279 public void event(MeterEvent meterEvent) {
280 eventExecutor.execute(() -> {
281 Meter meter = meterEvent.subject();
282 if (meter == null) {
283 log.error("Meter in event {} is null", meterEvent);
284 return;
285 }
286 MeterKey key = MeterKey.key(meter.deviceId(), meter.id());
287 if (deleteMeters && MeterEvent.Type.METER_REFERENCE_COUNT_ZERO.equals(meterEvent.type())) {
288 log.info("Zero Count Meter Event is received. Meter is {}", meter.id());
289 incrementMeterCount(key);
290
291 if (appId.equals(meter.appId()) && pendingRemoveMeters.get(key).get() == 3) {
292 log.info("Deleting unreferenced, no longer programmed Meter {}", meter.id());
293 deleteMeter(meter.deviceId(), meter.id());
294 }
295 }
296 if (MeterEvent.Type.METER_REMOVED.equals(meterEvent.type())) {
297 log.info("Meter Removed Event is received for {}", meter.id());
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000298 pendingRemoveMeters.remove(key);
299 removeMeterFromBpMapping(key);
300 }
301 });
302 }
303
304 private void incrementMeterCount(MeterKey key) {
305 if (key == null) {
306 return;
307 }
308 pendingRemoveMeters.compute(key,
309 (k, v) -> {
310 if (v == null) {
311 return new AtomicInteger(1);
312 }
313 v.addAndGet(1);
314 return v;
315 });
316 }
317
318 private void deleteMeter(DeviceId deviceId, MeterId meterId) {
319 Meter meter = meterService.getMeter(deviceId, meterId);
320 if (meter != null) {
321 MeterRequest meterRequest = DefaultMeterRequest.builder()
322 .withBands(meter.bands())
323 .withUnit(meter.unit())
324 .forDevice(deviceId)
325 .fromApp(appId)
326 .burst()
327 .remove();
328
329 meterService.withdraw(meterRequest, meterId);
330 }
331 }
332
333 private void removeMeterFromBpMapping(MeterKey meterKey) {
Jonathan Hart4f178fa2020-02-03 10:46:01 -0800334 List<Map.Entry<String, MeterKey>> meters = bpInfoToMeter.stream()
335 .filter(e -> e.getValue().equals(meterKey))
336 .collect(Collectors.toList());
337
338 meters.forEach(e -> bpInfoToMeter.remove(e.getKey(), e.getValue()));
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000339 }
340 }
341}