blob: 98e79a9d89a920c1499daca40ddbe9d2c1cd909d [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
pierventre3b39bd82021-08-18 09:40:14 +020074import static com.google.common.base.Preconditions.checkArgument;
Jordi Ortiz31d4d382017-07-19 10:52:26 +020075import static com.google.common.base.Preconditions.checkNotNull;
Andrea Campanellae3708782017-10-16 16:00:21 +020076import static com.google.common.base.Strings.isNullOrEmpty;
pierventre1b8afbc2020-07-13 14:07:05 +020077import static org.onlab.util.PredictableExecutor.newPredictableExecutor;
Andrea Campanellae3708782017-10-16 16:00:21 +020078import static org.onlab.util.Tools.get;
Jordi Ortiz31d4d382017-07-19 10:52:26 +020079import static org.onlab.util.Tools.groupedThreads;
Ray Milkeyd04e2272018-10-16 18:20:18 -070080import static org.onosproject.net.OsgiPropertyConstants.MM_FALLBACK_METER_POLL_FREQUENCY;
81import static org.onosproject.net.OsgiPropertyConstants.MM_FALLBACK_METER_POLL_FREQUENCY_DEFAULT;
82import static org.onosproject.net.OsgiPropertyConstants.MM_NUM_THREADS;
83import static org.onosproject.net.OsgiPropertyConstants.MM_NUM_THREADS_DEFAULT;
Gamze Abakaf57ef602019-03-11 06:52:48 +000084import static org.onosproject.net.OsgiPropertyConstants.MM_PURGE_ON_DISCONNECTION;
85import static org.onosproject.net.OsgiPropertyConstants.MM_PURGE_ON_DISCONNECTION_DEFAULT;
pierventre3b39bd82021-08-18 09:40:14 +020086import static org.onosproject.net.OsgiPropertyConstants.MM_USER_DEFINED_INDEX;
87import static org.onosproject.net.OsgiPropertyConstants.MM_USER_DEFINED_INDEX_DEFAULT;
alshabib1d2bc402015-07-31 17:04:11 -070088import static org.slf4j.LoggerFactory.getLogger;
89
alshabib1d2bc402015-07-31 17:04:11 -070090/**
91 * Provides implementation of the meter service APIs.
92 */
Ray Milkeyd04e2272018-10-16 18:20:18 -070093@Component(
Gamze Abakaf57ef602019-03-11 06:52:48 +000094 immediate = true,
95 service = {
96 MeterService.class,
97 MeterProviderRegistry.class
98 },
99 property = {
100 MM_NUM_THREADS + ":Integer=" + MM_NUM_THREADS_DEFAULT,
101 MM_FALLBACK_METER_POLL_FREQUENCY + ":Integer=" + MM_FALLBACK_METER_POLL_FREQUENCY_DEFAULT,
102 MM_PURGE_ON_DISCONNECTION + ":Boolean=" + MM_PURGE_ON_DISCONNECTION_DEFAULT,
pierventre3b39bd82021-08-18 09:40:14 +0200103 MM_USER_DEFINED_INDEX + ":Boolean=" + MM_USER_DEFINED_INDEX_DEFAULT,
Gamze Abakaf57ef602019-03-11 06:52:48 +0000104 }
Ray Milkeyd04e2272018-10-16 18:20:18 -0700105)
Thomas Vachuska11b99fc2017-04-27 12:51:04 -0700106public class MeterManager
107 extends AbstractListenerProviderRegistry<MeterEvent, MeterListener, MeterProvider, MeterProviderService>
alshabib1d2bc402015-07-31 17:04:11 -0700108 implements MeterService, MeterProviderRegistry {
pierventre1b8afbc2020-07-13 14:07:05 +0200109 // Installer related objects
110 private PredictableExecutor meterInstallers;
Jordi Ortiz31d4d382017-07-19 10:52:26 +0200111 private static final String WORKER_PATTERN = "installer-%d";
112 private static final String GROUP_THREAD_NAME = "onos/meter";
pierventre1b8afbc2020-07-13 14:07:05 +0200113 // Logging facility, meter store delegate and listener for device events.
alshabib1d2bc402015-07-31 17:04:11 -0700114 private final Logger log = getLogger(getClass());
115 private final MeterStoreDelegate delegate = new InternalMeterStoreDelegate();
Gamze Abakaf57ef602019-03-11 06:52:48 +0000116 private final DeviceListener deviceListener = new InternalDeviceListener();
alshabib1d2bc402015-07-31 17:04:11 -0700117
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700118 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigif094c612017-10-14 12:15:02 +0200119 private MeterStore store;
alshabib1d2bc402015-07-31 17:04:11 -0700120
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700121 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andrea Campanellae3708782017-10-16 16:00:21 +0200122 protected DriverService driverService;
123
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700124 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andrea Campanellae3708782017-10-16 16:00:21 +0200125 protected DeviceService deviceService;
126
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700127 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andrea Campanellae3708782017-10-16 16:00:21 +0200128 protected ComponentConfigService cfgService;
129
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700130 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andrea Campanellae3708782017-10-16 16:00:21 +0200131 protected MastershipService mastershipService;
132
Andrea Campanella32a9c0b2020-03-27 12:53:46 +0100133 @Reference(cardinality = ReferenceCardinality.MANDATORY)
134 protected NetworkConfigRegistry netCfgService;
135
pierventre1b8afbc2020-07-13 14:07:05 +0200136 @Reference(cardinality = ReferenceCardinality.MANDATORY)
137 protected ClusterService clusterService;
138
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700139 /** Number of worker threads. */
pierventre1b8afbc2020-07-13 14:07:05 +0200140 // TODO Set 0 to use the available processors
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700141 private int numThreads = MM_NUM_THREADS_DEFAULT;
142
143 /** Frequency (in seconds) for polling meters via fallback provider. */
Ray Milkeyd04e2272018-10-16 18:20:18 -0700144 private int fallbackMeterPollFrequency = MM_FALLBACK_METER_POLL_FREQUENCY_DEFAULT;
Andrea Campanellae3708782017-10-16 16:00:21 +0200145
Gamze Abakaf57ef602019-03-11 06:52:48 +0000146 /** Purge entries associated with a device when the device goes offline. */
147 private boolean purgeOnDisconnection = MM_PURGE_ON_DISCONNECTION_DEFAULT;
148
pierventre3b39bd82021-08-18 09:40:14 +0200149 /** Enable user defined index mode. Users can provide their own meter index. */
150 protected boolean userDefinedIndex = MM_USER_DEFINED_INDEX_DEFAULT;
151
pierventre1b8afbc2020-07-13 14:07:05 +0200152 // Action triggered when the futures related to submit and withdrawal complete
alshabibe1248b62015-08-20 17:21:55 -0700153 private TriConsumer<MeterRequest, MeterStoreResult, Throwable> onComplete;
alshabibeadfc8e2015-08-18 15:40:46 -0700154
pierventre1b8afbc2020-07-13 14:07:05 +0200155 // Meter provider reference
Andrea Campanellae3708782017-10-16 16:00:21 +0200156 private final MeterDriverProvider defaultProvider = new MeterDriverProvider();
157
pierventre1b8afbc2020-07-13 14:07:05 +0200158 // Node id used to verify who is charge of the meter ops
159 // (usually one node can modify the internal state of the device)
160 private NodeId local;
161
alshabib1d2bc402015-07-31 17:04:11 -0700162 @Activate
Andrea Campanellae3708782017-10-16 16:00:21 +0200163 public void activate(ComponentContext context) {
alshabib58fe6dc2015-08-19 17:16:13 -0700164 store.setDelegate(delegate);
Andrea Campanellae3708782017-10-16 16:00:21 +0200165 cfgService.registerProperties(getClass());
Jordi Ortiz3a6f3072016-11-07 10:23:48 +0100166 eventDispatcher.addSink(MeterEvent.class, listenerRegistry);
Gamze Abakaf57ef602019-03-11 06:52:48 +0000167 deviceService.addListener(deviceListener);
pierventre1b8afbc2020-07-13 14:07:05 +0200168 local = clusterService.getLocalNode().id();
169 // Consumer logic is the following:
170 // if there is an exceptional end (storage exception), on error is called
171 // else if there is a reason for the failure, on error is called with the reason
172 // else if the reason is empty, on success is called
173 // In all the cases the meter context code is consumed
Jordi Ortiz3a6f3072016-11-07 10:23:48 +0100174 onComplete = (request, result, error) -> {
alshabibe1248b62015-08-20 17:21:55 -0700175 request.context().ifPresent(c -> {
alshabibeadfc8e2015-08-18 15:40:46 -0700176 if (error != null) {
alshabibe1248b62015-08-20 17:21:55 -0700177 c.onError(request, MeterFailReason.UNKNOWN);
alshabibeadfc8e2015-08-18 15:40:46 -0700178 } else {
179 if (result.reason().isPresent()) {
alshabibe1248b62015-08-20 17:21:55 -0700180 c.onError(request, result.reason().get());
alshabibeadfc8e2015-08-18 15:40:46 -0700181 } else {
alshabibe1248b62015-08-20 17:21:55 -0700182 c.onSuccess(request);
alshabibeadfc8e2015-08-18 15:40:46 -0700183 }
184 }
185 });
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900186 };
Jordi Ortiz31d4d382017-07-19 10:52:26 +0200187
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700188 modified(context);
alshabib1d2bc402015-07-31 17:04:11 -0700189 log.info("Started");
190 }
191
Andrea Campanellae3708782017-10-16 16:00:21 +0200192 @Modified
193 public void modified(ComponentContext context) {
194 if (context != null) {
195 readComponentConfiguration(context);
196 }
197 defaultProvider.init(deviceService, createProviderService(defaultProvider),
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900198 mastershipService, fallbackMeterPollFrequency);
Andrea Campanellae3708782017-10-16 16:00:21 +0200199 }
200
alshabib1d2bc402015-07-31 17:04:11 -0700201 @Deactivate
202 public void deactivate() {
Andrea Campanellae3708782017-10-16 16:00:21 +0200203 defaultProvider.terminate();
alshabib58fe6dc2015-08-19 17:16:13 -0700204 store.unsetDelegate(delegate);
Thomas Vachuska11b99fc2017-04-27 12:51:04 -0700205 eventDispatcher.removeSink(MeterEvent.class);
Gamze Abakaf57ef602019-03-11 06:52:48 +0000206 deviceService.removeListener(deviceListener);
Andrea Campanellae3708782017-10-16 16:00:21 +0200207 cfgService.unregisterProperties(getClass(), false);
pierventre1b8afbc2020-07-13 14:07:05 +0200208 meterInstallers.shutdown();
alshabib1d2bc402015-07-31 17:04:11 -0700209 log.info("Stopped");
210 }
211
Andrea Campanellae3708782017-10-16 16:00:21 +0200212 /**
213 * Extracts properties from the component configuration context.
214 *
215 * @param context the component context
216 */
217 private void readComponentConfiguration(ComponentContext context) {
218 Dictionary<?, ?> properties = context.getProperties();
Gamze Abakaf57ef602019-03-11 06:52:48 +0000219 Boolean flag;
220
221 flag = Tools.isPropertyEnabled(properties, MM_PURGE_ON_DISCONNECTION);
222 if (flag == null) {
223 log.info("PurgeOnDisconnection is not configured," +
Andrea Campanella32a9c0b2020-03-27 12:53:46 +0100224 "using current value of {}", purgeOnDisconnection);
Gamze Abakaf57ef602019-03-11 06:52:48 +0000225 } else {
226 purgeOnDisconnection = flag;
227 log.info("Configured. PurgeOnDisconnection is {}",
Andrea Campanella32a9c0b2020-03-27 12:53:46 +0100228 purgeOnDisconnection ? "enabled" : "disabled");
Gamze Abakaf57ef602019-03-11 06:52:48 +0000229 }
Andrea Campanellae3708782017-10-16 16:00:21 +0200230
pierventre3b39bd82021-08-18 09:40:14 +0200231 flag = Tools.isPropertyEnabled(properties, MM_USER_DEFINED_INDEX);
232 boolean enable = flag == null ? userDefinedIndex : flag;
233 userDefinedIndex = store.userDefinedIndexMode(enable);
234 log.info("UserDefinedIndex is {}", userDefinedIndex ? "enabled" : "disabled");
235
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700236 String s = get(properties, MM_FALLBACK_METER_POLL_FREQUENCY);
Andrea Campanellae3708782017-10-16 16:00:21 +0200237 try {
Ray Milkeyd04e2272018-10-16 18:20:18 -0700238 fallbackMeterPollFrequency = isNullOrEmpty(s) ?
239 MM_FALLBACK_METER_POLL_FREQUENCY_DEFAULT : Integer.parseInt(s);
Andrea Campanellae3708782017-10-16 16:00:21 +0200240 } catch (NumberFormatException e) {
Ray Milkeyd04e2272018-10-16 18:20:18 -0700241 fallbackMeterPollFrequency = MM_FALLBACK_METER_POLL_FREQUENCY_DEFAULT;
Andrea Campanellae3708782017-10-16 16:00:21 +0200242 }
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700243
244 s = get(properties, MM_NUM_THREADS);
245 try {
246 numThreads = isNullOrEmpty(s) ? MM_NUM_THREADS_DEFAULT : Integer.parseInt(s);
247 } catch (NumberFormatException e) {
248 numThreads = MM_NUM_THREADS_DEFAULT;
249 }
pierventre1b8afbc2020-07-13 14:07:05 +0200250 if (meterInstallers != null) {
251 meterInstallers.shutdown();
252 }
253 meterInstallers = newPredictableExecutor(numThreads,
254 groupedThreads(GROUP_THREAD_NAME, WORKER_PATTERN, log));
Andrea Campanellae3708782017-10-16 16:00:21 +0200255 }
256
257 @Override
258 protected MeterProvider defaultProvider() {
259 return defaultProvider;
260 }
261
alshabib1d2bc402015-07-31 17:04:11 -0700262 @Override
263 protected MeterProviderService createProviderService(MeterProvider provider) {
264 return new InternalMeterProviderService(provider);
265 }
266
267 @Override
alshabibe1248b62015-08-20 17:21:55 -0700268 public Meter submit(MeterRequest request) {
柯志勇10068695d709dba2018-10-23 18:35:49 +0800269 checkNotNull(request, "request cannot be null.");
Wailok Shum79919522021-08-22 19:35:34 +0800270 MeterCellId cellId;
271 if (request.index().isPresent()) {
pierventre3b39bd82021-08-18 09:40:14 +0200272 checkArgument(userDefinedIndex, "Index cannot be provided when userDefinedIndex mode is disabled");
Wailok Shum79919522021-08-22 19:35:34 +0800273 // User provides index
274 if (request.scope().isGlobal()) {
275 cellId = MeterId.meterId(request.index().get());
276 } else {
277 cellId = PiMeterCellId.ofIndirect(
278 PiMeterId.of(request.scope().id()), request.index().get());
279 }
280 } else {
pierventre3b39bd82021-08-18 09:40:14 +0200281 checkArgument(!userDefinedIndex, "Index cannot be allocated when userDefinedIndex mode is enabled");
Wailok Shum79919522021-08-22 19:35:34 +0800282 // Allocate an id
283 cellId = allocateMeterId(request.deviceId(), request.scope());
284 }
alshabibe1248b62015-08-20 17:21:55 -0700285 Meter.Builder mBuilder = DefaultMeter.builder()
286 .forDevice(request.deviceId())
287 .fromApp(request.appId())
288 .withBands(request.bands())
Wailok Shum79919522021-08-22 19:35:34 +0800289 .withCellId(cellId)
alshabibe1248b62015-08-20 17:21:55 -0700290 .withUnit(request.unit());
alshabibe1248b62015-08-20 17:21:55 -0700291 if (request.isBurst()) {
292 mBuilder.burst();
293 }
Andrea Campanella5bdbe432021-05-03 15:59:19 +0200294 if (request.annotations() != null && !request.annotations().keys().isEmpty()) {
295 mBuilder.withAnnotations(request.annotations());
296 }
alshabibe1248b62015-08-20 17:21:55 -0700297 DefaultMeter m = (DefaultMeter) mBuilder.build();
pierventre1b8afbc2020-07-13 14:07:05 +0200298 // Meter installation logic (happy ending case)
299 // PENDING -> stats -> ADDED -> future completes
alshabib7bb05012015-08-05 10:15:09 -0700300 m.setState(MeterState.PENDING_ADD);
alshabibeadfc8e2015-08-18 15:40:46 -0700301 store.storeMeter(m).whenComplete((result, error) ->
alshabibe1248b62015-08-20 17:21:55 -0700302 onComplete.accept(request, result, error));
303 return m;
alshabib1d2bc402015-07-31 17:04:11 -0700304 }
305
306 @Override
alshabibe1248b62015-08-20 17:21:55 -0700307 public void withdraw(MeterRequest request, MeterId meterId) {
Wailok Shum79919522021-08-22 19:35:34 +0800308 withdraw(request, (MeterCellId) meterId);
309 }
310
311 @Override
312 public void withdraw(MeterRequest request, MeterCellId meterCellId) {
柯志勇10068695d709dba2018-10-23 18:35:49 +0800313 checkNotNull(request, "request cannot be null.");
alshabibe1248b62015-08-20 17:21:55 -0700314 Meter.Builder mBuilder = DefaultMeter.builder()
315 .forDevice(request.deviceId())
316 .fromApp(request.appId())
317 .withBands(request.bands())
Wailok Shum79919522021-08-22 19:35:34 +0800318 .withCellId(meterCellId)
alshabibe1248b62015-08-20 17:21:55 -0700319 .withUnit(request.unit());
alshabib1d2bc402015-07-31 17:04:11 -0700320
alshabibe1248b62015-08-20 17:21:55 -0700321 if (request.isBurst()) {
322 mBuilder.burst();
323 }
alshabibe1248b62015-08-20 17:21:55 -0700324 DefaultMeter m = (DefaultMeter) mBuilder.build();
pierventre1b8afbc2020-07-13 14:07:05 +0200325 // Meter removal logic (happy ending case)
326 // PENDING -> stats -> removed from the map -> future completes
327 // There is no transition to the REMOVED state
alshabib7bb05012015-08-05 10:15:09 -0700328 m.setState(MeterState.PENDING_REMOVE);
alshabibeadfc8e2015-08-18 15:40:46 -0700329 store.deleteMeter(m).whenComplete((result, error) ->
alshabibe1248b62015-08-20 17:21:55 -0700330 onComplete.accept(request, result, error));
alshabib1d2bc402015-07-31 17:04:11 -0700331 }
332
333 @Override
alshabib70aaa1b2015-09-25 14:30:59 -0700334 public Meter getMeter(DeviceId deviceId, MeterId id) {
Wailok Shum79919522021-08-22 19:35:34 +0800335 return getMeter(deviceId, (MeterCellId) id);
336 }
337
338 @Override
339 public Meter getMeter(DeviceId deviceId, MeterCellId id) {
alshabib70aaa1b2015-09-25 14:30:59 -0700340 MeterKey key = MeterKey.key(deviceId, id);
341 return store.getMeter(key);
alshabib1d2bc402015-07-31 17:04:11 -0700342 }
343
344 @Override
Jian Li1932b932016-01-03 00:35:40 -0800345 public Collection<Meter> getMeters(DeviceId deviceId) {
pierventrec0914ec2021-08-27 15:25:02 +0200346 return store.getAllMeters(deviceId);
347 }
348
349 @Override
350 public Collection<Meter> getMeters(DeviceId deviceId, MeterScope scope) {
351 return store.getAllMeters(deviceId, scope);
Jian Li1932b932016-01-03 00:35:40 -0800352 }
353
354 @Override
alshabib58fe6dc2015-08-19 17:16:13 -0700355 public Collection<Meter> getAllMeters() {
356 return store.getAllMeters();
357 }
358
Pier Luigibdcd9672017-10-13 13:54:48 +0200359 @Override
360 public MeterId allocateMeterId(DeviceId deviceId) {
pierventre1b8afbc2020-07-13 14:07:05 +0200361 // We delegate directly to the store
Pier Luigif094c612017-10-14 12:15:02 +0200362 return store.allocateMeterId(deviceId);
alshabib1d2bc402015-07-31 17:04:11 -0700363 }
364
Wailok Shum79919522021-08-22 19:35:34 +0800365 private MeterCellId allocateMeterId(DeviceId deviceId, MeterScope scope) {
366 return store.allocateMeterId(deviceId, scope);
367 }
368
Pier Luigibdcd9672017-10-13 13:54:48 +0200369 @Override
370 public void freeMeterId(DeviceId deviceId, MeterId meterId) {
pierventre1b8afbc2020-07-13 14:07:05 +0200371 // We delegate directly to the store
Pier Luigibdcd9672017-10-13 13:54:48 +0200372 store.freeMeterId(deviceId, meterId);
373 }
374
Andrea Campanella23250502020-05-13 15:36:57 +0200375 @Override
376 public void purgeMeters(DeviceId deviceId) {
pierventre1b8afbc2020-07-13 14:07:05 +0200377 // We delegate directly to the store
Andrea Campanella23250502020-05-13 15:36:57 +0200378 store.purgeMeter(deviceId);
379 }
380
Daniele Moro43ac2892021-07-15 17:02:59 +0200381 @Override
382 public void purgeMeters(DeviceId deviceId, ApplicationId appId) {
383 store.purgeMeters(deviceId, appId);
384 }
385
alshabib1d2bc402015-07-31 17:04:11 -0700386 private class InternalMeterProviderService
387 extends AbstractProviderService<MeterProvider>
388 implements MeterProviderService {
389
390 /**
391 * Creates a provider service on behalf of the specified provider.
392 *
393 * @param provider provider to which this service is being issued
394 */
395 protected InternalMeterProviderService(MeterProvider provider) {
396 super(provider);
397 }
398
399 @Override
alshabib7bb05012015-08-05 10:15:09 -0700400 public void meterOperationFailed(MeterOperation operation,
401 MeterFailReason reason) {
402 store.failedMeter(operation, reason);
alshabib1d2bc402015-07-31 17:04:11 -0700403 }
404
405 @Override
406 public void pushMeterMetrics(DeviceId deviceId, Collection<Meter> meterEntries) {
pierventre1b8afbc2020-07-13 14:07:05 +0200407 // Each update on the store is reflected on this collection
Jordi Ortiz9287b632017-06-22 11:01:37 +0200408 Collection<Meter> allMeters = store.getAllMeters(deviceId);
alshabib5eb79392015-08-19 18:09:55 -0700409
Wailok Shum79919522021-08-22 19:35:34 +0800410 Map<MeterCellId, Meter> meterEntriesMap = meterEntries.stream()
411 .collect(Collectors.toMap(Meter::meterCellId, Meter -> Meter));
Jordi Ortiz58896912017-03-06 14:51:05 +0100412
Jordi Ortiz205af452017-06-22 14:25:04 +0200413 // Look for meters defined in onos and missing in the device (restore)
Jordi Ortiz9287b632017-06-22 11:01:37 +0200414 allMeters.stream().forEach(m -> {
415 if ((m.state().equals(MeterState.PENDING_ADD) ||
416 m.state().equals(MeterState.ADDED)) &&
Wailok Shum79919522021-08-22 19:35:34 +0800417 !meterEntriesMap.containsKey(m.meterCellId())) {
Jordi Ortiz58896912017-03-06 14:51:05 +0100418 // The meter is missing in the device. Reinstall!
Jordi Ortiz205af452017-06-22 14:25:04 +0200419 log.debug("Adding meter missing in device {} {}", deviceId, m);
pierventre1b8afbc2020-07-13 14:07:05 +0200420 // offload the task to avoid the overloading of the sb threads
421 meterInstallers.execute(new MeterInstaller(deviceId, m, MeterOperation.Type.ADD));
Jordi Ortiz58896912017-03-06 14:51:05 +0100422 }
Jordi Ortiz58896912017-03-06 14:51:05 +0100423 });
424
Jordi Ortiz205af452017-06-22 14:25:04 +0200425 // Look for meters defined in the device and not in onos (remove)
426 meterEntriesMap.entrySet().stream()
Wailok Shum79919522021-08-22 19:35:34 +0800427 .filter(md -> !allMeters.stream().anyMatch(m -> m.meterCellId().equals(md.getKey())))
Jordi Ortiz205af452017-06-22 14:25:04 +0200428 .forEach(mio -> {
Jordi Ortiz205af452017-06-22 14:25:04 +0200429 Meter meter = mio.getValue();
Wailok Shum79919522021-08-22 19:35:34 +0800430 // The meter is missing in onos. Uninstall!
431 log.debug("Remove meter in device not in onos {} {}", deviceId, mio.getKey());
432 // offload the task to avoid the overloading of the sb threads
433 meterInstallers.execute(new MeterInstaller(deviceId, meter, MeterOperation.Type.REMOVE));
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900434 });
Jordi Ortiz205af452017-06-22 14:25:04 +0200435
pierventre1b8afbc2020-07-13 14:07:05 +0200436 // Update the meter stats in the store (first time move the state from pending to added)
pierventre44220052020-09-22 12:51:06 +0200437 Collection<Meter> addedMeters = Sets.newHashSet();
alshabib5eb79392015-08-19 18:09:55 -0700438 meterEntries.stream()
Jordi Ortiz9287b632017-06-22 11:01:37 +0200439 .filter(m -> allMeters.stream()
Wailok Shum79919522021-08-22 19:35:34 +0800440 .anyMatch(sm -> sm.deviceId().equals(deviceId) &&
441 sm.meterCellId().equals(m.meterCellId())))
pierventre44220052020-09-22 12:51:06 +0200442 .forEach(m -> {
443 Meter updatedMeter = store.updateMeterState(m);
444 if (updatedMeter != null && updatedMeter.state() == MeterState.ADDED) {
445 addedMeters.add(updatedMeter);
446 }
447 });
448 Collection<Meter> newAllMeters = Sets.newHashSet(allMeters);
449 newAllMeters.removeAll(addedMeters);
alshabib5eb79392015-08-19 18:09:55 -0700450
pierventre44220052020-09-22 12:51:06 +0200451 newAllMeters.forEach(m -> {
pierventre1b8afbc2020-07-13 14:07:05 +0200452 // Remove workflow. Regarding OpenFlow, meters have been removed from
453 // the device but they are still in the store, we will purge them definitely.
454 // Instead, P4Runtime devices will not remove the meter. The first workaround
455 // for P4Runtime will avoid to send a remove op. Then, we reach this point
456 // and we purge the meter from the store
Wailok Shum79919522021-08-22 19:35:34 +0800457 if (m.state() == MeterState.PENDING_REMOVE) {
458 log.debug("Delete meter {} now in store", m.meterCellId());
Wailok Shumf013a782021-07-26 16:51:01 +0800459 store.purgeMeter(m);
alshabib5eb79392015-08-19 18:09:55 -0700460 }
461 });
alshabib1d2bc402015-07-31 17:04:11 -0700462 }
Jordi Ortizaa8de492016-12-01 00:21:36 +0100463
464 @Override
465 public void pushMeterFeatures(DeviceId deviceId, MeterFeatures meterfeatures) {
466 store.storeMeterFeatures(meterfeatures);
467 }
468
469 @Override
Wailok Shumf013a782021-07-26 16:51:01 +0800470 public void pushMeterFeatures(DeviceId deviceId, Collection<MeterFeatures> meterfeatures) {
471 meterfeatures.forEach(mf -> store.storeMeterFeatures(mf));
472 }
473
474 @Override
Jordi Ortizaa8de492016-12-01 00:21:36 +0100475 public void deleteMeterFeatures(DeviceId deviceId) {
476 store.deleteMeterFeatures(deviceId);
477 }
alshabib1d2bc402015-07-31 17:04:11 -0700478 }
479
480 private class InternalMeterStoreDelegate implements MeterStoreDelegate {
481
482 @Override
483 public void notify(MeterEvent event) {
alshabibeadfc8e2015-08-18 15:40:46 -0700484 DeviceId deviceId = event.subject().deviceId();
alshabib7bb05012015-08-05 10:15:09 -0700485 switch (event.type()) {
pierventre1b8afbc2020-07-13 14:07:05 +0200486 // REQ events will trigger a modification in the device.
487 // Mastership check is performed inside the installer
488 // to avoid the blocking of the RAFT threads
alshabibeadfc8e2015-08-18 15:40:46 -0700489 case METER_ADD_REQ:
pierventre1b8afbc2020-07-13 14:07:05 +0200490 meterInstallers.execute(new MeterInstaller(deviceId, event.subject(),
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900491 MeterOperation.Type.ADD));
alshabib7bb05012015-08-05 10:15:09 -0700492 break;
alshabibeadfc8e2015-08-18 15:40:46 -0700493 case METER_REM_REQ:
pierventre1b8afbc2020-07-13 14:07:05 +0200494 meterInstallers.execute(new MeterInstaller(deviceId, event.subject(),
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900495 MeterOperation.Type.REMOVE));
alshabib7bb05012015-08-05 10:15:09 -0700496 break;
pierventre1b8afbc2020-07-13 14:07:05 +0200497 // Following events are forwarded to the apps subscribed for the meter events;
498 // installers are not involved in this task. In this case, the overhead for this op
499 // is almost null. Potentially we can introduce a store delegate thread.
Jordi Ortizdf28ecd2017-03-25 19:22:36 +0100500 case METER_ADDED:
Jordi Ortizdf28ecd2017-03-25 19:22:36 +0100501 case METER_REMOVED:
Gamze Abakadadae722018-09-12 10:55:35 +0000502 case METER_REFERENCE_COUNT_ZERO:
pierventre1b8afbc2020-07-13 14:07:05 +0200503 log.debug("Post {} event {}", event.type(), event.subject());
504 post(event);
Gamze Abakadadae722018-09-12 10:55:35 +0000505 break;
alshabib7bb05012015-08-05 10:15:09 -0700506 default:
507 log.warn("Unknown meter event {}", event.type());
508 }
alshabib1d2bc402015-07-31 17:04:11 -0700509
510 }
511 }
pierventre1b8afbc2020-07-13 14:07:05 +0200512
Jordi Ortiz31d4d382017-07-19 10:52:26 +0200513 /**
514 * Task that passes the meter down to the provider.
515 */
pierventre1b8afbc2020-07-13 14:07:05 +0200516 private class MeterInstaller implements PickyRunnable {
Jordi Ortiz31d4d382017-07-19 10:52:26 +0200517 private final DeviceId deviceId;
518 private final Meter meter;
519 private final MeterOperation.Type op;
520
521 public MeterInstaller(DeviceId deviceId, Meter meter, MeterOperation.Type op) {
522 this.deviceId = checkNotNull(deviceId);
523 this.meter = checkNotNull(meter);
524 this.op = checkNotNull(op);
525 }
526
527 @Override
528 public void run() {
pierventre1b8afbc2020-07-13 14:07:05 +0200529 // Check mastership and eventually execute the op on the device
530 log.debug("Meter {} request {}", op.name().toLowerCase(), meter);
531 NodeId master = mastershipService.getMasterFor(meter.deviceId());
532 if (!Objects.equals(local, master)) {
533 log.trace("Not the master of device {}, skipping installation of the meter {}",
Wailok Shum79919522021-08-22 19:35:34 +0800534 meter.deviceId(), meter.meterCellId());
pierventre1b8afbc2020-07-13 14:07:05 +0200535 return;
536 }
Jordi Ortiz31d4d382017-07-19 10:52:26 +0200537 MeterProvider p = getProvider(this.deviceId);
538 if (p == null) {
539 log.error("Unable to recover {}'s provider", deviceId);
540 return;
541 }
542 p.performMeterOperation(deviceId, new MeterOperation(meter, op));
543 }
pierventre1b8afbc2020-07-13 14:07:05 +0200544
545 @Override
546 public int hint() {
Wailok Shum79919522021-08-22 19:35:34 +0800547 return meter.meterCellId().hashCode();
pierventre1b8afbc2020-07-13 14:07:05 +0200548 }
Jordi Ortiz31d4d382017-07-19 10:52:26 +0200549 }
alshabib1d2bc402015-07-31 17:04:11 -0700550
Gamze Abakaf57ef602019-03-11 06:52:48 +0000551 private class InternalDeviceListener implements DeviceListener {
552
553 @Override
554 public void event(DeviceEvent event) {
pierventre52ef9332021-07-09 22:42:17 +0200555 DeviceId deviceId = event.subject().id();
556 meterInstallers.execute(() -> {
557 switch (event.type()) {
558 case DEVICE_REMOVED:
559 case DEVICE_AVAILABILITY_CHANGED:
560 if (!deviceService.isAvailable(deviceId)) {
561 BasicDeviceConfig cfg = netCfgService.getConfig(deviceId, BasicDeviceConfig.class);
562 //if purgeOnDisconnection is set for the device or it's a global configuration
563 // lets remove the meters.
564 boolean purge = cfg != null && cfg.isPurgeOnDisconnectionConfigured() ?
565 cfg.purgeOnDisconnection() : purgeOnDisconnection;
566 if (purge) {
567 log.info("PurgeOnDisconnection is requested for device {}, " +
568 "removing meters", deviceId);
569 store.purgeMeter(deviceId);
570 }
Gamze Abakaf57ef602019-03-11 06:52:48 +0000571 }
pierventre52ef9332021-07-09 22:42:17 +0200572 break;
573 default:
574 break;
575 }
576 }, deviceId.hashCode());
577
Gamze Abakaf57ef602019-03-11 06:52:48 +0000578 }
579 }
580
alshabib1d2bc402015-07-31 17:04:11 -0700581}