blob: 9b786e50c8f76a0b88bfc859125305124b6e6650 [file] [log] [blame]
alshabib1d2bc402015-07-31 17:04:11 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
alshabib1d2bc402015-07-31 17:04:11 -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 */
Ray Milkeyebdd4852017-10-18 16:19:28 -070016package org.onosproject.net.meter.impl;
alshabib1d2bc402015-07-31 17:04:11 -070017
pierventre44220052020-09-22 12:51:06 +020018import com.google.common.collect.Sets;
pierventre1b8afbc2020-07-13 14:07:05 +020019import org.onlab.util.PredictableExecutor;
20import org.onlab.util.PredictableExecutor.PickyRunnable;
Gamze Abakaf57ef602019-03-11 06:52:48 +000021import org.onlab.util.Tools;
alshabibeadfc8e2015-08-18 15:40:46 -070022import org.onlab.util.TriConsumer;
Andrea Campanellae3708782017-10-16 16:00:21 +020023import org.onosproject.cfg.ComponentConfigService;
pierventre1b8afbc2020-07-13 14:07:05 +020024import org.onosproject.cluster.ClusterService;
25import org.onosproject.cluster.NodeId;
Daniele Moro43ac2892021-07-15 17:02:59 +020026import org.onosproject.core.ApplicationId;
Andrea Campanellae3708782017-10-16 16:00:21 +020027import org.onosproject.mastership.MastershipService;
Jian Li1932b932016-01-03 00:35:40 -080028import org.onosproject.net.DeviceId;
Andrea Campanella32a9c0b2020-03-27 12:53:46 +010029import org.onosproject.net.config.NetworkConfigRegistry;
30import org.onosproject.net.config.basics.BasicDeviceConfig;
Gamze Abakaf57ef602019-03-11 06:52:48 +000031import org.onosproject.net.device.DeviceEvent;
32import org.onosproject.net.device.DeviceListener;
Andrea Campanellae3708782017-10-16 16:00:21 +020033import org.onosproject.net.device.DeviceService;
34import org.onosproject.net.driver.DriverService;
alshabib10c810b2015-08-18 16:59:04 -070035import org.onosproject.net.meter.DefaultMeter;
36import org.onosproject.net.meter.Meter;
Wailok Shum79919522021-08-22 19:35:34 +080037import org.onosproject.net.meter.MeterCellId;
alshabib10c810b2015-08-18 16:59:04 -070038import org.onosproject.net.meter.MeterEvent;
39import org.onosproject.net.meter.MeterFailReason;
Jordi Ortizaa8de492016-12-01 00:21:36 +010040import org.onosproject.net.meter.MeterFeatures;
alshabib10c810b2015-08-18 16:59:04 -070041import org.onosproject.net.meter.MeterId;
alshabib70aaa1b2015-09-25 14:30:59 -070042import org.onosproject.net.meter.MeterKey;
alshabib10c810b2015-08-18 16:59:04 -070043import org.onosproject.net.meter.MeterListener;
44import org.onosproject.net.meter.MeterOperation;
45import org.onosproject.net.meter.MeterProvider;
46import org.onosproject.net.meter.MeterProviderRegistry;
47import org.onosproject.net.meter.MeterProviderService;
alshabibe1248b62015-08-20 17:21:55 -070048import org.onosproject.net.meter.MeterRequest;
Wailok Shum79919522021-08-22 19:35:34 +080049import org.onosproject.net.meter.MeterScope;
alshabib10c810b2015-08-18 16:59:04 -070050import org.onosproject.net.meter.MeterService;
51import org.onosproject.net.meter.MeterState;
52import org.onosproject.net.meter.MeterStore;
53import org.onosproject.net.meter.MeterStoreDelegate;
54import org.onosproject.net.meter.MeterStoreResult;
alshabib1d2bc402015-07-31 17:04:11 -070055import org.onosproject.net.provider.AbstractListenerProviderRegistry;
56import org.onosproject.net.provider.AbstractProviderService;
Wailok Shum79919522021-08-22 19:35:34 +080057import org.onosproject.net.pi.model.PiMeterId;
58import org.onosproject.net.pi.runtime.PiMeterCellId;
Andrea Campanellae3708782017-10-16 16:00:21 +020059import org.osgi.service.component.ComponentContext;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070060import org.osgi.service.component.annotations.Activate;
61import org.osgi.service.component.annotations.Component;
62import org.osgi.service.component.annotations.Deactivate;
63import org.osgi.service.component.annotations.Modified;
64import org.osgi.service.component.annotations.Reference;
65import org.osgi.service.component.annotations.ReferenceCardinality;
alshabib1d2bc402015-07-31 17:04:11 -070066import org.slf4j.Logger;
67
68import java.util.Collection;
Andrea Campanellae3708782017-10-16 16:00:21 +020069import java.util.Dictionary;
alshabib5eb79392015-08-19 18:09:55 -070070import java.util.Map;
pierventre1b8afbc2020-07-13 14:07:05 +020071import java.util.Objects;
alshabib5eb79392015-08-19 18:09:55 -070072import java.util.stream.Collectors;
alshabib1d2bc402015-07-31 17:04:11 -070073
Jordi Ortiz31d4d382017-07-19 10:52:26 +020074import static com.google.common.base.Preconditions.checkNotNull;
Andrea Campanellae3708782017-10-16 16:00:21 +020075import static com.google.common.base.Strings.isNullOrEmpty;
pierventre1b8afbc2020-07-13 14:07:05 +020076import static org.onlab.util.PredictableExecutor.newPredictableExecutor;
Andrea Campanellae3708782017-10-16 16:00:21 +020077import static org.onlab.util.Tools.get;
Jordi Ortiz31d4d382017-07-19 10:52:26 +020078import static org.onlab.util.Tools.groupedThreads;
Ray Milkeyd04e2272018-10-16 18:20:18 -070079import static org.onosproject.net.OsgiPropertyConstants.MM_FALLBACK_METER_POLL_FREQUENCY;
80import static org.onosproject.net.OsgiPropertyConstants.MM_FALLBACK_METER_POLL_FREQUENCY_DEFAULT;
81import static org.onosproject.net.OsgiPropertyConstants.MM_NUM_THREADS;
82import static org.onosproject.net.OsgiPropertyConstants.MM_NUM_THREADS_DEFAULT;
Gamze Abakaf57ef602019-03-11 06:52:48 +000083import static org.onosproject.net.OsgiPropertyConstants.MM_PURGE_ON_DISCONNECTION;
84import static org.onosproject.net.OsgiPropertyConstants.MM_PURGE_ON_DISCONNECTION_DEFAULT;
alshabib1d2bc402015-07-31 17:04:11 -070085import static org.slf4j.LoggerFactory.getLogger;
86
alshabib1d2bc402015-07-31 17:04:11 -070087/**
88 * Provides implementation of the meter service APIs.
89 */
Ray Milkeyd04e2272018-10-16 18:20:18 -070090@Component(
Gamze Abakaf57ef602019-03-11 06:52:48 +000091 immediate = true,
92 service = {
93 MeterService.class,
94 MeterProviderRegistry.class
95 },
96 property = {
97 MM_NUM_THREADS + ":Integer=" + MM_NUM_THREADS_DEFAULT,
98 MM_FALLBACK_METER_POLL_FREQUENCY + ":Integer=" + MM_FALLBACK_METER_POLL_FREQUENCY_DEFAULT,
99 MM_PURGE_ON_DISCONNECTION + ":Boolean=" + MM_PURGE_ON_DISCONNECTION_DEFAULT,
100 }
Ray Milkeyd04e2272018-10-16 18:20:18 -0700101)
Thomas Vachuska11b99fc2017-04-27 12:51:04 -0700102public class MeterManager
103 extends AbstractListenerProviderRegistry<MeterEvent, MeterListener, MeterProvider, MeterProviderService>
alshabib1d2bc402015-07-31 17:04:11 -0700104 implements MeterService, MeterProviderRegistry {
pierventre1b8afbc2020-07-13 14:07:05 +0200105 // Installer related objects
106 private PredictableExecutor meterInstallers;
Jordi Ortiz31d4d382017-07-19 10:52:26 +0200107 private static final String WORKER_PATTERN = "installer-%d";
108 private static final String GROUP_THREAD_NAME = "onos/meter";
pierventre1b8afbc2020-07-13 14:07:05 +0200109 // Logging facility, meter store delegate and listener for device events.
alshabib1d2bc402015-07-31 17:04:11 -0700110 private final Logger log = getLogger(getClass());
111 private final MeterStoreDelegate delegate = new InternalMeterStoreDelegate();
Gamze Abakaf57ef602019-03-11 06:52:48 +0000112 private final DeviceListener deviceListener = new InternalDeviceListener();
alshabib1d2bc402015-07-31 17:04:11 -0700113
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700114 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigif094c612017-10-14 12:15:02 +0200115 private MeterStore store;
alshabib1d2bc402015-07-31 17:04:11 -0700116
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700117 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andrea Campanellae3708782017-10-16 16:00:21 +0200118 protected DriverService driverService;
119
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700120 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andrea Campanellae3708782017-10-16 16:00:21 +0200121 protected DeviceService deviceService;
122
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700123 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andrea Campanellae3708782017-10-16 16:00:21 +0200124 protected ComponentConfigService cfgService;
125
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700126 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andrea Campanellae3708782017-10-16 16:00:21 +0200127 protected MastershipService mastershipService;
128
Andrea Campanella32a9c0b2020-03-27 12:53:46 +0100129 @Reference(cardinality = ReferenceCardinality.MANDATORY)
130 protected NetworkConfigRegistry netCfgService;
131
pierventre1b8afbc2020-07-13 14:07:05 +0200132 @Reference(cardinality = ReferenceCardinality.MANDATORY)
133 protected ClusterService clusterService;
134
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700135 /** Number of worker threads. */
pierventre1b8afbc2020-07-13 14:07:05 +0200136 // TODO Set 0 to use the available processors
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700137 private int numThreads = MM_NUM_THREADS_DEFAULT;
138
139 /** Frequency (in seconds) for polling meters via fallback provider. */
Ray Milkeyd04e2272018-10-16 18:20:18 -0700140 private int fallbackMeterPollFrequency = MM_FALLBACK_METER_POLL_FREQUENCY_DEFAULT;
Andrea Campanellae3708782017-10-16 16:00:21 +0200141
Gamze Abakaf57ef602019-03-11 06:52:48 +0000142 /** Purge entries associated with a device when the device goes offline. */
143 private boolean purgeOnDisconnection = MM_PURGE_ON_DISCONNECTION_DEFAULT;
144
pierventre1b8afbc2020-07-13 14:07:05 +0200145 // Action triggered when the futures related to submit and withdrawal complete
alshabibe1248b62015-08-20 17:21:55 -0700146 private TriConsumer<MeterRequest, MeterStoreResult, Throwable> onComplete;
alshabibeadfc8e2015-08-18 15:40:46 -0700147
pierventre1b8afbc2020-07-13 14:07:05 +0200148 // Meter provider reference
Andrea Campanellae3708782017-10-16 16:00:21 +0200149 private final MeterDriverProvider defaultProvider = new MeterDriverProvider();
150
pierventre1b8afbc2020-07-13 14:07:05 +0200151 // Node id used to verify who is charge of the meter ops
152 // (usually one node can modify the internal state of the device)
153 private NodeId local;
154
alshabib1d2bc402015-07-31 17:04:11 -0700155 @Activate
Andrea Campanellae3708782017-10-16 16:00:21 +0200156 public void activate(ComponentContext context) {
alshabib58fe6dc2015-08-19 17:16:13 -0700157 store.setDelegate(delegate);
Andrea Campanellae3708782017-10-16 16:00:21 +0200158 cfgService.registerProperties(getClass());
Jordi Ortiz3a6f3072016-11-07 10:23:48 +0100159 eventDispatcher.addSink(MeterEvent.class, listenerRegistry);
Gamze Abakaf57ef602019-03-11 06:52:48 +0000160 deviceService.addListener(deviceListener);
pierventre1b8afbc2020-07-13 14:07:05 +0200161 local = clusterService.getLocalNode().id();
162 // Consumer logic is the following:
163 // if there is an exceptional end (storage exception), on error is called
164 // else if there is a reason for the failure, on error is called with the reason
165 // else if the reason is empty, on success is called
166 // In all the cases the meter context code is consumed
Jordi Ortiz3a6f3072016-11-07 10:23:48 +0100167 onComplete = (request, result, error) -> {
alshabibe1248b62015-08-20 17:21:55 -0700168 request.context().ifPresent(c -> {
alshabibeadfc8e2015-08-18 15:40:46 -0700169 if (error != null) {
alshabibe1248b62015-08-20 17:21:55 -0700170 c.onError(request, MeterFailReason.UNKNOWN);
alshabibeadfc8e2015-08-18 15:40:46 -0700171 } else {
172 if (result.reason().isPresent()) {
alshabibe1248b62015-08-20 17:21:55 -0700173 c.onError(request, result.reason().get());
alshabibeadfc8e2015-08-18 15:40:46 -0700174 } else {
alshabibe1248b62015-08-20 17:21:55 -0700175 c.onSuccess(request);
alshabibeadfc8e2015-08-18 15:40:46 -0700176 }
177 }
178 });
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900179 };
Jordi Ortiz31d4d382017-07-19 10:52:26 +0200180
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700181 modified(context);
alshabib1d2bc402015-07-31 17:04:11 -0700182 log.info("Started");
183 }
184
Andrea Campanellae3708782017-10-16 16:00:21 +0200185 @Modified
186 public void modified(ComponentContext context) {
187 if (context != null) {
188 readComponentConfiguration(context);
189 }
190 defaultProvider.init(deviceService, createProviderService(defaultProvider),
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900191 mastershipService, fallbackMeterPollFrequency);
Andrea Campanellae3708782017-10-16 16:00:21 +0200192 }
193
alshabib1d2bc402015-07-31 17:04:11 -0700194 @Deactivate
195 public void deactivate() {
Andrea Campanellae3708782017-10-16 16:00:21 +0200196 defaultProvider.terminate();
alshabib58fe6dc2015-08-19 17:16:13 -0700197 store.unsetDelegate(delegate);
Thomas Vachuska11b99fc2017-04-27 12:51:04 -0700198 eventDispatcher.removeSink(MeterEvent.class);
Gamze Abakaf57ef602019-03-11 06:52:48 +0000199 deviceService.removeListener(deviceListener);
Andrea Campanellae3708782017-10-16 16:00:21 +0200200 cfgService.unregisterProperties(getClass(), false);
pierventre1b8afbc2020-07-13 14:07:05 +0200201 meterInstallers.shutdown();
alshabib1d2bc402015-07-31 17:04:11 -0700202 log.info("Stopped");
203 }
204
Andrea Campanellae3708782017-10-16 16:00:21 +0200205 /**
206 * Extracts properties from the component configuration context.
207 *
208 * @param context the component context
209 */
210 private void readComponentConfiguration(ComponentContext context) {
211 Dictionary<?, ?> properties = context.getProperties();
Gamze Abakaf57ef602019-03-11 06:52:48 +0000212 Boolean flag;
213
214 flag = Tools.isPropertyEnabled(properties, MM_PURGE_ON_DISCONNECTION);
215 if (flag == null) {
216 log.info("PurgeOnDisconnection is not configured," +
Andrea Campanella32a9c0b2020-03-27 12:53:46 +0100217 "using current value of {}", purgeOnDisconnection);
Gamze Abakaf57ef602019-03-11 06:52:48 +0000218 } else {
219 purgeOnDisconnection = flag;
220 log.info("Configured. PurgeOnDisconnection is {}",
Andrea Campanella32a9c0b2020-03-27 12:53:46 +0100221 purgeOnDisconnection ? "enabled" : "disabled");
Gamze Abakaf57ef602019-03-11 06:52:48 +0000222 }
Andrea Campanellae3708782017-10-16 16:00:21 +0200223
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700224 String s = get(properties, MM_FALLBACK_METER_POLL_FREQUENCY);
Andrea Campanellae3708782017-10-16 16:00:21 +0200225 try {
Ray Milkeyd04e2272018-10-16 18:20:18 -0700226 fallbackMeterPollFrequency = isNullOrEmpty(s) ?
227 MM_FALLBACK_METER_POLL_FREQUENCY_DEFAULT : Integer.parseInt(s);
Andrea Campanellae3708782017-10-16 16:00:21 +0200228 } catch (NumberFormatException e) {
Ray Milkeyd04e2272018-10-16 18:20:18 -0700229 fallbackMeterPollFrequency = MM_FALLBACK_METER_POLL_FREQUENCY_DEFAULT;
Andrea Campanellae3708782017-10-16 16:00:21 +0200230 }
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700231
232 s = get(properties, MM_NUM_THREADS);
233 try {
234 numThreads = isNullOrEmpty(s) ? MM_NUM_THREADS_DEFAULT : Integer.parseInt(s);
235 } catch (NumberFormatException e) {
236 numThreads = MM_NUM_THREADS_DEFAULT;
237 }
pierventre1b8afbc2020-07-13 14:07:05 +0200238 if (meterInstallers != null) {
239 meterInstallers.shutdown();
240 }
241 meterInstallers = newPredictableExecutor(numThreads,
242 groupedThreads(GROUP_THREAD_NAME, WORKER_PATTERN, log));
Andrea Campanellae3708782017-10-16 16:00:21 +0200243 }
244
245 @Override
246 protected MeterProvider defaultProvider() {
247 return defaultProvider;
248 }
249
alshabib1d2bc402015-07-31 17:04:11 -0700250 @Override
251 protected MeterProviderService createProviderService(MeterProvider provider) {
252 return new InternalMeterProviderService(provider);
253 }
254
255 @Override
alshabibe1248b62015-08-20 17:21:55 -0700256 public Meter submit(MeterRequest request) {
柯志勇10068695d709dba2018-10-23 18:35:49 +0800257 checkNotNull(request, "request cannot be null.");
Wailok Shum79919522021-08-22 19:35:34 +0800258 MeterCellId cellId;
259 if (request.index().isPresent()) {
260 // User provides index
261 if (request.scope().isGlobal()) {
262 cellId = MeterId.meterId(request.index().get());
263 } else {
264 cellId = PiMeterCellId.ofIndirect(
265 PiMeterId.of(request.scope().id()), request.index().get());
266 }
267 } else {
268 // Allocate an id
269 cellId = allocateMeterId(request.deviceId(), request.scope());
270 }
alshabibe1248b62015-08-20 17:21:55 -0700271 Meter.Builder mBuilder = DefaultMeter.builder()
272 .forDevice(request.deviceId())
273 .fromApp(request.appId())
274 .withBands(request.bands())
Wailok Shum79919522021-08-22 19:35:34 +0800275 .withCellId(cellId)
alshabibe1248b62015-08-20 17:21:55 -0700276 .withUnit(request.unit());
alshabibe1248b62015-08-20 17:21:55 -0700277 if (request.isBurst()) {
278 mBuilder.burst();
279 }
Andrea Campanella5bdbe432021-05-03 15:59:19 +0200280 if (request.annotations() != null && !request.annotations().keys().isEmpty()) {
281 mBuilder.withAnnotations(request.annotations());
282 }
alshabibe1248b62015-08-20 17:21:55 -0700283 DefaultMeter m = (DefaultMeter) mBuilder.build();
pierventre1b8afbc2020-07-13 14:07:05 +0200284 // Meter installation logic (happy ending case)
285 // PENDING -> stats -> ADDED -> future completes
alshabib7bb05012015-08-05 10:15:09 -0700286 m.setState(MeterState.PENDING_ADD);
alshabibeadfc8e2015-08-18 15:40:46 -0700287 store.storeMeter(m).whenComplete((result, error) ->
alshabibe1248b62015-08-20 17:21:55 -0700288 onComplete.accept(request, result, error));
289 return m;
alshabib1d2bc402015-07-31 17:04:11 -0700290 }
291
292 @Override
alshabibe1248b62015-08-20 17:21:55 -0700293 public void withdraw(MeterRequest request, MeterId meterId) {
Wailok Shum79919522021-08-22 19:35:34 +0800294 withdraw(request, (MeterCellId) meterId);
295 }
296
297 @Override
298 public void withdraw(MeterRequest request, MeterCellId meterCellId) {
柯志勇10068695d709dba2018-10-23 18:35:49 +0800299 checkNotNull(request, "request cannot be null.");
alshabibe1248b62015-08-20 17:21:55 -0700300 Meter.Builder mBuilder = DefaultMeter.builder()
301 .forDevice(request.deviceId())
302 .fromApp(request.appId())
303 .withBands(request.bands())
Wailok Shum79919522021-08-22 19:35:34 +0800304 .withCellId(meterCellId)
alshabibe1248b62015-08-20 17:21:55 -0700305 .withUnit(request.unit());
alshabib1d2bc402015-07-31 17:04:11 -0700306
alshabibe1248b62015-08-20 17:21:55 -0700307 if (request.isBurst()) {
308 mBuilder.burst();
309 }
alshabibe1248b62015-08-20 17:21:55 -0700310 DefaultMeter m = (DefaultMeter) mBuilder.build();
pierventre1b8afbc2020-07-13 14:07:05 +0200311 // Meter removal logic (happy ending case)
312 // PENDING -> stats -> removed from the map -> future completes
313 // There is no transition to the REMOVED state
alshabib7bb05012015-08-05 10:15:09 -0700314 m.setState(MeterState.PENDING_REMOVE);
alshabibeadfc8e2015-08-18 15:40:46 -0700315 store.deleteMeter(m).whenComplete((result, error) ->
alshabibe1248b62015-08-20 17:21:55 -0700316 onComplete.accept(request, result, error));
alshabib1d2bc402015-07-31 17:04:11 -0700317 }
318
319 @Override
alshabib70aaa1b2015-09-25 14:30:59 -0700320 public Meter getMeter(DeviceId deviceId, MeterId id) {
Wailok Shum79919522021-08-22 19:35:34 +0800321 return getMeter(deviceId, (MeterCellId) id);
322 }
323
324 @Override
325 public Meter getMeter(DeviceId deviceId, MeterCellId id) {
alshabib70aaa1b2015-09-25 14:30:59 -0700326 MeterKey key = MeterKey.key(deviceId, id);
327 return store.getMeter(key);
alshabib1d2bc402015-07-31 17:04:11 -0700328 }
329
330 @Override
Jian Li1932b932016-01-03 00:35:40 -0800331 public Collection<Meter> getMeters(DeviceId deviceId) {
332 return store.getAllMeters().stream().filter(m ->
333 m.deviceId().equals(deviceId)).collect(Collectors.toList());
334 }
335
336 @Override
alshabib58fe6dc2015-08-19 17:16:13 -0700337 public Collection<Meter> getAllMeters() {
338 return store.getAllMeters();
339 }
340
Pier Luigibdcd9672017-10-13 13:54:48 +0200341 @Override
342 public MeterId allocateMeterId(DeviceId deviceId) {
pierventre1b8afbc2020-07-13 14:07:05 +0200343 // We delegate directly to the store
Pier Luigif094c612017-10-14 12:15:02 +0200344 return store.allocateMeterId(deviceId);
alshabib1d2bc402015-07-31 17:04:11 -0700345 }
346
Wailok Shum79919522021-08-22 19:35:34 +0800347 private MeterCellId allocateMeterId(DeviceId deviceId, MeterScope scope) {
348 return store.allocateMeterId(deviceId, scope);
349 }
350
Pier Luigibdcd9672017-10-13 13:54:48 +0200351 @Override
352 public void freeMeterId(DeviceId deviceId, MeterId meterId) {
pierventre1b8afbc2020-07-13 14:07:05 +0200353 // We delegate directly to the store
Pier Luigibdcd9672017-10-13 13:54:48 +0200354 store.freeMeterId(deviceId, meterId);
355 }
356
Andrea Campanella23250502020-05-13 15:36:57 +0200357 @Override
358 public void purgeMeters(DeviceId deviceId) {
pierventre1b8afbc2020-07-13 14:07:05 +0200359 // We delegate directly to the store
Andrea Campanella23250502020-05-13 15:36:57 +0200360 store.purgeMeter(deviceId);
361 }
362
Daniele Moro43ac2892021-07-15 17:02:59 +0200363 @Override
364 public void purgeMeters(DeviceId deviceId, ApplicationId appId) {
365 store.purgeMeters(deviceId, appId);
366 }
367
alshabib1d2bc402015-07-31 17:04:11 -0700368 private class InternalMeterProviderService
369 extends AbstractProviderService<MeterProvider>
370 implements MeterProviderService {
371
372 /**
373 * Creates a provider service on behalf of the specified provider.
374 *
375 * @param provider provider to which this service is being issued
376 */
377 protected InternalMeterProviderService(MeterProvider provider) {
378 super(provider);
379 }
380
381 @Override
alshabib7bb05012015-08-05 10:15:09 -0700382 public void meterOperationFailed(MeterOperation operation,
383 MeterFailReason reason) {
384 store.failedMeter(operation, reason);
alshabib1d2bc402015-07-31 17:04:11 -0700385 }
386
387 @Override
388 public void pushMeterMetrics(DeviceId deviceId, Collection<Meter> meterEntries) {
pierventre1b8afbc2020-07-13 14:07:05 +0200389 // Each update on the store is reflected on this collection
Jordi Ortiz9287b632017-06-22 11:01:37 +0200390 Collection<Meter> allMeters = store.getAllMeters(deviceId);
alshabib5eb79392015-08-19 18:09:55 -0700391
Wailok Shum79919522021-08-22 19:35:34 +0800392 Map<MeterCellId, Meter> meterEntriesMap = meterEntries.stream()
393 .collect(Collectors.toMap(Meter::meterCellId, Meter -> Meter));
Jordi Ortiz58896912017-03-06 14:51:05 +0100394
Jordi Ortiz205af452017-06-22 14:25:04 +0200395 // Look for meters defined in onos and missing in the device (restore)
Jordi Ortiz9287b632017-06-22 11:01:37 +0200396 allMeters.stream().forEach(m -> {
397 if ((m.state().equals(MeterState.PENDING_ADD) ||
398 m.state().equals(MeterState.ADDED)) &&
Wailok Shum79919522021-08-22 19:35:34 +0800399 !meterEntriesMap.containsKey(m.meterCellId())) {
Jordi Ortiz58896912017-03-06 14:51:05 +0100400 // The meter is missing in the device. Reinstall!
Jordi Ortiz205af452017-06-22 14:25:04 +0200401 log.debug("Adding meter missing in device {} {}", deviceId, m);
pierventre1b8afbc2020-07-13 14:07:05 +0200402 // offload the task to avoid the overloading of the sb threads
403 meterInstallers.execute(new MeterInstaller(deviceId, m, MeterOperation.Type.ADD));
Jordi Ortiz58896912017-03-06 14:51:05 +0100404 }
Jordi Ortiz58896912017-03-06 14:51:05 +0100405 });
406
Jordi Ortiz205af452017-06-22 14:25:04 +0200407 // Look for meters defined in the device and not in onos (remove)
408 meterEntriesMap.entrySet().stream()
Wailok Shum79919522021-08-22 19:35:34 +0800409 .filter(md -> !allMeters.stream().anyMatch(m -> m.meterCellId().equals(md.getKey())))
Jordi Ortiz205af452017-06-22 14:25:04 +0200410 .forEach(mio -> {
Jordi Ortiz205af452017-06-22 14:25:04 +0200411 Meter meter = mio.getValue();
Wailok Shum79919522021-08-22 19:35:34 +0800412 // The meter is missing in onos. Uninstall!
413 log.debug("Remove meter in device not in onos {} {}", deviceId, mio.getKey());
414 // offload the task to avoid the overloading of the sb threads
415 meterInstallers.execute(new MeterInstaller(deviceId, meter, MeterOperation.Type.REMOVE));
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900416 });
Jordi Ortiz205af452017-06-22 14:25:04 +0200417
pierventre1b8afbc2020-07-13 14:07:05 +0200418 // Update the meter stats in the store (first time move the state from pending to added)
pierventre44220052020-09-22 12:51:06 +0200419 Collection<Meter> addedMeters = Sets.newHashSet();
alshabib5eb79392015-08-19 18:09:55 -0700420 meterEntries.stream()
Jordi Ortiz9287b632017-06-22 11:01:37 +0200421 .filter(m -> allMeters.stream()
Wailok Shum79919522021-08-22 19:35:34 +0800422 .anyMatch(sm -> sm.deviceId().equals(deviceId) &&
423 sm.meterCellId().equals(m.meterCellId())))
pierventre44220052020-09-22 12:51:06 +0200424 .forEach(m -> {
425 Meter updatedMeter = store.updateMeterState(m);
426 if (updatedMeter != null && updatedMeter.state() == MeterState.ADDED) {
427 addedMeters.add(updatedMeter);
428 }
429 });
430 Collection<Meter> newAllMeters = Sets.newHashSet(allMeters);
431 newAllMeters.removeAll(addedMeters);
alshabib5eb79392015-08-19 18:09:55 -0700432
pierventre44220052020-09-22 12:51:06 +0200433 newAllMeters.forEach(m -> {
pierventre1b8afbc2020-07-13 14:07:05 +0200434 // Remove workflow. Regarding OpenFlow, meters have been removed from
435 // the device but they are still in the store, we will purge them definitely.
436 // Instead, P4Runtime devices will not remove the meter. The first workaround
437 // for P4Runtime will avoid to send a remove op. Then, we reach this point
438 // and we purge the meter from the store
Wailok Shum79919522021-08-22 19:35:34 +0800439 if (m.state() == MeterState.PENDING_REMOVE) {
440 log.debug("Delete meter {} now in store", m.meterCellId());
Wailok Shumf013a782021-07-26 16:51:01 +0800441 store.purgeMeter(m);
alshabib5eb79392015-08-19 18:09:55 -0700442 }
443 });
alshabib1d2bc402015-07-31 17:04:11 -0700444 }
Jordi Ortizaa8de492016-12-01 00:21:36 +0100445
446 @Override
447 public void pushMeterFeatures(DeviceId deviceId, MeterFeatures meterfeatures) {
448 store.storeMeterFeatures(meterfeatures);
449 }
450
451 @Override
Wailok Shumf013a782021-07-26 16:51:01 +0800452 public void pushMeterFeatures(DeviceId deviceId, Collection<MeterFeatures> meterfeatures) {
453 meterfeatures.forEach(mf -> store.storeMeterFeatures(mf));
454 }
455
456 @Override
Jordi Ortizaa8de492016-12-01 00:21:36 +0100457 public void deleteMeterFeatures(DeviceId deviceId) {
458 store.deleteMeterFeatures(deviceId);
459 }
alshabib1d2bc402015-07-31 17:04:11 -0700460 }
461
462 private class InternalMeterStoreDelegate implements MeterStoreDelegate {
463
464 @Override
465 public void notify(MeterEvent event) {
alshabibeadfc8e2015-08-18 15:40:46 -0700466 DeviceId deviceId = event.subject().deviceId();
alshabib7bb05012015-08-05 10:15:09 -0700467 switch (event.type()) {
pierventre1b8afbc2020-07-13 14:07:05 +0200468 // REQ events will trigger a modification in the device.
469 // Mastership check is performed inside the installer
470 // to avoid the blocking of the RAFT threads
alshabibeadfc8e2015-08-18 15:40:46 -0700471 case METER_ADD_REQ:
pierventre1b8afbc2020-07-13 14:07:05 +0200472 meterInstallers.execute(new MeterInstaller(deviceId, event.subject(),
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900473 MeterOperation.Type.ADD));
alshabib7bb05012015-08-05 10:15:09 -0700474 break;
alshabibeadfc8e2015-08-18 15:40:46 -0700475 case METER_REM_REQ:
pierventre1b8afbc2020-07-13 14:07:05 +0200476 meterInstallers.execute(new MeterInstaller(deviceId, event.subject(),
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900477 MeterOperation.Type.REMOVE));
alshabib7bb05012015-08-05 10:15:09 -0700478 break;
pierventre1b8afbc2020-07-13 14:07:05 +0200479 // Following events are forwarded to the apps subscribed for the meter events;
480 // installers are not involved in this task. In this case, the overhead for this op
481 // is almost null. Potentially we can introduce a store delegate thread.
Jordi Ortizdf28ecd2017-03-25 19:22:36 +0100482 case METER_ADDED:
Jordi Ortizdf28ecd2017-03-25 19:22:36 +0100483 case METER_REMOVED:
Gamze Abakadadae722018-09-12 10:55:35 +0000484 case METER_REFERENCE_COUNT_ZERO:
pierventre1b8afbc2020-07-13 14:07:05 +0200485 log.debug("Post {} event {}", event.type(), event.subject());
486 post(event);
Gamze Abakadadae722018-09-12 10:55:35 +0000487 break;
alshabib7bb05012015-08-05 10:15:09 -0700488 default:
489 log.warn("Unknown meter event {}", event.type());
490 }
alshabib1d2bc402015-07-31 17:04:11 -0700491
492 }
493 }
pierventre1b8afbc2020-07-13 14:07:05 +0200494
Jordi Ortiz31d4d382017-07-19 10:52:26 +0200495 /**
496 * Task that passes the meter down to the provider.
497 */
pierventre1b8afbc2020-07-13 14:07:05 +0200498 private class MeterInstaller implements PickyRunnable {
Jordi Ortiz31d4d382017-07-19 10:52:26 +0200499 private final DeviceId deviceId;
500 private final Meter meter;
501 private final MeterOperation.Type op;
502
503 public MeterInstaller(DeviceId deviceId, Meter meter, MeterOperation.Type op) {
504 this.deviceId = checkNotNull(deviceId);
505 this.meter = checkNotNull(meter);
506 this.op = checkNotNull(op);
507 }
508
509 @Override
510 public void run() {
pierventre1b8afbc2020-07-13 14:07:05 +0200511 // Check mastership and eventually execute the op on the device
512 log.debug("Meter {} request {}", op.name().toLowerCase(), meter);
513 NodeId master = mastershipService.getMasterFor(meter.deviceId());
514 if (!Objects.equals(local, master)) {
515 log.trace("Not the master of device {}, skipping installation of the meter {}",
Wailok Shum79919522021-08-22 19:35:34 +0800516 meter.deviceId(), meter.meterCellId());
pierventre1b8afbc2020-07-13 14:07:05 +0200517 return;
518 }
Jordi Ortiz31d4d382017-07-19 10:52:26 +0200519 MeterProvider p = getProvider(this.deviceId);
520 if (p == null) {
521 log.error("Unable to recover {}'s provider", deviceId);
522 return;
523 }
524 p.performMeterOperation(deviceId, new MeterOperation(meter, op));
525 }
pierventre1b8afbc2020-07-13 14:07:05 +0200526
527 @Override
528 public int hint() {
Wailok Shum79919522021-08-22 19:35:34 +0800529 return meter.meterCellId().hashCode();
pierventre1b8afbc2020-07-13 14:07:05 +0200530 }
Jordi Ortiz31d4d382017-07-19 10:52:26 +0200531 }
alshabib1d2bc402015-07-31 17:04:11 -0700532
Gamze Abakaf57ef602019-03-11 06:52:48 +0000533 private class InternalDeviceListener implements DeviceListener {
534
535 @Override
536 public void event(DeviceEvent event) {
pierventre52ef9332021-07-09 22:42:17 +0200537 DeviceId deviceId = event.subject().id();
538 meterInstallers.execute(() -> {
539 switch (event.type()) {
540 case DEVICE_REMOVED:
541 case DEVICE_AVAILABILITY_CHANGED:
542 if (!deviceService.isAvailable(deviceId)) {
543 BasicDeviceConfig cfg = netCfgService.getConfig(deviceId, BasicDeviceConfig.class);
544 //if purgeOnDisconnection is set for the device or it's a global configuration
545 // lets remove the meters.
546 boolean purge = cfg != null && cfg.isPurgeOnDisconnectionConfigured() ?
547 cfg.purgeOnDisconnection() : purgeOnDisconnection;
548 if (purge) {
549 log.info("PurgeOnDisconnection is requested for device {}, " +
550 "removing meters", deviceId);
551 store.purgeMeter(deviceId);
552 }
Gamze Abakaf57ef602019-03-11 06:52:48 +0000553 }
pierventre52ef9332021-07-09 22:42:17 +0200554 break;
555 default:
556 break;
557 }
558 }, deviceId.hashCode());
559
Gamze Abakaf57ef602019-03-11 06:52:48 +0000560 }
561 }
562
alshabib1d2bc402015-07-31 17:04:11 -0700563}