blob: 57ee153be73806139e729d981a103c4ecbad0935 [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;
166
Madan Jampani08bf17b2015-05-06 16:25:26 -0700167 private ScheduledFuture<?> backupTask;
Madan Jampani86940d92015-05-06 11:47:57 -0700168 private final ScheduledExecutorService backupSenderExecutor =
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700169 Executors.newSingleThreadScheduledExecutor(groupedThreads("onos/flow", "backup-sender", log));
Madan Jampani86940d92015-05-06 11:47:57 -0700170
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700171 private EventuallyConsistentMap<DeviceId, List<TableStatisticsEntry>> deviceTableStats;
172 private final EventuallyConsistentMapListener<DeviceId, List<TableStatisticsEntry>> tableStatsListener =
173 new InternalTableStatsListener();
174
175 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
176 protected StorageService storageService;
177
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700178 protected static final StoreSerializer SERIALIZER = StoreSerializer.using(
179 KryoNamespace.newBuilder()
Madan Jampani86940d92015-05-06 11:47:57 -0700180 .register(DistributedStoreSerializers.STORE_COMMON)
181 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700182 .build("FlowRuleStore"));
Madan Jampani86940d92015-05-06 11:47:57 -0700183
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700184 protected static final KryoNamespace.Builder SERIALIZER_BUILDER = KryoNamespace.newBuilder()
185 .register(KryoNamespaces.API)
186 .register(MastershipBasedTimestamp.class);
187
188
Madan Jampani86940d92015-05-06 11:47:57 -0700189 private IdGenerator idGenerator;
190 private NodeId local;
191
192 @Activate
193 public void activate(ComponentContext context) {
194 configService.registerProperties(getClass());
195
196 idGenerator = coreService.getIdGenerator(FlowRuleService.FLOW_OP_TOPIC);
197
198 local = clusterService.getLocalNode().id();
199
200 messageHandlingExecutor = Executors.newFixedThreadPool(
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700201 msgHandlerPoolSize, groupedThreads("onos/store/flow", "message-handlers", log));
Madan Jampani86940d92015-05-06 11:47:57 -0700202
203 registerMessageHandlers(messageHandlingExecutor);
204
Madan Jampani08bf17b2015-05-06 16:25:26 -0700205 if (backupEnabled) {
Madan Jampanif7536ab2015-05-07 23:23:23 -0700206 replicaInfoManager.addListener(flowTable);
Madan Jampani08bf17b2015-05-06 16:25:26 -0700207 backupTask = backupSenderExecutor.scheduleWithFixedDelay(
208 flowTable::backup,
209 0,
210 backupPeriod,
211 TimeUnit.MILLISECONDS);
212 }
Madan Jampani86940d92015-05-06 11:47:57 -0700213
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700214 deviceTableStats = storageService.<DeviceId, List<TableStatisticsEntry>>eventuallyConsistentMapBuilder()
215 .withName("onos-flow-table-stats")
216 .withSerializer(SERIALIZER_BUILDER)
217 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
218 .withTimestampProvider((k, v) -> new WallClockTimestamp())
219 .withTombstonesDisabled()
220 .build();
221 deviceTableStats.addListener(tableStatsListener);
222
Madan Jampani86940d92015-05-06 11:47:57 -0700223 logConfig("Started");
224 }
225
226 @Deactivate
227 public void deactivate(ComponentContext context) {
Madan Jampanif7536ab2015-05-07 23:23:23 -0700228 if (backupEnabled) {
229 replicaInfoManager.removeListener(flowTable);
230 backupTask.cancel(true);
231 }
Madan Jampani86940d92015-05-06 11:47:57 -0700232 configService.unregisterProperties(getClass(), false);
233 unregisterMessageHandlers();
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700234 deviceTableStats.removeListener(tableStatsListener);
235 deviceTableStats.destroy();
Madan Jampani86940d92015-05-06 11:47:57 -0700236 messageHandlingExecutor.shutdownNow();
237 backupSenderExecutor.shutdownNow();
238 log.info("Stopped");
239 }
240
241 @SuppressWarnings("rawtypes")
242 @Modified
243 public void modified(ComponentContext context) {
244 if (context == null) {
245 backupEnabled = DEFAULT_BACKUP_ENABLED;
246 logConfig("Default config");
247 return;
248 }
249
250 Dictionary properties = context.getProperties();
251 int newPoolSize;
252 boolean newBackupEnabled;
Madan Jampani08bf17b2015-05-06 16:25:26 -0700253 int newBackupPeriod;
Madan Jampani86940d92015-05-06 11:47:57 -0700254 try {
255 String s = get(properties, "msgHandlerPoolSize");
256 newPoolSize = isNullOrEmpty(s) ? msgHandlerPoolSize : Integer.parseInt(s.trim());
257
258 s = get(properties, "backupEnabled");
259 newBackupEnabled = isNullOrEmpty(s) ? backupEnabled : Boolean.parseBoolean(s.trim());
260
Madan Jampani08bf17b2015-05-06 16:25:26 -0700261 s = get(properties, "backupPeriod");
262 newBackupPeriod = isNullOrEmpty(s) ? backupPeriod : Integer.parseInt(s.trim());
263
Madan Jampani86940d92015-05-06 11:47:57 -0700264 } catch (NumberFormatException | ClassCastException e) {
265 newPoolSize = MESSAGE_HANDLER_THREAD_POOL_SIZE;
266 newBackupEnabled = DEFAULT_BACKUP_ENABLED;
Madan Jampani08bf17b2015-05-06 16:25:26 -0700267 newBackupPeriod = DEFAULT_BACKUP_PERIOD_MILLIS;
Madan Jampani86940d92015-05-06 11:47:57 -0700268 }
269
Madan Jampani08bf17b2015-05-06 16:25:26 -0700270 boolean restartBackupTask = false;
Madan Jampani86940d92015-05-06 11:47:57 -0700271 if (newBackupEnabled != backupEnabled) {
272 backupEnabled = newBackupEnabled;
Madan Jampanif7536ab2015-05-07 23:23:23 -0700273 if (!backupEnabled) {
274 replicaInfoManager.removeListener(flowTable);
275 if (backupTask != null) {
276 backupTask.cancel(false);
277 backupTask = null;
278 }
279 } else {
280 replicaInfoManager.addListener(flowTable);
Madan Jampani08bf17b2015-05-06 16:25:26 -0700281 }
282 restartBackupTask = backupEnabled;
283 }
284 if (newBackupPeriod != backupPeriod) {
285 backupPeriod = newBackupPeriod;
286 restartBackupTask = backupEnabled;
287 }
288 if (restartBackupTask) {
289 if (backupTask != null) {
290 // cancel previously running task
291 backupTask.cancel(false);
292 }
293 backupTask = backupSenderExecutor.scheduleWithFixedDelay(
294 flowTable::backup,
295 0,
296 backupPeriod,
297 TimeUnit.MILLISECONDS);
Madan Jampani86940d92015-05-06 11:47:57 -0700298 }
299 if (newPoolSize != msgHandlerPoolSize) {
300 msgHandlerPoolSize = newPoolSize;
301 ExecutorService oldMsgHandler = messageHandlingExecutor;
302 messageHandlingExecutor = Executors.newFixedThreadPool(
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800303 msgHandlerPoolSize, groupedThreads("onos/store/flow", "message-handlers", log));
Madan Jampani86940d92015-05-06 11:47:57 -0700304
305 // replace previously registered handlers.
306 registerMessageHandlers(messageHandlingExecutor);
307 oldMsgHandler.shutdown();
308 }
309 logConfig("Reconfigured");
310 }
311
312 private void registerMessageHandlers(ExecutorService executor) {
313
314 clusterCommunicator.addSubscriber(APPLY_BATCH_FLOWS, new OnStoreBatch(), executor);
315 clusterCommunicator.<FlowRuleBatchEvent>addSubscriber(
316 REMOTE_APPLY_COMPLETED, SERIALIZER::decode, this::notifyDelegate, executor);
317 clusterCommunicator.addSubscriber(
318 GET_FLOW_ENTRY, SERIALIZER::decode, flowTable::getFlowEntry, SERIALIZER::encode, executor);
319 clusterCommunicator.addSubscriber(
320 GET_DEVICE_FLOW_ENTRIES, SERIALIZER::decode, flowTable::getFlowEntries, SERIALIZER::encode, executor);
321 clusterCommunicator.addSubscriber(
322 REMOVE_FLOW_ENTRY, SERIALIZER::decode, this::removeFlowRuleInternal, SERIALIZER::encode, executor);
323 clusterCommunicator.addSubscriber(
324 REMOVE_FLOW_ENTRY, SERIALIZER::decode, this::removeFlowRuleInternal, SERIALIZER::encode, executor);
325 clusterCommunicator.addSubscriber(
Madan Jampani654b58a2015-05-22 11:28:11 -0700326 FLOW_TABLE_BACKUP, SERIALIZER::decode, flowTable::onBackupReceipt, SERIALIZER::encode, executor);
Madan Jampani86940d92015-05-06 11:47:57 -0700327 }
328
329 private void unregisterMessageHandlers() {
330 clusterCommunicator.removeSubscriber(REMOVE_FLOW_ENTRY);
331 clusterCommunicator.removeSubscriber(GET_DEVICE_FLOW_ENTRIES);
332 clusterCommunicator.removeSubscriber(GET_FLOW_ENTRY);
333 clusterCommunicator.removeSubscriber(APPLY_BATCH_FLOWS);
334 clusterCommunicator.removeSubscriber(REMOTE_APPLY_COMPLETED);
335 clusterCommunicator.removeSubscriber(FLOW_TABLE_BACKUP);
336 }
337
338 private void logConfig(String prefix) {
Madan Jampani08bf17b2015-05-06 16:25:26 -0700339 log.info("{} with msgHandlerPoolSize = {}; backupEnabled = {}, backupPeriod = {}",
340 prefix, msgHandlerPoolSize, backupEnabled, backupPeriod);
Madan Jampani86940d92015-05-06 11:47:57 -0700341 }
342
343 // This is not a efficient operation on a distributed sharded
344 // flow store. We need to revisit the need for this operation or at least
345 // make it device specific.
346 @Override
347 public int getFlowRuleCount() {
348 AtomicInteger sum = new AtomicInteger(0);
349 deviceService.getDevices().forEach(device -> sum.addAndGet(Iterables.size(getFlowEntries(device.id()))));
350 return sum.get();
351 }
352
353 @Override
354 public FlowEntry getFlowEntry(FlowRule rule) {
Madan Jampani6bd2d9f2015-05-14 14:10:42 -0700355 NodeId master = mastershipService.getMasterFor(rule.deviceId());
Madan Jampani86940d92015-05-06 11:47:57 -0700356
357 if (master == null) {
Thomas Vachuska88fd6902015-08-04 10:08:34 -0700358 log.debug("Failed to getFlowEntry: No master for {}", rule.deviceId());
Madan Jampani86940d92015-05-06 11:47:57 -0700359 return null;
360 }
361
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800362 if (Objects.equals(local, master)) {
Madan Jampani86940d92015-05-06 11:47:57 -0700363 return flowTable.getFlowEntry(rule);
364 }
365
366 log.trace("Forwarding getFlowEntry to {}, which is the primary (master) for device {}",
367 master, rule.deviceId());
368
369 return Tools.futureGetOrElse(clusterCommunicator.sendAndReceive(rule,
370 FlowStoreMessageSubjects.GET_FLOW_ENTRY,
371 SERIALIZER::encode,
372 SERIALIZER::decode,
373 master),
374 FLOW_RULE_STORE_TIMEOUT_MILLIS,
375 TimeUnit.MILLISECONDS,
376 null);
377 }
378
379 @Override
380 public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) {
Madan Jampani6bd2d9f2015-05-14 14:10:42 -0700381 NodeId master = mastershipService.getMasterFor(deviceId);
Madan Jampani86940d92015-05-06 11:47:57 -0700382
383 if (master == null) {
Thomas Vachuska88fd6902015-08-04 10:08:34 -0700384 log.debug("Failed to getFlowEntries: No master for {}", deviceId);
Madan Jampani86940d92015-05-06 11:47:57 -0700385 return Collections.emptyList();
386 }
387
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800388 if (Objects.equals(local, master)) {
Madan Jampani86940d92015-05-06 11:47:57 -0700389 return flowTable.getFlowEntries(deviceId);
390 }
391
392 log.trace("Forwarding getFlowEntries to {}, which is the primary (master) for device {}",
393 master, deviceId);
394
395 return Tools.futureGetOrElse(clusterCommunicator.sendAndReceive(deviceId,
396 FlowStoreMessageSubjects.GET_DEVICE_FLOW_ENTRIES,
397 SERIALIZER::encode,
398 SERIALIZER::decode,
399 master),
400 FLOW_RULE_STORE_TIMEOUT_MILLIS,
401 TimeUnit.MILLISECONDS,
402 Collections.emptyList());
403 }
404
405 @Override
406 public void storeFlowRule(FlowRule rule) {
407 storeBatch(new FlowRuleBatchOperation(
Sho SHIMIZU98ffca82015-05-11 08:39:24 -0700408 Collections.singletonList(new FlowRuleBatchEntry(FlowRuleOperation.ADD, rule)),
Madan Jampani86940d92015-05-06 11:47:57 -0700409 rule.deviceId(), idGenerator.getNewId()));
410 }
411
412 @Override
413 public void storeBatch(FlowRuleBatchOperation operation) {
414 if (operation.getOperations().isEmpty()) {
415 notifyDelegate(FlowRuleBatchEvent.completed(
416 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
417 new CompletedBatchOperation(true, Collections.emptySet(), operation.deviceId())));
418 return;
419 }
420
421 DeviceId deviceId = operation.deviceId();
Madan Jampani6bd2d9f2015-05-14 14:10:42 -0700422 NodeId master = mastershipService.getMasterFor(deviceId);
Madan Jampani86940d92015-05-06 11:47:57 -0700423
424 if (master == null) {
425 log.warn("No master for {} : flows will be marked for removal", deviceId);
426
427 updateStoreInternal(operation);
428
429 notifyDelegate(FlowRuleBatchEvent.completed(
430 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
431 new CompletedBatchOperation(true, Collections.emptySet(), operation.deviceId())));
432 return;
433 }
434
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800435 if (Objects.equals(local, master)) {
Madan Jampani86940d92015-05-06 11:47:57 -0700436 storeBatchInternal(operation);
437 return;
438 }
439
440 log.trace("Forwarding storeBatch to {}, which is the primary (master) for device {}",
441 master, deviceId);
442
Madan Jampani175e8fd2015-05-20 14:10:45 -0700443 clusterCommunicator.unicast(operation,
444 APPLY_BATCH_FLOWS,
445 SERIALIZER::encode,
446 master)
447 .whenComplete((result, error) -> {
Thomas Vachuskaa267ce42015-05-27 16:14:23 -0700448 if (error != null) {
Madan Jampani15f1bc42015-05-28 10:51:52 -0700449 log.warn("Failed to storeBatch: {} to {}", operation, master, error);
Madan Jampani86940d92015-05-06 11:47:57 -0700450
Thomas Vachuskaa267ce42015-05-27 16:14:23 -0700451 Set<FlowRule> allFailures = operation.getOperations()
452 .stream()
453 .map(op -> op.target())
454 .collect(Collectors.toSet());
Madan Jampani86940d92015-05-06 11:47:57 -0700455
Thomas Vachuskaa267ce42015-05-27 16:14:23 -0700456 notifyDelegate(FlowRuleBatchEvent.completed(
457 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
458 new CompletedBatchOperation(false, allFailures, deviceId)));
459 }
Madan Jampani175e8fd2015-05-20 14:10:45 -0700460 });
Madan Jampani86940d92015-05-06 11:47:57 -0700461 }
462
463 private void storeBatchInternal(FlowRuleBatchOperation operation) {
464
465 final DeviceId did = operation.deviceId();
466 //final Collection<FlowEntry> ft = flowTable.getFlowEntries(did);
467 Set<FlowRuleBatchEntry> currentOps = updateStoreInternal(operation);
468 if (currentOps.isEmpty()) {
469 batchOperationComplete(FlowRuleBatchEvent.completed(
470 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
471 new CompletedBatchOperation(true, Collections.emptySet(), did)));
472 return;
473 }
474
475 notifyDelegate(FlowRuleBatchEvent.requested(new
476 FlowRuleBatchRequest(operation.id(),
477 currentOps), operation.deviceId()));
478 }
479
480 private Set<FlowRuleBatchEntry> updateStoreInternal(FlowRuleBatchOperation operation) {
481 return operation.getOperations().stream().map(
482 op -> {
483 StoredFlowEntry entry;
484 switch (op.operator()) {
485 case ADD:
486 entry = new DefaultFlowEntry(op.target());
487 // always add requested FlowRule
488 // Note: 2 equal FlowEntry may have different treatment
489 flowTable.remove(entry.deviceId(), entry);
490 flowTable.add(entry);
491
492 return op;
493 case REMOVE:
494 entry = flowTable.getFlowEntry(op.target());
495 if (entry != null) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800496 //FIXME modification of "stored" flow entry outside of flow table
Madan Jampani86940d92015-05-06 11:47:57 -0700497 entry.setState(FlowEntryState.PENDING_REMOVE);
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800498 log.debug("Setting state of rule to pending remove: {}", entry);
Madan Jampani86940d92015-05-06 11:47:57 -0700499 return op;
500 }
501 break;
502 case MODIFY:
503 //TODO: figure this out at some point
504 break;
505 default:
506 log.warn("Unknown flow operation operator: {}", op.operator());
507 }
508 return null;
509 }
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800510 ).filter(Objects::nonNull).collect(Collectors.toSet());
Madan Jampani86940d92015-05-06 11:47:57 -0700511 }
512
513 @Override
514 public void deleteFlowRule(FlowRule rule) {
515 storeBatch(
516 new FlowRuleBatchOperation(
Sho SHIMIZU98ffca82015-05-11 08:39:24 -0700517 Collections.singletonList(
Madan Jampani86940d92015-05-06 11:47:57 -0700518 new FlowRuleBatchEntry(
519 FlowRuleOperation.REMOVE,
520 rule)), rule.deviceId(), idGenerator.getNewId()));
521 }
522
523 @Override
Charles Chan93fa7272016-01-26 22:27:02 -0800524 public FlowRuleEvent pendingFlowRule(FlowEntry rule) {
525 if (mastershipService.isLocalMaster(rule.deviceId())) {
526 StoredFlowEntry stored = flowTable.getFlowEntry(rule);
527 if (stored != null &&
528 stored.state() != FlowEntryState.PENDING_ADD) {
529 stored.setState(FlowEntryState.PENDING_ADD);
530 return new FlowRuleEvent(Type.RULE_UPDATED, rule);
531 }
532 }
533 return null;
534 }
535
536 @Override
Madan Jampani86940d92015-05-06 11:47:57 -0700537 public FlowRuleEvent addOrUpdateFlowRule(FlowEntry rule) {
Madan Jampani6bd2d9f2015-05-14 14:10:42 -0700538 NodeId master = mastershipService.getMasterFor(rule.deviceId());
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800539 if (Objects.equals(local, master)) {
Madan Jampani86940d92015-05-06 11:47:57 -0700540 return addOrUpdateFlowRuleInternal(rule);
541 }
542
543 log.warn("Tried to update FlowRule {} state,"
544 + " while the Node was not the master.", rule);
545 return null;
546 }
547
548 private FlowRuleEvent addOrUpdateFlowRuleInternal(FlowEntry rule) {
549 // check if this new rule is an update to an existing entry
550 StoredFlowEntry stored = flowTable.getFlowEntry(rule);
551 if (stored != null) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800552 //FIXME modification of "stored" flow entry outside of flow table
Madan Jampani86940d92015-05-06 11:47:57 -0700553 stored.setBytes(rule.bytes());
554 stored.setLife(rule.life());
555 stored.setPackets(rule.packets());
Jonathan Hart89e981f2016-01-04 13:59:55 -0800556 stored.setLastSeen();
Madan Jampani86940d92015-05-06 11:47:57 -0700557 if (stored.state() == FlowEntryState.PENDING_ADD) {
558 stored.setState(FlowEntryState.ADDED);
559 return new FlowRuleEvent(Type.RULE_ADDED, rule);
560 }
561 return new FlowRuleEvent(Type.RULE_UPDATED, rule);
562 }
563
564 // TODO: Confirm if this behavior is correct. See SimpleFlowRuleStore
565 // TODO: also update backup if the behavior is correct.
566 flowTable.add(rule);
567 return null;
568 }
569
570 @Override
571 public FlowRuleEvent removeFlowRule(FlowEntry rule) {
572 final DeviceId deviceId = rule.deviceId();
Madan Jampani6bd2d9f2015-05-14 14:10:42 -0700573 NodeId master = mastershipService.getMasterFor(deviceId);
Madan Jampani86940d92015-05-06 11:47:57 -0700574
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800575 if (Objects.equals(local, master)) {
Madan Jampani86940d92015-05-06 11:47:57 -0700576 // bypass and handle it locally
577 return removeFlowRuleInternal(rule);
578 }
579
580 if (master == null) {
581 log.warn("Failed to removeFlowRule: No master for {}", deviceId);
582 // TODO: revisit if this should be null (="no-op") or Exception
583 return null;
584 }
585
586 log.trace("Forwarding removeFlowRule to {}, which is the master for device {}",
587 master, deviceId);
588
589 return Futures.get(clusterCommunicator.sendAndReceive(
590 rule,
591 REMOVE_FLOW_ENTRY,
592 SERIALIZER::encode,
593 SERIALIZER::decode,
594 master),
595 FLOW_RULE_STORE_TIMEOUT_MILLIS,
596 TimeUnit.MILLISECONDS,
597 RuntimeException.class);
598 }
599
600 private FlowRuleEvent removeFlowRuleInternal(FlowEntry rule) {
601 final DeviceId deviceId = rule.deviceId();
602 // 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 -0800603 final FlowEntry removed = flowTable.remove(deviceId, rule);
604 // rule may be partial rule that is missing treatment, we should use rule from store instead
605 return removed != null ? new FlowRuleEvent(RULE_REMOVED, removed) : null;
Madan Jampani86940d92015-05-06 11:47:57 -0700606 }
607
608 @Override
Charles Chan0c7c43b2016-01-14 17:39:20 -0800609 public void purgeFlowRule(DeviceId deviceId) {
610 flowTable.purgeFlowRule(deviceId);
611 }
612
613 @Override
Madan Jampani86940d92015-05-06 11:47:57 -0700614 public void batchOperationComplete(FlowRuleBatchEvent event) {
615 //FIXME: need a per device pending response
616 NodeId nodeId = pendingResponses.remove(event.subject().batchId());
617 if (nodeId == null) {
618 notifyDelegate(event);
619 } else {
620 // TODO check unicast return value
621 clusterCommunicator.unicast(event, REMOTE_APPLY_COMPLETED, SERIALIZER::encode, nodeId);
622 //error log: log.warn("Failed to respond to peer for batch operation result");
623 }
624 }
625
626 private final class OnStoreBatch implements ClusterMessageHandler {
627
628 @Override
629 public void handle(final ClusterMessage message) {
630 FlowRuleBatchOperation operation = SERIALIZER.decode(message.payload());
631 log.debug("received batch request {}", operation);
632
633 final DeviceId deviceId = operation.deviceId();
Madan Jampani6bd2d9f2015-05-14 14:10:42 -0700634 NodeId master = mastershipService.getMasterFor(deviceId);
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800635 if (!Objects.equals(local, master)) {
Madan Jampani86940d92015-05-06 11:47:57 -0700636 Set<FlowRule> failures = new HashSet<>(operation.size());
637 for (FlowRuleBatchEntry op : operation.getOperations()) {
638 failures.add(op.target());
639 }
640 CompletedBatchOperation allFailed = new CompletedBatchOperation(false, failures, deviceId);
641 // This node is no longer the master, respond as all failed.
642 // TODO: we might want to wrap response in envelope
643 // to distinguish sw programming failure and hand over
644 // it make sense in the latter case to retry immediately.
645 message.respond(SERIALIZER.encode(allFailed));
646 return;
647 }
648
649 pendingResponses.put(operation.id(), message.sender());
650 storeBatchInternal(operation);
651 }
652 }
653
Madan Jampanif7536ab2015-05-07 23:23:23 -0700654 private class InternalFlowTable implements ReplicaInfoEventListener {
Madan Jampani86940d92015-05-06 11:47:57 -0700655
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800656 //TODO replace the Map<V,V> with ExtendedSet
657 private final Map<DeviceId, Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>
Madan Jampani5c3766c2015-06-02 15:54:41 -0700658 flowEntries = Maps.newConcurrentMap();
Madan Jampani86940d92015-05-06 11:47:57 -0700659
660 private final Map<DeviceId, Long> lastBackupTimes = Maps.newConcurrentMap();
661 private final Map<DeviceId, Long> lastUpdateTimes = Maps.newConcurrentMap();
662 private final Map<DeviceId, NodeId> lastBackupNodes = Maps.newConcurrentMap();
663
Madan Jampanif7536ab2015-05-07 23:23:23 -0700664 @Override
665 public void event(ReplicaInfoEvent event) {
Madan Jampania98bf932015-06-02 12:01:36 -0700666 if (!backupEnabled) {
667 return;
668 }
Madan Jampanif7536ab2015-05-07 23:23:23 -0700669 if (event.type() == ReplicaInfoEvent.Type.BACKUPS_CHANGED) {
670 DeviceId deviceId = event.subject();
Madan Jampani6bd2d9f2015-05-14 14:10:42 -0700671 NodeId master = mastershipService.getMasterFor(deviceId);
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800672 if (!Objects.equals(local, master)) {
Madan Jampanif7536ab2015-05-07 23:23:23 -0700673 // ignore since this event is for a device this node does not manage.
674 return;
675 }
Madan Jampani7267c552015-05-20 22:39:17 -0700676 NodeId newBackupNode = getBackupNode(deviceId);
677 NodeId currentBackupNode = lastBackupNodes.get(deviceId);
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800678 if (Objects.equals(newBackupNode, currentBackupNode)) {
Madan Jampanif7536ab2015-05-07 23:23:23 -0700679 // ignore since backup location hasn't changed.
680 return;
681 }
Madan Jampani7267c552015-05-20 22:39:17 -0700682 if (currentBackupNode != null && newBackupNode == null) {
683 // Current backup node is most likely down and no alternate backup node
684 // has been chosen. Clear current backup location so that we can resume
685 // backups when either current backup comes online or a different backup node
686 // is chosen.
687 log.warn("Lost backup location {} for deviceId {} and no alternate backup node exists. "
688 + "Flows can be lost if the master goes down", currentBackupNode, deviceId);
689 lastBackupNodes.remove(deviceId);
690 lastBackupTimes.remove(deviceId);
691 return;
692 // TODO: Pick any available node as backup and ensure hand-off occurs when
693 // a new master is elected.
694 }
Madan Jampani44839b82015-06-12 13:57:41 -0700695 log.debug("Backup location for {} has changed from {} to {}.",
Madan Jampani7267c552015-05-20 22:39:17 -0700696 deviceId, currentBackupNode, newBackupNode);
697 backupSenderExecutor.schedule(() -> backupFlowEntries(newBackupNode, Sets.newHashSet(deviceId)),
Madan Jampani03062682015-05-19 17:57:51 -0700698 0,
699 TimeUnit.SECONDS);
Madan Jampanif7536ab2015-05-07 23:23:23 -0700700 }
701 }
702
Madan Jampaniadea8902015-06-04 17:39:45 -0700703 private void sendBackups(NodeId nodeId, Set<DeviceId> deviceIds) {
704 // split up the devices into smaller batches and send them separately.
705 Iterables.partition(deviceIds, FLOW_TABLE_BACKUP_BATCH_SIZE)
706 .forEach(ids -> backupFlowEntries(nodeId, Sets.newHashSet(ids)));
707 }
708
Madan Jampanif7536ab2015-05-07 23:23:23 -0700709 private void backupFlowEntries(NodeId nodeId, Set<DeviceId> deviceIds) {
Madan Jampaniadea8902015-06-04 17:39:45 -0700710 if (deviceIds.isEmpty()) {
711 return;
712 }
Madan Jampanif7536ab2015-05-07 23:23:23 -0700713 log.debug("Sending flowEntries for devices {} to {} as backup.", deviceIds, nodeId);
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800714 Map<DeviceId, Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>
715 deviceFlowEntries = Maps.newConcurrentMap();
Madan Jampani85a9b0d2015-06-03 17:15:44 -0700716 deviceIds.forEach(id -> deviceFlowEntries.put(id, ImmutableMap.copyOf(getFlowTable(id))));
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800717 clusterCommunicator.<Map<DeviceId,
718 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>,
719 Set<DeviceId>>
720 sendAndReceive(deviceFlowEntries,
721 FLOW_TABLE_BACKUP,
722 SERIALIZER::encode,
723 SERIALIZER::decode,
724 nodeId)
725 .whenComplete((backedupDevices, error) -> {
726 Set<DeviceId> devicesNotBackedup = error != null ?
727 deviceFlowEntries.keySet() :
728 Sets.difference(deviceFlowEntries.keySet(), backedupDevices);
729 if (devicesNotBackedup.size() > 0) {
730 log.warn("Failed to backup devices: {}. Reason: {}",
731 devicesNotBackedup, error.getMessage());
732 }
733 if (backedupDevices != null) {
734 backedupDevices.forEach(id -> {
735 lastBackupTimes.put(id, System.currentTimeMillis());
736 lastBackupNodes.put(id, nodeId);
737 });
738 }
739 });
Madan Jampanif7536ab2015-05-07 23:23:23 -0700740 }
741
Madan Jampani86940d92015-05-06 11:47:57 -0700742 /**
743 * Returns the flow table for specified device.
744 *
745 * @param deviceId identifier of the device
746 * @return Map representing Flow Table of given device.
747 */
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800748 private Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> getFlowTable(DeviceId deviceId) {
Aaron Kruglikova62fdbb2015-10-27 16:32:06 -0700749 if (persistenceEnabled) {
750 return flowEntries.computeIfAbsent(deviceId, id -> persistenceService
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800751 .<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>persistentMapBuilder()
Aaron Kruglikova62fdbb2015-10-27 16:32:06 -0700752 .withName("FlowTable:" + deviceId.toString())
753 .withSerializer(new Serializer() {
754 @Override
755 public <T> byte[] encode(T object) {
756 return SERIALIZER.encode(object);
757 }
758
759 @Override
760 public <T> T decode(byte[] bytes) {
761 return SERIALIZER.decode(bytes);
762 }
763 })
764 .build());
765 } else {
766 return flowEntries.computeIfAbsent(deviceId, id -> Maps.newConcurrentMap());
767 }
Madan Jampani86940d92015-05-06 11:47:57 -0700768 }
769
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800770 private Map<StoredFlowEntry, StoredFlowEntry> getFlowEntriesInternal(DeviceId deviceId, FlowId flowId) {
771 return getFlowTable(deviceId).computeIfAbsent(flowId, id -> Maps.newConcurrentMap());
Madan Jampani86940d92015-05-06 11:47:57 -0700772 }
773
774 private StoredFlowEntry getFlowEntryInternal(FlowRule rule) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800775 return getFlowEntriesInternal(rule.deviceId(), rule.id()).get(rule);
Madan Jampani86940d92015-05-06 11:47:57 -0700776 }
777
778 private Set<FlowEntry> getFlowEntriesInternal(DeviceId deviceId) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800779 return getFlowTable(deviceId).values().stream()
780 .flatMap(m -> m.values().stream())
781 .collect(Collectors.toSet());
Madan Jampani86940d92015-05-06 11:47:57 -0700782 }
783
784 public StoredFlowEntry getFlowEntry(FlowRule rule) {
785 return getFlowEntryInternal(rule);
786 }
787
788 public Set<FlowEntry> getFlowEntries(DeviceId deviceId) {
789 return getFlowEntriesInternal(deviceId);
790 }
791
792 public void add(FlowEntry rule) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800793 getFlowEntriesInternal(rule.deviceId(), rule.id())
794 .compute((StoredFlowEntry) rule, (k, stored) -> {
795 //TODO compare stored and rule timestamps
796 //TODO the key is not updated
797 return (StoredFlowEntry) rule;
798 });
Madan Jampani86940d92015-05-06 11:47:57 -0700799 lastUpdateTimes.put(rule.deviceId(), System.currentTimeMillis());
800 }
801
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800802 public FlowEntry remove(DeviceId deviceId, FlowEntry rule) {
803 final AtomicReference<FlowEntry> removedRule = new AtomicReference<>();
804 getFlowEntriesInternal(rule.deviceId(), rule.id())
805 .computeIfPresent((StoredFlowEntry) rule, (k, stored) -> {
806 if (rule instanceof DefaultFlowEntry) {
807 DefaultFlowEntry toRemove = (DefaultFlowEntry) rule;
808 if (stored instanceof DefaultFlowEntry) {
809 DefaultFlowEntry storedEntry = (DefaultFlowEntry) stored;
810 if (toRemove.created() < storedEntry.created()) {
811 log.debug("Trying to remove more recent flow entry {} (stored: {})",
812 toRemove, stored);
813 // the key is not updated, removedRule remains null
814 return stored;
815 }
816 }
817 }
818 removedRule.set(stored);
819 return null;
820 });
821
822 if (removedRule.get() != null) {
Madan Jampani86940d92015-05-06 11:47:57 -0700823 lastUpdateTimes.put(deviceId, System.currentTimeMillis());
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800824 return removedRule.get();
825 } else {
826 return null;
Madan Jampani86940d92015-05-06 11:47:57 -0700827 }
828 }
829
Charles Chan0c7c43b2016-01-14 17:39:20 -0800830 public void purgeFlowRule(DeviceId deviceId) {
831 flowEntries.remove(deviceId);
832 }
833
Madan Jampani86940d92015-05-06 11:47:57 -0700834 private NodeId getBackupNode(DeviceId deviceId) {
835 List<NodeId> deviceStandbys = replicaInfoManager.getReplicaInfoFor(deviceId).backups();
836 // pick the standby which is most likely to become next master
837 return deviceStandbys.isEmpty() ? null : deviceStandbys.get(0);
838 }
839
840 private void backup() {
Madan Jampani08bf17b2015-05-06 16:25:26 -0700841 if (!backupEnabled) {
842 return;
843 }
Madan Jampani86940d92015-05-06 11:47:57 -0700844 try {
845 // determine the set of devices that we need to backup during this run.
Madan Jampani39b3b192016-05-19 08:08:29 -0700846 Set<DeviceId> devicesToBackup = flowEntries.keySet()
Madan Jampani86940d92015-05-06 11:47:57 -0700847 .stream()
Madan Jampani39b3b192016-05-19 08:08:29 -0700848 .filter(mastershipService::isLocalMaster)
Madan Jampani86940d92015-05-06 11:47:57 -0700849 .filter(deviceId -> {
850 Long lastBackupTime = lastBackupTimes.get(deviceId);
851 Long lastUpdateTime = lastUpdateTimes.get(deviceId);
852 NodeId lastBackupNode = lastBackupNodes.get(deviceId);
Madan Jampani7267c552015-05-20 22:39:17 -0700853 NodeId newBackupNode = getBackupNode(deviceId);
Madan Jampani86940d92015-05-06 11:47:57 -0700854 return lastBackupTime == null
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800855 || !Objects.equals(lastBackupNode, newBackupNode)
Madan Jampani86940d92015-05-06 11:47:57 -0700856 || (lastUpdateTime != null && lastUpdateTime > lastBackupTime);
857 })
858 .collect(Collectors.toSet());
859
860 // compute a mapping from node to the set of devices whose flow entries it should backup
861 Map<NodeId, Set<DeviceId>> devicesToBackupByNode = Maps.newHashMap();
862 devicesToBackup.forEach(deviceId -> {
863 NodeId backupLocation = getBackupNode(deviceId);
864 if (backupLocation != null) {
865 devicesToBackupByNode.computeIfAbsent(backupLocation, nodeId -> Sets.newHashSet())
866 .add(deviceId);
867 }
868 });
Madan Jampani86940d92015-05-06 11:47:57 -0700869 // send the device flow entries to their respective backup nodes
Madan Jampaniadea8902015-06-04 17:39:45 -0700870 devicesToBackupByNode.forEach(this::sendBackups);
Madan Jampani86940d92015-05-06 11:47:57 -0700871 } catch (Exception e) {
872 log.error("Backup failed.", e);
873 }
874 }
875
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800876 private Set<DeviceId> onBackupReceipt(Map<DeviceId,
877 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>> flowTables) {
Madan Jampani7267c552015-05-20 22:39:17 -0700878 log.debug("Received flowEntries for {} to backup", flowTables.keySet());
Madan Jampani654b58a2015-05-22 11:28:11 -0700879 Set<DeviceId> backedupDevices = Sets.newHashSet();
880 try {
Madan Jampania98bf932015-06-02 12:01:36 -0700881 flowTables.forEach((deviceId, deviceFlowTable) -> {
882 // Only process those devices are that not managed by the local node.
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800883 if (!Objects.equals(local, mastershipService.getMasterFor(deviceId))) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800884 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> backupFlowTable =
885 getFlowTable(deviceId);
Madan Jampania98bf932015-06-02 12:01:36 -0700886 backupFlowTable.clear();
887 backupFlowTable.putAll(deviceFlowTable);
888 backedupDevices.add(deviceId);
889 }
Madan Jampani08bf17b2015-05-06 16:25:26 -0700890 });
Madan Jampani654b58a2015-05-22 11:28:11 -0700891 } catch (Exception e) {
892 log.warn("Failure processing backup request", e);
893 }
894 return backedupDevices;
Madan Jampani86940d92015-05-06 11:47:57 -0700895 }
896 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700897
898 @Override
899 public FlowRuleEvent updateTableStatistics(DeviceId deviceId,
900 List<TableStatisticsEntry> tableStats) {
901 deviceTableStats.put(deviceId, tableStats);
902 return null;
903 }
904
905 @Override
906 public Iterable<TableStatisticsEntry> getTableStatistics(DeviceId deviceId) {
907 NodeId master = mastershipService.getMasterFor(deviceId);
908
909 if (master == null) {
910 log.debug("Failed to getTableStats: No master for {}", deviceId);
911 return Collections.emptyList();
912 }
913
914 List<TableStatisticsEntry> tableStats = deviceTableStats.get(deviceId);
915 if (tableStats == null) {
916 return Collections.emptyList();
917 }
918 return ImmutableList.copyOf(tableStats);
919 }
920
921 private class InternalTableStatsListener
922 implements EventuallyConsistentMapListener<DeviceId, List<TableStatisticsEntry>> {
923 @Override
924 public void event(EventuallyConsistentMapEvent<DeviceId,
925 List<TableStatisticsEntry>> event) {
926 //TODO: Generate an event to listeners (do we need?)
927 }
928 }
Madan Jampani86940d92015-05-06 11:47:57 -0700929}