blob: e1a8cffadd63f1a9eea341e7c424937cb85c629e [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);
352 return count != null ? count : 0;
Jon Hallfa132292017-10-24 11:11:24 -0700353 }
354
355 @Override
356 public FlowEntry getFlowEntry(FlowRule rule) {
357 NodeId master = mastershipService.getMasterFor(rule.deviceId());
358
359 if (master == null) {
360 log.debug("Failed to getFlowEntry: No master for {}", rule.deviceId());
361 return null;
362 }
363
364 if (Objects.equals(local, master)) {
365 return flowTable.getFlowEntry(rule);
366 }
367
368 log.trace("Forwarding getFlowEntry to {}, which is the primary (master) for device {}",
369 master, rule.deviceId());
370
371 return Tools.futureGetOrElse(clusterCommunicator.sendAndReceive(rule,
372 ECFlowRuleStoreMessageSubjects.GET_FLOW_ENTRY,
373 serializer::encode,
374 serializer::decode,
375 master),
376 FLOW_RULE_STORE_TIMEOUT_MILLIS,
377 TimeUnit.MILLISECONDS,
378 null);
379 }
380
381 @Override
382 public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) {
383 NodeId master = mastershipService.getMasterFor(deviceId);
384
385 if (master == null) {
386 log.debug("Failed to getFlowEntries: No master for {}", deviceId);
387 return Collections.emptyList();
388 }
389
390 if (Objects.equals(local, master)) {
391 return flowTable.getFlowEntries(deviceId);
392 }
393
394 log.trace("Forwarding getFlowEntries to {}, which is the primary (master) for device {}",
395 master, deviceId);
396
397 return Tools.futureGetOrElse(clusterCommunicator.sendAndReceive(deviceId,
398 ECFlowRuleStoreMessageSubjects.GET_DEVICE_FLOW_ENTRIES,
399 serializer::encode,
400 serializer::decode,
401 master),
402 FLOW_RULE_STORE_TIMEOUT_MILLIS,
403 TimeUnit.MILLISECONDS,
404 Collections.emptyList());
405 }
406
407 @Override
408 public void storeFlowRule(FlowRule rule) {
409 storeBatch(new FlowRuleBatchOperation(
410 Collections.singletonList(new FlowRuleBatchEntry(FlowRuleOperation.ADD, rule)),
411 rule.deviceId(), idGenerator.getNewId()));
412 }
413
414 @Override
415 public void storeBatch(FlowRuleBatchOperation operation) {
416 if (operation.getOperations().isEmpty()) {
417 notifyDelegate(FlowRuleBatchEvent.completed(
418 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
419 new CompletedBatchOperation(true, Collections.emptySet(), operation.deviceId())));
420 return;
421 }
422
423 DeviceId deviceId = operation.deviceId();
424 NodeId master = mastershipService.getMasterFor(deviceId);
425
426 if (master == null) {
427 log.warn("No master for {} ", deviceId);
428
429 updateStoreInternal(operation);
430
431 notifyDelegate(FlowRuleBatchEvent.completed(
432 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
433 new CompletedBatchOperation(true, Collections.emptySet(), operation.deviceId())));
434 return;
435 }
436
437 if (Objects.equals(local, master)) {
438 storeBatchInternal(operation);
439 return;
440 }
441
442 log.trace("Forwarding storeBatch to {}, which is the primary (master) for device {}",
443 master, deviceId);
444
445 clusterCommunicator.unicast(operation,
446 APPLY_BATCH_FLOWS,
447 serializer::encode,
448 master)
449 .whenComplete((result, error) -> {
450 if (error != null) {
451 log.warn("Failed to storeBatch: {} to {}", operation, master, error);
452
453 Set<FlowRule> allFailures = operation.getOperations()
454 .stream()
455 .map(op -> op.target())
456 .collect(Collectors.toSet());
457
458 notifyDelegate(FlowRuleBatchEvent.completed(
459 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
460 new CompletedBatchOperation(false, allFailures, deviceId)));
461 }
462 });
463 }
464
465 private void storeBatchInternal(FlowRuleBatchOperation operation) {
466
467 final DeviceId did = operation.deviceId();
468 //final Collection<FlowEntry> ft = flowTable.getFlowEntries(did);
469 Set<FlowRuleBatchEntry> currentOps = updateStoreInternal(operation);
470 if (currentOps.isEmpty()) {
471 batchOperationComplete(FlowRuleBatchEvent.completed(
472 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
473 new CompletedBatchOperation(true, Collections.emptySet(), did)));
474 return;
475 }
476
477 notifyDelegate(FlowRuleBatchEvent.requested(new
478 FlowRuleBatchRequest(operation.id(),
479 currentOps), operation.deviceId()));
480 }
481
482 private Set<FlowRuleBatchEntry> updateStoreInternal(FlowRuleBatchOperation operation) {
483 return operation.getOperations().stream().map(
484 op -> {
485 StoredFlowEntry entry;
486 switch (op.operator()) {
487 case ADD:
Thomas Vachuska914b0b12018-01-09 11:54:52 -0800488 case MODIFY:
Jon Hallfa132292017-10-24 11:11:24 -0700489 entry = new DefaultFlowEntry(op.target());
490 // always add requested FlowRule
491 // Note: 2 equal FlowEntry may have different treatment
492 flowTable.remove(entry.deviceId(), entry);
493 flowTable.add(entry);
494
495 return op;
496 case REMOVE:
497 entry = flowTable.getFlowEntry(op.target());
498 if (entry != null) {
499 //FIXME modification of "stored" flow entry outside of flow table
500 entry.setState(FlowEntryState.PENDING_REMOVE);
501 log.debug("Setting state of rule to pending remove: {}", entry);
502 return op;
503 }
504 break;
Jon Hallfa132292017-10-24 11:11:24 -0700505 default:
506 log.warn("Unknown flow operation operator: {}", op.operator());
507 }
508 return null;
509 }
510 ).filter(Objects::nonNull).collect(Collectors.toSet());
511 }
512
513 @Override
514 public void deleteFlowRule(FlowRule rule) {
515 storeBatch(
516 new FlowRuleBatchOperation(
517 Collections.singletonList(
518 new FlowRuleBatchEntry(
519 FlowRuleOperation.REMOVE,
520 rule)), rule.deviceId(), idGenerator.getNewId()));
521 }
522
523 @Override
524 public FlowRuleEvent pendingFlowRule(FlowEntry rule) {
525 if (mastershipService.isLocalMaster(rule.deviceId())) {
526 StoredFlowEntry stored = flowTable.getFlowEntry(rule);
527 if (stored != null &&
528 stored.state() != FlowEntryState.PENDING_ADD) {
529 stored.setState(FlowEntryState.PENDING_ADD);
530 return new FlowRuleEvent(Type.RULE_UPDATED, rule);
531 }
532 }
533 return null;
534 }
535
536 @Override
537 public FlowRuleEvent addOrUpdateFlowRule(FlowEntry rule) {
538 NodeId master = mastershipService.getMasterFor(rule.deviceId());
539 if (Objects.equals(local, master)) {
540 return addOrUpdateFlowRuleInternal(rule);
541 }
542
543 log.warn("Tried to update FlowRule {} state,"
544 + " while the Node was not the master.", rule);
545 return null;
546 }
547
548 private FlowRuleEvent addOrUpdateFlowRuleInternal(FlowEntry rule) {
549 // check if this new rule is an update to an existing entry
550 StoredFlowEntry stored = flowTable.getFlowEntry(rule);
551 if (stored != null) {
552 //FIXME modification of "stored" flow entry outside of flow table
553 stored.setBytes(rule.bytes());
554 stored.setLife(rule.life(TimeUnit.NANOSECONDS), TimeUnit.NANOSECONDS);
555 stored.setLiveType(rule.liveType());
556 stored.setPackets(rule.packets());
557 stored.setLastSeen();
558 if (stored.state() == FlowEntryState.PENDING_ADD) {
559 stored.setState(FlowEntryState.ADDED);
560 return new FlowRuleEvent(Type.RULE_ADDED, rule);
561 }
562 return new FlowRuleEvent(Type.RULE_UPDATED, rule);
563 }
564
565 // TODO: Confirm if this behavior is correct. See SimpleFlowRuleStore
566 // TODO: also update backup if the behavior is correct.
567 flowTable.add(rule);
568 return null;
569 }
570
571 @Override
572 public FlowRuleEvent removeFlowRule(FlowEntry rule) {
573 final DeviceId deviceId = rule.deviceId();
574 NodeId master = mastershipService.getMasterFor(deviceId);
575
576 if (Objects.equals(local, master)) {
577 // bypass and handle it locally
578 return removeFlowRuleInternal(rule);
579 }
580
581 if (master == null) {
582 log.warn("Failed to removeFlowRule: No master for {}", deviceId);
583 // TODO: revisit if this should be null (="no-op") or Exception
584 return null;
585 }
586
587 log.trace("Forwarding removeFlowRule to {}, which is the master for device {}",
588 master, deviceId);
589
590 return Futures.getUnchecked(clusterCommunicator.sendAndReceive(
591 rule,
592 REMOVE_FLOW_ENTRY,
593 serializer::encode,
594 serializer::decode,
595 master));
596 }
597
598 private FlowRuleEvent removeFlowRuleInternal(FlowEntry rule) {
599 final DeviceId deviceId = rule.deviceId();
600 // This is where one could mark a rule as removed and still keep it in the store.
601 final FlowEntry removed = flowTable.remove(deviceId, rule);
602 // rule may be partial rule that is missing treatment, we should use rule from store instead
603 return removed != null ? new FlowRuleEvent(RULE_REMOVED, removed) : null;
604 }
605
606 @Override
607 public void purgeFlowRule(DeviceId deviceId) {
608 flowTable.purgeFlowRule(deviceId);
609 }
610
611 @Override
612 public void purgeFlowRules() {
613 flowTable.purgeFlowRules();
614 }
615
616 @Override
617 public void batchOperationComplete(FlowRuleBatchEvent event) {
618 //FIXME: need a per device pending response
619 NodeId nodeId = pendingResponses.remove(event.subject().batchId());
620 if (nodeId == null) {
621 notifyDelegate(event);
622 } else {
623 // TODO check unicast return value
624 clusterCommunicator.unicast(event, REMOTE_APPLY_COMPLETED, serializer::encode, nodeId);
625 //error log: log.warn("Failed to respond to peer for batch operation result");
626 }
627 }
628
629 private final class OnStoreBatch implements ClusterMessageHandler {
630
631 @Override
632 public void handle(final ClusterMessage message) {
633 FlowRuleBatchOperation operation = serializer.decode(message.payload());
634 log.debug("received batch request {}", operation);
635
636 final DeviceId deviceId = operation.deviceId();
637 NodeId master = mastershipService.getMasterFor(deviceId);
638 if (!Objects.equals(local, master)) {
639 Set<FlowRule> failures = new HashSet<>(operation.size());
640 for (FlowRuleBatchEntry op : operation.getOperations()) {
641 failures.add(op.target());
642 }
643 CompletedBatchOperation allFailed = new CompletedBatchOperation(false, failures, deviceId);
644 // This node is no longer the master, respond as all failed.
645 // TODO: we might want to wrap response in envelope
646 // to distinguish sw programming failure and hand over
647 // it make sense in the latter case to retry immediately.
648 message.respond(serializer.encode(allFailed));
649 return;
650 }
651
652 pendingResponses.put(operation.id(), message.sender());
653 storeBatchInternal(operation);
654 }
655 }
656
657 private class BackupOperation {
658 private final NodeId nodeId;
659 private final DeviceId deviceId;
660
661 public BackupOperation(NodeId nodeId, DeviceId deviceId) {
662 this.nodeId = nodeId;
663 this.deviceId = deviceId;
664 }
665
666 @Override
667 public int hashCode() {
668 return Objects.hash(nodeId, deviceId);
669 }
670
671 @Override
672 public boolean equals(Object other) {
673 if (other != null && other instanceof BackupOperation) {
674 BackupOperation that = (BackupOperation) other;
675 return this.nodeId.equals(that.nodeId) &&
676 this.deviceId.equals(that.deviceId);
677 } else {
678 return false;
679 }
680 }
681 }
682
683 private class InternalFlowTable implements ReplicaInfoEventListener {
684
685 //TODO replace the Map<V,V> with ExtendedSet
686 private final Map<DeviceId, Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>
687 flowEntries = Maps.newConcurrentMap();
688
689 private final Map<BackupOperation, Long> lastBackupTimes = Maps.newConcurrentMap();
690 private final Map<DeviceId, Long> lastUpdateTimes = Maps.newConcurrentMap();
691
692 @Override
693 public void event(ReplicaInfoEvent event) {
694 eventHandler.execute(() -> handleEvent(event));
695 }
696
697 private void handleEvent(ReplicaInfoEvent event) {
698 DeviceId deviceId = event.subject();
699 if (!mastershipService.isLocalMaster(deviceId)) {
700 return;
701 }
702 if (event.type() == MASTER_CHANGED) {
703 lastUpdateTimes.put(deviceId, System.currentTimeMillis());
704 }
705 backupSenderExecutor.schedule(this::backup, 0, TimeUnit.SECONDS);
706 }
707
708 private void sendBackups(NodeId nodeId, Set<DeviceId> deviceIds) {
709 // split up the devices into smaller batches and send them separately.
710 Iterables.partition(deviceIds, FLOW_TABLE_BACKUP_BATCH_SIZE)
711 .forEach(ids -> backupFlowEntries(nodeId, Sets.newHashSet(ids)));
712 }
713
714 private void backupFlowEntries(NodeId nodeId, Set<DeviceId> deviceIds) {
715 if (deviceIds.isEmpty()) {
716 return;
717 }
718 log.debug("Sending flowEntries for devices {} to {} for backup.", deviceIds, nodeId);
719 Map<DeviceId, Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>
720 deviceFlowEntries = Maps.newConcurrentMap();
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800721 deviceIds.forEach(id -> {
722 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> copy = getFlowTableCopy(id);
723 int flowCount = copy.entrySet().stream()
724 .mapToInt(e -> e.getValue().values().size()).sum();
725 flowCounts.put(id, flowCount);
726 deviceFlowEntries.put(id, copy);
727 });
Jon Hallfa132292017-10-24 11:11:24 -0700728 clusterCommunicator.<Map<DeviceId,
729 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>,
730 Set<DeviceId>>
731 sendAndReceive(deviceFlowEntries,
732 FLOW_TABLE_BACKUP,
733 serializer::encode,
734 serializer::decode,
735 nodeId)
736 .whenComplete((backedupDevices, error) -> {
737 Set<DeviceId> devicesNotBackedup = error != null ?
738 deviceFlowEntries.keySet() :
739 Sets.difference(deviceFlowEntries.keySet(), backedupDevices);
740 if (devicesNotBackedup.size() > 0) {
741 log.warn("Failed to backup devices: {}. Reason: {}, Node: {}",
742 devicesNotBackedup, error != null ? error.getMessage() : "none",
743 nodeId);
744 }
745 if (backedupDevices != null) {
746 backedupDevices.forEach(id -> {
747 lastBackupTimes.put(new BackupOperation(nodeId, id), System.currentTimeMillis());
748 });
749 }
750 });
751 }
752
753 /**
754 * Returns the flow table for specified device.
755 *
756 * @param deviceId identifier of the device
757 * @return Map representing Flow Table of given device.
758 */
759 private Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> getFlowTable(DeviceId deviceId) {
760 if (persistenceEnabled) {
761 return flowEntries.computeIfAbsent(deviceId, id -> persistenceService
762 .<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>persistentMapBuilder()
763 .withName("FlowTable:" + deviceId.toString())
764 .withSerializer(new Serializer() {
765 @Override
766 public <T> byte[] encode(T object) {
767 return serializer.encode(object);
768 }
769
770 @Override
771 public <T> T decode(byte[] bytes) {
772 return serializer.decode(bytes);
773 }
774
775 @Override
776 public <T> T copy(T object) {
777 return serializer.copy(object);
778 }
779 })
780 .build());
781 } else {
782 return flowEntries.computeIfAbsent(deviceId, id -> Maps.newConcurrentMap());
783 }
784 }
785
786 private Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> getFlowTableCopy(DeviceId deviceId) {
787 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> copy = Maps.newHashMap();
788 if (persistenceEnabled) {
789 return flowEntries.computeIfAbsent(deviceId, id -> persistenceService
790 .<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>persistentMapBuilder()
791 .withName("FlowTable:" + deviceId.toString())
792 .withSerializer(new Serializer() {
793 @Override
794 public <T> byte[] encode(T object) {
795 return serializer.encode(object);
796 }
797
798 @Override
799 public <T> T decode(byte[] bytes) {
800 return serializer.decode(bytes);
801 }
802
803 @Override
804 public <T> T copy(T object) {
805 return serializer.copy(object);
806 }
807 })
808 .build());
809 } else {
810 flowEntries.computeIfAbsent(deviceId, id -> Maps.newConcurrentMap()).forEach((k, v) -> {
811 copy.put(k, Maps.newHashMap(v));
812 });
813 return copy;
814 }
815 }
816
817 private Map<StoredFlowEntry, StoredFlowEntry> getFlowEntriesInternal(DeviceId deviceId, FlowId flowId) {
818 return getFlowTable(deviceId).computeIfAbsent(flowId, id -> Maps.newConcurrentMap());
819 }
820
821 private StoredFlowEntry getFlowEntryInternal(FlowRule rule) {
822 return getFlowEntriesInternal(rule.deviceId(), rule.id()).get(rule);
823 }
824
825 private Set<FlowEntry> getFlowEntriesInternal(DeviceId deviceId) {
826 return getFlowTable(deviceId).values().stream()
827 .flatMap(m -> m.values().stream())
828 .collect(Collectors.toSet());
829 }
830
831 public StoredFlowEntry getFlowEntry(FlowRule rule) {
832 return getFlowEntryInternal(rule);
833 }
834
835 public Set<FlowEntry> getFlowEntries(DeviceId deviceId) {
836 return getFlowEntriesInternal(deviceId);
837 }
838
839 public void add(FlowEntry rule) {
840 getFlowEntriesInternal(rule.deviceId(), rule.id())
841 .compute((StoredFlowEntry) rule, (k, stored) -> {
842 //TODO compare stored and rule timestamps
843 //TODO the key is not updated
844 return (StoredFlowEntry) rule;
845 });
846 lastUpdateTimes.put(rule.deviceId(), System.currentTimeMillis());
847 }
848
849 public FlowEntry remove(DeviceId deviceId, FlowEntry rule) {
850 final AtomicReference<FlowEntry> removedRule = new AtomicReference<>();
Jordan Haltermance336f72018-01-16 17:08:09 -0800851 final Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> flowTable = getFlowTable(deviceId);
852 flowTable.computeIfPresent(rule.id(), (flowId, flowEntries) -> {
853 flowEntries.computeIfPresent((StoredFlowEntry) rule, (k, stored) -> {
Jon Hallfa132292017-10-24 11:11:24 -0700854 if (rule instanceof DefaultFlowEntry) {
855 DefaultFlowEntry toRemove = (DefaultFlowEntry) rule;
856 if (stored instanceof DefaultFlowEntry) {
857 DefaultFlowEntry storedEntry = (DefaultFlowEntry) stored;
858 if (toRemove.created() < storedEntry.created()) {
859 log.debug("Trying to remove more recent flow entry {} (stored: {})",
Jordan Haltermance336f72018-01-16 17:08:09 -0800860 toRemove, stored);
Jon Hallfa132292017-10-24 11:11:24 -0700861 // the key is not updated, removedRule remains null
862 return stored;
863 }
864 }
865 }
866 removedRule.set(stored);
867 return null;
868 });
Jordan Haltermance336f72018-01-16 17:08:09 -0800869 return flowEntries.isEmpty() ? null : flowEntries;
870 });
Jon Hallfa132292017-10-24 11:11:24 -0700871
872 if (removedRule.get() != null) {
873 lastUpdateTimes.put(deviceId, System.currentTimeMillis());
874 return removedRule.get();
875 } else {
876 return null;
877 }
878 }
879
880 public void purgeFlowRule(DeviceId deviceId) {
881 flowEntries.remove(deviceId);
882 }
883
884 public void purgeFlowRules() {
885 flowEntries.clear();
886 }
887
888 private List<NodeId> getBackupNodes(DeviceId deviceId) {
889 // The returned backup node list is in the order of preference i.e. next likely master first.
890 List<NodeId> allPossibleBackupNodes = replicaInfoManager.getReplicaInfoFor(deviceId).backups();
891 return ImmutableList.copyOf(allPossibleBackupNodes)
892 .subList(0, Math.min(allPossibleBackupNodes.size(), backupCount));
893 }
894
895 private void backup() {
896 try {
897 // compute a mapping from node to the set of devices whose flow entries it should backup
898 Map<NodeId, Set<DeviceId>> devicesToBackupByNode = Maps.newHashMap();
899 flowEntries.keySet().forEach(deviceId -> {
900 List<NodeId> backupNodes = getBackupNodes(deviceId);
901 backupNodes.forEach(backupNode -> {
902 if (lastBackupTimes.getOrDefault(new BackupOperation(backupNode, deviceId), 0L)
903 < lastUpdateTimes.getOrDefault(deviceId, 0L)) {
904 devicesToBackupByNode.computeIfAbsent(backupNode,
905 nodeId -> Sets.newHashSet()).add(deviceId);
906 }
907 });
908 });
909 // send the device flow entries to their respective backup nodes
910 devicesToBackupByNode.forEach(this::sendBackups);
911 } catch (Exception e) {
912 log.error("Backup failed.", e);
913 }
914 }
915
916 private Set<DeviceId> onBackupReceipt(Map<DeviceId,
917 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>> flowTables) {
918 log.debug("Received flowEntries for {} to backup", flowTables.keySet());
919 Set<DeviceId> backedupDevices = Sets.newHashSet();
920 try {
921 flowTables.forEach((deviceId, deviceFlowTable) -> {
922 // Only process those devices are that not managed by the local node.
923 if (!Objects.equals(local, mastershipService.getMasterFor(deviceId))) {
924 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> backupFlowTable =
925 getFlowTable(deviceId);
926 backupFlowTable.clear();
927 backupFlowTable.putAll(deviceFlowTable);
928 backedupDevices.add(deviceId);
929 }
930 });
931 } catch (Exception e) {
932 log.warn("Failure processing backup request", e);
933 }
934 return backedupDevices;
935 }
936 }
937
938 @Override
939 public FlowRuleEvent updateTableStatistics(DeviceId deviceId,
940 List<TableStatisticsEntry> tableStats) {
941 deviceTableStats.put(deviceId, tableStats);
942 return null;
943 }
944
945 @Override
946 public Iterable<TableStatisticsEntry> getTableStatistics(DeviceId deviceId) {
947 NodeId master = mastershipService.getMasterFor(deviceId);
948
949 if (master == null) {
950 log.debug("Failed to getTableStats: No master for {}", deviceId);
951 return Collections.emptyList();
952 }
953
954 List<TableStatisticsEntry> tableStats = deviceTableStats.get(deviceId);
955 if (tableStats == null) {
956 return Collections.emptyList();
957 }
958 return ImmutableList.copyOf(tableStats);
959 }
960
961 @Override
962 public long getActiveFlowRuleCount(DeviceId deviceId) {
963 return Streams.stream(getTableStatistics(deviceId))
964 .mapToLong(TableStatisticsEntry::activeFlowEntries)
965 .sum();
966 }
967
968 private class InternalTableStatsListener
969 implements EventuallyConsistentMapListener<DeviceId, List<TableStatisticsEntry>> {
970 @Override
971 public void event(EventuallyConsistentMapEvent<DeviceId,
972 List<TableStatisticsEntry>> event) {
973 //TODO: Generate an event to listeners (do we need?)
974 }
975 }
976}