blob: a259c26a83c36c43cfc645f3900339097f50b36b [file] [log] [blame]
Madan Jampani86940d92015-05-06 11:47:57 -07001 /*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2015-present Open Networking Laboratory
Madan Jampani86940d92015-05-06 11:47:57 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.store.flow.impl;
17
Brian O'Connora3e5cd52015-12-05 15:59:19 -080018 import com.google.common.collect.ImmutableList;
19 import com.google.common.collect.ImmutableMap;
20 import com.google.common.collect.Iterables;
21 import com.google.common.collect.Maps;
22 import com.google.common.collect.Sets;
23 import com.google.common.util.concurrent.Futures;
24 import org.apache.felix.scr.annotations.Activate;
25 import org.apache.felix.scr.annotations.Component;
26 import org.apache.felix.scr.annotations.Deactivate;
27 import org.apache.felix.scr.annotations.Modified;
28 import org.apache.felix.scr.annotations.Property;
29 import org.apache.felix.scr.annotations.Reference;
30 import org.apache.felix.scr.annotations.ReferenceCardinality;
31 import org.apache.felix.scr.annotations.Service;
32 import org.onlab.util.KryoNamespace;
33 import org.onlab.util.Tools;
34 import org.onosproject.cfg.ComponentConfigService;
35 import org.onosproject.cluster.ClusterService;
36 import org.onosproject.cluster.NodeId;
37 import org.onosproject.core.CoreService;
38 import org.onosproject.core.IdGenerator;
39 import org.onosproject.mastership.MastershipService;
40 import org.onosproject.net.DeviceId;
41 import org.onosproject.net.device.DeviceService;
42 import org.onosproject.net.flow.CompletedBatchOperation;
43 import org.onosproject.net.flow.DefaultFlowEntry;
44 import org.onosproject.net.flow.FlowEntry;
45 import org.onosproject.net.flow.FlowEntry.FlowEntryState;
46 import org.onosproject.net.flow.FlowId;
47 import org.onosproject.net.flow.FlowRule;
48 import org.onosproject.net.flow.FlowRuleBatchEntry;
49 import org.onosproject.net.flow.FlowRuleBatchEntry.FlowRuleOperation;
50 import org.onosproject.net.flow.FlowRuleBatchEvent;
51 import org.onosproject.net.flow.FlowRuleBatchOperation;
52 import org.onosproject.net.flow.FlowRuleBatchRequest;
53 import org.onosproject.net.flow.FlowRuleEvent;
54 import org.onosproject.net.flow.FlowRuleEvent.Type;
55 import org.onosproject.net.flow.FlowRuleService;
56 import org.onosproject.net.flow.FlowRuleStore;
57 import org.onosproject.net.flow.FlowRuleStoreDelegate;
58 import org.onosproject.net.flow.StoredFlowEntry;
59 import org.onosproject.net.flow.TableStatisticsEntry;
60 import org.onosproject.persistence.PersistenceService;
61 import org.onosproject.store.AbstractStore;
62 import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
63 import org.onosproject.store.cluster.messaging.ClusterMessage;
64 import org.onosproject.store.cluster.messaging.ClusterMessageHandler;
65 import org.onosproject.store.flow.ReplicaInfoEvent;
66 import org.onosproject.store.flow.ReplicaInfoEventListener;
67 import org.onosproject.store.flow.ReplicaInfoService;
68 import org.onosproject.store.impl.MastershipBasedTimestamp;
69 import org.onosproject.store.serializers.KryoNamespaces;
Brian O'Connora3e5cd52015-12-05 15:59:19 -080070 import org.onosproject.store.serializers.StoreSerializer;
71 import org.onosproject.store.serializers.custom.DistributedStoreSerializers;
72 import org.onosproject.store.service.EventuallyConsistentMap;
73 import org.onosproject.store.service.EventuallyConsistentMapEvent;
74 import org.onosproject.store.service.EventuallyConsistentMapListener;
75 import org.onosproject.store.service.Serializer;
76 import org.onosproject.store.service.StorageService;
77 import org.onosproject.store.service.WallClockTimestamp;
78 import org.osgi.service.component.ComponentContext;
79 import org.slf4j.Logger;
Madan Jampani86940d92015-05-06 11:47:57 -070080
Brian O'Connora3e5cd52015-12-05 15:59:19 -080081 import java.util.Collections;
82 import java.util.Dictionary;
83 import java.util.HashSet;
84 import java.util.List;
85 import java.util.Map;
Sho SHIMIZU828bc162016-01-13 23:10:43 -080086 import java.util.Objects;
Brian O'Connora3e5cd52015-12-05 15:59:19 -080087 import java.util.Set;
88 import java.util.concurrent.ExecutorService;
89 import java.util.concurrent.Executors;
90 import java.util.concurrent.ScheduledExecutorService;
91 import java.util.concurrent.ScheduledFuture;
92 import java.util.concurrent.TimeUnit;
93 import java.util.concurrent.atomic.AtomicInteger;
94 import java.util.concurrent.atomic.AtomicReference;
95 import java.util.stream.Collectors;
Madan Jampani86940d92015-05-06 11:47:57 -070096
Brian O'Connora3e5cd52015-12-05 15:59:19 -080097 import static com.google.common.base.Strings.isNullOrEmpty;
98 import static org.onlab.util.Tools.get;
99 import static org.onlab.util.Tools.groupedThreads;
100 import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_REMOVED;
101 import static org.onosproject.store.flow.impl.FlowStoreMessageSubjects.*;
102 import static org.slf4j.LoggerFactory.getLogger;
Madan Jampani86940d92015-05-06 11:47:57 -0700103
104/**
105 * Manages inventory of flow rules using a distributed state management protocol.
106 */
107@Component(immediate = true, enabled = true)
108@Service
Madan Jampani37d04c62016-04-25 15:53:55 -0700109public class DistributedFlowRuleStore
Madan Jampani86940d92015-05-06 11:47:57 -0700110 extends AbstractStore<FlowRuleBatchEvent, FlowRuleStoreDelegate>
111 implements FlowRuleStore {
112
113 private final Logger log = getLogger(getClass());
114
115 private static final int MESSAGE_HANDLER_THREAD_POOL_SIZE = 8;
116 private static final boolean DEFAULT_BACKUP_ENABLED = true;
Aaron Kruglikova62fdbb2015-10-27 16:32:06 -0700117 private static final boolean DEFAULT_PERSISTENCE_ENABLED = false;
Madan Jampani08bf17b2015-05-06 16:25:26 -0700118 private static final int DEFAULT_BACKUP_PERIOD_MILLIS = 2000;
Madan Jampani86940d92015-05-06 11:47:57 -0700119 private static final long FLOW_RULE_STORE_TIMEOUT_MILLIS = 5000;
Madan Jampaniadea8902015-06-04 17:39:45 -0700120 // number of devices whose flow entries will be backed up in one communication round
121 private static final int FLOW_TABLE_BACKUP_BATCH_SIZE = 1;
Madan Jampani86940d92015-05-06 11:47:57 -0700122
123 @Property(name = "msgHandlerPoolSize", intValue = MESSAGE_HANDLER_THREAD_POOL_SIZE,
124 label = "Number of threads in the message handler pool")
125 private int msgHandlerPoolSize = MESSAGE_HANDLER_THREAD_POOL_SIZE;
126
127 @Property(name = "backupEnabled", boolValue = DEFAULT_BACKUP_ENABLED,
128 label = "Indicates whether backups are enabled or not")
129 private boolean backupEnabled = DEFAULT_BACKUP_ENABLED;
130
Madan Jampani08bf17b2015-05-06 16:25:26 -0700131 @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;
Aaron Kruglikova62fdbb2015-10-27 16:32:06 -0700134 @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;
Madan Jampani08bf17b2015-05-06 16:25:26 -0700137
Madan Jampani86940d92015-05-06 11:47:57 -0700138 private InternalFlowTable flowTable = new InternalFlowTable();
139
140 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
141 protected ReplicaInfoService replicaInfoManager;
142
143 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
144 protected ClusterCommunicationService clusterCommunicator;
145
146 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
147 protected ClusterService clusterService;
148
149 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
150 protected DeviceService deviceService;
151
152 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
153 protected CoreService coreService;
154
155 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
156 protected ComponentConfigService configService;
157
158 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
159 protected MastershipService mastershipService;
160
Aaron Kruglikova62fdbb2015-10-27 16:32:06 -0700161 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
162 protected PersistenceService persistenceService;
163
Madan Jampani86940d92015-05-06 11:47:57 -0700164 private Map<Long, NodeId> pendingResponses = Maps.newConcurrentMap();
165 private ExecutorService messageHandlingExecutor;
Madan Jampani71c32ca2016-06-22 08:23:18 -0700166 private ExecutorService eventHandler;
Madan Jampani86940d92015-05-06 11:47:57 -0700167
Madan Jampani08bf17b2015-05-06 16:25:26 -0700168 private ScheduledFuture<?> backupTask;
Madan Jampani86940d92015-05-06 11:47:57 -0700169 private final ScheduledExecutorService backupSenderExecutor =
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700170 Executors.newSingleThreadScheduledExecutor(groupedThreads("onos/flow", "backup-sender", log));
Madan Jampani86940d92015-05-06 11:47:57 -0700171
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700172 private EventuallyConsistentMap<DeviceId, List<TableStatisticsEntry>> deviceTableStats;
173 private final EventuallyConsistentMapListener<DeviceId, List<TableStatisticsEntry>> tableStatsListener =
174 new InternalTableStatsListener();
175
176 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
177 protected StorageService storageService;
178
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700179 protected static final StoreSerializer SERIALIZER = StoreSerializer.using(
180 KryoNamespace.newBuilder()
Madan Jampani86940d92015-05-06 11:47:57 -0700181 .register(DistributedStoreSerializers.STORE_COMMON)
182 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700183 .build("FlowRuleStore"));
Madan Jampani86940d92015-05-06 11:47:57 -0700184
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700185 protected static final KryoNamespace.Builder SERIALIZER_BUILDER = KryoNamespace.newBuilder()
186 .register(KryoNamespaces.API)
187 .register(MastershipBasedTimestamp.class);
188
189
Madan Jampani86940d92015-05-06 11:47:57 -0700190 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
Madan Jampani71c32ca2016-06-22 08:23:18 -0700201 eventHandler = Executors.newSingleThreadExecutor(
202 groupedThreads("onos/flow", "event-handler", log));
Madan Jampani86940d92015-05-06 11:47:57 -0700203 messageHandlingExecutor = Executors.newFixedThreadPool(
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700204 msgHandlerPoolSize, groupedThreads("onos/store/flow", "message-handlers", log));
Madan Jampani86940d92015-05-06 11:47:57 -0700205
206 registerMessageHandlers(messageHandlingExecutor);
207
Madan Jampani08bf17b2015-05-06 16:25:26 -0700208 if (backupEnabled) {
Madan Jampanif7536ab2015-05-07 23:23:23 -0700209 replicaInfoManager.addListener(flowTable);
Madan Jampani08bf17b2015-05-06 16:25:26 -0700210 backupTask = backupSenderExecutor.scheduleWithFixedDelay(
211 flowTable::backup,
212 0,
213 backupPeriod,
214 TimeUnit.MILLISECONDS);
215 }
Madan Jampani86940d92015-05-06 11:47:57 -0700216
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700217 deviceTableStats = storageService.<DeviceId, List<TableStatisticsEntry>>eventuallyConsistentMapBuilder()
218 .withName("onos-flow-table-stats")
219 .withSerializer(SERIALIZER_BUILDER)
220 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
221 .withTimestampProvider((k, v) -> new WallClockTimestamp())
222 .withTombstonesDisabled()
223 .build();
224 deviceTableStats.addListener(tableStatsListener);
225
Madan Jampani86940d92015-05-06 11:47:57 -0700226 logConfig("Started");
227 }
228
229 @Deactivate
230 public void deactivate(ComponentContext context) {
Madan Jampanif7536ab2015-05-07 23:23:23 -0700231 if (backupEnabled) {
232 replicaInfoManager.removeListener(flowTable);
233 backupTask.cancel(true);
234 }
Madan Jampani86940d92015-05-06 11:47:57 -0700235 configService.unregisterProperties(getClass(), false);
236 unregisterMessageHandlers();
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700237 deviceTableStats.removeListener(tableStatsListener);
238 deviceTableStats.destroy();
Madan Jampani71c32ca2016-06-22 08:23:18 -0700239 eventHandler.shutdownNow();
Madan Jampani86940d92015-05-06 11:47:57 -0700240 messageHandlingExecutor.shutdownNow();
241 backupSenderExecutor.shutdownNow();
242 log.info("Stopped");
243 }
244
245 @SuppressWarnings("rawtypes")
246 @Modified
247 public void modified(ComponentContext context) {
248 if (context == null) {
249 backupEnabled = DEFAULT_BACKUP_ENABLED;
250 logConfig("Default config");
251 return;
252 }
253
254 Dictionary properties = context.getProperties();
255 int newPoolSize;
256 boolean newBackupEnabled;
Madan Jampani08bf17b2015-05-06 16:25:26 -0700257 int newBackupPeriod;
Madan Jampani86940d92015-05-06 11:47:57 -0700258 try {
259 String s = get(properties, "msgHandlerPoolSize");
260 newPoolSize = isNullOrEmpty(s) ? msgHandlerPoolSize : Integer.parseInt(s.trim());
261
262 s = get(properties, "backupEnabled");
263 newBackupEnabled = isNullOrEmpty(s) ? backupEnabled : Boolean.parseBoolean(s.trim());
264
Madan Jampani08bf17b2015-05-06 16:25:26 -0700265 s = get(properties, "backupPeriod");
266 newBackupPeriod = isNullOrEmpty(s) ? backupPeriod : Integer.parseInt(s.trim());
267
Madan Jampani86940d92015-05-06 11:47:57 -0700268 } catch (NumberFormatException | ClassCastException e) {
269 newPoolSize = MESSAGE_HANDLER_THREAD_POOL_SIZE;
270 newBackupEnabled = DEFAULT_BACKUP_ENABLED;
Madan Jampani08bf17b2015-05-06 16:25:26 -0700271 newBackupPeriod = DEFAULT_BACKUP_PERIOD_MILLIS;
Madan Jampani86940d92015-05-06 11:47:57 -0700272 }
273
Madan Jampani08bf17b2015-05-06 16:25:26 -0700274 boolean restartBackupTask = false;
Madan Jampani86940d92015-05-06 11:47:57 -0700275 if (newBackupEnabled != backupEnabled) {
276 backupEnabled = newBackupEnabled;
Madan Jampanif7536ab2015-05-07 23:23:23 -0700277 if (!backupEnabled) {
278 replicaInfoManager.removeListener(flowTable);
279 if (backupTask != null) {
280 backupTask.cancel(false);
281 backupTask = null;
282 }
283 } else {
284 replicaInfoManager.addListener(flowTable);
Madan Jampani08bf17b2015-05-06 16:25:26 -0700285 }
286 restartBackupTask = backupEnabled;
287 }
288 if (newBackupPeriod != backupPeriod) {
289 backupPeriod = newBackupPeriod;
290 restartBackupTask = backupEnabled;
291 }
292 if (restartBackupTask) {
293 if (backupTask != null) {
294 // cancel previously running task
295 backupTask.cancel(false);
296 }
297 backupTask = backupSenderExecutor.scheduleWithFixedDelay(
298 flowTable::backup,
299 0,
300 backupPeriod,
301 TimeUnit.MILLISECONDS);
Madan Jampani86940d92015-05-06 11:47:57 -0700302 }
303 if (newPoolSize != msgHandlerPoolSize) {
304 msgHandlerPoolSize = newPoolSize;
305 ExecutorService oldMsgHandler = messageHandlingExecutor;
306 messageHandlingExecutor = Executors.newFixedThreadPool(
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800307 msgHandlerPoolSize, groupedThreads("onos/store/flow", "message-handlers", log));
Madan Jampani86940d92015-05-06 11:47:57 -0700308
309 // replace previously registered handlers.
310 registerMessageHandlers(messageHandlingExecutor);
311 oldMsgHandler.shutdown();
312 }
313 logConfig("Reconfigured");
314 }
315
316 private void registerMessageHandlers(ExecutorService executor) {
317
318 clusterCommunicator.addSubscriber(APPLY_BATCH_FLOWS, new OnStoreBatch(), executor);
319 clusterCommunicator.<FlowRuleBatchEvent>addSubscriber(
320 REMOTE_APPLY_COMPLETED, SERIALIZER::decode, this::notifyDelegate, executor);
321 clusterCommunicator.addSubscriber(
322 GET_FLOW_ENTRY, SERIALIZER::decode, flowTable::getFlowEntry, SERIALIZER::encode, executor);
323 clusterCommunicator.addSubscriber(
324 GET_DEVICE_FLOW_ENTRIES, SERIALIZER::decode, flowTable::getFlowEntries, SERIALIZER::encode, executor);
325 clusterCommunicator.addSubscriber(
326 REMOVE_FLOW_ENTRY, SERIALIZER::decode, this::removeFlowRuleInternal, SERIALIZER::encode, executor);
327 clusterCommunicator.addSubscriber(
328 REMOVE_FLOW_ENTRY, SERIALIZER::decode, this::removeFlowRuleInternal, SERIALIZER::encode, executor);
329 clusterCommunicator.addSubscriber(
Madan Jampani654b58a2015-05-22 11:28:11 -0700330 FLOW_TABLE_BACKUP, SERIALIZER::decode, flowTable::onBackupReceipt, SERIALIZER::encode, executor);
Madan Jampani86940d92015-05-06 11:47:57 -0700331 }
332
333 private void unregisterMessageHandlers() {
334 clusterCommunicator.removeSubscriber(REMOVE_FLOW_ENTRY);
335 clusterCommunicator.removeSubscriber(GET_DEVICE_FLOW_ENTRIES);
336 clusterCommunicator.removeSubscriber(GET_FLOW_ENTRY);
337 clusterCommunicator.removeSubscriber(APPLY_BATCH_FLOWS);
338 clusterCommunicator.removeSubscriber(REMOTE_APPLY_COMPLETED);
339 clusterCommunicator.removeSubscriber(FLOW_TABLE_BACKUP);
340 }
341
342 private void logConfig(String prefix) {
Madan Jampani08bf17b2015-05-06 16:25:26 -0700343 log.info("{} with msgHandlerPoolSize = {}; backupEnabled = {}, backupPeriod = {}",
344 prefix, msgHandlerPoolSize, backupEnabled, backupPeriod);
Madan Jampani86940d92015-05-06 11:47:57 -0700345 }
346
347 // This is not a efficient operation on a distributed sharded
348 // flow store. We need to revisit the need for this operation or at least
349 // make it device specific.
350 @Override
351 public int getFlowRuleCount() {
352 AtomicInteger sum = new AtomicInteger(0);
353 deviceService.getDevices().forEach(device -> sum.addAndGet(Iterables.size(getFlowEntries(device.id()))));
354 return sum.get();
355 }
356
357 @Override
358 public FlowEntry getFlowEntry(FlowRule rule) {
Madan Jampani6bd2d9f2015-05-14 14:10:42 -0700359 NodeId master = mastershipService.getMasterFor(rule.deviceId());
Madan Jampani86940d92015-05-06 11:47:57 -0700360
361 if (master == null) {
Thomas Vachuska88fd6902015-08-04 10:08:34 -0700362 log.debug("Failed to getFlowEntry: No master for {}", rule.deviceId());
Madan Jampani86940d92015-05-06 11:47:57 -0700363 return null;
364 }
365
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800366 if (Objects.equals(local, master)) {
Madan Jampani86940d92015-05-06 11:47:57 -0700367 return flowTable.getFlowEntry(rule);
368 }
369
370 log.trace("Forwarding getFlowEntry to {}, which is the primary (master) for device {}",
371 master, rule.deviceId());
372
373 return Tools.futureGetOrElse(clusterCommunicator.sendAndReceive(rule,
374 FlowStoreMessageSubjects.GET_FLOW_ENTRY,
375 SERIALIZER::encode,
376 SERIALIZER::decode,
377 master),
378 FLOW_RULE_STORE_TIMEOUT_MILLIS,
379 TimeUnit.MILLISECONDS,
380 null);
381 }
382
383 @Override
384 public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) {
Madan Jampani6bd2d9f2015-05-14 14:10:42 -0700385 NodeId master = mastershipService.getMasterFor(deviceId);
Madan Jampani86940d92015-05-06 11:47:57 -0700386
387 if (master == null) {
Thomas Vachuska88fd6902015-08-04 10:08:34 -0700388 log.debug("Failed to getFlowEntries: No master for {}", deviceId);
Madan Jampani86940d92015-05-06 11:47:57 -0700389 return Collections.emptyList();
390 }
391
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800392 if (Objects.equals(local, master)) {
Madan Jampani86940d92015-05-06 11:47:57 -0700393 return flowTable.getFlowEntries(deviceId);
394 }
395
396 log.trace("Forwarding getFlowEntries to {}, which is the primary (master) for device {}",
397 master, deviceId);
398
399 return Tools.futureGetOrElse(clusterCommunicator.sendAndReceive(deviceId,
400 FlowStoreMessageSubjects.GET_DEVICE_FLOW_ENTRIES,
401 SERIALIZER::encode,
402 SERIALIZER::decode,
403 master),
404 FLOW_RULE_STORE_TIMEOUT_MILLIS,
405 TimeUnit.MILLISECONDS,
406 Collections.emptyList());
407 }
408
409 @Override
410 public void storeFlowRule(FlowRule rule) {
411 storeBatch(new FlowRuleBatchOperation(
Sho SHIMIZU98ffca82015-05-11 08:39:24 -0700412 Collections.singletonList(new FlowRuleBatchEntry(FlowRuleOperation.ADD, rule)),
Madan Jampani86940d92015-05-06 11:47:57 -0700413 rule.deviceId(), idGenerator.getNewId()));
414 }
415
416 @Override
417 public void storeBatch(FlowRuleBatchOperation operation) {
418 if (operation.getOperations().isEmpty()) {
419 notifyDelegate(FlowRuleBatchEvent.completed(
420 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
421 new CompletedBatchOperation(true, Collections.emptySet(), operation.deviceId())));
422 return;
423 }
424
425 DeviceId deviceId = operation.deviceId();
Madan Jampani6bd2d9f2015-05-14 14:10:42 -0700426 NodeId master = mastershipService.getMasterFor(deviceId);
Madan Jampani86940d92015-05-06 11:47:57 -0700427
428 if (master == null) {
429 log.warn("No master for {} : flows will be marked for removal", deviceId);
430
431 updateStoreInternal(operation);
432
433 notifyDelegate(FlowRuleBatchEvent.completed(
434 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
435 new CompletedBatchOperation(true, Collections.emptySet(), operation.deviceId())));
436 return;
437 }
438
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800439 if (Objects.equals(local, master)) {
Madan Jampani86940d92015-05-06 11:47:57 -0700440 storeBatchInternal(operation);
441 return;
442 }
443
444 log.trace("Forwarding storeBatch to {}, which is the primary (master) for device {}",
445 master, deviceId);
446
Madan Jampani175e8fd2015-05-20 14:10:45 -0700447 clusterCommunicator.unicast(operation,
448 APPLY_BATCH_FLOWS,
449 SERIALIZER::encode,
450 master)
451 .whenComplete((result, error) -> {
Thomas Vachuskaa267ce42015-05-27 16:14:23 -0700452 if (error != null) {
Madan Jampani15f1bc42015-05-28 10:51:52 -0700453 log.warn("Failed to storeBatch: {} to {}", operation, master, error);
Madan Jampani86940d92015-05-06 11:47:57 -0700454
Thomas Vachuskaa267ce42015-05-27 16:14:23 -0700455 Set<FlowRule> allFailures = operation.getOperations()
456 .stream()
457 .map(op -> op.target())
458 .collect(Collectors.toSet());
Madan Jampani86940d92015-05-06 11:47:57 -0700459
Thomas Vachuskaa267ce42015-05-27 16:14:23 -0700460 notifyDelegate(FlowRuleBatchEvent.completed(
461 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
462 new CompletedBatchOperation(false, allFailures, deviceId)));
463 }
Madan Jampani175e8fd2015-05-20 14:10:45 -0700464 });
Madan Jampani86940d92015-05-06 11:47:57 -0700465 }
466
467 private void storeBatchInternal(FlowRuleBatchOperation operation) {
468
469 final DeviceId did = operation.deviceId();
470 //final Collection<FlowEntry> ft = flowTable.getFlowEntries(did);
471 Set<FlowRuleBatchEntry> currentOps = updateStoreInternal(operation);
472 if (currentOps.isEmpty()) {
473 batchOperationComplete(FlowRuleBatchEvent.completed(
474 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
475 new CompletedBatchOperation(true, Collections.emptySet(), did)));
476 return;
477 }
478
479 notifyDelegate(FlowRuleBatchEvent.requested(new
480 FlowRuleBatchRequest(operation.id(),
481 currentOps), operation.deviceId()));
482 }
483
484 private Set<FlowRuleBatchEntry> updateStoreInternal(FlowRuleBatchOperation operation) {
485 return operation.getOperations().stream().map(
486 op -> {
487 StoredFlowEntry entry;
488 switch (op.operator()) {
489 case ADD:
490 entry = new DefaultFlowEntry(op.target());
491 // always add requested FlowRule
492 // Note: 2 equal FlowEntry may have different treatment
493 flowTable.remove(entry.deviceId(), entry);
494 flowTable.add(entry);
495
496 return op;
497 case REMOVE:
498 entry = flowTable.getFlowEntry(op.target());
499 if (entry != null) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800500 //FIXME modification of "stored" flow entry outside of flow table
Madan Jampani86940d92015-05-06 11:47:57 -0700501 entry.setState(FlowEntryState.PENDING_REMOVE);
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800502 log.debug("Setting state of rule to pending remove: {}", entry);
Madan Jampani86940d92015-05-06 11:47:57 -0700503 return op;
504 }
505 break;
506 case MODIFY:
507 //TODO: figure this out at some point
508 break;
509 default:
510 log.warn("Unknown flow operation operator: {}", op.operator());
511 }
512 return null;
513 }
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800514 ).filter(Objects::nonNull).collect(Collectors.toSet());
Madan Jampani86940d92015-05-06 11:47:57 -0700515 }
516
517 @Override
518 public void deleteFlowRule(FlowRule rule) {
519 storeBatch(
520 new FlowRuleBatchOperation(
Sho SHIMIZU98ffca82015-05-11 08:39:24 -0700521 Collections.singletonList(
Madan Jampani86940d92015-05-06 11:47:57 -0700522 new FlowRuleBatchEntry(
523 FlowRuleOperation.REMOVE,
524 rule)), rule.deviceId(), idGenerator.getNewId()));
525 }
526
527 @Override
Charles Chan93fa7272016-01-26 22:27:02 -0800528 public FlowRuleEvent pendingFlowRule(FlowEntry rule) {
529 if (mastershipService.isLocalMaster(rule.deviceId())) {
530 StoredFlowEntry stored = flowTable.getFlowEntry(rule);
531 if (stored != null &&
532 stored.state() != FlowEntryState.PENDING_ADD) {
533 stored.setState(FlowEntryState.PENDING_ADD);
534 return new FlowRuleEvent(Type.RULE_UPDATED, rule);
535 }
536 }
537 return null;
538 }
539
540 @Override
Madan Jampani86940d92015-05-06 11:47:57 -0700541 public FlowRuleEvent addOrUpdateFlowRule(FlowEntry rule) {
Madan Jampani6bd2d9f2015-05-14 14:10:42 -0700542 NodeId master = mastershipService.getMasterFor(rule.deviceId());
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800543 if (Objects.equals(local, master)) {
Madan Jampani86940d92015-05-06 11:47:57 -0700544 return addOrUpdateFlowRuleInternal(rule);
545 }
546
547 log.warn("Tried to update FlowRule {} state,"
548 + " while the Node was not the master.", rule);
549 return null;
550 }
551
552 private FlowRuleEvent addOrUpdateFlowRuleInternal(FlowEntry rule) {
553 // check if this new rule is an update to an existing entry
554 StoredFlowEntry stored = flowTable.getFlowEntry(rule);
555 if (stored != null) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800556 //FIXME modification of "stored" flow entry outside of flow table
Madan Jampani86940d92015-05-06 11:47:57 -0700557 stored.setBytes(rule.bytes());
558 stored.setLife(rule.life());
559 stored.setPackets(rule.packets());
Jonathan Hart89e981f2016-01-04 13:59:55 -0800560 stored.setLastSeen();
Madan Jampani86940d92015-05-06 11:47:57 -0700561 if (stored.state() == FlowEntryState.PENDING_ADD) {
562 stored.setState(FlowEntryState.ADDED);
563 return new FlowRuleEvent(Type.RULE_ADDED, rule);
564 }
565 return new FlowRuleEvent(Type.RULE_UPDATED, rule);
566 }
567
568 // TODO: Confirm if this behavior is correct. See SimpleFlowRuleStore
569 // TODO: also update backup if the behavior is correct.
570 flowTable.add(rule);
571 return null;
572 }
573
574 @Override
575 public FlowRuleEvent removeFlowRule(FlowEntry rule) {
576 final DeviceId deviceId = rule.deviceId();
Madan Jampani6bd2d9f2015-05-14 14:10:42 -0700577 NodeId master = mastershipService.getMasterFor(deviceId);
Madan Jampani86940d92015-05-06 11:47:57 -0700578
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800579 if (Objects.equals(local, master)) {
Madan Jampani86940d92015-05-06 11:47:57 -0700580 // bypass and handle it locally
581 return removeFlowRuleInternal(rule);
582 }
583
584 if (master == null) {
585 log.warn("Failed to removeFlowRule: No master for {}", deviceId);
586 // TODO: revisit if this should be null (="no-op") or Exception
587 return null;
588 }
589
590 log.trace("Forwarding removeFlowRule to {}, which is the master for device {}",
591 master, deviceId);
592
593 return Futures.get(clusterCommunicator.sendAndReceive(
594 rule,
595 REMOVE_FLOW_ENTRY,
596 SERIALIZER::encode,
597 SERIALIZER::decode,
598 master),
599 FLOW_RULE_STORE_TIMEOUT_MILLIS,
600 TimeUnit.MILLISECONDS,
601 RuntimeException.class);
602 }
603
604 private FlowRuleEvent removeFlowRuleInternal(FlowEntry rule) {
605 final DeviceId deviceId = rule.deviceId();
606 // This is where one could mark a rule as removed and still keep it in the store.
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800607 final FlowEntry removed = flowTable.remove(deviceId, rule);
608 // rule may be partial rule that is missing treatment, we should use rule from store instead
609 return removed != null ? new FlowRuleEvent(RULE_REMOVED, removed) : null;
Madan Jampani86940d92015-05-06 11:47:57 -0700610 }
611
612 @Override
Charles Chan0c7c43b2016-01-14 17:39:20 -0800613 public void purgeFlowRule(DeviceId deviceId) {
614 flowTable.purgeFlowRule(deviceId);
615 }
616
617 @Override
Madan Jampani86940d92015-05-06 11:47:57 -0700618 public void batchOperationComplete(FlowRuleBatchEvent event) {
619 //FIXME: need a per device pending response
620 NodeId nodeId = pendingResponses.remove(event.subject().batchId());
621 if (nodeId == null) {
622 notifyDelegate(event);
623 } else {
624 // TODO check unicast return value
625 clusterCommunicator.unicast(event, REMOTE_APPLY_COMPLETED, SERIALIZER::encode, nodeId);
626 //error log: log.warn("Failed to respond to peer for batch operation result");
627 }
628 }
629
630 private final class OnStoreBatch implements ClusterMessageHandler {
631
632 @Override
633 public void handle(final ClusterMessage message) {
634 FlowRuleBatchOperation operation = SERIALIZER.decode(message.payload());
635 log.debug("received batch request {}", operation);
636
637 final DeviceId deviceId = operation.deviceId();
Madan Jampani6bd2d9f2015-05-14 14:10:42 -0700638 NodeId master = mastershipService.getMasterFor(deviceId);
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800639 if (!Objects.equals(local, master)) {
Madan Jampani86940d92015-05-06 11:47:57 -0700640 Set<FlowRule> failures = new HashSet<>(operation.size());
641 for (FlowRuleBatchEntry op : operation.getOperations()) {
642 failures.add(op.target());
643 }
644 CompletedBatchOperation allFailed = new CompletedBatchOperation(false, failures, deviceId);
645 // This node is no longer the master, respond as all failed.
646 // TODO: we might want to wrap response in envelope
647 // to distinguish sw programming failure and hand over
648 // it make sense in the latter case to retry immediately.
649 message.respond(SERIALIZER.encode(allFailed));
650 return;
651 }
652
653 pendingResponses.put(operation.id(), message.sender());
654 storeBatchInternal(operation);
655 }
656 }
657
Madan Jampanif7536ab2015-05-07 23:23:23 -0700658 private class InternalFlowTable implements ReplicaInfoEventListener {
Madan Jampani86940d92015-05-06 11:47:57 -0700659
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800660 //TODO replace the Map<V,V> with ExtendedSet
661 private final Map<DeviceId, Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>
Madan Jampani5c3766c2015-06-02 15:54:41 -0700662 flowEntries = Maps.newConcurrentMap();
Madan Jampani86940d92015-05-06 11:47:57 -0700663
664 private final Map<DeviceId, Long> lastBackupTimes = Maps.newConcurrentMap();
665 private final Map<DeviceId, Long> lastUpdateTimes = Maps.newConcurrentMap();
666 private final Map<DeviceId, NodeId> lastBackupNodes = Maps.newConcurrentMap();
667
Madan Jampanif7536ab2015-05-07 23:23:23 -0700668 @Override
669 public void event(ReplicaInfoEvent event) {
Madan Jampani71c32ca2016-06-22 08:23:18 -0700670 eventHandler.execute(() -> handleEvent(event));
671 }
672
673 private void handleEvent(ReplicaInfoEvent event) {
Madan Jampania98bf932015-06-02 12:01:36 -0700674 if (!backupEnabled) {
675 return;
676 }
Madan Jampanif7536ab2015-05-07 23:23:23 -0700677 if (event.type() == ReplicaInfoEvent.Type.BACKUPS_CHANGED) {
678 DeviceId deviceId = event.subject();
Madan Jampani6bd2d9f2015-05-14 14:10:42 -0700679 NodeId master = mastershipService.getMasterFor(deviceId);
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800680 if (!Objects.equals(local, master)) {
Madan Jampanif7536ab2015-05-07 23:23:23 -0700681 // ignore since this event is for a device this node does not manage.
682 return;
683 }
Madan Jampani7267c552015-05-20 22:39:17 -0700684 NodeId newBackupNode = getBackupNode(deviceId);
685 NodeId currentBackupNode = lastBackupNodes.get(deviceId);
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800686 if (Objects.equals(newBackupNode, currentBackupNode)) {
Madan Jampanif7536ab2015-05-07 23:23:23 -0700687 // ignore since backup location hasn't changed.
688 return;
689 }
Madan Jampani7267c552015-05-20 22:39:17 -0700690 if (currentBackupNode != null && newBackupNode == null) {
691 // Current backup node is most likely down and no alternate backup node
692 // has been chosen. Clear current backup location so that we can resume
693 // backups when either current backup comes online or a different backup node
694 // is chosen.
695 log.warn("Lost backup location {} for deviceId {} and no alternate backup node exists. "
696 + "Flows can be lost if the master goes down", currentBackupNode, deviceId);
697 lastBackupNodes.remove(deviceId);
698 lastBackupTimes.remove(deviceId);
699 return;
700 // TODO: Pick any available node as backup and ensure hand-off occurs when
701 // a new master is elected.
702 }
Madan Jampani44839b82015-06-12 13:57:41 -0700703 log.debug("Backup location for {} has changed from {} to {}.",
Madan Jampani7267c552015-05-20 22:39:17 -0700704 deviceId, currentBackupNode, newBackupNode);
705 backupSenderExecutor.schedule(() -> backupFlowEntries(newBackupNode, Sets.newHashSet(deviceId)),
Madan Jampani03062682015-05-19 17:57:51 -0700706 0,
707 TimeUnit.SECONDS);
Madan Jampanif7536ab2015-05-07 23:23:23 -0700708 }
709 }
710
Madan Jampaniadea8902015-06-04 17:39:45 -0700711 private void sendBackups(NodeId nodeId, Set<DeviceId> deviceIds) {
712 // split up the devices into smaller batches and send them separately.
713 Iterables.partition(deviceIds, FLOW_TABLE_BACKUP_BATCH_SIZE)
714 .forEach(ids -> backupFlowEntries(nodeId, Sets.newHashSet(ids)));
715 }
716
Madan Jampanif7536ab2015-05-07 23:23:23 -0700717 private void backupFlowEntries(NodeId nodeId, Set<DeviceId> deviceIds) {
Madan Jampaniadea8902015-06-04 17:39:45 -0700718 if (deviceIds.isEmpty()) {
719 return;
720 }
Madan Jampanif7536ab2015-05-07 23:23:23 -0700721 log.debug("Sending flowEntries for devices {} to {} as backup.", deviceIds, nodeId);
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800722 Map<DeviceId, Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>
723 deviceFlowEntries = Maps.newConcurrentMap();
Madan Jampani85a9b0d2015-06-03 17:15:44 -0700724 deviceIds.forEach(id -> deviceFlowEntries.put(id, ImmutableMap.copyOf(getFlowTable(id))));
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800725 clusterCommunicator.<Map<DeviceId,
726 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>,
727 Set<DeviceId>>
728 sendAndReceive(deviceFlowEntries,
729 FLOW_TABLE_BACKUP,
730 SERIALIZER::encode,
731 SERIALIZER::decode,
732 nodeId)
733 .whenComplete((backedupDevices, error) -> {
734 Set<DeviceId> devicesNotBackedup = error != null ?
735 deviceFlowEntries.keySet() :
736 Sets.difference(deviceFlowEntries.keySet(), backedupDevices);
737 if (devicesNotBackedup.size() > 0) {
738 log.warn("Failed to backup devices: {}. Reason: {}",
739 devicesNotBackedup, error.getMessage());
740 }
741 if (backedupDevices != null) {
742 backedupDevices.forEach(id -> {
743 lastBackupTimes.put(id, System.currentTimeMillis());
744 lastBackupNodes.put(id, nodeId);
745 });
746 }
747 });
Madan Jampanif7536ab2015-05-07 23:23:23 -0700748 }
749
Madan Jampani86940d92015-05-06 11:47:57 -0700750 /**
751 * Returns the flow table for specified device.
752 *
753 * @param deviceId identifier of the device
754 * @return Map representing Flow Table of given device.
755 */
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800756 private Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> getFlowTable(DeviceId deviceId) {
Aaron Kruglikova62fdbb2015-10-27 16:32:06 -0700757 if (persistenceEnabled) {
758 return flowEntries.computeIfAbsent(deviceId, id -> persistenceService
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800759 .<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>persistentMapBuilder()
Aaron Kruglikova62fdbb2015-10-27 16:32:06 -0700760 .withName("FlowTable:" + deviceId.toString())
761 .withSerializer(new Serializer() {
762 @Override
763 public <T> byte[] encode(T object) {
764 return SERIALIZER.encode(object);
765 }
766
767 @Override
768 public <T> T decode(byte[] bytes) {
769 return SERIALIZER.decode(bytes);
770 }
771 })
772 .build());
773 } else {
774 return flowEntries.computeIfAbsent(deviceId, id -> Maps.newConcurrentMap());
775 }
Madan Jampani86940d92015-05-06 11:47:57 -0700776 }
777
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800778 private Map<StoredFlowEntry, StoredFlowEntry> getFlowEntriesInternal(DeviceId deviceId, FlowId flowId) {
779 return getFlowTable(deviceId).computeIfAbsent(flowId, id -> Maps.newConcurrentMap());
Madan Jampani86940d92015-05-06 11:47:57 -0700780 }
781
782 private StoredFlowEntry getFlowEntryInternal(FlowRule rule) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800783 return getFlowEntriesInternal(rule.deviceId(), rule.id()).get(rule);
Madan Jampani86940d92015-05-06 11:47:57 -0700784 }
785
786 private Set<FlowEntry> getFlowEntriesInternal(DeviceId deviceId) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800787 return getFlowTable(deviceId).values().stream()
788 .flatMap(m -> m.values().stream())
789 .collect(Collectors.toSet());
Madan Jampani86940d92015-05-06 11:47:57 -0700790 }
791
792 public StoredFlowEntry getFlowEntry(FlowRule rule) {
793 return getFlowEntryInternal(rule);
794 }
795
796 public Set<FlowEntry> getFlowEntries(DeviceId deviceId) {
797 return getFlowEntriesInternal(deviceId);
798 }
799
800 public void add(FlowEntry rule) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800801 getFlowEntriesInternal(rule.deviceId(), rule.id())
802 .compute((StoredFlowEntry) rule, (k, stored) -> {
803 //TODO compare stored and rule timestamps
804 //TODO the key is not updated
805 return (StoredFlowEntry) rule;
806 });
Madan Jampani86940d92015-05-06 11:47:57 -0700807 lastUpdateTimes.put(rule.deviceId(), System.currentTimeMillis());
808 }
809
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800810 public FlowEntry remove(DeviceId deviceId, FlowEntry rule) {
811 final AtomicReference<FlowEntry> removedRule = new AtomicReference<>();
812 getFlowEntriesInternal(rule.deviceId(), rule.id())
813 .computeIfPresent((StoredFlowEntry) rule, (k, stored) -> {
814 if (rule instanceof DefaultFlowEntry) {
815 DefaultFlowEntry toRemove = (DefaultFlowEntry) rule;
816 if (stored instanceof DefaultFlowEntry) {
817 DefaultFlowEntry storedEntry = (DefaultFlowEntry) stored;
818 if (toRemove.created() < storedEntry.created()) {
819 log.debug("Trying to remove more recent flow entry {} (stored: {})",
820 toRemove, stored);
821 // the key is not updated, removedRule remains null
822 return stored;
823 }
824 }
825 }
826 removedRule.set(stored);
827 return null;
828 });
829
830 if (removedRule.get() != null) {
Madan Jampani86940d92015-05-06 11:47:57 -0700831 lastUpdateTimes.put(deviceId, System.currentTimeMillis());
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800832 return removedRule.get();
833 } else {
834 return null;
Madan Jampani86940d92015-05-06 11:47:57 -0700835 }
836 }
837
Charles Chan0c7c43b2016-01-14 17:39:20 -0800838 public void purgeFlowRule(DeviceId deviceId) {
839 flowEntries.remove(deviceId);
840 }
841
Madan Jampani86940d92015-05-06 11:47:57 -0700842 private NodeId getBackupNode(DeviceId deviceId) {
843 List<NodeId> deviceStandbys = replicaInfoManager.getReplicaInfoFor(deviceId).backups();
844 // pick the standby which is most likely to become next master
845 return deviceStandbys.isEmpty() ? null : deviceStandbys.get(0);
846 }
847
848 private void backup() {
Madan Jampani08bf17b2015-05-06 16:25:26 -0700849 if (!backupEnabled) {
850 return;
851 }
Madan Jampani86940d92015-05-06 11:47:57 -0700852 try {
853 // determine the set of devices that we need to backup during this run.
Madan Jampani39b3b192016-05-19 08:08:29 -0700854 Set<DeviceId> devicesToBackup = flowEntries.keySet()
Madan Jampani86940d92015-05-06 11:47:57 -0700855 .stream()
Madan Jampani39b3b192016-05-19 08:08:29 -0700856 .filter(mastershipService::isLocalMaster)
Madan Jampani86940d92015-05-06 11:47:57 -0700857 .filter(deviceId -> {
858 Long lastBackupTime = lastBackupTimes.get(deviceId);
859 Long lastUpdateTime = lastUpdateTimes.get(deviceId);
860 NodeId lastBackupNode = lastBackupNodes.get(deviceId);
Madan Jampani7267c552015-05-20 22:39:17 -0700861 NodeId newBackupNode = getBackupNode(deviceId);
Madan Jampani86940d92015-05-06 11:47:57 -0700862 return lastBackupTime == null
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800863 || !Objects.equals(lastBackupNode, newBackupNode)
Madan Jampani86940d92015-05-06 11:47:57 -0700864 || (lastUpdateTime != null && lastUpdateTime > lastBackupTime);
865 })
866 .collect(Collectors.toSet());
867
868 // compute a mapping from node to the set of devices whose flow entries it should backup
869 Map<NodeId, Set<DeviceId>> devicesToBackupByNode = Maps.newHashMap();
870 devicesToBackup.forEach(deviceId -> {
871 NodeId backupLocation = getBackupNode(deviceId);
872 if (backupLocation != null) {
873 devicesToBackupByNode.computeIfAbsent(backupLocation, nodeId -> Sets.newHashSet())
874 .add(deviceId);
875 }
876 });
Madan Jampani86940d92015-05-06 11:47:57 -0700877 // send the device flow entries to their respective backup nodes
Madan Jampaniadea8902015-06-04 17:39:45 -0700878 devicesToBackupByNode.forEach(this::sendBackups);
Madan Jampani86940d92015-05-06 11:47:57 -0700879 } catch (Exception e) {
880 log.error("Backup failed.", e);
881 }
882 }
883
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800884 private Set<DeviceId> onBackupReceipt(Map<DeviceId,
885 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>> flowTables) {
Madan Jampani7267c552015-05-20 22:39:17 -0700886 log.debug("Received flowEntries for {} to backup", flowTables.keySet());
Madan Jampani654b58a2015-05-22 11:28:11 -0700887 Set<DeviceId> backedupDevices = Sets.newHashSet();
888 try {
Madan Jampania98bf932015-06-02 12:01:36 -0700889 flowTables.forEach((deviceId, deviceFlowTable) -> {
890 // Only process those devices are that not managed by the local node.
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800891 if (!Objects.equals(local, mastershipService.getMasterFor(deviceId))) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800892 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> backupFlowTable =
893 getFlowTable(deviceId);
Madan Jampania98bf932015-06-02 12:01:36 -0700894 backupFlowTable.clear();
895 backupFlowTable.putAll(deviceFlowTable);
896 backedupDevices.add(deviceId);
897 }
Madan Jampani08bf17b2015-05-06 16:25:26 -0700898 });
Madan Jampani654b58a2015-05-22 11:28:11 -0700899 } catch (Exception e) {
900 log.warn("Failure processing backup request", e);
901 }
902 return backedupDevices;
Madan Jampani86940d92015-05-06 11:47:57 -0700903 }
904 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700905
906 @Override
907 public FlowRuleEvent updateTableStatistics(DeviceId deviceId,
908 List<TableStatisticsEntry> tableStats) {
909 deviceTableStats.put(deviceId, tableStats);
910 return null;
911 }
912
913 @Override
914 public Iterable<TableStatisticsEntry> getTableStatistics(DeviceId deviceId) {
915 NodeId master = mastershipService.getMasterFor(deviceId);
916
917 if (master == null) {
918 log.debug("Failed to getTableStats: No master for {}", deviceId);
919 return Collections.emptyList();
920 }
921
922 List<TableStatisticsEntry> tableStats = deviceTableStats.get(deviceId);
923 if (tableStats == null) {
924 return Collections.emptyList();
925 }
926 return ImmutableList.copyOf(tableStats);
927 }
928
929 private class InternalTableStatsListener
930 implements EventuallyConsistentMapListener<DeviceId, List<TableStatisticsEntry>> {
931 @Override
932 public void event(EventuallyConsistentMapEvent<DeviceId,
933 List<TableStatisticsEntry>> event) {
934 //TODO: Generate an event to listeners (do we need?)
935 }
936 }
Madan Jampani86940d92015-05-06 11:47:57 -0700937}