blob: aaaf766b1de518388a2e20f47e7042cf6321c197 [file] [log] [blame]
Yoonseon Hane026a7f2017-08-23 06:05:25 +09001/*
2 * Copyright 2017-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 */
16
17package org.onosproject.incubator.store.virtual.impl;
18
19import com.google.common.base.MoreObjects;
20import com.google.common.collect.ComparisonChain;
21import com.google.common.collect.ImmutableList;
22import com.google.common.collect.Iterables;
23import com.google.common.collect.Maps;
24import com.google.common.util.concurrent.Futures;
25import org.apache.felix.scr.annotations.Activate;
26import org.apache.felix.scr.annotations.Component;
27import org.apache.felix.scr.annotations.Deactivate;
28import org.apache.felix.scr.annotations.Modified;
29import org.apache.felix.scr.annotations.Property;
30import org.apache.felix.scr.annotations.Reference;
31import org.apache.felix.scr.annotations.ReferenceCardinality;
32import org.apache.felix.scr.annotations.Service;
33import org.onlab.util.KryoNamespace;
34import org.onlab.util.Tools;
35import org.onosproject.cfg.ComponentConfigService;
36import org.onosproject.cluster.ClusterService;
37import org.onosproject.cluster.NodeId;
38import org.onosproject.core.CoreService;
39import org.onosproject.core.IdGenerator;
40import org.onosproject.incubator.net.virtual.NetworkId;
41import org.onosproject.incubator.net.virtual.VirtualNetworkFlowRuleStore;
42import org.onosproject.incubator.net.virtual.VirtualNetworkService;
43import org.onosproject.incubator.store.virtual.impl.primitives.VirtualDeviceId;
44import org.onosproject.incubator.store.virtual.impl.primitives.VirtualFlowEntry;
45import org.onosproject.incubator.store.virtual.impl.primitives.VirtualFlowRule;
46import org.onosproject.incubator.store.virtual.impl.primitives.VirtualFlowRuleBatchEvent;
47import org.onosproject.incubator.store.virtual.impl.primitives.VirtualFlowRuleBatchOperation;
48import org.onosproject.mastership.MastershipService;
49import org.onosproject.net.DeviceId;
50import org.onosproject.net.device.DeviceService;
51import org.onosproject.net.flow.BatchOperationEntry;
52import org.onosproject.net.flow.CompletedBatchOperation;
53import org.onosproject.net.flow.DefaultFlowEntry;
54import org.onosproject.net.flow.FlowEntry;
55import org.onosproject.net.flow.FlowId;
56import org.onosproject.net.flow.FlowRule;
Ray Milkey7bf273c2017-09-27 16:15:15 -070057import org.onosproject.net.flow.oldbatch.FlowRuleBatchEntry;
58import org.onosproject.net.flow.oldbatch.FlowRuleBatchEvent;
59import org.onosproject.net.flow.oldbatch.FlowRuleBatchOperation;
60import org.onosproject.net.flow.oldbatch.FlowRuleBatchRequest;
Yoonseon Hane026a7f2017-08-23 06:05:25 +090061import org.onosproject.net.flow.FlowRuleEvent;
62import org.onosproject.net.flow.FlowRuleService;
63import org.onosproject.net.flow.FlowRuleStoreDelegate;
64import org.onosproject.net.flow.StoredFlowEntry;
65import org.onosproject.net.flow.TableStatisticsEntry;
66import org.onosproject.store.Timestamp;
67import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
68import org.onosproject.store.cluster.messaging.ClusterMessage;
69import org.onosproject.store.cluster.messaging.ClusterMessageHandler;
70import org.onosproject.store.cluster.messaging.MessageSubject;
71import org.onosproject.store.serializers.KryoNamespaces;
72import org.onosproject.store.service.EventuallyConsistentMap;
73import org.onosproject.store.service.EventuallyConsistentMapEvent;
74import org.onosproject.store.service.EventuallyConsistentMapListener;
75import org.onosproject.store.service.Serializer;
76import org.onosproject.store.service.StorageService;
77import org.onosproject.store.service.WallClockTimestamp;
78import org.osgi.service.component.ComponentContext;
79import org.slf4j.Logger;
80
81import java.util.Collections;
82import java.util.Dictionary;
83import java.util.HashSet;
84import java.util.List;
85import java.util.Map;
86import java.util.Objects;
87import java.util.Set;
88import java.util.concurrent.ExecutorService;
89import java.util.concurrent.Executors;
90import java.util.concurrent.TimeUnit;
91import java.util.concurrent.atomic.AtomicInteger;
92import java.util.concurrent.atomic.AtomicReference;
93import java.util.stream.Collectors;
94
95import static com.google.common.base.Preconditions.checkArgument;
96import static com.google.common.base.Strings.isNullOrEmpty;
97import static org.onlab.util.Tools.get;
98import static org.onlab.util.Tools.groupedThreads;
99import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_REMOVED;
100import static org.slf4j.LoggerFactory.getLogger;
101
102/**
103 * Manages inventory of flow rules using a distributed state management protocol
104 * for virtual networks.
105 */
106//TODO: support backup and persistent mechanism
107@Component(immediate = true, enabled = false)
108@Service
109public class DistributedVirtualFlowRuleStore
110 extends AbstractVirtualStore<FlowRuleBatchEvent, FlowRuleStoreDelegate>
111 implements VirtualNetworkFlowRuleStore {
112
113 private final Logger log = getLogger(getClass());
114
115 //TODO: confirm this working fine with multiple thread more than 1
116 private static final int MESSAGE_HANDLER_THREAD_POOL_SIZE = 1;
117 private static final boolean DEFAULT_PERSISTENCE_ENABLED = false;
118 private static final int DEFAULT_BACKUP_PERIOD_MILLIS = 2000;
119 private static final long FLOW_RULE_STORE_TIMEOUT_MILLIS = 5000;
120
121 private static final String FLOW_OP_TOPIC = "virtual-flow-ops-ids";
122
123 // MessageSubjects used by DistributedVirtualFlowRuleStore peer-peer communication.
124 private static final MessageSubject APPLY_BATCH_FLOWS
125 = new MessageSubject("virtual-peer-forward-apply-batch");
126 private static final MessageSubject GET_FLOW_ENTRY
127 = new MessageSubject("virtual-peer-forward-get-flow-entry");
128 private static final MessageSubject GET_DEVICE_FLOW_ENTRIES
129 = new MessageSubject("virtual-peer-forward-get-device-flow-entries");
130 private static final MessageSubject REMOVE_FLOW_ENTRY
131 = new MessageSubject("virtual-peer-forward-remove-flow-entry");
132 private static final MessageSubject REMOTE_APPLY_COMPLETED
133 = new MessageSubject("virtual-peer-apply-completed");
134
135 @Property(name = "msgHandlerPoolSize", intValue = MESSAGE_HANDLER_THREAD_POOL_SIZE,
136 label = "Number of threads in the message handler pool")
137 private int msgHandlerPoolSize = MESSAGE_HANDLER_THREAD_POOL_SIZE;
138
139 @Property(name = "backupPeriod", intValue = DEFAULT_BACKUP_PERIOD_MILLIS,
140 label = "Delay in ms between successive backup runs")
141 private int backupPeriod = DEFAULT_BACKUP_PERIOD_MILLIS;
142 @Property(name = "persistenceEnabled", boolValue = false,
143 label = "Indicates whether or not changes in the flow table should be persisted to disk.")
144 private boolean persistenceEnabled = DEFAULT_PERSISTENCE_ENABLED;
145
146 private InternalFlowTable flowTable = new InternalFlowTable();
147
148 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
149 protected CoreService coreService;
150
151 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
152 protected ClusterService clusterService;
153
154 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
155 protected ClusterCommunicationService clusterCommunicator;
156
157 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
158 protected ComponentConfigService configService;
159
160 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
161 protected StorageService storageService;
162
163 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
164 protected VirtualNetworkService vnaService;
165
166 private Map<Long, NodeId> pendingResponses = Maps.newConcurrentMap();
167 private ExecutorService messageHandlingExecutor;
168 private ExecutorService eventHandler;
169
170 private EventuallyConsistentMap<NetworkId, Map<DeviceId, List<TableStatisticsEntry>>> deviceTableStats;
171 private final EventuallyConsistentMapListener<NetworkId, Map<DeviceId, List<TableStatisticsEntry>>>
172 tableStatsListener = new InternalTableStatsListener();
173
174
175 protected final Serializer serializer = Serializer.using(KryoNamespace.newBuilder()
176 .register(KryoNamespaces.API)
177 .register(NetworkId.class)
178 .register(VirtualFlowRuleBatchOperation.class)
179 .register(VirtualFlowRuleBatchEvent.class)
180 .build());
181
182 protected final KryoNamespace.Builder serializerBuilder = KryoNamespace.newBuilder()
183 .register(KryoNamespaces.API)
184 .register(MastershipBasedTimestamp.class);
185
186 private IdGenerator idGenerator;
187 private NodeId local;
188
189
190 @Activate
191 public void activate(ComponentContext context) {
192 configService.registerProperties(getClass());
193
194 idGenerator = coreService.getIdGenerator(FLOW_OP_TOPIC);
195
196 local = clusterService.getLocalNode().id();
197
198 eventHandler = Executors.newSingleThreadExecutor(
199 groupedThreads("onos/virtual-flow", "event-handler", log));
200 messageHandlingExecutor = Executors.newFixedThreadPool(
201 msgHandlerPoolSize, groupedThreads("onos/store/virtual-flow", "message-handlers", log));
202
203 registerMessageHandlers(messageHandlingExecutor);
204
205 deviceTableStats = storageService
206 .<NetworkId, Map<DeviceId, List<TableStatisticsEntry>>>eventuallyConsistentMapBuilder()
207 .withName("onos-virtual-flow-table-stats")
208 .withSerializer(serializerBuilder)
209 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
210 .withTimestampProvider((k, v) -> new WallClockTimestamp())
211 .withTombstonesDisabled()
212 .build();
213 deviceTableStats.addListener(tableStatsListener);
214
215 logConfig("Started");
216 }
217
218 @Deactivate
219 public void deactivate(ComponentContext context) {
220 configService.unregisterProperties(getClass(), false);
221 unregisterMessageHandlers();
222 deviceTableStats.removeListener(tableStatsListener);
223 deviceTableStats.destroy();
224 eventHandler.shutdownNow();
225 messageHandlingExecutor.shutdownNow();
226 log.info("Stopped");
227 }
228
229 @SuppressWarnings("rawtypes")
230 @Modified
231 public void modified(ComponentContext context) {
232 if (context == null) {
233 logConfig("Default config");
234 return;
235 }
236
237 Dictionary properties = context.getProperties();
238 int newPoolSize;
239 int newBackupPeriod;
240 try {
241 String s = get(properties, "msgHandlerPoolSize");
242 newPoolSize = isNullOrEmpty(s) ? msgHandlerPoolSize : Integer.parseInt(s.trim());
243
244 s = get(properties, "backupPeriod");
245 newBackupPeriod = isNullOrEmpty(s) ? backupPeriod : Integer.parseInt(s.trim());
246 } catch (NumberFormatException | ClassCastException e) {
247 newPoolSize = MESSAGE_HANDLER_THREAD_POOL_SIZE;
248 newBackupPeriod = DEFAULT_BACKUP_PERIOD_MILLIS;
249 }
250
251 boolean restartBackupTask = false;
252
253 if (newBackupPeriod != backupPeriod) {
254 backupPeriod = newBackupPeriod;
255 restartBackupTask = true;
256 }
257 if (restartBackupTask) {
258 log.warn("Currently, backup tasks are not supported.");
259 }
260 if (newPoolSize != msgHandlerPoolSize) {
261 msgHandlerPoolSize = newPoolSize;
262 ExecutorService oldMsgHandler = messageHandlingExecutor;
263 messageHandlingExecutor = Executors.newFixedThreadPool(
264 msgHandlerPoolSize, groupedThreads("onos/store/virtual-flow", "message-handlers", log));
265
266 // replace previously registered handlers.
267 registerMessageHandlers(messageHandlingExecutor);
268 oldMsgHandler.shutdown();
269 }
270
271 logConfig("Reconfigured");
272 }
273
274 @Override
275 public int getFlowRuleCount(NetworkId networkId) {
276 AtomicInteger sum = new AtomicInteger(0);
277 DeviceService deviceService = vnaService.get(networkId, DeviceService.class);
278 deviceService.getDevices()
279 .forEach(device -> sum.addAndGet(
280 Iterables.size(getFlowEntries(networkId, device.id()))));
281 return sum.get();
282 }
283
284 @Override
285 public FlowEntry getFlowEntry(NetworkId networkId, FlowRule rule) {
286 MastershipService mastershipService =
287 vnaService.get(networkId, MastershipService.class);
288 NodeId master = mastershipService.getMasterFor(rule.deviceId());
289
290 if (master == null) {
291 log.debug("Failed to getFlowEntry: No master for {}, vnet {}",
292 rule.deviceId(), networkId);
293 return null;
294 }
295
296 if (Objects.equals(local, master)) {
297 return flowTable.getFlowEntry(networkId, rule);
298 }
299
300 log.trace("Forwarding getFlowEntry to {}, which is the primary (master) " +
301 "for device {}, vnet {}",
302 master, rule.deviceId(), networkId);
303
304 VirtualFlowRule vRule = new VirtualFlowRule(networkId, rule);
305
306 return Tools.futureGetOrElse(clusterCommunicator.sendAndReceive(vRule,
307 GET_FLOW_ENTRY,
308 serializer::encode,
309 serializer::decode,
310 master),
311 FLOW_RULE_STORE_TIMEOUT_MILLIS,
312 TimeUnit.MILLISECONDS,
313 null);
314 }
315
316 @Override
317 public Iterable<FlowEntry> getFlowEntries(NetworkId networkId, DeviceId deviceId) {
318 MastershipService mastershipService =
319 vnaService.get(networkId, MastershipService.class);
320 NodeId master = mastershipService.getMasterFor(deviceId);
321
322 if (master == null) {
323 log.debug("Failed to getFlowEntries: No master for {}, vnet {}", deviceId, networkId);
324 return Collections.emptyList();
325 }
326
327 if (Objects.equals(local, master)) {
328 return flowTable.getFlowEntries(networkId, deviceId);
329 }
330
331 log.trace("Forwarding getFlowEntries to {}, which is the primary (master) for device {}",
332 master, deviceId);
333
334 return Tools.futureGetOrElse(
335 clusterCommunicator.sendAndReceive(deviceId,
336 GET_DEVICE_FLOW_ENTRIES,
337 serializer::encode,
338 serializer::decode,
339 master),
340 FLOW_RULE_STORE_TIMEOUT_MILLIS,
341 TimeUnit.MILLISECONDS,
342 Collections.emptyList());
343 }
344
345 @Override
346 public void storeBatch(NetworkId networkId, FlowRuleBatchOperation operation) {
347 if (operation.getOperations().isEmpty()) {
348 notifyDelegate(networkId, FlowRuleBatchEvent.completed(
349 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
350 new CompletedBatchOperation(true, Collections.emptySet(), operation.deviceId())));
351 return;
352 }
353
354 DeviceId deviceId = operation.deviceId();
355 MastershipService mastershipService =
356 vnaService.get(networkId, MastershipService.class);
357 NodeId master = mastershipService.getMasterFor(deviceId);
358
359 if (master == null) {
360 log.warn("No master for {}, vnet {} : flows will be marked for removal", deviceId, networkId);
361
362 updateStoreInternal(networkId, operation);
363
364 notifyDelegate(networkId, FlowRuleBatchEvent.completed(
365 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
366 new CompletedBatchOperation(true, Collections.emptySet(), operation.deviceId())));
367 return;
368 }
369
370 if (Objects.equals(local, master)) {
371 storeBatchInternal(networkId, operation);
372 return;
373 }
374
375 log.trace("Forwarding storeBatch to {}, which is the primary (master) for device {}, vent {}",
376 master, deviceId, networkId);
377
378 clusterCommunicator.unicast(new VirtualFlowRuleBatchOperation(networkId, operation),
379 APPLY_BATCH_FLOWS,
380 serializer::encode,
381 master)
382 .whenComplete((result, error) -> {
383 if (error != null) {
384 log.warn("Failed to storeBatch: {} to {}", operation, master, error);
385
386 Set<FlowRule> allFailures = operation.getOperations()
387 .stream()
388 .map(BatchOperationEntry::target)
389 .collect(Collectors.toSet());
390
391 notifyDelegate(networkId, FlowRuleBatchEvent.completed(
392 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
393 new CompletedBatchOperation(false, allFailures, deviceId)));
394 }
395 });
396 }
397
398 @Override
399 public void batchOperationComplete(NetworkId networkId, FlowRuleBatchEvent event) {
400 //FIXME: need a per device pending response
401 NodeId nodeId = pendingResponses.remove(event.subject().batchId());
402 if (nodeId == null) {
403 notifyDelegate(networkId, event);
404 } else {
405 // TODO check unicast return value
406 clusterCommunicator.unicast(new VirtualFlowRuleBatchEvent(networkId, event),
407 REMOTE_APPLY_COMPLETED, serializer::encode, nodeId);
408 //error log: log.warn("Failed to respond to peer for batch operation result");
409 }
410 }
411
412 @Override
413 public void deleteFlowRule(NetworkId networkId, FlowRule rule) {
414 storeBatch(networkId,
415 new FlowRuleBatchOperation(
416 Collections.singletonList(
417 new FlowRuleBatchEntry(
418 FlowRuleBatchEntry.FlowRuleOperation.REMOVE,
419 rule)), rule.deviceId(), idGenerator.getNewId()));
420 }
421
422 @Override
423 public FlowRuleEvent addOrUpdateFlowRule(NetworkId networkId, FlowEntry rule) {
424 MastershipService mastershipService =
425 vnaService.get(networkId, MastershipService.class);
426 NodeId master = mastershipService.getMasterFor(rule.deviceId());
427 if (Objects.equals(local, master)) {
428 return addOrUpdateFlowRuleInternal(networkId, rule);
429 }
430
431 log.warn("Tried to update FlowRule {} state,"
432 + " while the Node was not the master.", rule);
433 return null;
434 }
435
436 private FlowRuleEvent addOrUpdateFlowRuleInternal(NetworkId networkId, FlowEntry rule) {
437 // check if this new rule is an update to an existing entry
438 StoredFlowEntry stored = flowTable.getFlowEntry(networkId, rule);
439 if (stored != null) {
440 //FIXME modification of "stored" flow entry outside of flow table
441 stored.setBytes(rule.bytes());
442 stored.setLife(rule.life(TimeUnit.NANOSECONDS), TimeUnit.NANOSECONDS);
443 stored.setLiveType(rule.liveType());
444 stored.setPackets(rule.packets());
445 stored.setLastSeen();
446 if (stored.state() == FlowEntry.FlowEntryState.PENDING_ADD) {
447 stored.setState(FlowEntry.FlowEntryState.ADDED);
448 return new FlowRuleEvent(FlowRuleEvent.Type.RULE_ADDED, rule);
449 }
450 return new FlowRuleEvent(FlowRuleEvent.Type.RULE_UPDATED, rule);
451 }
452
453 // TODO: Confirm if this behavior is correct. See SimpleFlowRuleStore
454 // TODO: also update backup if the behavior is correct.
455 flowTable.add(networkId, rule);
456 return null;
457 }
458
459 @Override
460 public FlowRuleEvent removeFlowRule(NetworkId networkId, FlowEntry rule) {
461 final DeviceId deviceId = rule.deviceId();
462
463 MastershipService mastershipService =
464 vnaService.get(networkId, MastershipService.class);
465 NodeId master = mastershipService.getMasterFor(deviceId);
466
467 if (Objects.equals(local, master)) {
468 // bypass and handle it locally
469 return removeFlowRuleInternal(new VirtualFlowEntry(networkId, rule));
470 }
471
472 if (master == null) {
473 log.warn("Failed to removeFlowRule: No master for {}", deviceId);
474 // TODO: revisit if this should be null (="no-op") or Exception
475 return null;
476 }
477
478 log.trace("Forwarding removeFlowRule to {}, which is the master for device {}",
479 master, deviceId);
480
481 return Futures.getUnchecked(clusterCommunicator.sendAndReceive(
482 new VirtualFlowEntry(networkId, rule),
483 REMOVE_FLOW_ENTRY,
484 serializer::encode,
485 serializer::decode,
486 master));
487 }
488
489 @Override
490 public FlowRuleEvent pendingFlowRule(NetworkId networkId, FlowEntry rule) {
491 MastershipService mastershipService =
492 vnaService.get(networkId, MastershipService.class);
493 if (mastershipService.isLocalMaster(rule.deviceId())) {
494 StoredFlowEntry stored = flowTable.getFlowEntry(networkId, rule);
495 if (stored != null &&
496 stored.state() != FlowEntry.FlowEntryState.PENDING_ADD) {
497 stored.setState(FlowEntry.FlowEntryState.PENDING_ADD);
498 return new FlowRuleEvent(FlowRuleEvent.Type.RULE_UPDATED, rule);
499 }
500 }
501 return null;
502 }
503
504 @Override
505 public void purgeFlowRules(NetworkId networkId) {
506 flowTable.purgeFlowRules(networkId);
507 }
508
509 @Override
510 public FlowRuleEvent updateTableStatistics(NetworkId networkId,
511 DeviceId deviceId,
512 List<TableStatisticsEntry> tableStats) {
513 if (deviceTableStats.get(networkId) == null) {
514 deviceTableStats.put(networkId, Maps.newConcurrentMap());
515 }
516 deviceTableStats.get(networkId).put(deviceId, tableStats);
517 return null;
518 }
519
520 @Override
521 public Iterable<TableStatisticsEntry> getTableStatistics(NetworkId networkId, DeviceId deviceId) {
522 MastershipService mastershipService =
523 vnaService.get(networkId, MastershipService.class);
524 NodeId master = mastershipService.getMasterFor(deviceId);
525
526 if (master == null) {
527 log.debug("Failed to getTableStats: No master for {}", deviceId);
528 return Collections.emptyList();
529 }
530
531 if (deviceTableStats.get(networkId) == null) {
532 deviceTableStats.put(networkId, Maps.newConcurrentMap());
533 }
534
535 List<TableStatisticsEntry> tableStats = deviceTableStats.get(networkId).get(deviceId);
536 if (tableStats == null) {
537 return Collections.emptyList();
538 }
539 return ImmutableList.copyOf(tableStats);
540 }
541
542 private void registerMessageHandlers(ExecutorService executor) {
543 clusterCommunicator.addSubscriber(APPLY_BATCH_FLOWS, new OnStoreBatch(), executor);
544 clusterCommunicator.<VirtualFlowRuleBatchEvent>addSubscriber(
545 REMOTE_APPLY_COMPLETED, serializer::decode,
546 this::notifyDelicateByNetwork, executor);
547 clusterCommunicator.addSubscriber(
548 GET_FLOW_ENTRY, serializer::decode, this::getFlowEntryByNetwork,
549 serializer::encode, executor);
550 clusterCommunicator.addSubscriber(
551 GET_DEVICE_FLOW_ENTRIES, serializer::decode,
552 this::getFlowEntriesByNetwork,
553 serializer::encode, executor);
554 clusterCommunicator.addSubscriber(
555 REMOVE_FLOW_ENTRY, serializer::decode, this::removeFlowRuleInternal,
556 serializer::encode, executor);
557 }
558
559 private void unregisterMessageHandlers() {
560 clusterCommunicator.removeSubscriber(REMOVE_FLOW_ENTRY);
561 clusterCommunicator.removeSubscriber(GET_DEVICE_FLOW_ENTRIES);
562 clusterCommunicator.removeSubscriber(GET_FLOW_ENTRY);
563 clusterCommunicator.removeSubscriber(APPLY_BATCH_FLOWS);
564 clusterCommunicator.removeSubscriber(REMOTE_APPLY_COMPLETED);
565 }
566
567
568 private void logConfig(String prefix) {
569 log.info("{} with msgHandlerPoolSize = {}; backupPeriod = {}",
570 prefix, msgHandlerPoolSize, backupPeriod);
571 }
572
573 private void storeBatchInternal(NetworkId networkId, FlowRuleBatchOperation operation) {
574
575 final DeviceId did = operation.deviceId();
576 //final Collection<FlowEntry> ft = flowTable.getFlowEntries(did);
577 Set<FlowRuleBatchEntry> currentOps = updateStoreInternal(networkId, operation);
578 if (currentOps.isEmpty()) {
579 batchOperationComplete(networkId, FlowRuleBatchEvent.completed(
580 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
581 new CompletedBatchOperation(true, Collections.emptySet(), did)));
582 return;
583 }
584
585 //Confirm that flowrule service is created
586 vnaService.get(networkId, FlowRuleService.class);
587
588 notifyDelegate(networkId, FlowRuleBatchEvent.requested(new
589 FlowRuleBatchRequest(operation.id(),
590 currentOps), operation.deviceId()));
591 }
592
593 private Set<FlowRuleBatchEntry> updateStoreInternal(NetworkId networkId,
594 FlowRuleBatchOperation operation) {
595 return operation.getOperations().stream().map(
596 op -> {
597 StoredFlowEntry entry;
598 switch (op.operator()) {
599 case ADD:
600 entry = new DefaultFlowEntry(op.target());
601 // always add requested FlowRule
602 // Note: 2 equal FlowEntry may have different treatment
603 flowTable.remove(networkId, entry.deviceId(), entry);
604 flowTable.add(networkId, entry);
605
606 return op;
607 case REMOVE:
608 entry = flowTable.getFlowEntry(networkId, op.target());
609 if (entry != null) {
610 //FIXME modification of "stored" flow entry outside of flow table
611 entry.setState(FlowEntry.FlowEntryState.PENDING_REMOVE);
612 log.debug("Setting state of rule to pending remove: {}", entry);
613 return op;
614 }
615 break;
616 case MODIFY:
617 //TODO: figure this out at some point
618 break;
619 default:
620 log.warn("Unknown flow operation operator: {}", op.operator());
621 }
622 return null;
623 }
624 ).filter(Objects::nonNull).collect(Collectors.toSet());
625 }
626
627 private FlowRuleEvent removeFlowRuleInternal(VirtualFlowEntry rule) {
628 final DeviceId deviceId = rule.flowEntry().deviceId();
629 // This is where one could mark a rule as removed and still keep it in the store.
630 final FlowEntry removed = flowTable.remove(rule.networkId(), deviceId, rule.flowEntry());
631 // rule may be partial rule that is missing treatment, we should use rule from store instead
632 return removed != null ? new FlowRuleEvent(RULE_REMOVED, removed) : null;
633 }
634
635 private final class OnStoreBatch implements ClusterMessageHandler {
636
637 @Override
638 public void handle(final ClusterMessage message) {
639 VirtualFlowRuleBatchOperation vOperation = serializer.decode(message.payload());
640 log.debug("received batch request {}", vOperation);
641
642 FlowRuleBatchOperation operation = vOperation.operation();
643
644 final DeviceId deviceId = operation.deviceId();
645 MastershipService mastershipService =
646 vnaService.get(vOperation.networkId(), MastershipService.class);
647 NodeId master = mastershipService.getMasterFor(deviceId);
648 if (!Objects.equals(local, master)) {
649 Set<FlowRule> failures = new HashSet<>(operation.size());
650 for (FlowRuleBatchEntry op : operation.getOperations()) {
651 failures.add(op.target());
652 }
653 CompletedBatchOperation allFailed = new CompletedBatchOperation(false, failures, deviceId);
654 // This node is no longer the master, respond as all failed.
655 // TODO: we might want to wrap response in envelope
656 // to distinguish sw programming failure and hand over
657 // it make sense in the latter case to retry immediately.
658 message.respond(serializer.encode(allFailed));
659 return;
660 }
661
662 pendingResponses.put(operation.id(), message.sender());
663 storeBatchInternal(vOperation.networkId(), operation);
664 }
665 }
666
667 /**
668 * Returns flow rule entry using virtual flow rule.
669 *
670 * @param rule an encapsulated flow rule to be queried
671 */
672 private FlowEntry getFlowEntryByNetwork(VirtualFlowRule rule) {
673 return flowTable.getFlowEntry(rule.networkId(), rule.rule());
674 }
675
676 /**
677 * returns flow entries using virtual device id.
678 *
679 * @param deviceId an encapsulated virtual device id
680 * @return a set of flow entries
681 */
682 private Set<FlowEntry> getFlowEntriesByNetwork(VirtualDeviceId deviceId) {
683 return flowTable.getFlowEntries(deviceId.networkId(), deviceId.deviceId());
684 }
685
686 /**
687 * span out Flow Rule Batch event according to virtual network id.
688 *
689 * @param event a event to be span out
690 */
691 private void notifyDelicateByNetwork(VirtualFlowRuleBatchEvent event) {
692 batchOperationComplete(event.networkId(), event.event());
693 }
694
695 private class InternalFlowTable {
696 //TODO replace the Map<V,V> with ExtendedSet
697 //TODO: support backup mechanism
698 private final Map<NetworkId, Map<DeviceId, Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>>
699 flowEntriesMap = Maps.newConcurrentMap();
700 private final Map<NetworkId, Map<DeviceId, Long>> lastUpdateTimesMap = Maps.newConcurrentMap();
701
702 private Map<DeviceId, Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>
703 getFlowEntriesByNetwork(NetworkId networkId) {
704 return flowEntriesMap.computeIfAbsent(networkId, k -> Maps.newConcurrentMap());
705 }
706
707 private Map<DeviceId, Long> getLastUpdateTimesByNetwork(NetworkId networkId) {
708 return lastUpdateTimesMap.computeIfAbsent(networkId, k -> Maps.newConcurrentMap());
709 }
710
711 /**
712 * Returns the flow table for specified device.
713 *
714 * @param networkId virtual network identifier
715 * @param deviceId identifier of the device
716 * @return Map representing Flow Table of given device.
717 */
718 private Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>
719 getFlowTable(NetworkId networkId, DeviceId deviceId) {
720 Map<DeviceId, Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>
721 flowEntries = getFlowEntriesByNetwork(networkId);
722 if (persistenceEnabled) {
723 //TODO: support persistent
724 log.warn("Persistent is not supported");
725 return null;
726 } else {
727 return flowEntries.computeIfAbsent(deviceId, id -> Maps.newConcurrentMap());
728 }
729 }
730
731 private Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>
732 getFlowTableCopy(NetworkId networkId, DeviceId deviceId) {
733
734 Map<DeviceId, Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>
735 flowEntries = getFlowEntriesByNetwork(networkId);
736 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> copy = Maps.newHashMap();
737
738 if (persistenceEnabled) {
739 //TODO: support persistent
740 log.warn("Persistent is not supported");
741 return null;
742 } else {
743 flowEntries.computeIfAbsent(deviceId, id -> Maps.newConcurrentMap()).forEach((k, v) -> {
744 copy.put(k, Maps.newHashMap(v));
745 });
746 return copy;
747 }
748 }
749
750 private Map<StoredFlowEntry, StoredFlowEntry>
751 getFlowEntriesInternal(NetworkId networkId, DeviceId deviceId, FlowId flowId) {
752
753 return getFlowTable(networkId, deviceId)
754 .computeIfAbsent(flowId, id -> Maps.newConcurrentMap());
755 }
756
757 private StoredFlowEntry getFlowEntryInternal(NetworkId networkId, FlowRule rule) {
758
759 return getFlowEntriesInternal(networkId, rule.deviceId(), rule.id()).get(rule);
760 }
761
762 private Set<FlowEntry> getFlowEntriesInternal(NetworkId networkId, DeviceId deviceId) {
763
764 return getFlowTable(networkId, deviceId).values().stream()
765 .flatMap(m -> m.values().stream())
766 .collect(Collectors.toSet());
767 }
768
769 public StoredFlowEntry getFlowEntry(NetworkId networkId, FlowRule rule) {
770 return getFlowEntryInternal(networkId, rule);
771 }
772
773 public Set<FlowEntry> getFlowEntries(NetworkId networkId, DeviceId deviceId) {
774
775 return getFlowEntriesInternal(networkId, deviceId);
776 }
777
778 public void add(NetworkId networkId, FlowEntry rule) {
779 Map<DeviceId, Long> lastUpdateTimes = getLastUpdateTimesByNetwork(networkId);
780
781 getFlowEntriesInternal(networkId, rule.deviceId(), rule.id())
782 .compute((StoredFlowEntry) rule, (k, stored) -> {
783 //TODO compare stored and rule timestamps
784 //TODO the key is not updated
785 return (StoredFlowEntry) rule;
786 });
787 lastUpdateTimes.put(rule.deviceId(), System.currentTimeMillis());
788 }
789
790 public FlowEntry remove(NetworkId networkId, DeviceId deviceId, FlowEntry rule) {
791 final AtomicReference<FlowEntry> removedRule = new AtomicReference<>();
792 Map<DeviceId, Long> lastUpdateTimes = getLastUpdateTimesByNetwork(networkId);
793
794 getFlowEntriesInternal(networkId, rule.deviceId(), rule.id())
795 .computeIfPresent((StoredFlowEntry) rule, (k, stored) -> {
796 if (rule instanceof DefaultFlowEntry) {
797 DefaultFlowEntry toRemove = (DefaultFlowEntry) rule;
798 if (stored instanceof DefaultFlowEntry) {
799 DefaultFlowEntry storedEntry = (DefaultFlowEntry) stored;
800 if (toRemove.created() < storedEntry.created()) {
801 log.debug("Trying to remove more recent flow entry {} (stored: {})",
802 toRemove, stored);
803 // the key is not updated, removedRule remains null
804 return stored;
805 }
806 }
807 }
808 removedRule.set(stored);
809 return null;
810 });
811
812 if (removedRule.get() != null) {
813 lastUpdateTimes.put(deviceId, System.currentTimeMillis());
814 return removedRule.get();
815 } else {
816 return null;
817 }
818 }
819
820 public void purgeFlowRule(NetworkId networkId, DeviceId deviceId) {
821 Map<DeviceId, Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>
822 flowEntries = getFlowEntriesByNetwork(networkId);
823 flowEntries.remove(deviceId);
824 }
825
826 public void purgeFlowRules(NetworkId networkId) {
827 Map<DeviceId, Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>
828 flowEntries = getFlowEntriesByNetwork(networkId);
829 flowEntries.clear();
830 }
831 }
832
833 private class InternalTableStatsListener
834 implements EventuallyConsistentMapListener<NetworkId, Map<DeviceId, List<TableStatisticsEntry>>> {
835
836 @Override
837 public void event(EventuallyConsistentMapEvent<NetworkId, Map<DeviceId,
838 List<TableStatisticsEntry>>> event) {
839 //TODO: Generate an event to listeners (do we need?)
840 }
841 }
842
843 public final class MastershipBasedTimestamp implements Timestamp {
844
845 private final long termNumber;
846 private final long sequenceNumber;
847
848 /**
849 * Default constructor for serialization.
850 */
851 protected MastershipBasedTimestamp() {
852 this.termNumber = -1;
853 this.sequenceNumber = -1;
854 }
855
856 /**
857 * Default version tuple.
858 *
859 * @param termNumber the mastership termNumber
860 * @param sequenceNumber the sequenceNumber number within the termNumber
861 */
862 public MastershipBasedTimestamp(long termNumber, long sequenceNumber) {
863 this.termNumber = termNumber;
864 this.sequenceNumber = sequenceNumber;
865 }
866
867 @Override
868 public int compareTo(Timestamp o) {
869 checkArgument(o instanceof MastershipBasedTimestamp,
870 "Must be MastershipBasedTimestamp", o);
871 MastershipBasedTimestamp that = (MastershipBasedTimestamp) o;
872
873 return ComparisonChain.start()
874 .compare(this.termNumber, that.termNumber)
875 .compare(this.sequenceNumber, that.sequenceNumber)
876 .result();
877 }
878
879 @Override
880 public int hashCode() {
881 return Objects.hash(termNumber, sequenceNumber);
882 }
883
884 @Override
885 public boolean equals(Object obj) {
886 if (this == obj) {
887 return true;
888 }
889 if (!(obj instanceof MastershipBasedTimestamp)) {
890 return false;
891 }
892 MastershipBasedTimestamp that = (MastershipBasedTimestamp) obj;
893 return Objects.equals(this.termNumber, that.termNumber) &&
894 Objects.equals(this.sequenceNumber, that.sequenceNumber);
895 }
896
897 @Override
898 public String toString() {
899 return MoreObjects.toStringHelper(getClass())
900 .add("termNumber", termNumber)
901 .add("sequenceNumber", sequenceNumber)
902 .toString();
903 }
904
905 /**
906 * Returns the termNumber.
907 *
908 * @return termNumber
909 */
910 public long termNumber() {
911 return termNumber;
912 }
913
914 /**
915 * Returns the sequenceNumber number.
916 *
917 * @return sequenceNumber
918 */
919 public long sequenceNumber() {
920 return sequenceNumber;
921 }
922 }
923}