blob: 2d864f91159843bdd235cbebd7b630bf4a527e59 [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;
Madan Jampanic6d69f72016-07-15 15:47:12 -070019import com.google.common.collect.ImmutableMap;
20import com.google.common.collect.Iterables;
21import com.google.common.collect.Maps;
22import com.google.common.collect.Sets;
23import com.google.common.util.concurrent.Futures;
24
25import org.apache.felix.scr.annotations.Activate;
26import org.apache.felix.scr.annotations.Component;
27import org.apache.felix.scr.annotations.Deactivate;
28import org.apache.felix.scr.annotations.Modified;
29import org.apache.felix.scr.annotations.Property;
30import org.apache.felix.scr.annotations.Reference;
31import org.apache.felix.scr.annotations.ReferenceCardinality;
32import org.apache.felix.scr.annotations.Service;
33import org.onlab.util.KryoNamespace;
34import org.onlab.util.Tools;
35import org.onosproject.cfg.ComponentConfigService;
36import org.onosproject.cluster.ClusterService;
37import org.onosproject.cluster.NodeId;
38import org.onosproject.core.CoreService;
39import org.onosproject.core.IdGenerator;
40import org.onosproject.mastership.MastershipService;
41import org.onosproject.net.DeviceId;
42import org.onosproject.net.device.DeviceService;
43import org.onosproject.net.flow.CompletedBatchOperation;
44import org.onosproject.net.flow.DefaultFlowEntry;
45import org.onosproject.net.flow.FlowEntry;
46import org.onosproject.net.flow.FlowEntry.FlowEntryState;
47import org.onosproject.net.flow.FlowId;
48import org.onosproject.net.flow.FlowRule;
49import org.onosproject.net.flow.FlowRuleBatchEntry;
50import org.onosproject.net.flow.FlowRuleBatchEntry.FlowRuleOperation;
51import org.onosproject.net.flow.FlowRuleBatchEvent;
52import org.onosproject.net.flow.FlowRuleBatchOperation;
53import org.onosproject.net.flow.FlowRuleBatchRequest;
54import org.onosproject.net.flow.FlowRuleEvent;
55import org.onosproject.net.flow.FlowRuleEvent.Type;
56import org.onosproject.net.flow.FlowRuleService;
57import org.onosproject.net.flow.FlowRuleStore;
58import org.onosproject.net.flow.FlowRuleStoreDelegate;
59import org.onosproject.net.flow.StoredFlowEntry;
60import org.onosproject.net.flow.TableStatisticsEntry;
61import org.onosproject.persistence.PersistenceService;
62import org.onosproject.store.AbstractStore;
63import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
64import org.onosproject.store.cluster.messaging.ClusterMessage;
65import org.onosproject.store.cluster.messaging.ClusterMessageHandler;
66import org.onosproject.store.flow.ReplicaInfoEvent;
67import org.onosproject.store.flow.ReplicaInfoEventListener;
68import org.onosproject.store.flow.ReplicaInfoService;
69import org.onosproject.store.impl.MastershipBasedTimestamp;
70import org.onosproject.store.serializers.KryoNamespaces;
Madan Jampanic6d69f72016-07-15 15:47:12 -070071import org.onosproject.store.service.EventuallyConsistentMap;
72import org.onosproject.store.service.EventuallyConsistentMapEvent;
73import org.onosproject.store.service.EventuallyConsistentMapListener;
74import org.onosproject.store.service.Serializer;
75import org.onosproject.store.service.StorageService;
76import org.onosproject.store.service.WallClockTimestamp;
77import org.osgi.service.component.ComponentContext;
78import org.slf4j.Logger;
Madan Jampani86940d92015-05-06 11:47:57 -070079
Brian O'Connora3e5cd52015-12-05 15:59:19 -080080 import java.util.Collections;
Madan Jampanic6d69f72016-07-15 15:47:12 -070081import java.util.Dictionary;
82import java.util.HashSet;
83import java.util.List;
84import java.util.Map;
85import java.util.Objects;
86import java.util.Set;
87import java.util.concurrent.ExecutorService;
88import java.util.concurrent.Executors;
89import java.util.concurrent.ScheduledExecutorService;
90import java.util.concurrent.ScheduledFuture;
91import java.util.concurrent.TimeUnit;
92import java.util.concurrent.atomic.AtomicInteger;
93import java.util.concurrent.atomic.AtomicReference;
94import java.util.stream.Collectors;
Madan Jampani86940d92015-05-06 11:47:57 -070095
Brian O'Connora3e5cd52015-12-05 15:59:19 -080096 import static com.google.common.base.Strings.isNullOrEmpty;
Madan Jampanic6d69f72016-07-15 15:47:12 -070097import static org.onlab.util.Tools.get;
98import static org.onlab.util.Tools.groupedThreads;
99import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_REMOVED;
100import static org.onosproject.store.flow.ReplicaInfoEvent.Type.MASTER_CHANGED;
101import static org.onosproject.store.flow.impl.FlowStoreMessageSubjects.*;
102import 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 */
Sho SHIMIZU5c396e32016-08-12 15:19:12 -0700107@Component(immediate = true)
Madan Jampani86940d92015-05-06 11:47:57 -0700108@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;
Madan Jampanic6d69f72016-07-15 15:47:12 -0700117 private static final int DEFAULT_MAX_BACKUP_COUNT = 2;
Aaron Kruglikova62fdbb2015-10-27 16:32:06 -0700118 private static final boolean DEFAULT_PERSISTENCE_ENABLED = false;
Madan Jampani08bf17b2015-05-06 16:25:26 -0700119 private static final int DEFAULT_BACKUP_PERIOD_MILLIS = 2000;
Madan Jampani86940d92015-05-06 11:47:57 -0700120 private static final long FLOW_RULE_STORE_TIMEOUT_MILLIS = 5000;
Madan Jampaniadea8902015-06-04 17:39:45 -0700121 // number of devices whose flow entries will be backed up in one communication round
122 private static final int FLOW_TABLE_BACKUP_BATCH_SIZE = 1;
Madan Jampani86940d92015-05-06 11:47:57 -0700123
124 @Property(name = "msgHandlerPoolSize", intValue = MESSAGE_HANDLER_THREAD_POOL_SIZE,
125 label = "Number of threads in the message handler pool")
126 private int msgHandlerPoolSize = MESSAGE_HANDLER_THREAD_POOL_SIZE;
127
128 @Property(name = "backupEnabled", boolValue = DEFAULT_BACKUP_ENABLED,
129 label = "Indicates whether backups are enabled or not")
Madan Jampanic6d69f72016-07-15 15:47:12 -0700130 private volatile boolean backupEnabled = DEFAULT_BACKUP_ENABLED;
Madan Jampani86940d92015-05-06 11:47:57 -0700131
Madan Jampani08bf17b2015-05-06 16:25:26 -0700132 @Property(name = "backupPeriod", intValue = DEFAULT_BACKUP_PERIOD_MILLIS,
133 label = "Delay in ms between successive backup runs")
134 private int backupPeriod = DEFAULT_BACKUP_PERIOD_MILLIS;
Aaron Kruglikova62fdbb2015-10-27 16:32:06 -0700135 @Property(name = "persistenceEnabled", boolValue = false,
136 label = "Indicates whether or not changes in the flow table should be persisted to disk.")
137 private boolean persistenceEnabled = DEFAULT_PERSISTENCE_ENABLED;
Madan Jampani08bf17b2015-05-06 16:25:26 -0700138
Madan Jampanic6d69f72016-07-15 15:47:12 -0700139 @Property(name = "backupCount", intValue = DEFAULT_MAX_BACKUP_COUNT,
140 label = "Max number of backup copies for each device")
141 private volatile int backupCount = DEFAULT_MAX_BACKUP_COUNT;
142
Madan Jampani86940d92015-05-06 11:47:57 -0700143 private InternalFlowTable flowTable = new InternalFlowTable();
144
145 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
146 protected ReplicaInfoService replicaInfoManager;
147
148 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
149 protected ClusterCommunicationService clusterCommunicator;
150
151 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
152 protected ClusterService clusterService;
153
154 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
155 protected DeviceService deviceService;
156
157 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
158 protected CoreService coreService;
159
160 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
161 protected ComponentConfigService configService;
162
163 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
164 protected MastershipService mastershipService;
165
Aaron Kruglikova62fdbb2015-10-27 16:32:06 -0700166 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
167 protected PersistenceService persistenceService;
168
Madan Jampani86940d92015-05-06 11:47:57 -0700169 private Map<Long, NodeId> pendingResponses = Maps.newConcurrentMap();
170 private ExecutorService messageHandlingExecutor;
Madan Jampani71c32ca2016-06-22 08:23:18 -0700171 private ExecutorService eventHandler;
Madan Jampani86940d92015-05-06 11:47:57 -0700172
Madan Jampani08bf17b2015-05-06 16:25:26 -0700173 private ScheduledFuture<?> backupTask;
Madan Jampani86940d92015-05-06 11:47:57 -0700174 private final ScheduledExecutorService backupSenderExecutor =
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700175 Executors.newSingleThreadScheduledExecutor(groupedThreads("onos/flow", "backup-sender", log));
Madan Jampani86940d92015-05-06 11:47:57 -0700176
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700177 private EventuallyConsistentMap<DeviceId, List<TableStatisticsEntry>> deviceTableStats;
178 private final EventuallyConsistentMapListener<DeviceId, List<TableStatisticsEntry>> tableStatsListener =
179 new InternalTableStatsListener();
180
181 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
182 protected StorageService storageService;
183
Madan Jampani884d4432016-08-23 10:46:55 -0700184 protected final Serializer serializer = Serializer.using(KryoNamespaces.API);
Madan Jampani86940d92015-05-06 11:47:57 -0700185
Madan Jampani884d4432016-08-23 10:46:55 -0700186 protected final KryoNamespace.Builder serializerBuilder = KryoNamespace.newBuilder()
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700187 .register(KryoNamespaces.API)
188 .register(MastershipBasedTimestamp.class);
189
190
Madan Jampani86940d92015-05-06 11:47:57 -0700191 private IdGenerator idGenerator;
192 private NodeId local;
193
194 @Activate
195 public void activate(ComponentContext context) {
196 configService.registerProperties(getClass());
197
198 idGenerator = coreService.getIdGenerator(FlowRuleService.FLOW_OP_TOPIC);
199
200 local = clusterService.getLocalNode().id();
201
Madan Jampani71c32ca2016-06-22 08:23:18 -0700202 eventHandler = Executors.newSingleThreadExecutor(
203 groupedThreads("onos/flow", "event-handler", log));
Madan Jampani86940d92015-05-06 11:47:57 -0700204 messageHandlingExecutor = Executors.newFixedThreadPool(
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700205 msgHandlerPoolSize, groupedThreads("onos/store/flow", "message-handlers", log));
Madan Jampani86940d92015-05-06 11:47:57 -0700206
207 registerMessageHandlers(messageHandlingExecutor);
208
Madan Jampani08bf17b2015-05-06 16:25:26 -0700209 if (backupEnabled) {
Madan Jampanif7536ab2015-05-07 23:23:23 -0700210 replicaInfoManager.addListener(flowTable);
Madan Jampani08bf17b2015-05-06 16:25:26 -0700211 backupTask = backupSenderExecutor.scheduleWithFixedDelay(
212 flowTable::backup,
213 0,
214 backupPeriod,
215 TimeUnit.MILLISECONDS);
216 }
Madan Jampani86940d92015-05-06 11:47:57 -0700217
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700218 deviceTableStats = storageService.<DeviceId, List<TableStatisticsEntry>>eventuallyConsistentMapBuilder()
219 .withName("onos-flow-table-stats")
Madan Jampani884d4432016-08-23 10:46:55 -0700220 .withSerializer(serializerBuilder)
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700221 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
222 .withTimestampProvider((k, v) -> new WallClockTimestamp())
223 .withTombstonesDisabled()
224 .build();
225 deviceTableStats.addListener(tableStatsListener);
226
Madan Jampani86940d92015-05-06 11:47:57 -0700227 logConfig("Started");
228 }
229
230 @Deactivate
231 public void deactivate(ComponentContext context) {
Madan Jampanif7536ab2015-05-07 23:23:23 -0700232 if (backupEnabled) {
233 replicaInfoManager.removeListener(flowTable);
234 backupTask.cancel(true);
235 }
Madan Jampani86940d92015-05-06 11:47:57 -0700236 configService.unregisterProperties(getClass(), false);
237 unregisterMessageHandlers();
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700238 deviceTableStats.removeListener(tableStatsListener);
239 deviceTableStats.destroy();
Madan Jampani71c32ca2016-06-22 08:23:18 -0700240 eventHandler.shutdownNow();
Madan Jampani86940d92015-05-06 11:47:57 -0700241 messageHandlingExecutor.shutdownNow();
242 backupSenderExecutor.shutdownNow();
243 log.info("Stopped");
244 }
245
246 @SuppressWarnings("rawtypes")
247 @Modified
248 public void modified(ComponentContext context) {
249 if (context == null) {
250 backupEnabled = DEFAULT_BACKUP_ENABLED;
251 logConfig("Default config");
252 return;
253 }
254
255 Dictionary properties = context.getProperties();
256 int newPoolSize;
257 boolean newBackupEnabled;
Madan Jampani08bf17b2015-05-06 16:25:26 -0700258 int newBackupPeriod;
Madan Jampanic6d69f72016-07-15 15:47:12 -0700259 int newBackupCount;
Madan Jampani86940d92015-05-06 11:47:57 -0700260 try {
261 String s = get(properties, "msgHandlerPoolSize");
262 newPoolSize = isNullOrEmpty(s) ? msgHandlerPoolSize : Integer.parseInt(s.trim());
263
264 s = get(properties, "backupEnabled");
265 newBackupEnabled = isNullOrEmpty(s) ? backupEnabled : Boolean.parseBoolean(s.trim());
266
Madan Jampani08bf17b2015-05-06 16:25:26 -0700267 s = get(properties, "backupPeriod");
268 newBackupPeriod = isNullOrEmpty(s) ? backupPeriod : Integer.parseInt(s.trim());
269
Madan Jampanic6d69f72016-07-15 15:47:12 -0700270 s = get(properties, "backupCount");
271 newBackupCount = isNullOrEmpty(s) ? backupCount : Integer.parseInt(s.trim());
Madan Jampani86940d92015-05-06 11:47:57 -0700272 } catch (NumberFormatException | ClassCastException e) {
273 newPoolSize = MESSAGE_HANDLER_THREAD_POOL_SIZE;
274 newBackupEnabled = DEFAULT_BACKUP_ENABLED;
Madan Jampani08bf17b2015-05-06 16:25:26 -0700275 newBackupPeriod = DEFAULT_BACKUP_PERIOD_MILLIS;
Madan Jampanic6d69f72016-07-15 15:47:12 -0700276 newBackupCount = DEFAULT_MAX_BACKUP_COUNT;
Madan Jampani86940d92015-05-06 11:47:57 -0700277 }
278
Madan Jampani08bf17b2015-05-06 16:25:26 -0700279 boolean restartBackupTask = false;
Madan Jampani86940d92015-05-06 11:47:57 -0700280 if (newBackupEnabled != backupEnabled) {
281 backupEnabled = newBackupEnabled;
Madan Jampanif7536ab2015-05-07 23:23:23 -0700282 if (!backupEnabled) {
283 replicaInfoManager.removeListener(flowTable);
284 if (backupTask != null) {
285 backupTask.cancel(false);
286 backupTask = null;
287 }
288 } else {
289 replicaInfoManager.addListener(flowTable);
Madan Jampani08bf17b2015-05-06 16:25:26 -0700290 }
291 restartBackupTask = backupEnabled;
292 }
293 if (newBackupPeriod != backupPeriod) {
294 backupPeriod = newBackupPeriod;
295 restartBackupTask = backupEnabled;
296 }
297 if (restartBackupTask) {
298 if (backupTask != null) {
299 // cancel previously running task
300 backupTask.cancel(false);
301 }
302 backupTask = backupSenderExecutor.scheduleWithFixedDelay(
303 flowTable::backup,
304 0,
305 backupPeriod,
306 TimeUnit.MILLISECONDS);
Madan Jampani86940d92015-05-06 11:47:57 -0700307 }
308 if (newPoolSize != msgHandlerPoolSize) {
309 msgHandlerPoolSize = newPoolSize;
310 ExecutorService oldMsgHandler = messageHandlingExecutor;
311 messageHandlingExecutor = Executors.newFixedThreadPool(
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800312 msgHandlerPoolSize, groupedThreads("onos/store/flow", "message-handlers", log));
Madan Jampani86940d92015-05-06 11:47:57 -0700313
314 // replace previously registered handlers.
315 registerMessageHandlers(messageHandlingExecutor);
316 oldMsgHandler.shutdown();
317 }
Madan Jampanic6d69f72016-07-15 15:47:12 -0700318 if (backupCount != newBackupCount) {
319 backupCount = newBackupCount;
320 }
Madan Jampani86940d92015-05-06 11:47:57 -0700321 logConfig("Reconfigured");
322 }
323
324 private void registerMessageHandlers(ExecutorService executor) {
325
326 clusterCommunicator.addSubscriber(APPLY_BATCH_FLOWS, new OnStoreBatch(), executor);
327 clusterCommunicator.<FlowRuleBatchEvent>addSubscriber(
Madan Jampani884d4432016-08-23 10:46:55 -0700328 REMOTE_APPLY_COMPLETED, serializer::decode, this::notifyDelegate, executor);
Madan Jampani86940d92015-05-06 11:47:57 -0700329 clusterCommunicator.addSubscriber(
Madan Jampani884d4432016-08-23 10:46:55 -0700330 GET_FLOW_ENTRY, serializer::decode, flowTable::getFlowEntry, serializer::encode, executor);
Madan Jampani86940d92015-05-06 11:47:57 -0700331 clusterCommunicator.addSubscriber(
Madan Jampani884d4432016-08-23 10:46:55 -0700332 GET_DEVICE_FLOW_ENTRIES, serializer::decode, flowTable::getFlowEntries, serializer::encode, executor);
Madan Jampani86940d92015-05-06 11:47:57 -0700333 clusterCommunicator.addSubscriber(
Madan Jampani884d4432016-08-23 10:46:55 -0700334 REMOVE_FLOW_ENTRY, serializer::decode, this::removeFlowRuleInternal, serializer::encode, executor);
Madan Jampani86940d92015-05-06 11:47:57 -0700335 clusterCommunicator.addSubscriber(
Madan Jampani884d4432016-08-23 10:46:55 -0700336 REMOVE_FLOW_ENTRY, serializer::decode, this::removeFlowRuleInternal, serializer::encode, executor);
Madan Jampani86940d92015-05-06 11:47:57 -0700337 clusterCommunicator.addSubscriber(
Madan Jampani884d4432016-08-23 10:46:55 -0700338 FLOW_TABLE_BACKUP, serializer::decode, flowTable::onBackupReceipt, serializer::encode, executor);
Madan Jampani86940d92015-05-06 11:47:57 -0700339 }
340
341 private void unregisterMessageHandlers() {
342 clusterCommunicator.removeSubscriber(REMOVE_FLOW_ENTRY);
343 clusterCommunicator.removeSubscriber(GET_DEVICE_FLOW_ENTRIES);
344 clusterCommunicator.removeSubscriber(GET_FLOW_ENTRY);
345 clusterCommunicator.removeSubscriber(APPLY_BATCH_FLOWS);
346 clusterCommunicator.removeSubscriber(REMOTE_APPLY_COMPLETED);
347 clusterCommunicator.removeSubscriber(FLOW_TABLE_BACKUP);
348 }
349
350 private void logConfig(String prefix) {
Madan Jampanic6d69f72016-07-15 15:47:12 -0700351 log.info("{} with msgHandlerPoolSize = {}; backupEnabled = {}, backupPeriod = {}, backupCount = {}",
352 prefix, msgHandlerPoolSize, backupEnabled, backupPeriod, backupCount);
Madan Jampani86940d92015-05-06 11:47:57 -0700353 }
354
355 // This is not a efficient operation on a distributed sharded
356 // flow store. We need to revisit the need for this operation or at least
357 // make it device specific.
358 @Override
359 public int getFlowRuleCount() {
360 AtomicInteger sum = new AtomicInteger(0);
361 deviceService.getDevices().forEach(device -> sum.addAndGet(Iterables.size(getFlowEntries(device.id()))));
362 return sum.get();
363 }
364
365 @Override
366 public FlowEntry getFlowEntry(FlowRule rule) {
Madan Jampani6bd2d9f2015-05-14 14:10:42 -0700367 NodeId master = mastershipService.getMasterFor(rule.deviceId());
Madan Jampani86940d92015-05-06 11:47:57 -0700368
369 if (master == null) {
Thomas Vachuska88fd6902015-08-04 10:08:34 -0700370 log.debug("Failed to getFlowEntry: No master for {}", rule.deviceId());
Madan Jampani86940d92015-05-06 11:47:57 -0700371 return null;
372 }
373
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800374 if (Objects.equals(local, master)) {
Madan Jampani86940d92015-05-06 11:47:57 -0700375 return flowTable.getFlowEntry(rule);
376 }
377
378 log.trace("Forwarding getFlowEntry to {}, which is the primary (master) for device {}",
379 master, rule.deviceId());
380
381 return Tools.futureGetOrElse(clusterCommunicator.sendAndReceive(rule,
382 FlowStoreMessageSubjects.GET_FLOW_ENTRY,
Madan Jampani884d4432016-08-23 10:46:55 -0700383 serializer::encode,
384 serializer::decode,
Madan Jampani86940d92015-05-06 11:47:57 -0700385 master),
386 FLOW_RULE_STORE_TIMEOUT_MILLIS,
387 TimeUnit.MILLISECONDS,
388 null);
389 }
390
391 @Override
392 public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) {
Madan Jampani6bd2d9f2015-05-14 14:10:42 -0700393 NodeId master = mastershipService.getMasterFor(deviceId);
Madan Jampani86940d92015-05-06 11:47:57 -0700394
395 if (master == null) {
Thomas Vachuska88fd6902015-08-04 10:08:34 -0700396 log.debug("Failed to getFlowEntries: No master for {}", deviceId);
Madan Jampani86940d92015-05-06 11:47:57 -0700397 return Collections.emptyList();
398 }
399
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800400 if (Objects.equals(local, master)) {
Madan Jampani86940d92015-05-06 11:47:57 -0700401 return flowTable.getFlowEntries(deviceId);
402 }
403
404 log.trace("Forwarding getFlowEntries to {}, which is the primary (master) for device {}",
405 master, deviceId);
406
407 return Tools.futureGetOrElse(clusterCommunicator.sendAndReceive(deviceId,
408 FlowStoreMessageSubjects.GET_DEVICE_FLOW_ENTRIES,
Madan Jampani884d4432016-08-23 10:46:55 -0700409 serializer::encode,
410 serializer::decode,
Madan Jampani86940d92015-05-06 11:47:57 -0700411 master),
412 FLOW_RULE_STORE_TIMEOUT_MILLIS,
413 TimeUnit.MILLISECONDS,
414 Collections.emptyList());
415 }
416
417 @Override
418 public void storeFlowRule(FlowRule rule) {
419 storeBatch(new FlowRuleBatchOperation(
Sho SHIMIZU98ffca82015-05-11 08:39:24 -0700420 Collections.singletonList(new FlowRuleBatchEntry(FlowRuleOperation.ADD, rule)),
Madan Jampani86940d92015-05-06 11:47:57 -0700421 rule.deviceId(), idGenerator.getNewId()));
422 }
423
424 @Override
425 public void storeBatch(FlowRuleBatchOperation operation) {
426 if (operation.getOperations().isEmpty()) {
427 notifyDelegate(FlowRuleBatchEvent.completed(
428 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
429 new CompletedBatchOperation(true, Collections.emptySet(), operation.deviceId())));
430 return;
431 }
432
433 DeviceId deviceId = operation.deviceId();
Madan Jampani6bd2d9f2015-05-14 14:10:42 -0700434 NodeId master = mastershipService.getMasterFor(deviceId);
Madan Jampani86940d92015-05-06 11:47:57 -0700435
436 if (master == null) {
437 log.warn("No master for {} : flows will be marked for removal", deviceId);
438
439 updateStoreInternal(operation);
440
441 notifyDelegate(FlowRuleBatchEvent.completed(
442 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
443 new CompletedBatchOperation(true, Collections.emptySet(), operation.deviceId())));
444 return;
445 }
446
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800447 if (Objects.equals(local, master)) {
Madan Jampani86940d92015-05-06 11:47:57 -0700448 storeBatchInternal(operation);
449 return;
450 }
451
452 log.trace("Forwarding storeBatch to {}, which is the primary (master) for device {}",
453 master, deviceId);
454
Madan Jampani175e8fd2015-05-20 14:10:45 -0700455 clusterCommunicator.unicast(operation,
456 APPLY_BATCH_FLOWS,
Madan Jampani884d4432016-08-23 10:46:55 -0700457 serializer::encode,
Madan Jampani175e8fd2015-05-20 14:10:45 -0700458 master)
459 .whenComplete((result, error) -> {
Thomas Vachuskaa267ce42015-05-27 16:14:23 -0700460 if (error != null) {
Madan Jampani15f1bc42015-05-28 10:51:52 -0700461 log.warn("Failed to storeBatch: {} to {}", operation, master, error);
Madan Jampani86940d92015-05-06 11:47:57 -0700462
Thomas Vachuskaa267ce42015-05-27 16:14:23 -0700463 Set<FlowRule> allFailures = operation.getOperations()
464 .stream()
465 .map(op -> op.target())
466 .collect(Collectors.toSet());
Madan Jampani86940d92015-05-06 11:47:57 -0700467
Thomas Vachuskaa267ce42015-05-27 16:14:23 -0700468 notifyDelegate(FlowRuleBatchEvent.completed(
469 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
470 new CompletedBatchOperation(false, allFailures, deviceId)));
471 }
Madan Jampani175e8fd2015-05-20 14:10:45 -0700472 });
Madan Jampani86940d92015-05-06 11:47:57 -0700473 }
474
475 private void storeBatchInternal(FlowRuleBatchOperation operation) {
476
477 final DeviceId did = operation.deviceId();
478 //final Collection<FlowEntry> ft = flowTable.getFlowEntries(did);
479 Set<FlowRuleBatchEntry> currentOps = updateStoreInternal(operation);
480 if (currentOps.isEmpty()) {
481 batchOperationComplete(FlowRuleBatchEvent.completed(
482 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
483 new CompletedBatchOperation(true, Collections.emptySet(), did)));
484 return;
485 }
486
487 notifyDelegate(FlowRuleBatchEvent.requested(new
488 FlowRuleBatchRequest(operation.id(),
489 currentOps), operation.deviceId()));
490 }
491
492 private Set<FlowRuleBatchEntry> updateStoreInternal(FlowRuleBatchOperation operation) {
493 return operation.getOperations().stream().map(
494 op -> {
495 StoredFlowEntry entry;
496 switch (op.operator()) {
497 case ADD:
498 entry = new DefaultFlowEntry(op.target());
499 // always add requested FlowRule
500 // Note: 2 equal FlowEntry may have different treatment
501 flowTable.remove(entry.deviceId(), entry);
502 flowTable.add(entry);
503
504 return op;
505 case REMOVE:
506 entry = flowTable.getFlowEntry(op.target());
507 if (entry != null) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800508 //FIXME modification of "stored" flow entry outside of flow table
Madan Jampani86940d92015-05-06 11:47:57 -0700509 entry.setState(FlowEntryState.PENDING_REMOVE);
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800510 log.debug("Setting state of rule to pending remove: {}", entry);
Madan Jampani86940d92015-05-06 11:47:57 -0700511 return op;
512 }
513 break;
514 case MODIFY:
515 //TODO: figure this out at some point
516 break;
517 default:
518 log.warn("Unknown flow operation operator: {}", op.operator());
519 }
520 return null;
521 }
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800522 ).filter(Objects::nonNull).collect(Collectors.toSet());
Madan Jampani86940d92015-05-06 11:47:57 -0700523 }
524
525 @Override
526 public void deleteFlowRule(FlowRule rule) {
527 storeBatch(
528 new FlowRuleBatchOperation(
Sho SHIMIZU98ffca82015-05-11 08:39:24 -0700529 Collections.singletonList(
Madan Jampani86940d92015-05-06 11:47:57 -0700530 new FlowRuleBatchEntry(
531 FlowRuleOperation.REMOVE,
532 rule)), rule.deviceId(), idGenerator.getNewId()));
533 }
534
535 @Override
Charles Chan93fa7272016-01-26 22:27:02 -0800536 public FlowRuleEvent pendingFlowRule(FlowEntry rule) {
537 if (mastershipService.isLocalMaster(rule.deviceId())) {
538 StoredFlowEntry stored = flowTable.getFlowEntry(rule);
539 if (stored != null &&
540 stored.state() != FlowEntryState.PENDING_ADD) {
541 stored.setState(FlowEntryState.PENDING_ADD);
542 return new FlowRuleEvent(Type.RULE_UPDATED, rule);
543 }
544 }
545 return null;
546 }
547
548 @Override
Madan Jampani86940d92015-05-06 11:47:57 -0700549 public FlowRuleEvent addOrUpdateFlowRule(FlowEntry rule) {
Madan Jampani6bd2d9f2015-05-14 14:10:42 -0700550 NodeId master = mastershipService.getMasterFor(rule.deviceId());
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800551 if (Objects.equals(local, master)) {
Madan Jampani86940d92015-05-06 11:47:57 -0700552 return addOrUpdateFlowRuleInternal(rule);
553 }
554
555 log.warn("Tried to update FlowRule {} state,"
556 + " while the Node was not the master.", rule);
557 return null;
558 }
559
560 private FlowRuleEvent addOrUpdateFlowRuleInternal(FlowEntry rule) {
561 // check if this new rule is an update to an existing entry
562 StoredFlowEntry stored = flowTable.getFlowEntry(rule);
563 if (stored != null) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800564 //FIXME modification of "stored" flow entry outside of flow table
Madan Jampani86940d92015-05-06 11:47:57 -0700565 stored.setBytes(rule.bytes());
Thiago Santos877914d2016-07-20 18:29:29 -0300566 stored.setLife(rule.life(TimeUnit.NANOSECONDS), TimeUnit.NANOSECONDS);
Madan Jampani86940d92015-05-06 11:47:57 -0700567 stored.setPackets(rule.packets());
Jonathan Hart89e981f2016-01-04 13:59:55 -0800568 stored.setLastSeen();
Madan Jampani86940d92015-05-06 11:47:57 -0700569 if (stored.state() == FlowEntryState.PENDING_ADD) {
570 stored.setState(FlowEntryState.ADDED);
571 return new FlowRuleEvent(Type.RULE_ADDED, rule);
572 }
573 return new FlowRuleEvent(Type.RULE_UPDATED, rule);
574 }
575
576 // TODO: Confirm if this behavior is correct. See SimpleFlowRuleStore
577 // TODO: also update backup if the behavior is correct.
578 flowTable.add(rule);
579 return null;
580 }
581
582 @Override
583 public FlowRuleEvent removeFlowRule(FlowEntry rule) {
584 final DeviceId deviceId = rule.deviceId();
Madan Jampani6bd2d9f2015-05-14 14:10:42 -0700585 NodeId master = mastershipService.getMasterFor(deviceId);
Madan Jampani86940d92015-05-06 11:47:57 -0700586
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800587 if (Objects.equals(local, master)) {
Madan Jampani86940d92015-05-06 11:47:57 -0700588 // bypass and handle it locally
589 return removeFlowRuleInternal(rule);
590 }
591
592 if (master == null) {
593 log.warn("Failed to removeFlowRule: No master for {}", deviceId);
594 // TODO: revisit if this should be null (="no-op") or Exception
595 return null;
596 }
597
598 log.trace("Forwarding removeFlowRule to {}, which is the master for device {}",
599 master, deviceId);
600
Madan Jampani222229e2016-07-14 10:43:25 -0700601 return Futures.getUnchecked(clusterCommunicator.sendAndReceive(
Madan Jampani86940d92015-05-06 11:47:57 -0700602 rule,
603 REMOVE_FLOW_ENTRY,
Madan Jampani884d4432016-08-23 10:46:55 -0700604 serializer::encode,
605 serializer::decode,
Madan Jampani222229e2016-07-14 10:43:25 -0700606 master));
Madan Jampani86940d92015-05-06 11:47:57 -0700607 }
608
609 private FlowRuleEvent removeFlowRuleInternal(FlowEntry rule) {
610 final DeviceId deviceId = rule.deviceId();
611 // 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 -0800612 final FlowEntry removed = flowTable.remove(deviceId, rule);
613 // rule may be partial rule that is missing treatment, we should use rule from store instead
614 return removed != null ? new FlowRuleEvent(RULE_REMOVED, removed) : null;
Madan Jampani86940d92015-05-06 11:47:57 -0700615 }
616
617 @Override
Charles Chan0c7c43b2016-01-14 17:39:20 -0800618 public void purgeFlowRule(DeviceId deviceId) {
619 flowTable.purgeFlowRule(deviceId);
620 }
621
622 @Override
Madan Jampani86940d92015-05-06 11:47:57 -0700623 public void batchOperationComplete(FlowRuleBatchEvent event) {
624 //FIXME: need a per device pending response
625 NodeId nodeId = pendingResponses.remove(event.subject().batchId());
626 if (nodeId == null) {
627 notifyDelegate(event);
628 } else {
629 // TODO check unicast return value
Madan Jampani884d4432016-08-23 10:46:55 -0700630 clusterCommunicator.unicast(event, REMOTE_APPLY_COMPLETED, serializer::encode, nodeId);
Madan Jampani86940d92015-05-06 11:47:57 -0700631 //error log: log.warn("Failed to respond to peer for batch operation result");
632 }
633 }
634
635 private final class OnStoreBatch implements ClusterMessageHandler {
636
637 @Override
638 public void handle(final ClusterMessage message) {
Madan Jampani884d4432016-08-23 10:46:55 -0700639 FlowRuleBatchOperation operation = serializer.decode(message.payload());
Madan Jampani86940d92015-05-06 11:47:57 -0700640 log.debug("received batch request {}", operation);
641
642 final DeviceId deviceId = operation.deviceId();
Madan Jampani6bd2d9f2015-05-14 14:10:42 -0700643 NodeId master = mastershipService.getMasterFor(deviceId);
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800644 if (!Objects.equals(local, master)) {
Madan Jampani86940d92015-05-06 11:47:57 -0700645 Set<FlowRule> failures = new HashSet<>(operation.size());
646 for (FlowRuleBatchEntry op : operation.getOperations()) {
647 failures.add(op.target());
648 }
649 CompletedBatchOperation allFailed = new CompletedBatchOperation(false, failures, deviceId);
650 // This node is no longer the master, respond as all failed.
651 // TODO: we might want to wrap response in envelope
652 // to distinguish sw programming failure and hand over
653 // it make sense in the latter case to retry immediately.
Madan Jampani884d4432016-08-23 10:46:55 -0700654 message.respond(serializer.encode(allFailed));
Madan Jampani86940d92015-05-06 11:47:57 -0700655 return;
656 }
657
658 pendingResponses.put(operation.id(), message.sender());
659 storeBatchInternal(operation);
660 }
661 }
662
Madan Jampanic6d69f72016-07-15 15:47:12 -0700663 private class BackupOperation {
664 private final NodeId nodeId;
665 private final DeviceId deviceId;
666
667 public BackupOperation(NodeId nodeId, DeviceId deviceId) {
668 this.nodeId = nodeId;
669 this.deviceId = deviceId;
670 }
671
672 @Override
673 public int hashCode() {
674 return Objects.hash(nodeId, deviceId);
675 }
676
677 @Override
678 public boolean equals(Object other) {
679 if (other != null && other instanceof BackupOperation) {
680 BackupOperation that = (BackupOperation) other;
681 return this.nodeId.equals(that.nodeId) &&
682 this.deviceId.equals(that.deviceId);
683 } else {
684 return false;
685 }
686 }
687 }
688
Madan Jampanif7536ab2015-05-07 23:23:23 -0700689 private class InternalFlowTable implements ReplicaInfoEventListener {
Madan Jampani86940d92015-05-06 11:47:57 -0700690
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800691 //TODO replace the Map<V,V> with ExtendedSet
692 private final Map<DeviceId, Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>
Madan Jampani5c3766c2015-06-02 15:54:41 -0700693 flowEntries = Maps.newConcurrentMap();
Madan Jampani86940d92015-05-06 11:47:57 -0700694
Madan Jampanic6d69f72016-07-15 15:47:12 -0700695 private final Map<BackupOperation, Long> lastBackupTimes = Maps.newConcurrentMap();
Madan Jampani86940d92015-05-06 11:47:57 -0700696 private final Map<DeviceId, Long> lastUpdateTimes = Maps.newConcurrentMap();
Madan Jampani86940d92015-05-06 11:47:57 -0700697
Madan Jampanif7536ab2015-05-07 23:23:23 -0700698 @Override
699 public void event(ReplicaInfoEvent event) {
Madan Jampani71c32ca2016-06-22 08:23:18 -0700700 eventHandler.execute(() -> handleEvent(event));
701 }
702
703 private void handleEvent(ReplicaInfoEvent event) {
Madan Jampanic6d69f72016-07-15 15:47:12 -0700704 DeviceId deviceId = event.subject();
705 if (!backupEnabled || !mastershipService.isLocalMaster(deviceId)) {
Madan Jampania98bf932015-06-02 12:01:36 -0700706 return;
707 }
Madan Jampanic6d69f72016-07-15 15:47:12 -0700708 if (event.type() == MASTER_CHANGED) {
709 lastUpdateTimes.put(deviceId, System.currentTimeMillis());
Madan Jampanif7536ab2015-05-07 23:23:23 -0700710 }
Madan Jampanic6d69f72016-07-15 15:47:12 -0700711 backupSenderExecutor.schedule(this::backup, 0, TimeUnit.SECONDS);
Madan Jampanif7536ab2015-05-07 23:23:23 -0700712 }
713
Madan Jampaniadea8902015-06-04 17:39:45 -0700714 private void sendBackups(NodeId nodeId, Set<DeviceId> deviceIds) {
715 // split up the devices into smaller batches and send them separately.
716 Iterables.partition(deviceIds, FLOW_TABLE_BACKUP_BATCH_SIZE)
717 .forEach(ids -> backupFlowEntries(nodeId, Sets.newHashSet(ids)));
718 }
719
Madan Jampanif7536ab2015-05-07 23:23:23 -0700720 private void backupFlowEntries(NodeId nodeId, Set<DeviceId> deviceIds) {
Madan Jampaniadea8902015-06-04 17:39:45 -0700721 if (deviceIds.isEmpty()) {
722 return;
723 }
Madan Jampanic6d69f72016-07-15 15:47:12 -0700724 log.debug("Sending flowEntries for devices {} to {} for backup.", deviceIds, nodeId);
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800725 Map<DeviceId, Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>
726 deviceFlowEntries = Maps.newConcurrentMap();
Madan Jampani85a9b0d2015-06-03 17:15:44 -0700727 deviceIds.forEach(id -> deviceFlowEntries.put(id, ImmutableMap.copyOf(getFlowTable(id))));
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800728 clusterCommunicator.<Map<DeviceId,
729 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>,
730 Set<DeviceId>>
731 sendAndReceive(deviceFlowEntries,
732 FLOW_TABLE_BACKUP,
Madan Jampani884d4432016-08-23 10:46:55 -0700733 serializer::encode,
734 serializer::decode,
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800735 nodeId)
736 .whenComplete((backedupDevices, error) -> {
737 Set<DeviceId> devicesNotBackedup = error != null ?
738 deviceFlowEntries.keySet() :
739 Sets.difference(deviceFlowEntries.keySet(), backedupDevices);
740 if (devicesNotBackedup.size() > 0) {
741 log.warn("Failed to backup devices: {}. Reason: {}",
Thomas Vachuskac10a9482016-08-03 10:31:11 -0700742 devicesNotBackedup, error != null ? error.getMessage() : "none");
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800743 }
744 if (backedupDevices != null) {
745 backedupDevices.forEach(id -> {
Madan Jampanic6d69f72016-07-15 15:47:12 -0700746 lastBackupTimes.put(new BackupOperation(nodeId, id), System.currentTimeMillis());
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800747 });
748 }
749 });
Madan Jampanif7536ab2015-05-07 23:23:23 -0700750 }
751
Madan Jampani86940d92015-05-06 11:47:57 -0700752 /**
753 * Returns the flow table for specified device.
754 *
755 * @param deviceId identifier of the device
756 * @return Map representing Flow Table of given device.
757 */
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800758 private Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> getFlowTable(DeviceId deviceId) {
Aaron Kruglikova62fdbb2015-10-27 16:32:06 -0700759 if (persistenceEnabled) {
760 return flowEntries.computeIfAbsent(deviceId, id -> persistenceService
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800761 .<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>persistentMapBuilder()
Aaron Kruglikova62fdbb2015-10-27 16:32:06 -0700762 .withName("FlowTable:" + deviceId.toString())
763 .withSerializer(new Serializer() {
764 @Override
765 public <T> byte[] encode(T object) {
Madan Jampani884d4432016-08-23 10:46:55 -0700766 return serializer.encode(object);
Aaron Kruglikova62fdbb2015-10-27 16:32:06 -0700767 }
768
769 @Override
770 public <T> T decode(byte[] bytes) {
Madan Jampani884d4432016-08-23 10:46:55 -0700771 return serializer.decode(bytes);
Aaron Kruglikova62fdbb2015-10-27 16:32:06 -0700772 }
773 })
774 .build());
775 } else {
776 return flowEntries.computeIfAbsent(deviceId, id -> Maps.newConcurrentMap());
777 }
Madan Jampani86940d92015-05-06 11:47:57 -0700778 }
779
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800780 private Map<StoredFlowEntry, StoredFlowEntry> getFlowEntriesInternal(DeviceId deviceId, FlowId flowId) {
781 return getFlowTable(deviceId).computeIfAbsent(flowId, id -> Maps.newConcurrentMap());
Madan Jampani86940d92015-05-06 11:47:57 -0700782 }
783
784 private StoredFlowEntry getFlowEntryInternal(FlowRule rule) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800785 return getFlowEntriesInternal(rule.deviceId(), rule.id()).get(rule);
Madan Jampani86940d92015-05-06 11:47:57 -0700786 }
787
788 private Set<FlowEntry> getFlowEntriesInternal(DeviceId deviceId) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800789 return getFlowTable(deviceId).values().stream()
790 .flatMap(m -> m.values().stream())
791 .collect(Collectors.toSet());
Madan Jampani86940d92015-05-06 11:47:57 -0700792 }
793
794 public StoredFlowEntry getFlowEntry(FlowRule rule) {
795 return getFlowEntryInternal(rule);
796 }
797
798 public Set<FlowEntry> getFlowEntries(DeviceId deviceId) {
799 return getFlowEntriesInternal(deviceId);
800 }
801
802 public void add(FlowEntry rule) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800803 getFlowEntriesInternal(rule.deviceId(), rule.id())
804 .compute((StoredFlowEntry) rule, (k, stored) -> {
805 //TODO compare stored and rule timestamps
806 //TODO the key is not updated
807 return (StoredFlowEntry) rule;
808 });
Madan Jampani86940d92015-05-06 11:47:57 -0700809 lastUpdateTimes.put(rule.deviceId(), System.currentTimeMillis());
810 }
811
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800812 public FlowEntry remove(DeviceId deviceId, FlowEntry rule) {
813 final AtomicReference<FlowEntry> removedRule = new AtomicReference<>();
814 getFlowEntriesInternal(rule.deviceId(), rule.id())
815 .computeIfPresent((StoredFlowEntry) rule, (k, stored) -> {
816 if (rule instanceof DefaultFlowEntry) {
817 DefaultFlowEntry toRemove = (DefaultFlowEntry) rule;
818 if (stored instanceof DefaultFlowEntry) {
819 DefaultFlowEntry storedEntry = (DefaultFlowEntry) stored;
820 if (toRemove.created() < storedEntry.created()) {
821 log.debug("Trying to remove more recent flow entry {} (stored: {})",
822 toRemove, stored);
823 // the key is not updated, removedRule remains null
824 return stored;
825 }
826 }
827 }
828 removedRule.set(stored);
829 return null;
830 });
831
832 if (removedRule.get() != null) {
Madan Jampani86940d92015-05-06 11:47:57 -0700833 lastUpdateTimes.put(deviceId, System.currentTimeMillis());
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800834 return removedRule.get();
835 } else {
836 return null;
Madan Jampani86940d92015-05-06 11:47:57 -0700837 }
838 }
839
Charles Chan0c7c43b2016-01-14 17:39:20 -0800840 public void purgeFlowRule(DeviceId deviceId) {
841 flowEntries.remove(deviceId);
842 }
843
Madan Jampanic6d69f72016-07-15 15:47:12 -0700844 private List<NodeId> getBackupNodes(DeviceId deviceId) {
845 // The returned backup node list is in the order of preference i.e. next likely master first.
846 List<NodeId> allPossibleBackupNodes = replicaInfoManager.getReplicaInfoFor(deviceId).backups();
847 return ImmutableList.copyOf(allPossibleBackupNodes)
848 .subList(0, Math.min(allPossibleBackupNodes.size(), backupCount));
Madan Jampani86940d92015-05-06 11:47:57 -0700849 }
850
851 private void backup() {
Madan Jampani08bf17b2015-05-06 16:25:26 -0700852 if (!backupEnabled) {
853 return;
854 }
Madan Jampani86940d92015-05-06 11:47:57 -0700855 try {
Madan Jampani86940d92015-05-06 11:47:57 -0700856 // compute a mapping from node to the set of devices whose flow entries it should backup
857 Map<NodeId, Set<DeviceId>> devicesToBackupByNode = Maps.newHashMap();
Sho SHIMIZUa09e1bb2016-08-01 14:25:25 -0700858 flowEntries.keySet().forEach(deviceId -> {
Madan Jampanic6d69f72016-07-15 15:47:12 -0700859 List<NodeId> backupNodes = getBackupNodes(deviceId);
860 backupNodes.forEach(backupNode -> {
861 if (lastBackupTimes.getOrDefault(new BackupOperation(backupNode, deviceId), 0L)
862 < lastUpdateTimes.getOrDefault(deviceId, 0L)) {
863 devicesToBackupByNode.computeIfAbsent(backupNode,
864 nodeId -> Sets.newHashSet()).add(deviceId);
865 }
866 });
Madan Jampani86940d92015-05-06 11:47:57 -0700867 });
Madan Jampani86940d92015-05-06 11:47:57 -0700868 // send the device flow entries to their respective backup nodes
Madan Jampaniadea8902015-06-04 17:39:45 -0700869 devicesToBackupByNode.forEach(this::sendBackups);
Madan Jampani86940d92015-05-06 11:47:57 -0700870 } catch (Exception e) {
871 log.error("Backup failed.", e);
872 }
873 }
874
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800875 private Set<DeviceId> onBackupReceipt(Map<DeviceId,
876 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>> flowTables) {
Madan Jampani7267c552015-05-20 22:39:17 -0700877 log.debug("Received flowEntries for {} to backup", flowTables.keySet());
Madan Jampani654b58a2015-05-22 11:28:11 -0700878 Set<DeviceId> backedupDevices = Sets.newHashSet();
879 try {
Madan Jampania98bf932015-06-02 12:01:36 -0700880 flowTables.forEach((deviceId, deviceFlowTable) -> {
881 // Only process those devices are that not managed by the local node.
Sho SHIMIZU828bc162016-01-13 23:10:43 -0800882 if (!Objects.equals(local, mastershipService.getMasterFor(deviceId))) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800883 Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> backupFlowTable =
884 getFlowTable(deviceId);
Madan Jampania98bf932015-06-02 12:01:36 -0700885 backupFlowTable.clear();
886 backupFlowTable.putAll(deviceFlowTable);
887 backedupDevices.add(deviceId);
888 }
Madan Jampani08bf17b2015-05-06 16:25:26 -0700889 });
Madan Jampani654b58a2015-05-22 11:28:11 -0700890 } catch (Exception e) {
891 log.warn("Failure processing backup request", e);
892 }
893 return backedupDevices;
Madan Jampani86940d92015-05-06 11:47:57 -0700894 }
895 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700896
897 @Override
898 public FlowRuleEvent updateTableStatistics(DeviceId deviceId,
899 List<TableStatisticsEntry> tableStats) {
900 deviceTableStats.put(deviceId, tableStats);
901 return null;
902 }
903
904 @Override
905 public Iterable<TableStatisticsEntry> getTableStatistics(DeviceId deviceId) {
906 NodeId master = mastershipService.getMasterFor(deviceId);
907
908 if (master == null) {
909 log.debug("Failed to getTableStats: No master for {}", deviceId);
910 return Collections.emptyList();
911 }
912
913 List<TableStatisticsEntry> tableStats = deviceTableStats.get(deviceId);
914 if (tableStats == null) {
915 return Collections.emptyList();
916 }
917 return ImmutableList.copyOf(tableStats);
918 }
919
920 private class InternalTableStatsListener
921 implements EventuallyConsistentMapListener<DeviceId, List<TableStatisticsEntry>> {
922 @Override
923 public void event(EventuallyConsistentMapEvent<DeviceId,
924 List<TableStatisticsEntry>> event) {
925 //TODO: Generate an event to listeners (do we need?)
926 }
927 }
Madan Jampani86940d92015-05-06 11:47:57 -0700928}