blob: b50adf8310586ad68421dacc63b694f3e50aef92 [file] [log] [blame]
Jon Hallfa132292017-10-24 11:11:24 -07001 /*
2 * Copyright 2014-present Open Networking Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.store.flow.impl;
17
18import java.util.Collections;
19import java.util.Dictionary;
20import java.util.HashSet;
21import java.util.List;
22import java.util.Map;
23import java.util.Objects;
24import java.util.Set;
25import java.util.concurrent.ExecutorService;
26import java.util.concurrent.Executors;
27import java.util.concurrent.ScheduledExecutorService;
28import java.util.concurrent.ScheduledFuture;
29import java.util.concurrent.TimeUnit;
30import java.util.concurrent.atomic.AtomicReference;
31import java.util.stream.Collectors;
32
33import com.google.common.collect.Streams;
34import org.apache.felix.scr.annotations.Activate;
35import org.apache.felix.scr.annotations.Component;
36import org.apache.felix.scr.annotations.Deactivate;
37import org.apache.felix.scr.annotations.Modified;
38import org.apache.felix.scr.annotations.Property;
39import org.apache.felix.scr.annotations.Reference;
40import org.apache.felix.scr.annotations.ReferenceCardinality;
41import org.apache.felix.scr.annotations.Service;
42import org.onlab.util.KryoNamespace;
43import org.onlab.util.Tools;
44import org.onosproject.cfg.ComponentConfigService;
45import org.onosproject.cluster.ClusterService;
46import org.onosproject.cluster.NodeId;
47import org.onosproject.core.CoreService;
48import org.onosproject.core.IdGenerator;
49import org.onosproject.mastership.MastershipService;
50import org.onosproject.net.DeviceId;
51import org.onosproject.net.device.DeviceService;
52import org.onosproject.net.flow.CompletedBatchOperation;
53import org.onosproject.net.flow.DefaultFlowEntry;
54import org.onosproject.net.flow.FlowEntry;
55import org.onosproject.net.flow.FlowEntry.FlowEntryState;
56import org.onosproject.net.flow.FlowId;
57import org.onosproject.net.flow.FlowRule;
58import org.onosproject.net.flow.oldbatch.FlowRuleBatchEntry;
59import org.onosproject.net.flow.oldbatch.FlowRuleBatchEntry.FlowRuleOperation;
60import org.onosproject.net.flow.oldbatch.FlowRuleBatchEvent;
61import org.onosproject.net.flow.oldbatch.FlowRuleBatchOperation;
62import org.onosproject.net.flow.oldbatch.FlowRuleBatchRequest;
63import org.onosproject.net.flow.FlowRuleEvent;
64import org.onosproject.net.flow.FlowRuleEvent.Type;
65import org.onosproject.net.flow.FlowRuleService;
66import org.onosproject.net.flow.FlowRuleStore;
67import org.onosproject.net.flow.FlowRuleStoreDelegate;
68import org.onosproject.net.flow.StoredFlowEntry;
69import org.onosproject.net.flow.TableStatisticsEntry;
70import org.onosproject.persistence.PersistenceService;
71import org.onosproject.store.AbstractStore;
72import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
73import org.onosproject.store.cluster.messaging.ClusterMessage;
74import org.onosproject.store.cluster.messaging.ClusterMessageHandler;
75import org.onosproject.store.flow.ReplicaInfoEvent;
76import org.onosproject.store.flow.ReplicaInfoEventListener;
77import org.onosproject.store.flow.ReplicaInfoService;
78import org.onosproject.store.impl.MastershipBasedTimestamp;
79import org.onosproject.store.serializers.KryoNamespaces;
80import org.onosproject.store.service.EventuallyConsistentMap;
81import org.onosproject.store.service.EventuallyConsistentMapEvent;
82import org.onosproject.store.service.EventuallyConsistentMapListener;
83import org.onosproject.store.service.Serializer;
84import org.onosproject.store.service.StorageService;
85import org.onosproject.store.service.WallClockTimestamp;
86import org.osgi.service.component.ComponentContext;
87import org.slf4j.Logger;
88
89import com.google.common.collect.ImmutableList;
90import com.google.common.collect.Iterables;
91import com.google.common.collect.Maps;
92import com.google.common.collect.Sets;
93import com.google.common.util.concurrent.Futures;
94
95import static com.google.common.base.Strings.isNullOrEmpty;
96import static org.onlab.util.Tools.get;
97import static org.onlab.util.Tools.groupedThreads;
98import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_REMOVED;
99import static org.onosproject.store.flow.ReplicaInfoEvent.Type.MASTER_CHANGED;
100import static org.onosproject.store.flow.impl.ECFlowRuleStoreMessageSubjects.APPLY_BATCH_FLOWS;
101import static org.onosproject.store.flow.impl.ECFlowRuleStoreMessageSubjects.FLOW_TABLE_BACKUP;
102import static org.onosproject.store.flow.impl.ECFlowRuleStoreMessageSubjects.GET_DEVICE_FLOW_ENTRIES;
103import static org.onosproject.store.flow.impl.ECFlowRuleStoreMessageSubjects.GET_FLOW_ENTRY;
104import static org.onosproject.store.flow.impl.ECFlowRuleStoreMessageSubjects.REMOTE_APPLY_COMPLETED;
105import static org.onosproject.store.flow.impl.ECFlowRuleStoreMessageSubjects.REMOVE_FLOW_ENTRY;
106import static org.slf4j.LoggerFactory.getLogger;
107
108/**
109 * Manages inventory of flow rules using a distributed state management protocol.
110 */
Thomas Vachuska71026b22018-01-05 16:01:44 -0800111@Component(immediate = true)
Jon Hallfa132292017-10-24 11:11:24 -0700112@Service
113public class ECFlowRuleStore
114 extends AbstractStore<FlowRuleBatchEvent, FlowRuleStoreDelegate>
115 implements FlowRuleStore {
116
117 private final Logger log = getLogger(getClass());
118
119 private static final int MESSAGE_HANDLER_THREAD_POOL_SIZE = 8;
120 private static final int DEFAULT_MAX_BACKUP_COUNT = 2;
121 private static final boolean DEFAULT_PERSISTENCE_ENABLED = false;
122 private static final int DEFAULT_BACKUP_PERIOD_MILLIS = 2000;
123 private static final long FLOW_RULE_STORE_TIMEOUT_MILLIS = 5000;
124 // number of devices whose flow entries will be backed up in one communication round
125 private static final int FLOW_TABLE_BACKUP_BATCH_SIZE = 1;
126
127 @Property(name = "msgHandlerPoolSize", intValue = MESSAGE_HANDLER_THREAD_POOL_SIZE,
128 label = "Number of threads in the message handler pool")
129 private int msgHandlerPoolSize = MESSAGE_HANDLER_THREAD_POOL_SIZE;
130
131 @Property(name = "backupPeriod", intValue = DEFAULT_BACKUP_PERIOD_MILLIS,
132 label = "Delay in ms between successive backup runs")
133 private int backupPeriod = DEFAULT_BACKUP_PERIOD_MILLIS;
134 @Property(name = "persistenceEnabled", boolValue = false,
135 label = "Indicates whether or not changes in the flow table should be persisted to disk.")
136 private boolean persistenceEnabled = DEFAULT_PERSISTENCE_ENABLED;
137
138 @Property(name = "backupCount", intValue = DEFAULT_MAX_BACKUP_COUNT,
139 label = "Max number of backup copies for each device")
140 private volatile int backupCount = DEFAULT_MAX_BACKUP_COUNT;
141
142 private InternalFlowTable flowTable = new InternalFlowTable();
143
144 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
145 protected ReplicaInfoService replicaInfoManager;
146
147 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
148 protected ClusterCommunicationService clusterCommunicator;
149
150 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
151 protected ClusterService clusterService;
152
153 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
154 protected DeviceService deviceService;
155
156 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
157 protected CoreService coreService;
158
159 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
160 protected ComponentConfigService configService;
161
162 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
163 protected MastershipService mastershipService;
164
165 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
166 protected PersistenceService persistenceService;
167
168 private Map<Long, NodeId> pendingResponses = Maps.newConcurrentMap();
169 private ExecutorService messageHandlingExecutor;
170 private ExecutorService eventHandler;
171
172 private ScheduledFuture<?> backupTask;
173 private final ScheduledExecutorService backupSenderExecutor =
174 Executors.newSingleThreadScheduledExecutor(groupedThreads("onos/flow", "backup-sender", log));
175
176 private EventuallyConsistentMap<DeviceId, List<TableStatisticsEntry>> deviceTableStats;
177 private final EventuallyConsistentMapListener<DeviceId, List<TableStatisticsEntry>> tableStatsListener =
178 new InternalTableStatsListener();
179
180 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
181 protected StorageService storageService;
182
183 protected final Serializer serializer = Serializer.using(KryoNamespaces.API);
184
185 protected final KryoNamespace.Builder serializerBuilder = KryoNamespace.newBuilder()
186 .register(KryoNamespaces.API)
187 .register(MastershipBasedTimestamp.class);
188
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800189 private EventuallyConsistentMap<DeviceId, Integer> flowCounts;
Jon Hallfa132292017-10-24 11:11:24 -0700190
191 private IdGenerator idGenerator;
192 private NodeId local;
193
194 @Activate
195 public void activate(ComponentContext context) {
196 configService.registerProperties(getClass());
197
198 idGenerator = coreService.getIdGenerator(FlowRuleService.FLOW_OP_TOPIC);
199
200 local = clusterService.getLocalNode().id();
201
202 eventHandler = Executors.newSingleThreadExecutor(
203 groupedThreads("onos/flow", "event-handler", log));
204 messageHandlingExecutor = Executors.newFixedThreadPool(
205 msgHandlerPoolSize, groupedThreads("onos/store/flow", "message-handlers", log));
206
207 registerMessageHandlers(messageHandlingExecutor);
208
209 replicaInfoManager.addListener(flowTable);
210 backupTask = backupSenderExecutor.scheduleWithFixedDelay(
211 flowTable::backup,
212 0,
213 backupPeriod,
214 TimeUnit.MILLISECONDS);
215
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800216 flowCounts = storageService.<DeviceId, Integer>eventuallyConsistentMapBuilder()
217 .withName("onos-flow-counts")
218 .withSerializer(serializerBuilder)
219 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
220 .withTimestampProvider((k, v) -> new WallClockTimestamp())
221 .withTombstonesDisabled()
222 .build();
223
Jon Hallfa132292017-10-24 11:11:24 -0700224 deviceTableStats = storageService.<DeviceId, List<TableStatisticsEntry>>eventuallyConsistentMapBuilder()
225 .withName("onos-flow-table-stats")
226 .withSerializer(serializerBuilder)
227 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
228 .withTimestampProvider((k, v) -> new WallClockTimestamp())
229 .withTombstonesDisabled()
230 .build();
231 deviceTableStats.addListener(tableStatsListener);
232
233 logConfig("Started");
234 }
235
236 @Deactivate
237 public void deactivate(ComponentContext context) {
238 replicaInfoManager.removeListener(flowTable);
239 backupTask.cancel(true);
240 configService.unregisterProperties(getClass(), false);
241 unregisterMessageHandlers();
242 deviceTableStats.removeListener(tableStatsListener);
243 deviceTableStats.destroy();
244 eventHandler.shutdownNow();
245 messageHandlingExecutor.shutdownNow();
246 backupSenderExecutor.shutdownNow();
247 log.info("Stopped");
248 }
249
250 @SuppressWarnings("rawtypes")
251 @Modified
252 public void modified(ComponentContext context) {
253 if (context == null) {
254 logConfig("Default config");
255 return;
256 }
257
258 Dictionary properties = context.getProperties();
259 int newPoolSize;
260 int newBackupPeriod;
261 int newBackupCount;
262 try {
263 String s = get(properties, "msgHandlerPoolSize");
264 newPoolSize = isNullOrEmpty(s) ? msgHandlerPoolSize : Integer.parseInt(s.trim());
265
266 s = get(properties, "backupPeriod");
267 newBackupPeriod = isNullOrEmpty(s) ? backupPeriod : Integer.parseInt(s.trim());
268
269 s = get(properties, "backupCount");
270 newBackupCount = isNullOrEmpty(s) ? backupCount : Integer.parseInt(s.trim());
271 } catch (NumberFormatException | ClassCastException e) {
272 newPoolSize = MESSAGE_HANDLER_THREAD_POOL_SIZE;
273 newBackupPeriod = DEFAULT_BACKUP_PERIOD_MILLIS;
274 newBackupCount = DEFAULT_MAX_BACKUP_COUNT;
275 }
276
277 boolean restartBackupTask = false;
278
279 if (newBackupPeriod != backupPeriod) {
280 backupPeriod = newBackupPeriod;
281 restartBackupTask = true;
282 }
283 if (restartBackupTask) {
284 if (backupTask != null) {
285 // cancel previously running task
286 backupTask.cancel(false);
287 }
288 backupTask = backupSenderExecutor.scheduleWithFixedDelay(
289 flowTable::backup,
290 0,
291 backupPeriod,
292 TimeUnit.MILLISECONDS);
293 }
294 if (newPoolSize != msgHandlerPoolSize) {
295 msgHandlerPoolSize = newPoolSize;
296 ExecutorService oldMsgHandler = messageHandlingExecutor;
297 messageHandlingExecutor = Executors.newFixedThreadPool(
298 msgHandlerPoolSize, groupedThreads("onos/store/flow", "message-handlers", log));
299
300 // replace previously registered handlers.
301 registerMessageHandlers(messageHandlingExecutor);
302 oldMsgHandler.shutdown();
303 }
304 if (backupCount != newBackupCount) {
305 backupCount = newBackupCount;
306 }
307 logConfig("Reconfigured");
308 }
309
310 private void registerMessageHandlers(ExecutorService executor) {
311
312 clusterCommunicator.addSubscriber(APPLY_BATCH_FLOWS, new OnStoreBatch(), executor);
313 clusterCommunicator.<FlowRuleBatchEvent>addSubscriber(
314 REMOTE_APPLY_COMPLETED, serializer::decode, this::notifyDelegate, executor);
315 clusterCommunicator.addSubscriber(
316 GET_FLOW_ENTRY, serializer::decode, flowTable::getFlowEntry, serializer::encode, executor);
317 clusterCommunicator.addSubscriber(
318 GET_DEVICE_FLOW_ENTRIES, serializer::decode, flowTable::getFlowEntries, serializer::encode, executor);
319 clusterCommunicator.addSubscriber(
320 REMOVE_FLOW_ENTRY, serializer::decode, this::removeFlowRuleInternal, serializer::encode, executor);
321 clusterCommunicator.addSubscriber(
322 FLOW_TABLE_BACKUP, serializer::decode, flowTable::onBackupReceipt, serializer::encode, executor);
323 }
324
325 private void unregisterMessageHandlers() {
326 clusterCommunicator.removeSubscriber(REMOVE_FLOW_ENTRY);
327 clusterCommunicator.removeSubscriber(GET_DEVICE_FLOW_ENTRIES);
328 clusterCommunicator.removeSubscriber(GET_FLOW_ENTRY);
329 clusterCommunicator.removeSubscriber(APPLY_BATCH_FLOWS);
330 clusterCommunicator.removeSubscriber(REMOTE_APPLY_COMPLETED);
331 clusterCommunicator.removeSubscriber(FLOW_TABLE_BACKUP);
332 }
333
334 private void logConfig(String prefix) {
335 log.info("{} with msgHandlerPoolSize = {}; backupPeriod = {}, backupCount = {}",
336 prefix, msgHandlerPoolSize, backupPeriod, backupCount);
337 }
338
339 // This is not a efficient operation on a distributed sharded
340 // flow store. We need to revisit the need for this operation or at least
341 // make it device specific.
342 @Override
343 public int getFlowRuleCount() {
344 return Streams.stream(deviceService.getDevices()).parallel()
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800345 .mapToInt(device -> getFlowRuleCount(device.id()))
346 .sum();
347 }
348
349 @Override
350 public int getFlowRuleCount(DeviceId deviceId) {
351 Integer count = flowCounts.get(deviceId);
Andrea Campanella76cbdfb2018-03-12 17:44:18 -0700352 return count != null ? count : flowTable.flowEntries.get(deviceId) != null ?
353 flowTable.flowEntries.get(deviceId).keySet().size() : 0;
Jon Hallfa132292017-10-24 11:11:24 -0700354 }
355
356 @Override
357 public FlowEntry getFlowEntry(FlowRule rule) {
358 NodeId master = mastershipService.getMasterFor(rule.deviceId());
359
360 if (master == null) {
361 log.debug("Failed to getFlowEntry: No master for {}", rule.deviceId());
362 return null;
363 }
364
365 if (Objects.equals(local, master)) {
366 return flowTable.getFlowEntry(rule);
367 }
368
369 log.trace("Forwarding getFlowEntry to {}, which is the primary (master) for device {}",
370 master, rule.deviceId());
371
372 return Tools.futureGetOrElse(clusterCommunicator.sendAndReceive(rule,
373 ECFlowRuleStoreMessageSubjects.GET_FLOW_ENTRY,
374 serializer::encode,
375 serializer::decode,
376 master),
377 FLOW_RULE_STORE_TIMEOUT_MILLIS,
378 TimeUnit.MILLISECONDS,
379 null);
380 }
381
382 @Override
383 public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) {
384 NodeId master = mastershipService.getMasterFor(deviceId);
385
386 if (master == null) {
387 log.debug("Failed to getFlowEntries: No master for {}", deviceId);
388 return Collections.emptyList();
389 }
390
391 if (Objects.equals(local, master)) {
392 return flowTable.getFlowEntries(deviceId);
393 }
394
395 log.trace("Forwarding getFlowEntries to {}, which is the primary (master) for device {}",
396 master, deviceId);
397
398 return Tools.futureGetOrElse(clusterCommunicator.sendAndReceive(deviceId,
399 ECFlowRuleStoreMessageSubjects.GET_DEVICE_FLOW_ENTRIES,
400 serializer::encode,
401 serializer::decode,
402 master),
403 FLOW_RULE_STORE_TIMEOUT_MILLIS,
404 TimeUnit.MILLISECONDS,
405 Collections.emptyList());
406 }
407
408 @Override
409 public void storeFlowRule(FlowRule rule) {
410 storeBatch(new FlowRuleBatchOperation(
411 Collections.singletonList(new FlowRuleBatchEntry(FlowRuleOperation.ADD, rule)),
412 rule.deviceId(), idGenerator.getNewId()));
413 }
414
415 @Override
416 public void storeBatch(FlowRuleBatchOperation operation) {
417 if (operation.getOperations().isEmpty()) {
418 notifyDelegate(FlowRuleBatchEvent.completed(
419 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
420 new CompletedBatchOperation(true, Collections.emptySet(), operation.deviceId())));
421 return;
422 }
423
424 DeviceId deviceId = operation.deviceId();
425 NodeId master = mastershipService.getMasterFor(deviceId);
426
427 if (master == null) {
428 log.warn("No master for {} ", deviceId);
429
430 updateStoreInternal(operation);
431
432 notifyDelegate(FlowRuleBatchEvent.completed(
433 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
434 new CompletedBatchOperation(true, Collections.emptySet(), operation.deviceId())));
435 return;
436 }
437
438 if (Objects.equals(local, master)) {
439 storeBatchInternal(operation);
440 return;
441 }
442
443 log.trace("Forwarding storeBatch to {}, which is the primary (master) for device {}",
444 master, deviceId);
445
446 clusterCommunicator.unicast(operation,
447 APPLY_BATCH_FLOWS,
448 serializer::encode,
449 master)
450 .whenComplete((result, error) -> {
451 if (error != null) {
452 log.warn("Failed to storeBatch: {} to {}", operation, master, error);
453
454 Set<FlowRule> allFailures = operation.getOperations()
455 .stream()
456 .map(op -> op.target())
457 .collect(Collectors.toSet());
458
459 notifyDelegate(FlowRuleBatchEvent.completed(
460 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
461 new CompletedBatchOperation(false, allFailures, deviceId)));
462 }
463 });
464 }
465
466 private void storeBatchInternal(FlowRuleBatchOperation operation) {
467
468 final DeviceId did = operation.deviceId();
469 //final Collection<FlowEntry> ft = flowTable.getFlowEntries(did);
470 Set<FlowRuleBatchEntry> currentOps = updateStoreInternal(operation);
471 if (currentOps.isEmpty()) {
472 batchOperationComplete(FlowRuleBatchEvent.completed(
473 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
474 new CompletedBatchOperation(true, Collections.emptySet(), did)));
475 return;
476 }
477
478 notifyDelegate(FlowRuleBatchEvent.requested(new
479 FlowRuleBatchRequest(operation.id(),
480 currentOps), operation.deviceId()));
481 }
482
483 private Set<FlowRuleBatchEntry> updateStoreInternal(FlowRuleBatchOperation operation) {
484 return operation.getOperations().stream().map(
485 op -> {
486 StoredFlowEntry entry;
487 switch (op.operator()) {
488 case ADD:
Thomas Vachuska914b0b12018-01-09 11:54:52 -0800489 case MODIFY:
Jon Hallfa132292017-10-24 11:11:24 -0700490 entry = new DefaultFlowEntry(op.target());
491 // always add requested FlowRule
492 // Note: 2 equal FlowEntry may have different treatment
493 flowTable.remove(entry.deviceId(), entry);
494 flowTable.add(entry);
495
496 return op;
497 case REMOVE:
498 entry = flowTable.getFlowEntry(op.target());
499 if (entry != null) {
500 //FIXME modification of "stored" flow entry outside of flow table
501 entry.setState(FlowEntryState.PENDING_REMOVE);
502 log.debug("Setting state of rule to pending remove: {}", entry);
503 return op;
504 }
505 break;
Jon Hallfa132292017-10-24 11:11:24 -0700506 default:
507 log.warn("Unknown flow operation operator: {}", op.operator());
508 }
509 return null;
510 }
511 ).filter(Objects::nonNull).collect(Collectors.toSet());
512 }
513
514 @Override
515 public void deleteFlowRule(FlowRule rule) {
516 storeBatch(
517 new FlowRuleBatchOperation(
518 Collections.singletonList(
519 new FlowRuleBatchEntry(
520 FlowRuleOperation.REMOVE,
521 rule)), rule.deviceId(), idGenerator.getNewId()));
522 }
523
524 @Override
525 public FlowRuleEvent pendingFlowRule(FlowEntry rule) {
526 if (mastershipService.isLocalMaster(rule.deviceId())) {
527 StoredFlowEntry stored = flowTable.getFlowEntry(rule);
528 if (stored != null &&
529 stored.state() != FlowEntryState.PENDING_ADD) {
530 stored.setState(FlowEntryState.PENDING_ADD);
531 return new FlowRuleEvent(Type.RULE_UPDATED, rule);
532 }
533 }
534 return null;
535 }
536
537 @Override
538 public FlowRuleEvent addOrUpdateFlowRule(FlowEntry rule) {
539 NodeId master = mastershipService.getMasterFor(rule.deviceId());
540 if (Objects.equals(local, master)) {
541 return addOrUpdateFlowRuleInternal(rule);
542 }
543
544 log.warn("Tried to update FlowRule {} state,"
545 + " while the Node was not the master.", rule);
546 return null;
547 }
548
549 private FlowRuleEvent addOrUpdateFlowRuleInternal(FlowEntry rule) {
550 // check if this new rule is an update to an existing entry
551 StoredFlowEntry stored = flowTable.getFlowEntry(rule);
552 if (stored != null) {
553 //FIXME modification of "stored" flow entry outside of flow table
554 stored.setBytes(rule.bytes());
555 stored.setLife(rule.life(TimeUnit.NANOSECONDS), TimeUnit.NANOSECONDS);
556 stored.setLiveType(rule.liveType());
557 stored.setPackets(rule.packets());
558 stored.setLastSeen();
559 if (stored.state() == FlowEntryState.PENDING_ADD) {
560 stored.setState(FlowEntryState.ADDED);
561 return new FlowRuleEvent(Type.RULE_ADDED, rule);
562 }
563 return new FlowRuleEvent(Type.RULE_UPDATED, rule);
564 }
565
566 // TODO: Confirm if this behavior is correct. See SimpleFlowRuleStore
567 // TODO: also update backup if the behavior is correct.
568 flowTable.add(rule);
569 return null;
570 }
571
572 @Override
573 public FlowRuleEvent removeFlowRule(FlowEntry rule) {
574 final DeviceId deviceId = rule.deviceId();
575 NodeId master = mastershipService.getMasterFor(deviceId);
576
577 if (Objects.equals(local, master)) {
578 // bypass and handle it locally
579 return removeFlowRuleInternal(rule);
580 }
581
582 if (master == null) {
583 log.warn("Failed to removeFlowRule: No master for {}", deviceId);
584 // TODO: revisit if this should be null (="no-op") or Exception
585 return null;
586 }
587
588 log.trace("Forwarding removeFlowRule to {}, which is the master for device {}",
589 master, deviceId);
590
591 return Futures.getUnchecked(clusterCommunicator.sendAndReceive(
592 rule,
593 REMOVE_FLOW_ENTRY,
594 serializer::encode,
595 serializer::decode,
596 master));
597 }
598
599 private FlowRuleEvent removeFlowRuleInternal(FlowEntry rule) {
600 final DeviceId deviceId = rule.deviceId();
601 // This is where one could mark a rule as removed and still keep it in the store.
602 final FlowEntry removed = flowTable.remove(deviceId, rule);
603 // rule may be partial rule that is missing treatment, we should use rule from store instead
604 return removed != null ? new FlowRuleEvent(RULE_REMOVED, removed) : null;
605 }
606
607 @Override
608 public void purgeFlowRule(DeviceId deviceId) {
609 flowTable.purgeFlowRule(deviceId);
610 }
611
612 @Override
613 public void purgeFlowRules() {
614 flowTable.purgeFlowRules();
615 }
616
617 @Override
618 public void batchOperationComplete(FlowRuleBatchEvent event) {
619 //FIXME: need a per device pending response
620 NodeId nodeId = pendingResponses.remove(event.subject().batchId());
621 if (nodeId == null) {
622 notifyDelegate(event);
623 } else {
624 // TODO check unicast return value
625 clusterCommunicator.unicast(event, REMOTE_APPLY_COMPLETED, serializer::encode, nodeId);
626 //error log: log.warn("Failed to respond to peer for batch operation result");
627 }
628 }
629
630 private final class OnStoreBatch implements ClusterMessageHandler {
631
632 @Override
633 public void handle(final ClusterMessage message) {
634 FlowRuleBatchOperation operation = serializer.decode(message.payload());
635 log.debug("received batch request {}", operation);
636
637 final DeviceId deviceId = operation.deviceId();
638 NodeId master = mastershipService.getMasterFor(deviceId);
639 if (!Objects.equals(local, master)) {
640 Set<FlowRule> failures = new HashSet<>(operation.size());
641 for (FlowRuleBatchEntry op : operation.getOperations()) {
642 failures.add(op.target());
643 }
644 CompletedBatchOperation allFailed = new CompletedBatchOperation(false, failures, deviceId);
645 // This node is no longer the master, respond as all failed.
646 // TODO: we might want to wrap response in envelope
647 // to distinguish sw programming failure and hand over
648 // it make sense in the latter case to retry immediately.
649 message.respond(serializer.encode(allFailed));
650 return;
651 }
652
653 pendingResponses.put(operation.id(), message.sender());
654 storeBatchInternal(operation);
655 }
656 }
657
658 private class BackupOperation {
659 private final NodeId nodeId;
660 private final DeviceId deviceId;
661
662 public BackupOperation(NodeId nodeId, DeviceId deviceId) {
663 this.nodeId = nodeId;
664 this.deviceId = deviceId;
665 }
666
667 @Override
668 public int hashCode() {
669 return Objects.hash(nodeId, deviceId);
670 }
671
672 @Override
673 public boolean equals(Object other) {
674 if (other != null && other instanceof BackupOperation) {
675 BackupOperation that = (BackupOperation) other;
676 return this.nodeId.equals(that.nodeId) &&
677 this.deviceId.equals(that.deviceId);
678 } else {
679 return false;
680 }
681 }
682 }
683
684 private class InternalFlowTable implements ReplicaInfoEventListener {
685
686 //TODO replace the Map<V,V> with ExtendedSet
687 private final Map<DeviceId, Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>
688 flowEntries = Maps.newConcurrentMap();
689
690 private final Map<BackupOperation, Long> lastBackupTimes = Maps.newConcurrentMap();
691 private final Map<DeviceId, Long> lastUpdateTimes = Maps.newConcurrentMap();
692
693 @Override
694 public void event(ReplicaInfoEvent event) {
695 eventHandler.execute(() -> handleEvent(event));
696 }
697
698 private void handleEvent(ReplicaInfoEvent event) {
699 DeviceId deviceId = event.subject();
700 if (!mastershipService.isLocalMaster(deviceId)) {
701 return;
702 }
703 if (event.type() == MASTER_CHANGED) {
704 lastUpdateTimes.put(deviceId, System.currentTimeMillis());
705 }
706 backupSenderExecutor.schedule(this::backup, 0, TimeUnit.SECONDS);
707 }
708
709 private void sendBackups(NodeId nodeId, Set<DeviceId> deviceIds) {
710 // split up the devices into smaller batches and send them separately.
711 Iterables.partition(deviceIds, FLOW_TABLE_BACKUP_BATCH_SIZE)
712 .forEach(ids -> backupFlowEntries(nodeId, Sets.newHashSet(ids)));
713 }
714
715 private void backupFlowEntries(NodeId nodeId, Set<DeviceId> deviceIds) {
716 if (deviceIds.isEmpty()) {
717 return;
718 }
719 log.debug("Sending flowEntries for devices {} to {} for backup.", deviceIds, nodeId);
720 Map<DeviceId, Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>
721 deviceFlowEntries = Maps.newConcurrentMap();
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800722 deviceIds.forEach(id -> {
723 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> copy = getFlowTableCopy(id);
724 int flowCount = copy.entrySet().stream()
725 .mapToInt(e -> e.getValue().values().size()).sum();
726 flowCounts.put(id, flowCount);
727 deviceFlowEntries.put(id, copy);
728 });
Jon Hallfa132292017-10-24 11:11:24 -0700729 clusterCommunicator.<Map<DeviceId,
730 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>,
731 Set<DeviceId>>
732 sendAndReceive(deviceFlowEntries,
733 FLOW_TABLE_BACKUP,
734 serializer::encode,
735 serializer::decode,
736 nodeId)
737 .whenComplete((backedupDevices, error) -> {
738 Set<DeviceId> devicesNotBackedup = error != null ?
739 deviceFlowEntries.keySet() :
740 Sets.difference(deviceFlowEntries.keySet(), backedupDevices);
741 if (devicesNotBackedup.size() > 0) {
742 log.warn("Failed to backup devices: {}. Reason: {}, Node: {}",
743 devicesNotBackedup, error != null ? error.getMessage() : "none",
744 nodeId);
745 }
746 if (backedupDevices != null) {
747 backedupDevices.forEach(id -> {
748 lastBackupTimes.put(new BackupOperation(nodeId, id), System.currentTimeMillis());
749 });
750 }
751 });
752 }
753
754 /**
755 * Returns the flow table for specified device.
756 *
757 * @param deviceId identifier of the device
758 * @return Map representing Flow Table of given device.
759 */
760 private Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> getFlowTable(DeviceId deviceId) {
761 if (persistenceEnabled) {
762 return flowEntries.computeIfAbsent(deviceId, id -> persistenceService
763 .<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>persistentMapBuilder()
764 .withName("FlowTable:" + deviceId.toString())
765 .withSerializer(new Serializer() {
766 @Override
767 public <T> byte[] encode(T object) {
768 return serializer.encode(object);
769 }
770
771 @Override
772 public <T> T decode(byte[] bytes) {
773 return serializer.decode(bytes);
774 }
775
776 @Override
777 public <T> T copy(T object) {
778 return serializer.copy(object);
779 }
780 })
781 .build());
782 } else {
783 return flowEntries.computeIfAbsent(deviceId, id -> Maps.newConcurrentMap());
784 }
785 }
786
787 private Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> getFlowTableCopy(DeviceId deviceId) {
788 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> copy = Maps.newHashMap();
789 if (persistenceEnabled) {
790 return flowEntries.computeIfAbsent(deviceId, id -> persistenceService
791 .<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>persistentMapBuilder()
792 .withName("FlowTable:" + deviceId.toString())
793 .withSerializer(new Serializer() {
794 @Override
795 public <T> byte[] encode(T object) {
796 return serializer.encode(object);
797 }
798
799 @Override
800 public <T> T decode(byte[] bytes) {
801 return serializer.decode(bytes);
802 }
803
804 @Override
805 public <T> T copy(T object) {
806 return serializer.copy(object);
807 }
808 })
809 .build());
810 } else {
811 flowEntries.computeIfAbsent(deviceId, id -> Maps.newConcurrentMap()).forEach((k, v) -> {
812 copy.put(k, Maps.newHashMap(v));
813 });
814 return copy;
815 }
816 }
817
818 private Map<StoredFlowEntry, StoredFlowEntry> getFlowEntriesInternal(DeviceId deviceId, FlowId flowId) {
819 return getFlowTable(deviceId).computeIfAbsent(flowId, id -> Maps.newConcurrentMap());
820 }
821
822 private StoredFlowEntry getFlowEntryInternal(FlowRule rule) {
823 return getFlowEntriesInternal(rule.deviceId(), rule.id()).get(rule);
824 }
825
826 private Set<FlowEntry> getFlowEntriesInternal(DeviceId deviceId) {
827 return getFlowTable(deviceId).values().stream()
828 .flatMap(m -> m.values().stream())
829 .collect(Collectors.toSet());
830 }
831
832 public StoredFlowEntry getFlowEntry(FlowRule rule) {
833 return getFlowEntryInternal(rule);
834 }
835
836 public Set<FlowEntry> getFlowEntries(DeviceId deviceId) {
837 return getFlowEntriesInternal(deviceId);
838 }
839
840 public void add(FlowEntry rule) {
841 getFlowEntriesInternal(rule.deviceId(), rule.id())
842 .compute((StoredFlowEntry) rule, (k, stored) -> {
843 //TODO compare stored and rule timestamps
844 //TODO the key is not updated
845 return (StoredFlowEntry) rule;
846 });
847 lastUpdateTimes.put(rule.deviceId(), System.currentTimeMillis());
848 }
849
850 public FlowEntry remove(DeviceId deviceId, FlowEntry rule) {
851 final AtomicReference<FlowEntry> removedRule = new AtomicReference<>();
Jordan Haltermance336f72018-01-16 17:08:09 -0800852 final Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> flowTable = getFlowTable(deviceId);
853 flowTable.computeIfPresent(rule.id(), (flowId, flowEntries) -> {
854 flowEntries.computeIfPresent((StoredFlowEntry) rule, (k, stored) -> {
Jon Hallfa132292017-10-24 11:11:24 -0700855 if (rule instanceof DefaultFlowEntry) {
856 DefaultFlowEntry toRemove = (DefaultFlowEntry) rule;
857 if (stored instanceof DefaultFlowEntry) {
858 DefaultFlowEntry storedEntry = (DefaultFlowEntry) stored;
859 if (toRemove.created() < storedEntry.created()) {
860 log.debug("Trying to remove more recent flow entry {} (stored: {})",
Jordan Haltermance336f72018-01-16 17:08:09 -0800861 toRemove, stored);
Jon Hallfa132292017-10-24 11:11:24 -0700862 // the key is not updated, removedRule remains null
863 return stored;
864 }
865 }
866 }
867 removedRule.set(stored);
868 return null;
869 });
Jordan Haltermance336f72018-01-16 17:08:09 -0800870 return flowEntries.isEmpty() ? null : flowEntries;
871 });
Jon Hallfa132292017-10-24 11:11:24 -0700872
873 if (removedRule.get() != null) {
874 lastUpdateTimes.put(deviceId, System.currentTimeMillis());
875 return removedRule.get();
876 } else {
877 return null;
878 }
879 }
880
881 public void purgeFlowRule(DeviceId deviceId) {
882 flowEntries.remove(deviceId);
883 }
884
885 public void purgeFlowRules() {
886 flowEntries.clear();
887 }
888
889 private List<NodeId> getBackupNodes(DeviceId deviceId) {
890 // The returned backup node list is in the order of preference i.e. next likely master first.
891 List<NodeId> allPossibleBackupNodes = replicaInfoManager.getReplicaInfoFor(deviceId).backups();
892 return ImmutableList.copyOf(allPossibleBackupNodes)
893 .subList(0, Math.min(allPossibleBackupNodes.size(), backupCount));
894 }
895
896 private void backup() {
897 try {
898 // compute a mapping from node to the set of devices whose flow entries it should backup
899 Map<NodeId, Set<DeviceId>> devicesToBackupByNode = Maps.newHashMap();
900 flowEntries.keySet().forEach(deviceId -> {
901 List<NodeId> backupNodes = getBackupNodes(deviceId);
902 backupNodes.forEach(backupNode -> {
903 if (lastBackupTimes.getOrDefault(new BackupOperation(backupNode, deviceId), 0L)
904 < lastUpdateTimes.getOrDefault(deviceId, 0L)) {
905 devicesToBackupByNode.computeIfAbsent(backupNode,
906 nodeId -> Sets.newHashSet()).add(deviceId);
907 }
908 });
909 });
910 // send the device flow entries to their respective backup nodes
911 devicesToBackupByNode.forEach(this::sendBackups);
912 } catch (Exception e) {
913 log.error("Backup failed.", e);
914 }
915 }
916
917 private Set<DeviceId> onBackupReceipt(Map<DeviceId,
918 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>> flowTables) {
919 log.debug("Received flowEntries for {} to backup", flowTables.keySet());
920 Set<DeviceId> backedupDevices = Sets.newHashSet();
921 try {
922 flowTables.forEach((deviceId, deviceFlowTable) -> {
923 // Only process those devices are that not managed by the local node.
924 if (!Objects.equals(local, mastershipService.getMasterFor(deviceId))) {
925 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> backupFlowTable =
926 getFlowTable(deviceId);
927 backupFlowTable.clear();
928 backupFlowTable.putAll(deviceFlowTable);
929 backedupDevices.add(deviceId);
930 }
931 });
932 } catch (Exception e) {
933 log.warn("Failure processing backup request", e);
934 }
935 return backedupDevices;
936 }
937 }
938
939 @Override
940 public FlowRuleEvent updateTableStatistics(DeviceId deviceId,
941 List<TableStatisticsEntry> tableStats) {
942 deviceTableStats.put(deviceId, tableStats);
943 return null;
944 }
945
946 @Override
947 public Iterable<TableStatisticsEntry> getTableStatistics(DeviceId deviceId) {
948 NodeId master = mastershipService.getMasterFor(deviceId);
949
950 if (master == null) {
951 log.debug("Failed to getTableStats: No master for {}", deviceId);
952 return Collections.emptyList();
953 }
954
955 List<TableStatisticsEntry> tableStats = deviceTableStats.get(deviceId);
956 if (tableStats == null) {
957 return Collections.emptyList();
958 }
959 return ImmutableList.copyOf(tableStats);
960 }
961
962 @Override
963 public long getActiveFlowRuleCount(DeviceId deviceId) {
964 return Streams.stream(getTableStatistics(deviceId))
965 .mapToLong(TableStatisticsEntry::activeFlowEntries)
966 .sum();
967 }
968
969 private class InternalTableStatsListener
970 implements EventuallyConsistentMapListener<DeviceId, List<TableStatisticsEntry>> {
971 @Override
972 public void event(EventuallyConsistentMapEvent<DeviceId,
973 List<TableStatisticsEntry>> event) {
974 //TODO: Generate an event to listeners (do we need?)
975 }
976 }
977}