blob: b3a2e36b4cdd4f05cb0c5c7fa08d0ef544caa8a1 [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
Madan Jampani222229e2016-07-14 10:43:25 -0700593 return Futures.getUnchecked(clusterCommunicator.sendAndReceive(
Madan Jampani86940d92015-05-06 11:47:57 -0700594 rule,
595 REMOVE_FLOW_ENTRY,
596 SERIALIZER::encode,
597 SERIALIZER::decode,
Madan Jampani222229e2016-07-14 10:43:25 -0700598 master));
Madan Jampani86940d92015-05-06 11:47:57 -0700599 }
600
601 private FlowRuleEvent removeFlowRuleInternal(FlowEntry rule) {
602 final DeviceId deviceId = rule.deviceId();
603 // 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 -0800604 final FlowEntry removed = flowTable.remove(deviceId, rule);
605 // rule may be partial rule that is missing treatment, we should use rule from store instead
606 return removed != null ? new FlowRuleEvent(RULE_REMOVED, removed) : null;
Madan Jampani86940d92015-05-06 11:47:57 -0700607 }
608
609 @Override
Charles Chan0c7c43b2016-01-14 17:39:20 -0800610 public void purgeFlowRule(DeviceId deviceId) {
611 flowTable.purgeFlowRule(deviceId);
612 }
613
614 @Override
Madan Jampani86940d92015-05-06 11:47:57 -0700615 public void batchOperationComplete(FlowRuleBatchEvent event) {
616 //FIXME: need a per device pending response
617 NodeId nodeId = pendingResponses.remove(event.subject().batchId());
618 if (nodeId == null) {
619 notifyDelegate(event);
620 } else {
621 // TODO check unicast return value
622 clusterCommunicator.unicast(event, REMOTE_APPLY_COMPLETED, SERIALIZER::encode, nodeId);
623 //error log: log.warn("Failed to respond to peer for batch operation result");
624 }
625 }
626
627 private final class OnStoreBatch implements ClusterMessageHandler {
628
629 @Override
630 public void handle(final ClusterMessage message) {
631 FlowRuleBatchOperation operation = SERIALIZER.decode(message.payload());
632 log.debug("received batch request {}", operation);
633
634 final DeviceId deviceId = operation.deviceId();
Madan Jampani6bd2d9f2015-05-14 14:10:42 -0700635 NodeId master = mastershipService.getMasterFor(deviceId);
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800636 if (!Objects.equals(local, master)) {
Madan Jampani86940d92015-05-06 11:47:57 -0700637 Set<FlowRule> failures = new HashSet<>(operation.size());
638 for (FlowRuleBatchEntry op : operation.getOperations()) {
639 failures.add(op.target());
640 }
641 CompletedBatchOperation allFailed = new CompletedBatchOperation(false, failures, deviceId);
642 // This node is no longer the master, respond as all failed.
643 // TODO: we might want to wrap response in envelope
644 // to distinguish sw programming failure and hand over
645 // it make sense in the latter case to retry immediately.
646 message.respond(SERIALIZER.encode(allFailed));
647 return;
648 }
649
650 pendingResponses.put(operation.id(), message.sender());
651 storeBatchInternal(operation);
652 }
653 }
654
Madan Jampanif7536ab2015-05-07 23:23:23 -0700655 private class InternalFlowTable implements ReplicaInfoEventListener {
Madan Jampani86940d92015-05-06 11:47:57 -0700656
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800657 //TODO replace the Map<V,V> with ExtendedSet
658 private final Map<DeviceId, Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>
Madan Jampani5c3766c2015-06-02 15:54:41 -0700659 flowEntries = Maps.newConcurrentMap();
Madan Jampani86940d92015-05-06 11:47:57 -0700660
661 private final Map<DeviceId, Long> lastBackupTimes = Maps.newConcurrentMap();
662 private final Map<DeviceId, Long> lastUpdateTimes = Maps.newConcurrentMap();
663 private final Map<DeviceId, NodeId> lastBackupNodes = Maps.newConcurrentMap();
664
Madan Jampanif7536ab2015-05-07 23:23:23 -0700665 @Override
666 public void event(ReplicaInfoEvent event) {
Madan Jampani71c32ca2016-06-22 08:23:18 -0700667 eventHandler.execute(() -> handleEvent(event));
668 }
669
670 private void handleEvent(ReplicaInfoEvent event) {
Madan Jampania98bf932015-06-02 12:01:36 -0700671 if (!backupEnabled) {
672 return;
673 }
Madan Jampanif7536ab2015-05-07 23:23:23 -0700674 if (event.type() == ReplicaInfoEvent.Type.BACKUPS_CHANGED) {
675 DeviceId deviceId = event.subject();
Madan Jampani6bd2d9f2015-05-14 14:10:42 -0700676 NodeId master = mastershipService.getMasterFor(deviceId);
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800677 if (!Objects.equals(local, master)) {
Madan Jampanif7536ab2015-05-07 23:23:23 -0700678 // ignore since this event is for a device this node does not manage.
679 return;
680 }
Madan Jampani7267c552015-05-20 22:39:17 -0700681 NodeId newBackupNode = getBackupNode(deviceId);
682 NodeId currentBackupNode = lastBackupNodes.get(deviceId);
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800683 if (Objects.equals(newBackupNode, currentBackupNode)) {
Madan Jampanif7536ab2015-05-07 23:23:23 -0700684 // ignore since backup location hasn't changed.
685 return;
686 }
Madan Jampani7267c552015-05-20 22:39:17 -0700687 if (currentBackupNode != null && newBackupNode == null) {
688 // Current backup node is most likely down and no alternate backup node
689 // has been chosen. Clear current backup location so that we can resume
690 // backups when either current backup comes online or a different backup node
691 // is chosen.
692 log.warn("Lost backup location {} for deviceId {} and no alternate backup node exists. "
693 + "Flows can be lost if the master goes down", currentBackupNode, deviceId);
694 lastBackupNodes.remove(deviceId);
695 lastBackupTimes.remove(deviceId);
696 return;
697 // TODO: Pick any available node as backup and ensure hand-off occurs when
698 // a new master is elected.
699 }
Madan Jampani44839b82015-06-12 13:57:41 -0700700 log.debug("Backup location for {} has changed from {} to {}.",
Madan Jampani7267c552015-05-20 22:39:17 -0700701 deviceId, currentBackupNode, newBackupNode);
702 backupSenderExecutor.schedule(() -> backupFlowEntries(newBackupNode, Sets.newHashSet(deviceId)),
Madan Jampani03062682015-05-19 17:57:51 -0700703 0,
704 TimeUnit.SECONDS);
Madan Jampanif7536ab2015-05-07 23:23:23 -0700705 }
706 }
707
Madan Jampaniadea8902015-06-04 17:39:45 -0700708 private void sendBackups(NodeId nodeId, Set<DeviceId> deviceIds) {
709 // split up the devices into smaller batches and send them separately.
710 Iterables.partition(deviceIds, FLOW_TABLE_BACKUP_BATCH_SIZE)
711 .forEach(ids -> backupFlowEntries(nodeId, Sets.newHashSet(ids)));
712 }
713
Madan Jampanif7536ab2015-05-07 23:23:23 -0700714 private void backupFlowEntries(NodeId nodeId, Set<DeviceId> deviceIds) {
Madan Jampaniadea8902015-06-04 17:39:45 -0700715 if (deviceIds.isEmpty()) {
716 return;
717 }
Madan Jampanif7536ab2015-05-07 23:23:23 -0700718 log.debug("Sending flowEntries for devices {} to {} as backup.", deviceIds, nodeId);
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800719 Map<DeviceId, Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>
720 deviceFlowEntries = Maps.newConcurrentMap();
Madan Jampani85a9b0d2015-06-03 17:15:44 -0700721 deviceIds.forEach(id -> deviceFlowEntries.put(id, ImmutableMap.copyOf(getFlowTable(id))));
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800722 clusterCommunicator.<Map<DeviceId,
723 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>,
724 Set<DeviceId>>
725 sendAndReceive(deviceFlowEntries,
726 FLOW_TABLE_BACKUP,
727 SERIALIZER::encode,
728 SERIALIZER::decode,
729 nodeId)
730 .whenComplete((backedupDevices, error) -> {
731 Set<DeviceId> devicesNotBackedup = error != null ?
732 deviceFlowEntries.keySet() :
733 Sets.difference(deviceFlowEntries.keySet(), backedupDevices);
734 if (devicesNotBackedup.size() > 0) {
735 log.warn("Failed to backup devices: {}. Reason: {}",
736 devicesNotBackedup, error.getMessage());
737 }
738 if (backedupDevices != null) {
739 backedupDevices.forEach(id -> {
740 lastBackupTimes.put(id, System.currentTimeMillis());
741 lastBackupNodes.put(id, nodeId);
742 });
743 }
744 });
Madan Jampanif7536ab2015-05-07 23:23:23 -0700745 }
746
Madan Jampani86940d92015-05-06 11:47:57 -0700747 /**
748 * Returns the flow table for specified device.
749 *
750 * @param deviceId identifier of the device
751 * @return Map representing Flow Table of given device.
752 */
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800753 private Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> getFlowTable(DeviceId deviceId) {
Aaron Kruglikova62fdbb2015-10-27 16:32:06 -0700754 if (persistenceEnabled) {
755 return flowEntries.computeIfAbsent(deviceId, id -> persistenceService
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800756 .<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>persistentMapBuilder()
Aaron Kruglikova62fdbb2015-10-27 16:32:06 -0700757 .withName("FlowTable:" + deviceId.toString())
758 .withSerializer(new Serializer() {
759 @Override
760 public <T> byte[] encode(T object) {
761 return SERIALIZER.encode(object);
762 }
763
764 @Override
765 public <T> T decode(byte[] bytes) {
766 return SERIALIZER.decode(bytes);
767 }
768 })
769 .build());
770 } else {
771 return flowEntries.computeIfAbsent(deviceId, id -> Maps.newConcurrentMap());
772 }
Madan Jampani86940d92015-05-06 11:47:57 -0700773 }
774
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800775 private Map<StoredFlowEntry, StoredFlowEntry> getFlowEntriesInternal(DeviceId deviceId, FlowId flowId) {
776 return getFlowTable(deviceId).computeIfAbsent(flowId, id -> Maps.newConcurrentMap());
Madan Jampani86940d92015-05-06 11:47:57 -0700777 }
778
779 private StoredFlowEntry getFlowEntryInternal(FlowRule rule) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800780 return getFlowEntriesInternal(rule.deviceId(), rule.id()).get(rule);
Madan Jampani86940d92015-05-06 11:47:57 -0700781 }
782
783 private Set<FlowEntry> getFlowEntriesInternal(DeviceId deviceId) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800784 return getFlowTable(deviceId).values().stream()
785 .flatMap(m -> m.values().stream())
786 .collect(Collectors.toSet());
Madan Jampani86940d92015-05-06 11:47:57 -0700787 }
788
789 public StoredFlowEntry getFlowEntry(FlowRule rule) {
790 return getFlowEntryInternal(rule);
791 }
792
793 public Set<FlowEntry> getFlowEntries(DeviceId deviceId) {
794 return getFlowEntriesInternal(deviceId);
795 }
796
797 public void add(FlowEntry rule) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800798 getFlowEntriesInternal(rule.deviceId(), rule.id())
799 .compute((StoredFlowEntry) rule, (k, stored) -> {
800 //TODO compare stored and rule timestamps
801 //TODO the key is not updated
802 return (StoredFlowEntry) rule;
803 });
Madan Jampani86940d92015-05-06 11:47:57 -0700804 lastUpdateTimes.put(rule.deviceId(), System.currentTimeMillis());
805 }
806
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800807 public FlowEntry remove(DeviceId deviceId, FlowEntry rule) {
808 final AtomicReference<FlowEntry> removedRule = new AtomicReference<>();
809 getFlowEntriesInternal(rule.deviceId(), rule.id())
810 .computeIfPresent((StoredFlowEntry) rule, (k, stored) -> {
811 if (rule instanceof DefaultFlowEntry) {
812 DefaultFlowEntry toRemove = (DefaultFlowEntry) rule;
813 if (stored instanceof DefaultFlowEntry) {
814 DefaultFlowEntry storedEntry = (DefaultFlowEntry) stored;
815 if (toRemove.created() < storedEntry.created()) {
816 log.debug("Trying to remove more recent flow entry {} (stored: {})",
817 toRemove, stored);
818 // the key is not updated, removedRule remains null
819 return stored;
820 }
821 }
822 }
823 removedRule.set(stored);
824 return null;
825 });
826
827 if (removedRule.get() != null) {
Madan Jampani86940d92015-05-06 11:47:57 -0700828 lastUpdateTimes.put(deviceId, System.currentTimeMillis());
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800829 return removedRule.get();
830 } else {
831 return null;
Madan Jampani86940d92015-05-06 11:47:57 -0700832 }
833 }
834
Charles Chan0c7c43b2016-01-14 17:39:20 -0800835 public void purgeFlowRule(DeviceId deviceId) {
836 flowEntries.remove(deviceId);
837 }
838
Madan Jampani86940d92015-05-06 11:47:57 -0700839 private NodeId getBackupNode(DeviceId deviceId) {
840 List<NodeId> deviceStandbys = replicaInfoManager.getReplicaInfoFor(deviceId).backups();
841 // pick the standby which is most likely to become next master
842 return deviceStandbys.isEmpty() ? null : deviceStandbys.get(0);
843 }
844
845 private void backup() {
Madan Jampani08bf17b2015-05-06 16:25:26 -0700846 if (!backupEnabled) {
847 return;
848 }
Madan Jampani86940d92015-05-06 11:47:57 -0700849 try {
850 // determine the set of devices that we need to backup during this run.
Madan Jampani39b3b192016-05-19 08:08:29 -0700851 Set<DeviceId> devicesToBackup = flowEntries.keySet()
Madan Jampani86940d92015-05-06 11:47:57 -0700852 .stream()
Madan Jampani39b3b192016-05-19 08:08:29 -0700853 .filter(mastershipService::isLocalMaster)
Madan Jampani86940d92015-05-06 11:47:57 -0700854 .filter(deviceId -> {
855 Long lastBackupTime = lastBackupTimes.get(deviceId);
856 Long lastUpdateTime = lastUpdateTimes.get(deviceId);
857 NodeId lastBackupNode = lastBackupNodes.get(deviceId);
Madan Jampani7267c552015-05-20 22:39:17 -0700858 NodeId newBackupNode = getBackupNode(deviceId);
Madan Jampani86940d92015-05-06 11:47:57 -0700859 return lastBackupTime == null
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800860 || !Objects.equals(lastBackupNode, newBackupNode)
Madan Jampani86940d92015-05-06 11:47:57 -0700861 || (lastUpdateTime != null && lastUpdateTime > lastBackupTime);
862 })
863 .collect(Collectors.toSet());
864
865 // compute a mapping from node to the set of devices whose flow entries it should backup
866 Map<NodeId, Set<DeviceId>> devicesToBackupByNode = Maps.newHashMap();
867 devicesToBackup.forEach(deviceId -> {
868 NodeId backupLocation = getBackupNode(deviceId);
869 if (backupLocation != null) {
870 devicesToBackupByNode.computeIfAbsent(backupLocation, nodeId -> Sets.newHashSet())
871 .add(deviceId);
872 }
873 });
Madan Jampani86940d92015-05-06 11:47:57 -0700874 // send the device flow entries to their respective backup nodes
Madan Jampaniadea8902015-06-04 17:39:45 -0700875 devicesToBackupByNode.forEach(this::sendBackups);
Madan Jampani86940d92015-05-06 11:47:57 -0700876 } catch (Exception e) {
877 log.error("Backup failed.", e);
878 }
879 }
880
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800881 private Set<DeviceId> onBackupReceipt(Map<DeviceId,
882 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>> flowTables) {
Madan Jampani7267c552015-05-20 22:39:17 -0700883 log.debug("Received flowEntries for {} to backup", flowTables.keySet());
Madan Jampani654b58a2015-05-22 11:28:11 -0700884 Set<DeviceId> backedupDevices = Sets.newHashSet();
885 try {
Madan Jampania98bf932015-06-02 12:01:36 -0700886 flowTables.forEach((deviceId, deviceFlowTable) -> {
887 // Only process those devices are that not managed by the local node.
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800888 if (!Objects.equals(local, mastershipService.getMasterFor(deviceId))) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800889 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> backupFlowTable =
890 getFlowTable(deviceId);
Madan Jampania98bf932015-06-02 12:01:36 -0700891 backupFlowTable.clear();
892 backupFlowTable.putAll(deviceFlowTable);
893 backedupDevices.add(deviceId);
894 }
Madan Jampani08bf17b2015-05-06 16:25:26 -0700895 });
Madan Jampani654b58a2015-05-22 11:28:11 -0700896 } catch (Exception e) {
897 log.warn("Failure processing backup request", e);
898 }
899 return backedupDevices;
Madan Jampani86940d92015-05-06 11:47:57 -0700900 }
901 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700902
903 @Override
904 public FlowRuleEvent updateTableStatistics(DeviceId deviceId,
905 List<TableStatisticsEntry> tableStats) {
906 deviceTableStats.put(deviceId, tableStats);
907 return null;
908 }
909
910 @Override
911 public Iterable<TableStatisticsEntry> getTableStatistics(DeviceId deviceId) {
912 NodeId master = mastershipService.getMasterFor(deviceId);
913
914 if (master == null) {
915 log.debug("Failed to getTableStats: No master for {}", deviceId);
916 return Collections.emptyList();
917 }
918
919 List<TableStatisticsEntry> tableStats = deviceTableStats.get(deviceId);
920 if (tableStats == null) {
921 return Collections.emptyList();
922 }
923 return ImmutableList.copyOf(tableStats);
924 }
925
926 private class InternalTableStatsListener
927 implements EventuallyConsistentMapListener<DeviceId, List<TableStatisticsEntry>> {
928 @Override
929 public void event(EventuallyConsistentMapEvent<DeviceId,
930 List<TableStatisticsEntry>> event) {
931 //TODO: Generate an event to listeners (do we need?)
932 }
933 }
Madan Jampani86940d92015-05-06 11:47:57 -0700934}