blob: 39ef3d906e21f009b445f03db78ce1ba62ad67cb [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;
Andrea Campanellae3708782017-10-16 16:00:21 +020026import org.onosproject.mastership.MastershipService;
Jian Li1932b932016-01-03 00:35:40 -080027import org.onosproject.net.DeviceId;
Andrea Campanella32a9c0b2020-03-27 12:53:46 +010028import org.onosproject.net.config.NetworkConfigRegistry;
29import org.onosproject.net.config.basics.BasicDeviceConfig;
Gamze Abakaf57ef602019-03-11 06:52:48 +000030import org.onosproject.net.device.DeviceEvent;
31import org.onosproject.net.device.DeviceListener;
Andrea Campanellae3708782017-10-16 16:00:21 +020032import org.onosproject.net.device.DeviceService;
33import org.onosproject.net.driver.DriverService;
alshabib10c810b2015-08-18 16:59:04 -070034import org.onosproject.net.meter.DefaultMeter;
35import org.onosproject.net.meter.Meter;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070036import org.onosproject.net.meter.MeterCellId.MeterCellType;
alshabib10c810b2015-08-18 16:59:04 -070037import org.onosproject.net.meter.MeterEvent;
38import org.onosproject.net.meter.MeterFailReason;
Jordi Ortizaa8de492016-12-01 00:21:36 +010039import org.onosproject.net.meter.MeterFeatures;
alshabib10c810b2015-08-18 16:59:04 -070040import org.onosproject.net.meter.MeterId;
alshabib70aaa1b2015-09-25 14:30:59 -070041import org.onosproject.net.meter.MeterKey;
alshabib10c810b2015-08-18 16:59:04 -070042import org.onosproject.net.meter.MeterListener;
43import org.onosproject.net.meter.MeterOperation;
44import org.onosproject.net.meter.MeterProvider;
45import org.onosproject.net.meter.MeterProviderRegistry;
46import org.onosproject.net.meter.MeterProviderService;
alshabibe1248b62015-08-20 17:21:55 -070047import org.onosproject.net.meter.MeterRequest;
alshabib10c810b2015-08-18 16:59:04 -070048import org.onosproject.net.meter.MeterService;
49import org.onosproject.net.meter.MeterState;
50import org.onosproject.net.meter.MeterStore;
51import org.onosproject.net.meter.MeterStoreDelegate;
52import org.onosproject.net.meter.MeterStoreResult;
alshabib1d2bc402015-07-31 17:04:11 -070053import org.onosproject.net.provider.AbstractListenerProviderRegistry;
54import org.onosproject.net.provider.AbstractProviderService;
Andrea Campanellae3708782017-10-16 16:00:21 +020055import org.osgi.service.component.ComponentContext;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070056import org.osgi.service.component.annotations.Activate;
57import org.osgi.service.component.annotations.Component;
58import org.osgi.service.component.annotations.Deactivate;
59import org.osgi.service.component.annotations.Modified;
60import org.osgi.service.component.annotations.Reference;
61import org.osgi.service.component.annotations.ReferenceCardinality;
alshabib1d2bc402015-07-31 17:04:11 -070062import org.slf4j.Logger;
63
64import java.util.Collection;
Andrea Campanellae3708782017-10-16 16:00:21 +020065import java.util.Dictionary;
alshabib5eb79392015-08-19 18:09:55 -070066import java.util.Map;
pierventre1b8afbc2020-07-13 14:07:05 +020067import java.util.Objects;
alshabib5eb79392015-08-19 18:09:55 -070068import java.util.stream.Collectors;
alshabib1d2bc402015-07-31 17:04:11 -070069
Jordi Ortiz31d4d382017-07-19 10:52:26 +020070import static com.google.common.base.Preconditions.checkNotNull;
Andrea Campanellae3708782017-10-16 16:00:21 +020071import static com.google.common.base.Strings.isNullOrEmpty;
pierventre1b8afbc2020-07-13 14:07:05 +020072import static org.onlab.util.PredictableExecutor.newPredictableExecutor;
Andrea Campanellae3708782017-10-16 16:00:21 +020073import static org.onlab.util.Tools.get;
Jordi Ortiz31d4d382017-07-19 10:52:26 +020074import static org.onlab.util.Tools.groupedThreads;
Ray Milkeyd04e2272018-10-16 18:20:18 -070075import static org.onosproject.net.OsgiPropertyConstants.MM_FALLBACK_METER_POLL_FREQUENCY;
76import static org.onosproject.net.OsgiPropertyConstants.MM_FALLBACK_METER_POLL_FREQUENCY_DEFAULT;
77import static org.onosproject.net.OsgiPropertyConstants.MM_NUM_THREADS;
78import static org.onosproject.net.OsgiPropertyConstants.MM_NUM_THREADS_DEFAULT;
Gamze Abakaf57ef602019-03-11 06:52:48 +000079import static org.onosproject.net.OsgiPropertyConstants.MM_PURGE_ON_DISCONNECTION;
80import static org.onosproject.net.OsgiPropertyConstants.MM_PURGE_ON_DISCONNECTION_DEFAULT;
alshabib1d2bc402015-07-31 17:04:11 -070081import static org.slf4j.LoggerFactory.getLogger;
82
alshabib1d2bc402015-07-31 17:04:11 -070083/**
84 * Provides implementation of the meter service APIs.
85 */
Ray Milkeyd04e2272018-10-16 18:20:18 -070086@Component(
Gamze Abakaf57ef602019-03-11 06:52:48 +000087 immediate = true,
88 service = {
89 MeterService.class,
90 MeterProviderRegistry.class
91 },
92 property = {
93 MM_NUM_THREADS + ":Integer=" + MM_NUM_THREADS_DEFAULT,
94 MM_FALLBACK_METER_POLL_FREQUENCY + ":Integer=" + MM_FALLBACK_METER_POLL_FREQUENCY_DEFAULT,
95 MM_PURGE_ON_DISCONNECTION + ":Boolean=" + MM_PURGE_ON_DISCONNECTION_DEFAULT,
96 }
Ray Milkeyd04e2272018-10-16 18:20:18 -070097)
Thomas Vachuska11b99fc2017-04-27 12:51:04 -070098public class MeterManager
99 extends AbstractListenerProviderRegistry<MeterEvent, MeterListener, MeterProvider, MeterProviderService>
alshabib1d2bc402015-07-31 17:04:11 -0700100 implements MeterService, MeterProviderRegistry {
pierventre1b8afbc2020-07-13 14:07:05 +0200101 // Installer related objects
102 private PredictableExecutor meterInstallers;
Jordi Ortiz31d4d382017-07-19 10:52:26 +0200103 private static final String WORKER_PATTERN = "installer-%d";
104 private static final String GROUP_THREAD_NAME = "onos/meter";
pierventre1b8afbc2020-07-13 14:07:05 +0200105 // Logging facility, meter store delegate and listener for device events.
alshabib1d2bc402015-07-31 17:04:11 -0700106 private final Logger log = getLogger(getClass());
107 private final MeterStoreDelegate delegate = new InternalMeterStoreDelegate();
Gamze Abakaf57ef602019-03-11 06:52:48 +0000108 private final DeviceListener deviceListener = new InternalDeviceListener();
alshabib1d2bc402015-07-31 17:04:11 -0700109
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700110 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigif094c612017-10-14 12:15:02 +0200111 private MeterStore store;
alshabib1d2bc402015-07-31 17:04:11 -0700112
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700113 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andrea Campanellae3708782017-10-16 16:00:21 +0200114 protected DriverService driverService;
115
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700116 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andrea Campanellae3708782017-10-16 16:00:21 +0200117 protected DeviceService deviceService;
118
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700119 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andrea Campanellae3708782017-10-16 16:00:21 +0200120 protected ComponentConfigService cfgService;
121
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700122 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andrea Campanellae3708782017-10-16 16:00:21 +0200123 protected MastershipService mastershipService;
124
Andrea Campanella32a9c0b2020-03-27 12:53:46 +0100125 @Reference(cardinality = ReferenceCardinality.MANDATORY)
126 protected NetworkConfigRegistry netCfgService;
127
pierventre1b8afbc2020-07-13 14:07:05 +0200128 @Reference(cardinality = ReferenceCardinality.MANDATORY)
129 protected ClusterService clusterService;
130
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700131 /** Number of worker threads. */
pierventre1b8afbc2020-07-13 14:07:05 +0200132 // TODO Set 0 to use the available processors
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700133 private int numThreads = MM_NUM_THREADS_DEFAULT;
134
135 /** Frequency (in seconds) for polling meters via fallback provider. */
Ray Milkeyd04e2272018-10-16 18:20:18 -0700136 private int fallbackMeterPollFrequency = MM_FALLBACK_METER_POLL_FREQUENCY_DEFAULT;
Andrea Campanellae3708782017-10-16 16:00:21 +0200137
Gamze Abakaf57ef602019-03-11 06:52:48 +0000138 /** Purge entries associated with a device when the device goes offline. */
139 private boolean purgeOnDisconnection = MM_PURGE_ON_DISCONNECTION_DEFAULT;
140
pierventre1b8afbc2020-07-13 14:07:05 +0200141 // Action triggered when the futures related to submit and withdrawal complete
alshabibe1248b62015-08-20 17:21:55 -0700142 private TriConsumer<MeterRequest, MeterStoreResult, Throwable> onComplete;
alshabibeadfc8e2015-08-18 15:40:46 -0700143
pierventre1b8afbc2020-07-13 14:07:05 +0200144 // Meter provider reference
Andrea Campanellae3708782017-10-16 16:00:21 +0200145 private final MeterDriverProvider defaultProvider = new MeterDriverProvider();
146
pierventre1b8afbc2020-07-13 14:07:05 +0200147 // Node id used to verify who is charge of the meter ops
148 // (usually one node can modify the internal state of the device)
149 private NodeId local;
150
alshabib1d2bc402015-07-31 17:04:11 -0700151 @Activate
Andrea Campanellae3708782017-10-16 16:00:21 +0200152 public void activate(ComponentContext context) {
alshabib58fe6dc2015-08-19 17:16:13 -0700153 store.setDelegate(delegate);
Andrea Campanellae3708782017-10-16 16:00:21 +0200154 cfgService.registerProperties(getClass());
Jordi Ortiz3a6f3072016-11-07 10:23:48 +0100155 eventDispatcher.addSink(MeterEvent.class, listenerRegistry);
Gamze Abakaf57ef602019-03-11 06:52:48 +0000156 deviceService.addListener(deviceListener);
pierventre1b8afbc2020-07-13 14:07:05 +0200157 local = clusterService.getLocalNode().id();
158 // Consumer logic is the following:
159 // if there is an exceptional end (storage exception), on error is called
160 // else if there is a reason for the failure, on error is called with the reason
161 // else if the reason is empty, on success is called
162 // In all the cases the meter context code is consumed
Jordi Ortiz3a6f3072016-11-07 10:23:48 +0100163 onComplete = (request, result, error) -> {
alshabibe1248b62015-08-20 17:21:55 -0700164 request.context().ifPresent(c -> {
alshabibeadfc8e2015-08-18 15:40:46 -0700165 if (error != null) {
alshabibe1248b62015-08-20 17:21:55 -0700166 c.onError(request, MeterFailReason.UNKNOWN);
alshabibeadfc8e2015-08-18 15:40:46 -0700167 } else {
168 if (result.reason().isPresent()) {
alshabibe1248b62015-08-20 17:21:55 -0700169 c.onError(request, result.reason().get());
alshabibeadfc8e2015-08-18 15:40:46 -0700170 } else {
alshabibe1248b62015-08-20 17:21:55 -0700171 c.onSuccess(request);
alshabibeadfc8e2015-08-18 15:40:46 -0700172 }
173 }
174 });
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900175 };
Jordi Ortiz31d4d382017-07-19 10:52:26 +0200176
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700177 modified(context);
alshabib1d2bc402015-07-31 17:04:11 -0700178 log.info("Started");
179 }
180
Andrea Campanellae3708782017-10-16 16:00:21 +0200181 @Modified
182 public void modified(ComponentContext context) {
183 if (context != null) {
184 readComponentConfiguration(context);
185 }
186 defaultProvider.init(deviceService, createProviderService(defaultProvider),
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900187 mastershipService, fallbackMeterPollFrequency);
Andrea Campanellae3708782017-10-16 16:00:21 +0200188 }
189
alshabib1d2bc402015-07-31 17:04:11 -0700190 @Deactivate
191 public void deactivate() {
Andrea Campanellae3708782017-10-16 16:00:21 +0200192 defaultProvider.terminate();
alshabib58fe6dc2015-08-19 17:16:13 -0700193 store.unsetDelegate(delegate);
Thomas Vachuska11b99fc2017-04-27 12:51:04 -0700194 eventDispatcher.removeSink(MeterEvent.class);
Gamze Abakaf57ef602019-03-11 06:52:48 +0000195 deviceService.removeListener(deviceListener);
Andrea Campanellae3708782017-10-16 16:00:21 +0200196 cfgService.unregisterProperties(getClass(), false);
pierventre1b8afbc2020-07-13 14:07:05 +0200197 meterInstallers.shutdown();
alshabib1d2bc402015-07-31 17:04:11 -0700198 log.info("Stopped");
199 }
200
Andrea Campanellae3708782017-10-16 16:00:21 +0200201 /**
202 * Extracts properties from the component configuration context.
203 *
204 * @param context the component context
205 */
206 private void readComponentConfiguration(ComponentContext context) {
207 Dictionary<?, ?> properties = context.getProperties();
Gamze Abakaf57ef602019-03-11 06:52:48 +0000208 Boolean flag;
209
210 flag = Tools.isPropertyEnabled(properties, MM_PURGE_ON_DISCONNECTION);
211 if (flag == null) {
212 log.info("PurgeOnDisconnection is not configured," +
Andrea Campanella32a9c0b2020-03-27 12:53:46 +0100213 "using current value of {}", purgeOnDisconnection);
Gamze Abakaf57ef602019-03-11 06:52:48 +0000214 } else {
215 purgeOnDisconnection = flag;
216 log.info("Configured. PurgeOnDisconnection is {}",
Andrea Campanella32a9c0b2020-03-27 12:53:46 +0100217 purgeOnDisconnection ? "enabled" : "disabled");
Gamze Abakaf57ef602019-03-11 06:52:48 +0000218 }
Andrea Campanellae3708782017-10-16 16:00:21 +0200219
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700220 String s = get(properties, MM_FALLBACK_METER_POLL_FREQUENCY);
Andrea Campanellae3708782017-10-16 16:00:21 +0200221 try {
Ray Milkeyd04e2272018-10-16 18:20:18 -0700222 fallbackMeterPollFrequency = isNullOrEmpty(s) ?
223 MM_FALLBACK_METER_POLL_FREQUENCY_DEFAULT : Integer.parseInt(s);
Andrea Campanellae3708782017-10-16 16:00:21 +0200224 } catch (NumberFormatException e) {
Ray Milkeyd04e2272018-10-16 18:20:18 -0700225 fallbackMeterPollFrequency = MM_FALLBACK_METER_POLL_FREQUENCY_DEFAULT;
Andrea Campanellae3708782017-10-16 16:00:21 +0200226 }
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700227
228 s = get(properties, MM_NUM_THREADS);
229 try {
230 numThreads = isNullOrEmpty(s) ? MM_NUM_THREADS_DEFAULT : Integer.parseInt(s);
231 } catch (NumberFormatException e) {
232 numThreads = MM_NUM_THREADS_DEFAULT;
233 }
pierventre1b8afbc2020-07-13 14:07:05 +0200234 if (meterInstallers != null) {
235 meterInstallers.shutdown();
236 }
237 meterInstallers = newPredictableExecutor(numThreads,
238 groupedThreads(GROUP_THREAD_NAME, WORKER_PATTERN, log));
Andrea Campanellae3708782017-10-16 16:00:21 +0200239 }
240
241 @Override
242 protected MeterProvider defaultProvider() {
243 return defaultProvider;
244 }
245
alshabib1d2bc402015-07-31 17:04:11 -0700246 @Override
247 protected MeterProviderService createProviderService(MeterProvider provider) {
248 return new InternalMeterProviderService(provider);
249 }
250
251 @Override
alshabibe1248b62015-08-20 17:21:55 -0700252 public Meter submit(MeterRequest request) {
柯志勇10068695d709dba2018-10-23 18:35:49 +0800253 checkNotNull(request, "request cannot be null.");
pierventre1b8afbc2020-07-13 14:07:05 +0200254 // Allocate an id and then submit the request
alshabib70aaa1b2015-09-25 14:30:59 -0700255 MeterId id = allocateMeterId(request.deviceId());
alshabibe1248b62015-08-20 17:21:55 -0700256 Meter.Builder mBuilder = DefaultMeter.builder()
257 .forDevice(request.deviceId())
258 .fromApp(request.appId())
259 .withBands(request.bands())
Gamze Abaka65f27f12018-07-09 06:40:24 +0000260 .withCellId(id)
alshabibe1248b62015-08-20 17:21:55 -0700261 .withUnit(request.unit());
alshabibe1248b62015-08-20 17:21:55 -0700262 if (request.isBurst()) {
263 mBuilder.burst();
264 }
Andrea Campanella5bdbe432021-05-03 15:59:19 +0200265 if (request.annotations() != null && !request.annotations().keys().isEmpty()) {
266 mBuilder.withAnnotations(request.annotations());
267 }
alshabibe1248b62015-08-20 17:21:55 -0700268 DefaultMeter m = (DefaultMeter) mBuilder.build();
pierventre1b8afbc2020-07-13 14:07:05 +0200269 // Meter installation logic (happy ending case)
270 // PENDING -> stats -> ADDED -> future completes
alshabib7bb05012015-08-05 10:15:09 -0700271 m.setState(MeterState.PENDING_ADD);
alshabibeadfc8e2015-08-18 15:40:46 -0700272 store.storeMeter(m).whenComplete((result, error) ->
alshabibe1248b62015-08-20 17:21:55 -0700273 onComplete.accept(request, result, error));
274 return m;
alshabib1d2bc402015-07-31 17:04:11 -0700275 }
276
277 @Override
alshabibe1248b62015-08-20 17:21:55 -0700278 public void withdraw(MeterRequest request, MeterId meterId) {
柯志勇10068695d709dba2018-10-23 18:35:49 +0800279 checkNotNull(request, "request cannot be null.");
alshabibe1248b62015-08-20 17:21:55 -0700280 Meter.Builder mBuilder = DefaultMeter.builder()
281 .forDevice(request.deviceId())
282 .fromApp(request.appId())
283 .withBands(request.bands())
Gamze Abaka65f27f12018-07-09 06:40:24 +0000284 .withCellId(meterId)
alshabibe1248b62015-08-20 17:21:55 -0700285 .withUnit(request.unit());
alshabib1d2bc402015-07-31 17:04:11 -0700286
alshabibe1248b62015-08-20 17:21:55 -0700287 if (request.isBurst()) {
288 mBuilder.burst();
289 }
alshabibe1248b62015-08-20 17:21:55 -0700290 DefaultMeter m = (DefaultMeter) mBuilder.build();
pierventre1b8afbc2020-07-13 14:07:05 +0200291 // Meter removal logic (happy ending case)
292 // PENDING -> stats -> removed from the map -> future completes
293 // There is no transition to the REMOVED state
alshabib7bb05012015-08-05 10:15:09 -0700294 m.setState(MeterState.PENDING_REMOVE);
alshabibeadfc8e2015-08-18 15:40:46 -0700295 store.deleteMeter(m).whenComplete((result, error) ->
alshabibe1248b62015-08-20 17:21:55 -0700296 onComplete.accept(request, result, error));
alshabib1d2bc402015-07-31 17:04:11 -0700297 }
298
299 @Override
alshabib70aaa1b2015-09-25 14:30:59 -0700300 public Meter getMeter(DeviceId deviceId, MeterId id) {
301 MeterKey key = MeterKey.key(deviceId, id);
302 return store.getMeter(key);
alshabib1d2bc402015-07-31 17:04:11 -0700303 }
304
305 @Override
Jian Li1932b932016-01-03 00:35:40 -0800306 public Collection<Meter> getMeters(DeviceId deviceId) {
307 return store.getAllMeters().stream().filter(m ->
308 m.deviceId().equals(deviceId)).collect(Collectors.toList());
309 }
310
311 @Override
alshabib58fe6dc2015-08-19 17:16:13 -0700312 public Collection<Meter> getAllMeters() {
313 return store.getAllMeters();
314 }
315
Pier Luigibdcd9672017-10-13 13:54:48 +0200316 @Override
317 public MeterId allocateMeterId(DeviceId deviceId) {
pierventre1b8afbc2020-07-13 14:07:05 +0200318 // We delegate directly to the store
Pier Luigif094c612017-10-14 12:15:02 +0200319 return store.allocateMeterId(deviceId);
alshabib1d2bc402015-07-31 17:04:11 -0700320 }
321
Pier Luigibdcd9672017-10-13 13:54:48 +0200322 @Override
323 public void freeMeterId(DeviceId deviceId, MeterId meterId) {
pierventre1b8afbc2020-07-13 14:07:05 +0200324 // We delegate directly to the store
Pier Luigibdcd9672017-10-13 13:54:48 +0200325 store.freeMeterId(deviceId, meterId);
326 }
327
Andrea Campanella23250502020-05-13 15:36:57 +0200328 @Override
329 public void purgeMeters(DeviceId deviceId) {
pierventre1b8afbc2020-07-13 14:07:05 +0200330 // We delegate directly to the store
Andrea Campanella23250502020-05-13 15:36:57 +0200331 store.purgeMeter(deviceId);
332 }
333
alshabib1d2bc402015-07-31 17:04:11 -0700334 private class InternalMeterProviderService
335 extends AbstractProviderService<MeterProvider>
336 implements MeterProviderService {
337
338 /**
339 * Creates a provider service on behalf of the specified provider.
340 *
341 * @param provider provider to which this service is being issued
342 */
343 protected InternalMeterProviderService(MeterProvider provider) {
344 super(provider);
345 }
346
347 @Override
alshabib7bb05012015-08-05 10:15:09 -0700348 public void meterOperationFailed(MeterOperation operation,
349 MeterFailReason reason) {
350 store.failedMeter(operation, reason);
alshabib1d2bc402015-07-31 17:04:11 -0700351 }
352
353 @Override
354 public void pushMeterMetrics(DeviceId deviceId, Collection<Meter> meterEntries) {
pierventre1b8afbc2020-07-13 14:07:05 +0200355 // Each update on the store is reflected on this collection
Jordi Ortiz9287b632017-06-22 11:01:37 +0200356 Collection<Meter> allMeters = store.getAllMeters(deviceId);
alshabib5eb79392015-08-19 18:09:55 -0700357
Jordi Ortiz58896912017-03-06 14:51:05 +0100358 Map<MeterId, Meter> meterEntriesMap = meterEntries.stream()
359 .collect(Collectors.toMap(Meter::id, Meter -> Meter));
360
Jordi Ortiz205af452017-06-22 14:25:04 +0200361 // Look for meters defined in onos and missing in the device (restore)
Jordi Ortiz9287b632017-06-22 11:01:37 +0200362 allMeters.stream().forEach(m -> {
363 if ((m.state().equals(MeterState.PENDING_ADD) ||
364 m.state().equals(MeterState.ADDED)) &&
365 !meterEntriesMap.containsKey(m.id())) {
Jordi Ortiz58896912017-03-06 14:51:05 +0100366 // The meter is missing in the device. Reinstall!
Jordi Ortiz205af452017-06-22 14:25:04 +0200367 log.debug("Adding meter missing in device {} {}", deviceId, m);
pierventre1b8afbc2020-07-13 14:07:05 +0200368 // offload the task to avoid the overloading of the sb threads
369 meterInstallers.execute(new MeterInstaller(deviceId, m, MeterOperation.Type.ADD));
Jordi Ortiz58896912017-03-06 14:51:05 +0100370 }
Jordi Ortiz58896912017-03-06 14:51:05 +0100371 });
372
Jordi Ortiz205af452017-06-22 14:25:04 +0200373 // Look for meters defined in the device and not in onos (remove)
374 meterEntriesMap.entrySet().stream()
375 .filter(md -> !allMeters.stream().anyMatch(m -> m.id().equals(md.getKey())))
376 .forEach(mio -> {
Jordi Ortiz205af452017-06-22 14:25:04 +0200377 Meter meter = mio.getValue();
pierventre1b8afbc2020-07-13 14:07:05 +0200378 // FIXME: Removing a meter is meaningful for OpenFlow, but not for P4Runtime.
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900379 // In P4Runtime meter cells cannot be removed. For the
380 // moment, we make the distinction between OpenFlow and
381 // P4Runtime by looking at the MeterCellType (always
382 // INDEX for OpenFlow).
383 if (meter.meterCellId().type() == MeterCellType.INDEX) {
384 // The meter is missing in onos. Uninstall!
385 log.debug("Remove meter in device not in onos {} {}", deviceId, mio.getKey());
pierventre1b8afbc2020-07-13 14:07:05 +0200386 // offload the task to avoid the overloading of the sb threads
387 meterInstallers.execute(new MeterInstaller(deviceId, meter, MeterOperation.Type.REMOVE));
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900388 }
389 });
Jordi Ortiz205af452017-06-22 14:25:04 +0200390
pierventre1b8afbc2020-07-13 14:07:05 +0200391 // Update the meter stats in the store (first time move the state from pending to added)
pierventre44220052020-09-22 12:51:06 +0200392 Collection<Meter> addedMeters = Sets.newHashSet();
alshabib5eb79392015-08-19 18:09:55 -0700393 meterEntries.stream()
Jordi Ortiz9287b632017-06-22 11:01:37 +0200394 .filter(m -> allMeters.stream()
395 .anyMatch(sm -> sm.deviceId().equals(deviceId) && sm.id().equals(m.id())))
pierventre44220052020-09-22 12:51:06 +0200396 .forEach(m -> {
397 Meter updatedMeter = store.updateMeterState(m);
398 if (updatedMeter != null && updatedMeter.state() == MeterState.ADDED) {
399 addedMeters.add(updatedMeter);
400 }
401 });
402 Collection<Meter> newAllMeters = Sets.newHashSet(allMeters);
403 newAllMeters.removeAll(addedMeters);
alshabib5eb79392015-08-19 18:09:55 -0700404
pierventre44220052020-09-22 12:51:06 +0200405 newAllMeters.forEach(m -> {
pierventre1b8afbc2020-07-13 14:07:05 +0200406 // FIXME: Installing a meter is meaningful for OpenFlow, but not for P4Runtime.
407 // It looks like this flow is used only for p4runtime to emulate the installation
408 // since meters are already instantiated - we need just modify the params.
Saurav Das381c7ca2020-09-21 15:26:50 -0700409 if (m.state() == MeterState.PENDING_ADD && m.meterCellId().type() != MeterCellType.INDEX) {
pierventre1b8afbc2020-07-13 14:07:05 +0200410 // offload the task to avoid the overloading of the sb threads
pierventre44220052020-09-22 12:51:06 +0200411 log.debug("Modify meter {} in device {}", m.id(), deviceId);
pierventre1b8afbc2020-07-13 14:07:05 +0200412 meterInstallers.execute(new MeterInstaller(m.deviceId(), m, MeterOperation.Type.MODIFY));
413 // Remove workflow. Regarding OpenFlow, meters have been removed from
414 // the device but they are still in the store, we will purge them definitely.
415 // Instead, P4Runtime devices will not remove the meter. The first workaround
416 // for P4Runtime will avoid to send a remove op. Then, we reach this point
417 // and we purge the meter from the store
Konstantinos Kanonakisa45755d2016-03-14 11:31:23 -0500418 } else if (m.state() == MeterState.PENDING_REMOVE) {
pierventre44220052020-09-22 12:51:06 +0200419 log.debug("Delete meter {} now in store", m.id());
alshabib5eb79392015-08-19 18:09:55 -0700420 store.deleteMeterNow(m);
421 }
422 });
alshabib1d2bc402015-07-31 17:04:11 -0700423 }
Jordi Ortizaa8de492016-12-01 00:21:36 +0100424
425 @Override
426 public void pushMeterFeatures(DeviceId deviceId, MeterFeatures meterfeatures) {
427 store.storeMeterFeatures(meterfeatures);
428 }
429
430 @Override
431 public void deleteMeterFeatures(DeviceId deviceId) {
432 store.deleteMeterFeatures(deviceId);
433 }
alshabib1d2bc402015-07-31 17:04:11 -0700434 }
435
436 private class InternalMeterStoreDelegate implements MeterStoreDelegate {
437
438 @Override
439 public void notify(MeterEvent event) {
alshabibeadfc8e2015-08-18 15:40:46 -0700440 DeviceId deviceId = event.subject().deviceId();
alshabib7bb05012015-08-05 10:15:09 -0700441 switch (event.type()) {
pierventre1b8afbc2020-07-13 14:07:05 +0200442 // REQ events will trigger a modification in the device.
443 // Mastership check is performed inside the installer
444 // to avoid the blocking of the RAFT threads
alshabibeadfc8e2015-08-18 15:40:46 -0700445 case METER_ADD_REQ:
pierventre1b8afbc2020-07-13 14:07:05 +0200446 meterInstallers.execute(new MeterInstaller(deviceId, event.subject(),
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900447 MeterOperation.Type.ADD));
alshabib7bb05012015-08-05 10:15:09 -0700448 break;
alshabibeadfc8e2015-08-18 15:40:46 -0700449 case METER_REM_REQ:
pierventre1b8afbc2020-07-13 14:07:05 +0200450 meterInstallers.execute(new MeterInstaller(deviceId, event.subject(),
Frank Wangd7e3b4b2017-09-24 13:37:54 +0900451 MeterOperation.Type.REMOVE));
alshabib7bb05012015-08-05 10:15:09 -0700452 break;
pierventre1b8afbc2020-07-13 14:07:05 +0200453 // Following events are forwarded to the apps subscribed for the meter events;
454 // installers are not involved in this task. In this case, the overhead for this op
455 // is almost null. Potentially we can introduce a store delegate thread.
Jordi Ortizdf28ecd2017-03-25 19:22:36 +0100456 case METER_ADDED:
Jordi Ortizdf28ecd2017-03-25 19:22:36 +0100457 case METER_REMOVED:
Gamze Abakadadae722018-09-12 10:55:35 +0000458 case METER_REFERENCE_COUNT_ZERO:
pierventre1b8afbc2020-07-13 14:07:05 +0200459 log.debug("Post {} event {}", event.type(), event.subject());
460 post(event);
Gamze Abakadadae722018-09-12 10:55:35 +0000461 break;
alshabib7bb05012015-08-05 10:15:09 -0700462 default:
463 log.warn("Unknown meter event {}", event.type());
464 }
alshabib1d2bc402015-07-31 17:04:11 -0700465
466 }
467 }
pierventre1b8afbc2020-07-13 14:07:05 +0200468
Jordi Ortiz31d4d382017-07-19 10:52:26 +0200469 /**
470 * Task that passes the meter down to the provider.
471 */
pierventre1b8afbc2020-07-13 14:07:05 +0200472 private class MeterInstaller implements PickyRunnable {
Jordi Ortiz31d4d382017-07-19 10:52:26 +0200473 private final DeviceId deviceId;
474 private final Meter meter;
475 private final MeterOperation.Type op;
476
477 public MeterInstaller(DeviceId deviceId, Meter meter, MeterOperation.Type op) {
478 this.deviceId = checkNotNull(deviceId);
479 this.meter = checkNotNull(meter);
480 this.op = checkNotNull(op);
481 }
482
483 @Override
484 public void run() {
pierventre1b8afbc2020-07-13 14:07:05 +0200485 // Check mastership and eventually execute the op on the device
486 log.debug("Meter {} request {}", op.name().toLowerCase(), meter);
487 NodeId master = mastershipService.getMasterFor(meter.deviceId());
488 if (!Objects.equals(local, master)) {
489 log.trace("Not the master of device {}, skipping installation of the meter {}",
490 meter.deviceId(), meter.id());
491 return;
492 }
Jordi Ortiz31d4d382017-07-19 10:52:26 +0200493 MeterProvider p = getProvider(this.deviceId);
494 if (p == null) {
495 log.error("Unable to recover {}'s provider", deviceId);
496 return;
497 }
498 p.performMeterOperation(deviceId, new MeterOperation(meter, op));
499 }
pierventre1b8afbc2020-07-13 14:07:05 +0200500
501 @Override
502 public int hint() {
503 return meter.id().hashCode();
504 }
Jordi Ortiz31d4d382017-07-19 10:52:26 +0200505 }
alshabib1d2bc402015-07-31 17:04:11 -0700506
Gamze Abakaf57ef602019-03-11 06:52:48 +0000507 private class InternalDeviceListener implements DeviceListener {
508
509 @Override
510 public void event(DeviceEvent event) {
511 switch (event.type()) {
512 case DEVICE_REMOVED:
513 case DEVICE_AVAILABILITY_CHANGED:
514 DeviceId deviceId = event.subject().id();
515 if (!deviceService.isAvailable(deviceId)) {
Andrea Campanella32a9c0b2020-03-27 12:53:46 +0100516 BasicDeviceConfig cfg = netCfgService.getConfig(deviceId, BasicDeviceConfig.class);
517 //if purgeOnDisconnection is set for the device or it's a global configuration
518 // lets remove the meters.
519 boolean purge = cfg != null && cfg.isPurgeOnDisconnectionConfigured() ?
520 cfg.purgeOnDisconnection() : purgeOnDisconnection;
521 if (purge) {
522 log.info("PurgeOnDisconnection is requested for device {}, " +
523 "removing meters", deviceId);
Gamze Abakaf57ef602019-03-11 06:52:48 +0000524 store.purgeMeter(deviceId);
525 }
526 }
527 break;
528 default:
529 break;
530 }
531 }
532 }
533
alshabib1d2bc402015-07-31 17:04:11 -0700534}