blob: cd29b77f7567b31f51bcd1e91b79143f55f448ad [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
189
190 private IdGenerator idGenerator;
191 private NodeId local;
192
193 @Activate
194 public void activate(ComponentContext context) {
195 configService.registerProperties(getClass());
196
197 idGenerator = coreService.getIdGenerator(FlowRuleService.FLOW_OP_TOPIC);
198
199 local = clusterService.getLocalNode().id();
200
201 eventHandler = Executors.newSingleThreadExecutor(
202 groupedThreads("onos/flow", "event-handler", log));
203 messageHandlingExecutor = Executors.newFixedThreadPool(
204 msgHandlerPoolSize, groupedThreads("onos/store/flow", "message-handlers", log));
205
206 registerMessageHandlers(messageHandlingExecutor);
207
208 replicaInfoManager.addListener(flowTable);
209 backupTask = backupSenderExecutor.scheduleWithFixedDelay(
210 flowTable::backup,
211 0,
212 backupPeriod,
213 TimeUnit.MILLISECONDS);
214
215 deviceTableStats = storageService.<DeviceId, List<TableStatisticsEntry>>eventuallyConsistentMapBuilder()
216 .withName("onos-flow-table-stats")
217 .withSerializer(serializerBuilder)
218 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
219 .withTimestampProvider((k, v) -> new WallClockTimestamp())
220 .withTombstonesDisabled()
221 .build();
222 deviceTableStats.addListener(tableStatsListener);
223
224 logConfig("Started");
225 }
226
227 @Deactivate
228 public void deactivate(ComponentContext context) {
229 replicaInfoManager.removeListener(flowTable);
230 backupTask.cancel(true);
231 configService.unregisterProperties(getClass(), false);
232 unregisterMessageHandlers();
233 deviceTableStats.removeListener(tableStatsListener);
234 deviceTableStats.destroy();
235 eventHandler.shutdownNow();
236 messageHandlingExecutor.shutdownNow();
237 backupSenderExecutor.shutdownNow();
238 log.info("Stopped");
239 }
240
241 @SuppressWarnings("rawtypes")
242 @Modified
243 public void modified(ComponentContext context) {
244 if (context == null) {
245 logConfig("Default config");
246 return;
247 }
248
249 Dictionary properties = context.getProperties();
250 int newPoolSize;
251 int newBackupPeriod;
252 int newBackupCount;
253 try {
254 String s = get(properties, "msgHandlerPoolSize");
255 newPoolSize = isNullOrEmpty(s) ? msgHandlerPoolSize : Integer.parseInt(s.trim());
256
257 s = get(properties, "backupPeriod");
258 newBackupPeriod = isNullOrEmpty(s) ? backupPeriod : Integer.parseInt(s.trim());
259
260 s = get(properties, "backupCount");
261 newBackupCount = isNullOrEmpty(s) ? backupCount : Integer.parseInt(s.trim());
262 } catch (NumberFormatException | ClassCastException e) {
263 newPoolSize = MESSAGE_HANDLER_THREAD_POOL_SIZE;
264 newBackupPeriod = DEFAULT_BACKUP_PERIOD_MILLIS;
265 newBackupCount = DEFAULT_MAX_BACKUP_COUNT;
266 }
267
268 boolean restartBackupTask = false;
269
270 if (newBackupPeriod != backupPeriod) {
271 backupPeriod = newBackupPeriod;
272 restartBackupTask = true;
273 }
274 if (restartBackupTask) {
275 if (backupTask != null) {
276 // cancel previously running task
277 backupTask.cancel(false);
278 }
279 backupTask = backupSenderExecutor.scheduleWithFixedDelay(
280 flowTable::backup,
281 0,
282 backupPeriod,
283 TimeUnit.MILLISECONDS);
284 }
285 if (newPoolSize != msgHandlerPoolSize) {
286 msgHandlerPoolSize = newPoolSize;
287 ExecutorService oldMsgHandler = messageHandlingExecutor;
288 messageHandlingExecutor = Executors.newFixedThreadPool(
289 msgHandlerPoolSize, groupedThreads("onos/store/flow", "message-handlers", log));
290
291 // replace previously registered handlers.
292 registerMessageHandlers(messageHandlingExecutor);
293 oldMsgHandler.shutdown();
294 }
295 if (backupCount != newBackupCount) {
296 backupCount = newBackupCount;
297 }
298 logConfig("Reconfigured");
299 }
300
301 private void registerMessageHandlers(ExecutorService executor) {
302
303 clusterCommunicator.addSubscriber(APPLY_BATCH_FLOWS, new OnStoreBatch(), executor);
304 clusterCommunicator.<FlowRuleBatchEvent>addSubscriber(
305 REMOTE_APPLY_COMPLETED, serializer::decode, this::notifyDelegate, executor);
306 clusterCommunicator.addSubscriber(
307 GET_FLOW_ENTRY, serializer::decode, flowTable::getFlowEntry, serializer::encode, executor);
308 clusterCommunicator.addSubscriber(
309 GET_DEVICE_FLOW_ENTRIES, serializer::decode, flowTable::getFlowEntries, serializer::encode, executor);
310 clusterCommunicator.addSubscriber(
311 REMOVE_FLOW_ENTRY, serializer::decode, this::removeFlowRuleInternal, serializer::encode, executor);
312 clusterCommunicator.addSubscriber(
313 FLOW_TABLE_BACKUP, serializer::decode, flowTable::onBackupReceipt, serializer::encode, executor);
314 }
315
316 private void unregisterMessageHandlers() {
317 clusterCommunicator.removeSubscriber(REMOVE_FLOW_ENTRY);
318 clusterCommunicator.removeSubscriber(GET_DEVICE_FLOW_ENTRIES);
319 clusterCommunicator.removeSubscriber(GET_FLOW_ENTRY);
320 clusterCommunicator.removeSubscriber(APPLY_BATCH_FLOWS);
321 clusterCommunicator.removeSubscriber(REMOTE_APPLY_COMPLETED);
322 clusterCommunicator.removeSubscriber(FLOW_TABLE_BACKUP);
323 }
324
325 private void logConfig(String prefix) {
326 log.info("{} with msgHandlerPoolSize = {}; backupPeriod = {}, backupCount = {}",
327 prefix, msgHandlerPoolSize, backupPeriod, backupCount);
328 }
329
330 // This is not a efficient operation on a distributed sharded
331 // flow store. We need to revisit the need for this operation or at least
332 // make it device specific.
333 @Override
334 public int getFlowRuleCount() {
335 return Streams.stream(deviceService.getDevices()).parallel()
336 .mapToInt(device -> Iterables.size(getFlowEntries(device.id())))
337 .sum();
338 }
339
340 @Override
341 public FlowEntry getFlowEntry(FlowRule rule) {
342 NodeId master = mastershipService.getMasterFor(rule.deviceId());
343
344 if (master == null) {
345 log.debug("Failed to getFlowEntry: No master for {}", rule.deviceId());
346 return null;
347 }
348
349 if (Objects.equals(local, master)) {
350 return flowTable.getFlowEntry(rule);
351 }
352
353 log.trace("Forwarding getFlowEntry to {}, which is the primary (master) for device {}",
354 master, rule.deviceId());
355
356 return Tools.futureGetOrElse(clusterCommunicator.sendAndReceive(rule,
357 ECFlowRuleStoreMessageSubjects.GET_FLOW_ENTRY,
358 serializer::encode,
359 serializer::decode,
360 master),
361 FLOW_RULE_STORE_TIMEOUT_MILLIS,
362 TimeUnit.MILLISECONDS,
363 null);
364 }
365
366 @Override
367 public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) {
368 NodeId master = mastershipService.getMasterFor(deviceId);
369
370 if (master == null) {
371 log.debug("Failed to getFlowEntries: No master for {}", deviceId);
372 return Collections.emptyList();
373 }
374
375 if (Objects.equals(local, master)) {
376 return flowTable.getFlowEntries(deviceId);
377 }
378
379 log.trace("Forwarding getFlowEntries to {}, which is the primary (master) for device {}",
380 master, deviceId);
381
382 return Tools.futureGetOrElse(clusterCommunicator.sendAndReceive(deviceId,
383 ECFlowRuleStoreMessageSubjects.GET_DEVICE_FLOW_ENTRIES,
384 serializer::encode,
385 serializer::decode,
386 master),
387 FLOW_RULE_STORE_TIMEOUT_MILLIS,
388 TimeUnit.MILLISECONDS,
389 Collections.emptyList());
390 }
391
392 @Override
393 public void storeFlowRule(FlowRule rule) {
394 storeBatch(new FlowRuleBatchOperation(
395 Collections.singletonList(new FlowRuleBatchEntry(FlowRuleOperation.ADD, rule)),
396 rule.deviceId(), idGenerator.getNewId()));
397 }
398
399 @Override
400 public void storeBatch(FlowRuleBatchOperation operation) {
401 if (operation.getOperations().isEmpty()) {
402 notifyDelegate(FlowRuleBatchEvent.completed(
403 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
404 new CompletedBatchOperation(true, Collections.emptySet(), operation.deviceId())));
405 return;
406 }
407
408 DeviceId deviceId = operation.deviceId();
409 NodeId master = mastershipService.getMasterFor(deviceId);
410
411 if (master == null) {
412 log.warn("No master for {} ", deviceId);
413
414 updateStoreInternal(operation);
415
416 notifyDelegate(FlowRuleBatchEvent.completed(
417 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
418 new CompletedBatchOperation(true, Collections.emptySet(), operation.deviceId())));
419 return;
420 }
421
422 if (Objects.equals(local, master)) {
423 storeBatchInternal(operation);
424 return;
425 }
426
427 log.trace("Forwarding storeBatch to {}, which is the primary (master) for device {}",
428 master, deviceId);
429
430 clusterCommunicator.unicast(operation,
431 APPLY_BATCH_FLOWS,
432 serializer::encode,
433 master)
434 .whenComplete((result, error) -> {
435 if (error != null) {
436 log.warn("Failed to storeBatch: {} to {}", operation, master, error);
437
438 Set<FlowRule> allFailures = operation.getOperations()
439 .stream()
440 .map(op -> op.target())
441 .collect(Collectors.toSet());
442
443 notifyDelegate(FlowRuleBatchEvent.completed(
444 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
445 new CompletedBatchOperation(false, allFailures, deviceId)));
446 }
447 });
448 }
449
450 private void storeBatchInternal(FlowRuleBatchOperation operation) {
451
452 final DeviceId did = operation.deviceId();
453 //final Collection<FlowEntry> ft = flowTable.getFlowEntries(did);
454 Set<FlowRuleBatchEntry> currentOps = updateStoreInternal(operation);
455 if (currentOps.isEmpty()) {
456 batchOperationComplete(FlowRuleBatchEvent.completed(
457 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
458 new CompletedBatchOperation(true, Collections.emptySet(), did)));
459 return;
460 }
461
462 notifyDelegate(FlowRuleBatchEvent.requested(new
463 FlowRuleBatchRequest(operation.id(),
464 currentOps), operation.deviceId()));
465 }
466
467 private Set<FlowRuleBatchEntry> updateStoreInternal(FlowRuleBatchOperation operation) {
468 return operation.getOperations().stream().map(
469 op -> {
470 StoredFlowEntry entry;
471 switch (op.operator()) {
472 case ADD:
473 entry = new DefaultFlowEntry(op.target());
474 // always add requested FlowRule
475 // Note: 2 equal FlowEntry may have different treatment
476 flowTable.remove(entry.deviceId(), entry);
477 flowTable.add(entry);
478
479 return op;
480 case REMOVE:
481 entry = flowTable.getFlowEntry(op.target());
482 if (entry != null) {
483 //FIXME modification of "stored" flow entry outside of flow table
484 entry.setState(FlowEntryState.PENDING_REMOVE);
485 log.debug("Setting state of rule to pending remove: {}", entry);
486 return op;
487 }
488 break;
489 case MODIFY:
490 //TODO: figure this out at some point
491 break;
492 default:
493 log.warn("Unknown flow operation operator: {}", op.operator());
494 }
495 return null;
496 }
497 ).filter(Objects::nonNull).collect(Collectors.toSet());
498 }
499
500 @Override
501 public void deleteFlowRule(FlowRule rule) {
502 storeBatch(
503 new FlowRuleBatchOperation(
504 Collections.singletonList(
505 new FlowRuleBatchEntry(
506 FlowRuleOperation.REMOVE,
507 rule)), rule.deviceId(), idGenerator.getNewId()));
508 }
509
510 @Override
511 public FlowRuleEvent pendingFlowRule(FlowEntry rule) {
512 if (mastershipService.isLocalMaster(rule.deviceId())) {
513 StoredFlowEntry stored = flowTable.getFlowEntry(rule);
514 if (stored != null &&
515 stored.state() != FlowEntryState.PENDING_ADD) {
516 stored.setState(FlowEntryState.PENDING_ADD);
517 return new FlowRuleEvent(Type.RULE_UPDATED, rule);
518 }
519 }
520 return null;
521 }
522
523 @Override
524 public FlowRuleEvent addOrUpdateFlowRule(FlowEntry rule) {
525 NodeId master = mastershipService.getMasterFor(rule.deviceId());
526 if (Objects.equals(local, master)) {
527 return addOrUpdateFlowRuleInternal(rule);
528 }
529
530 log.warn("Tried to update FlowRule {} state,"
531 + " while the Node was not the master.", rule);
532 return null;
533 }
534
535 private FlowRuleEvent addOrUpdateFlowRuleInternal(FlowEntry rule) {
536 // check if this new rule is an update to an existing entry
537 StoredFlowEntry stored = flowTable.getFlowEntry(rule);
538 if (stored != null) {
539 //FIXME modification of "stored" flow entry outside of flow table
540 stored.setBytes(rule.bytes());
541 stored.setLife(rule.life(TimeUnit.NANOSECONDS), TimeUnit.NANOSECONDS);
542 stored.setLiveType(rule.liveType());
543 stored.setPackets(rule.packets());
544 stored.setLastSeen();
545 if (stored.state() == FlowEntryState.PENDING_ADD) {
546 stored.setState(FlowEntryState.ADDED);
547 return new FlowRuleEvent(Type.RULE_ADDED, rule);
548 }
549 return new FlowRuleEvent(Type.RULE_UPDATED, rule);
550 }
551
552 // TODO: Confirm if this behavior is correct. See SimpleFlowRuleStore
553 // TODO: also update backup if the behavior is correct.
554 flowTable.add(rule);
555 return null;
556 }
557
558 @Override
559 public FlowRuleEvent removeFlowRule(FlowEntry rule) {
560 final DeviceId deviceId = rule.deviceId();
561 NodeId master = mastershipService.getMasterFor(deviceId);
562
563 if (Objects.equals(local, master)) {
564 // bypass and handle it locally
565 return removeFlowRuleInternal(rule);
566 }
567
568 if (master == null) {
569 log.warn("Failed to removeFlowRule: No master for {}", deviceId);
570 // TODO: revisit if this should be null (="no-op") or Exception
571 return null;
572 }
573
574 log.trace("Forwarding removeFlowRule to {}, which is the master for device {}",
575 master, deviceId);
576
577 return Futures.getUnchecked(clusterCommunicator.sendAndReceive(
578 rule,
579 REMOVE_FLOW_ENTRY,
580 serializer::encode,
581 serializer::decode,
582 master));
583 }
584
585 private FlowRuleEvent removeFlowRuleInternal(FlowEntry rule) {
586 final DeviceId deviceId = rule.deviceId();
587 // This is where one could mark a rule as removed and still keep it in the store.
588 final FlowEntry removed = flowTable.remove(deviceId, rule);
589 // rule may be partial rule that is missing treatment, we should use rule from store instead
590 return removed != null ? new FlowRuleEvent(RULE_REMOVED, removed) : null;
591 }
592
593 @Override
594 public void purgeFlowRule(DeviceId deviceId) {
595 flowTable.purgeFlowRule(deviceId);
596 }
597
598 @Override
599 public void purgeFlowRules() {
600 flowTable.purgeFlowRules();
601 }
602
603 @Override
604 public void batchOperationComplete(FlowRuleBatchEvent event) {
605 //FIXME: need a per device pending response
606 NodeId nodeId = pendingResponses.remove(event.subject().batchId());
607 if (nodeId == null) {
608 notifyDelegate(event);
609 } else {
610 // TODO check unicast return value
611 clusterCommunicator.unicast(event, REMOTE_APPLY_COMPLETED, serializer::encode, nodeId);
612 //error log: log.warn("Failed to respond to peer for batch operation result");
613 }
614 }
615
616 private final class OnStoreBatch implements ClusterMessageHandler {
617
618 @Override
619 public void handle(final ClusterMessage message) {
620 FlowRuleBatchOperation operation = serializer.decode(message.payload());
621 log.debug("received batch request {}", operation);
622
623 final DeviceId deviceId = operation.deviceId();
624 NodeId master = mastershipService.getMasterFor(deviceId);
625 if (!Objects.equals(local, master)) {
626 Set<FlowRule> failures = new HashSet<>(operation.size());
627 for (FlowRuleBatchEntry op : operation.getOperations()) {
628 failures.add(op.target());
629 }
630 CompletedBatchOperation allFailed = new CompletedBatchOperation(false, failures, deviceId);
631 // This node is no longer the master, respond as all failed.
632 // TODO: we might want to wrap response in envelope
633 // to distinguish sw programming failure and hand over
634 // it make sense in the latter case to retry immediately.
635 message.respond(serializer.encode(allFailed));
636 return;
637 }
638
639 pendingResponses.put(operation.id(), message.sender());
640 storeBatchInternal(operation);
641 }
642 }
643
644 private class BackupOperation {
645 private final NodeId nodeId;
646 private final DeviceId deviceId;
647
648 public BackupOperation(NodeId nodeId, DeviceId deviceId) {
649 this.nodeId = nodeId;
650 this.deviceId = deviceId;
651 }
652
653 @Override
654 public int hashCode() {
655 return Objects.hash(nodeId, deviceId);
656 }
657
658 @Override
659 public boolean equals(Object other) {
660 if (other != null && other instanceof BackupOperation) {
661 BackupOperation that = (BackupOperation) other;
662 return this.nodeId.equals(that.nodeId) &&
663 this.deviceId.equals(that.deviceId);
664 } else {
665 return false;
666 }
667 }
668 }
669
670 private class InternalFlowTable implements ReplicaInfoEventListener {
671
672 //TODO replace the Map<V,V> with ExtendedSet
673 private final Map<DeviceId, Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>
674 flowEntries = Maps.newConcurrentMap();
675
676 private final Map<BackupOperation, Long> lastBackupTimes = Maps.newConcurrentMap();
677 private final Map<DeviceId, Long> lastUpdateTimes = Maps.newConcurrentMap();
678
679 @Override
680 public void event(ReplicaInfoEvent event) {
681 eventHandler.execute(() -> handleEvent(event));
682 }
683
684 private void handleEvent(ReplicaInfoEvent event) {
685 DeviceId deviceId = event.subject();
686 if (!mastershipService.isLocalMaster(deviceId)) {
687 return;
688 }
689 if (event.type() == MASTER_CHANGED) {
690 lastUpdateTimes.put(deviceId, System.currentTimeMillis());
691 }
692 backupSenderExecutor.schedule(this::backup, 0, TimeUnit.SECONDS);
693 }
694
695 private void sendBackups(NodeId nodeId, Set<DeviceId> deviceIds) {
696 // split up the devices into smaller batches and send them separately.
697 Iterables.partition(deviceIds, FLOW_TABLE_BACKUP_BATCH_SIZE)
698 .forEach(ids -> backupFlowEntries(nodeId, Sets.newHashSet(ids)));
699 }
700
701 private void backupFlowEntries(NodeId nodeId, Set<DeviceId> deviceIds) {
702 if (deviceIds.isEmpty()) {
703 return;
704 }
705 log.debug("Sending flowEntries for devices {} to {} for backup.", deviceIds, nodeId);
706 Map<DeviceId, Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>
707 deviceFlowEntries = Maps.newConcurrentMap();
708 deviceIds.forEach(id -> deviceFlowEntries.put(id, getFlowTableCopy(id)));
709 clusterCommunicator.<Map<DeviceId,
710 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>,
711 Set<DeviceId>>
712 sendAndReceive(deviceFlowEntries,
713 FLOW_TABLE_BACKUP,
714 serializer::encode,
715 serializer::decode,
716 nodeId)
717 .whenComplete((backedupDevices, error) -> {
718 Set<DeviceId> devicesNotBackedup = error != null ?
719 deviceFlowEntries.keySet() :
720 Sets.difference(deviceFlowEntries.keySet(), backedupDevices);
721 if (devicesNotBackedup.size() > 0) {
722 log.warn("Failed to backup devices: {}. Reason: {}, Node: {}",
723 devicesNotBackedup, error != null ? error.getMessage() : "none",
724 nodeId);
725 }
726 if (backedupDevices != null) {
727 backedupDevices.forEach(id -> {
728 lastBackupTimes.put(new BackupOperation(nodeId, id), System.currentTimeMillis());
729 });
730 }
731 });
732 }
733
734 /**
735 * Returns the flow table for specified device.
736 *
737 * @param deviceId identifier of the device
738 * @return Map representing Flow Table of given device.
739 */
740 private Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> getFlowTable(DeviceId deviceId) {
741 if (persistenceEnabled) {
742 return flowEntries.computeIfAbsent(deviceId, id -> persistenceService
743 .<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>persistentMapBuilder()
744 .withName("FlowTable:" + deviceId.toString())
745 .withSerializer(new Serializer() {
746 @Override
747 public <T> byte[] encode(T object) {
748 return serializer.encode(object);
749 }
750
751 @Override
752 public <T> T decode(byte[] bytes) {
753 return serializer.decode(bytes);
754 }
755
756 @Override
757 public <T> T copy(T object) {
758 return serializer.copy(object);
759 }
760 })
761 .build());
762 } else {
763 return flowEntries.computeIfAbsent(deviceId, id -> Maps.newConcurrentMap());
764 }
765 }
766
767 private Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> getFlowTableCopy(DeviceId deviceId) {
768 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> copy = Maps.newHashMap();
769 if (persistenceEnabled) {
770 return flowEntries.computeIfAbsent(deviceId, id -> persistenceService
771 .<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>persistentMapBuilder()
772 .withName("FlowTable:" + deviceId.toString())
773 .withSerializer(new Serializer() {
774 @Override
775 public <T> byte[] encode(T object) {
776 return serializer.encode(object);
777 }
778
779 @Override
780 public <T> T decode(byte[] bytes) {
781 return serializer.decode(bytes);
782 }
783
784 @Override
785 public <T> T copy(T object) {
786 return serializer.copy(object);
787 }
788 })
789 .build());
790 } else {
791 flowEntries.computeIfAbsent(deviceId, id -> Maps.newConcurrentMap()).forEach((k, v) -> {
792 copy.put(k, Maps.newHashMap(v));
793 });
794 return copy;
795 }
796 }
797
798 private Map<StoredFlowEntry, StoredFlowEntry> getFlowEntriesInternal(DeviceId deviceId, FlowId flowId) {
799 return getFlowTable(deviceId).computeIfAbsent(flowId, id -> Maps.newConcurrentMap());
800 }
801
802 private StoredFlowEntry getFlowEntryInternal(FlowRule rule) {
803 return getFlowEntriesInternal(rule.deviceId(), rule.id()).get(rule);
804 }
805
806 private Set<FlowEntry> getFlowEntriesInternal(DeviceId deviceId) {
807 return getFlowTable(deviceId).values().stream()
808 .flatMap(m -> m.values().stream())
809 .collect(Collectors.toSet());
810 }
811
812 public StoredFlowEntry getFlowEntry(FlowRule rule) {
813 return getFlowEntryInternal(rule);
814 }
815
816 public Set<FlowEntry> getFlowEntries(DeviceId deviceId) {
817 return getFlowEntriesInternal(deviceId);
818 }
819
820 public void add(FlowEntry rule) {
821 getFlowEntriesInternal(rule.deviceId(), rule.id())
822 .compute((StoredFlowEntry) rule, (k, stored) -> {
823 //TODO compare stored and rule timestamps
824 //TODO the key is not updated
825 return (StoredFlowEntry) rule;
826 });
827 lastUpdateTimes.put(rule.deviceId(), System.currentTimeMillis());
828 }
829
830 public FlowEntry remove(DeviceId deviceId, FlowEntry rule) {
831 final AtomicReference<FlowEntry> removedRule = new AtomicReference<>();
832 getFlowEntriesInternal(rule.deviceId(), rule.id())
833 .computeIfPresent((StoredFlowEntry) rule, (k, stored) -> {
834 if (rule instanceof DefaultFlowEntry) {
835 DefaultFlowEntry toRemove = (DefaultFlowEntry) rule;
836 if (stored instanceof DefaultFlowEntry) {
837 DefaultFlowEntry storedEntry = (DefaultFlowEntry) stored;
838 if (toRemove.created() < storedEntry.created()) {
839 log.debug("Trying to remove more recent flow entry {} (stored: {})",
840 toRemove, stored);
841 // the key is not updated, removedRule remains null
842 return stored;
843 }
844 }
845 }
846 removedRule.set(stored);
847 return null;
848 });
849
850 if (removedRule.get() != null) {
851 lastUpdateTimes.put(deviceId, System.currentTimeMillis());
852 return removedRule.get();
853 } else {
854 return null;
855 }
856 }
857
858 public void purgeFlowRule(DeviceId deviceId) {
859 flowEntries.remove(deviceId);
860 }
861
862 public void purgeFlowRules() {
863 flowEntries.clear();
864 }
865
866 private List<NodeId> getBackupNodes(DeviceId deviceId) {
867 // The returned backup node list is in the order of preference i.e. next likely master first.
868 List<NodeId> allPossibleBackupNodes = replicaInfoManager.getReplicaInfoFor(deviceId).backups();
869 return ImmutableList.copyOf(allPossibleBackupNodes)
870 .subList(0, Math.min(allPossibleBackupNodes.size(), backupCount));
871 }
872
873 private void backup() {
874 try {
875 // compute a mapping from node to the set of devices whose flow entries it should backup
876 Map<NodeId, Set<DeviceId>> devicesToBackupByNode = Maps.newHashMap();
877 flowEntries.keySet().forEach(deviceId -> {
878 List<NodeId> backupNodes = getBackupNodes(deviceId);
879 backupNodes.forEach(backupNode -> {
880 if (lastBackupTimes.getOrDefault(new BackupOperation(backupNode, deviceId), 0L)
881 < lastUpdateTimes.getOrDefault(deviceId, 0L)) {
882 devicesToBackupByNode.computeIfAbsent(backupNode,
883 nodeId -> Sets.newHashSet()).add(deviceId);
884 }
885 });
886 });
887 // send the device flow entries to their respective backup nodes
888 devicesToBackupByNode.forEach(this::sendBackups);
889 } catch (Exception e) {
890 log.error("Backup failed.", e);
891 }
892 }
893
894 private Set<DeviceId> onBackupReceipt(Map<DeviceId,
895 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>> flowTables) {
896 log.debug("Received flowEntries for {} to backup", flowTables.keySet());
897 Set<DeviceId> backedupDevices = Sets.newHashSet();
898 try {
899 flowTables.forEach((deviceId, deviceFlowTable) -> {
900 // Only process those devices are that not managed by the local node.
901 if (!Objects.equals(local, mastershipService.getMasterFor(deviceId))) {
902 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> backupFlowTable =
903 getFlowTable(deviceId);
904 backupFlowTable.clear();
905 backupFlowTable.putAll(deviceFlowTable);
906 backedupDevices.add(deviceId);
907 }
908 });
909 } catch (Exception e) {
910 log.warn("Failure processing backup request", e);
911 }
912 return backedupDevices;
913 }
914 }
915
916 @Override
917 public FlowRuleEvent updateTableStatistics(DeviceId deviceId,
918 List<TableStatisticsEntry> tableStats) {
919 deviceTableStats.put(deviceId, tableStats);
920 return null;
921 }
922
923 @Override
924 public Iterable<TableStatisticsEntry> getTableStatistics(DeviceId deviceId) {
925 NodeId master = mastershipService.getMasterFor(deviceId);
926
927 if (master == null) {
928 log.debug("Failed to getTableStats: No master for {}", deviceId);
929 return Collections.emptyList();
930 }
931
932 List<TableStatisticsEntry> tableStats = deviceTableStats.get(deviceId);
933 if (tableStats == null) {
934 return Collections.emptyList();
935 }
936 return ImmutableList.copyOf(tableStats);
937 }
938
939 @Override
940 public long getActiveFlowRuleCount(DeviceId deviceId) {
941 return Streams.stream(getTableStatistics(deviceId))
942 .mapToLong(TableStatisticsEntry::activeFlowEntries)
943 .sum();
944 }
945
946 private class InternalTableStatsListener
947 implements EventuallyConsistentMapListener<DeviceId, List<TableStatisticsEntry>> {
948 @Override
949 public void event(EventuallyConsistentMapEvent<DeviceId,
950 List<TableStatisticsEntry>> event) {
951 //TODO: Generate an event to listeners (do we need?)
952 }
953 }
954}