blob: 781e24b0b5208a927d6ae07f91286e90053dca4c [file] [log] [blame]
Madan Jampanib0a3dd62015-03-17 13:41:27 -07001 /*
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07002 * Copyright 2014 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian O'Connorabafb502014-12-02 22:26:20 -080016package org.onosproject.store.flow.impl;
alshabib339a3d92014-09-26 17:54:32 -070017
Madan Jampanib0a3dd62015-03-17 13:41:27 -070018import com.google.common.cache.CacheBuilder;
19import com.google.common.cache.CacheLoader;
20import com.google.common.cache.LoadingCache;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080021import com.google.common.collect.ImmutableList;
22import com.google.common.collect.Iterables;
23import com.google.common.collect.Maps;
24import com.google.common.collect.Sets;
Madan Jampanib0a3dd62015-03-17 13:41:27 -070025import com.hazelcast.core.IMap;
26
alshabib339a3d92014-09-26 17:54:32 -070027import org.apache.felix.scr.annotations.Activate;
28import org.apache.felix.scr.annotations.Component;
29import org.apache.felix.scr.annotations.Deactivate;
Brian O'Connorc4f351d2015-03-10 20:53:11 -070030import org.apache.felix.scr.annotations.Modified;
31import org.apache.felix.scr.annotations.Property;
Madan Jampani38b250d2014-10-17 11:02:38 -070032import org.apache.felix.scr.annotations.Reference;
33import org.apache.felix.scr.annotations.ReferenceCardinality;
alshabib339a3d92014-09-26 17:54:32 -070034import org.apache.felix.scr.annotations.Service;
Madan Jampanib0a3dd62015-03-17 13:41:27 -070035import org.onlab.util.BoundedThreadPool;
Jonathan Hart4fb5cde2014-12-22 12:09:07 -080036import org.onlab.util.KryoNamespace;
Madan Jampanib0a3dd62015-03-17 13:41:27 -070037import org.onlab.util.NewConcurrentHashMap;
Brian O'Connorc4f351d2015-03-10 20:53:11 -070038import org.onosproject.cfg.ComponentConfigService;
Brian O'Connorabafb502014-12-02 22:26:20 -080039import org.onosproject.cluster.ClusterService;
40import org.onosproject.cluster.NodeId;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080041import org.onosproject.core.CoreService;
42import org.onosproject.core.IdGenerator;
Brian O'Connorabafb502014-12-02 22:26:20 -080043import org.onosproject.net.Device;
44import org.onosproject.net.DeviceId;
45import org.onosproject.net.device.DeviceService;
46import org.onosproject.net.flow.CompletedBatchOperation;
47import org.onosproject.net.flow.DefaultFlowEntry;
48import org.onosproject.net.flow.FlowEntry;
49import org.onosproject.net.flow.FlowEntry.FlowEntryState;
50import org.onosproject.net.flow.FlowId;
51import org.onosproject.net.flow.FlowRule;
52import org.onosproject.net.flow.FlowRuleBatchEntry;
Jonathan Hart4fb5cde2014-12-22 12:09:07 -080053import org.onosproject.net.flow.FlowRuleBatchEntry.FlowRuleOperation;
Brian O'Connorabafb502014-12-02 22:26:20 -080054import org.onosproject.net.flow.FlowRuleBatchEvent;
55import org.onosproject.net.flow.FlowRuleBatchOperation;
56import org.onosproject.net.flow.FlowRuleBatchRequest;
57import org.onosproject.net.flow.FlowRuleEvent;
Brian O'Connorabafb502014-12-02 22:26:20 -080058import org.onosproject.net.flow.FlowRuleEvent.Type;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080059import org.onosproject.net.flow.FlowRuleService;
Brian O'Connorabafb502014-12-02 22:26:20 -080060import org.onosproject.net.flow.FlowRuleStore;
61import org.onosproject.net.flow.FlowRuleStoreDelegate;
62import org.onosproject.net.flow.StoredFlowEntry;
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.ReplicaInfo;
67import org.onosproject.store.flow.ReplicaInfoEvent;
68import org.onosproject.store.flow.ReplicaInfoEventListener;
69import org.onosproject.store.flow.ReplicaInfoService;
Madan Jampanib0a3dd62015-03-17 13:41:27 -070070import org.onosproject.store.hz.AbstractHazelcastStore;
71import org.onosproject.store.hz.SMap;
Brian O'Connorabafb502014-12-02 22:26:20 -080072import org.onosproject.store.serializers.KryoSerializer;
73import org.onosproject.store.serializers.StoreSerializer;
74import org.onosproject.store.serializers.impl.DistributedStoreSerializers;
Brian O'Connorc4f351d2015-03-10 20:53:11 -070075import org.osgi.service.component.ComponentContext;
alshabib339a3d92014-09-26 17:54:32 -070076import org.slf4j.Logger;
77
Brian O'Connor72cb19a2015-01-16 16:14:41 -080078import java.io.IOException;
Madan Jampanib0a3dd62015-03-17 13:41:27 -070079import java.util.ArrayList;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080080import java.util.Arrays;
81import java.util.Collections;
Brian O'Connorc4f351d2015-03-10 20:53:11 -070082import java.util.Dictionary;
Madan Jampanib0a3dd62015-03-17 13:41:27 -070083import java.util.HashSet;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080084import java.util.List;
85import java.util.Map;
Madan Jampanib0a3dd62015-03-17 13:41:27 -070086import java.util.Map.Entry;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080087import java.util.Set;
88import java.util.concurrent.ConcurrentHashMap;
89import java.util.concurrent.ConcurrentMap;
90import java.util.concurrent.CopyOnWriteArraySet;
91import java.util.concurrent.ExecutionException;
92import java.util.concurrent.ExecutorService;
93import java.util.concurrent.Executors;
94import java.util.concurrent.Future;
95import java.util.concurrent.TimeUnit;
96import java.util.concurrent.TimeoutException;
97import java.util.stream.Collectors;
98
Madan Jampanib0a3dd62015-03-17 13:41:27 -070099import static com.google.common.base.Preconditions.checkNotNull;
100import static org.apache.commons.lang3.concurrent.ConcurrentUtils.createIfAbsentUnchecked;
Brian O'Connorc4f351d2015-03-10 20:53:11 -0700101import static com.google.common.base.Strings.isNullOrEmpty;
Thomas Vachuska6519e6f2015-03-11 02:29:31 -0700102import static org.onlab.util.Tools.get;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800103import static org.onlab.util.Tools.groupedThreads;
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800104import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_REMOVED;
105import static org.onosproject.store.flow.impl.FlowStoreMessageSubjects.*;
106import static org.slf4j.LoggerFactory.getLogger;
alshabib339a3d92014-09-26 17:54:32 -0700107
108/**
Madan Jampani38b250d2014-10-17 11:02:38 -0700109 * Manages inventory of flow rules using a distributed state management protocol.
alshabib339a3d92014-09-26 17:54:32 -0700110 */
alshabib339a3d92014-09-26 17:54:32 -0700111@Component(immediate = true)
112@Service
113public class DistributedFlowRuleStore
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700114 extends AbstractHazelcastStore<FlowRuleBatchEvent, FlowRuleStoreDelegate>
alshabib1c319ff2014-10-04 20:29:09 -0700115 implements FlowRuleStore {
alshabib339a3d92014-09-26 17:54:32 -0700116
117 private final Logger log = getLogger(getClass());
118
Madan Jampani2af244a2015-02-22 13:12:01 -0800119 private static final int MESSAGE_HANDLER_THREAD_POOL_SIZE = 8;
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700120 private static final boolean DEFAULT_BACKUP_ENABLED = true;
Brian O'Connorc4f351d2015-03-10 20:53:11 -0700121 private static final long FLOW_RULE_STORE_TIMEOUT_MILLIS = 5000;
122
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;
Madan Jampani2af244a2015-02-22 13:12:01 -0800130
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700131 private InternalFlowTable flowTable = new InternalFlowTable();
132
133 /*private final ConcurrentMap<DeviceId, ConcurrentMap<FlowId, Set<StoredFlowEntry>>>
134 flowEntries = new ConcurrentHashMap<>();*/
alshabib339a3d92014-09-26 17:54:32 -0700135
Madan Jampani38b250d2014-10-17 11:02:38 -0700136 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700137 protected ReplicaInfoService replicaInfoManager;
Madan Jampani38b250d2014-10-17 11:02:38 -0700138
139 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700140 protected ClusterCommunicationService clusterCommunicator;
Madan Jampani38b250d2014-10-17 11:02:38 -0700141
142 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700143 protected ClusterService clusterService;
144
145 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
146 protected DeviceService deviceService;
147
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800148 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
149 protected CoreService coreService;
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700150
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700151 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Brian O'Connorc4f351d2015-03-10 20:53:11 -0700152 protected ComponentConfigService configService;
153
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800154 private Map<Long, NodeId> pendingResponses = Maps.newConcurrentMap();
Yuta HIGUCHIbf89c742014-10-27 15:10:02 -0700155
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700156 // Cache of SMaps used for backup data. each SMap contain device flow table
157 private LoadingCache<DeviceId, SMap<FlowId, ImmutableList<StoredFlowEntry>>> smaps;
158
Madan Jampani2af244a2015-02-22 13:12:01 -0800159 private ExecutorService messageHandlingExecutor;
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700160
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700161 private final ExecutorService backupExecutors =
162 BoundedThreadPool.newSingleThreadExecutor(groupedThreads("onos/flow", "async-backups"));
163 //Executors.newSingleThreadExecutor(groupedThreads("onos/flow", "async-backups"));
164
165 private boolean syncBackup = false;
166
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700167 protected static final StoreSerializer SERIALIZER = new KryoSerializer() {
Madan Jampani38b250d2014-10-17 11:02:38 -0700168 @Override
169 protected void setupKryoPool() {
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -0700170 serializerPool = KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800171 .register(DistributedStoreSerializers.STORE_COMMON)
172 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
Yuta HIGUCHI2f158332014-11-25 13:32:06 -0800173 .register(FlowRuleEvent.class)
Jonathan Hart4fb5cde2014-12-22 12:09:07 -0800174 .register(FlowRuleEvent.Type.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800175 .build();
Madan Jampani38b250d2014-10-17 11:02:38 -0700176 }
177 };
178
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700179 private ReplicaInfoEventListener replicaInfoEventListener;
180
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800181 private IdGenerator idGenerator;
182
Madan Jampanicd48bfd2015-03-25 18:06:22 -0700183 private NodeId local;
184
alshabib339a3d92014-09-26 17:54:32 -0700185 @Activate
Brian O'Connorc4f351d2015-03-10 20:53:11 -0700186 public void activate(ComponentContext context) {
187 configService.registerProperties(getClass());
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700188 super.serializer = SERIALIZER;
189 super.theInstance = storeService.getHazelcastInstance();
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700190
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800191 idGenerator = coreService.getIdGenerator(FlowRuleService.FLOW_OP_TOPIC);
192
Madan Jampanicd48bfd2015-03-25 18:06:22 -0700193 local = clusterService.getLocalNode().id();
194
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700195 // Cache to create SMap on demand
196 smaps = CacheBuilder.newBuilder()
197 .softValues()
198 .build(new SMapLoader());
199
Madan Jampani2af244a2015-02-22 13:12:01 -0800200 messageHandlingExecutor = Executors.newFixedThreadPool(
Brian O'Connorc4f351d2015-03-10 20:53:11 -0700201 msgHandlerPoolSize, groupedThreads("onos/store/flow", "message-handlers"));
Madan Jampani2af244a2015-02-22 13:12:01 -0800202
Madan Jampanicd48bfd2015-03-25 18:06:22 -0700203 registerMessageHandlers(messageHandlingExecutor);
Yuta HIGUCHIdfa45c12014-11-24 18:38:53 -0800204
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700205 replicaInfoEventListener = new InternalReplicaInfoEventListener();
206
207 replicaInfoManager.addListener(replicaInfoEventListener);
208
Brian O'Connorc4f351d2015-03-10 20:53:11 -0700209 logConfig("Started");
alshabib339a3d92014-09-26 17:54:32 -0700210 }
211
212 @Deactivate
Brian O'Connorc4f351d2015-03-10 20:53:11 -0700213 public void deactivate(ComponentContext context) {
214 configService.unregisterProperties(getClass(), false);
Madan Jampanicd48bfd2015-03-25 18:06:22 -0700215 unregisterMessageHandlers();
216 messageHandlingExecutor.shutdownNow();
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700217 replicaInfoManager.removeListener(replicaInfoEventListener);
alshabib339a3d92014-09-26 17:54:32 -0700218 log.info("Stopped");
219 }
220
Brian O'Connorc4f351d2015-03-10 20:53:11 -0700221 @Modified
222 public void modified(ComponentContext context) {
223 if (context == null) {
224 backupEnabled = DEFAULT_BACKUP_ENABLED;
225 logConfig("Default config");
226 return;
227 }
228
229 Dictionary properties = context.getProperties();
230 int newPoolSize;
231 boolean newBackupEnabled;
232 try {
Thomas Vachuska6519e6f2015-03-11 02:29:31 -0700233 String s = get(properties, "msgHandlerPoolSize");
Brian O'Connorc4f351d2015-03-10 20:53:11 -0700234 newPoolSize = isNullOrEmpty(s) ? msgHandlerPoolSize : Integer.parseInt(s.trim());
235
Thomas Vachuska6519e6f2015-03-11 02:29:31 -0700236 s = get(properties, "backupEnabled");
Brian O'Connorc4f351d2015-03-10 20:53:11 -0700237 newBackupEnabled = isNullOrEmpty(s) ? backupEnabled : Boolean.parseBoolean(s.trim());
238
239 } catch (NumberFormatException | ClassCastException e) {
240 newPoolSize = MESSAGE_HANDLER_THREAD_POOL_SIZE;
241 newBackupEnabled = DEFAULT_BACKUP_ENABLED;
242 }
243
Madan Jampanicd48bfd2015-03-25 18:06:22 -0700244 if (newBackupEnabled != backupEnabled) {
Brian O'Connorc4f351d2015-03-10 20:53:11 -0700245 backupEnabled = newBackupEnabled;
Madan Jampanicd48bfd2015-03-25 18:06:22 -0700246 }
247 if (newPoolSize != msgHandlerPoolSize) {
248 msgHandlerPoolSize = newPoolSize;
Brian O'Connorc4f351d2015-03-10 20:53:11 -0700249 ExecutorService oldMsgHandler = messageHandlingExecutor;
250 messageHandlingExecutor = Executors.newFixedThreadPool(
251 msgHandlerPoolSize, groupedThreads("onos/store/flow", "message-handlers"));
Madan Jampanicd48bfd2015-03-25 18:06:22 -0700252
253 // replace previously registered handlers.
254 registerMessageHandlers(messageHandlingExecutor);
Brian O'Connorc4f351d2015-03-10 20:53:11 -0700255 oldMsgHandler.shutdown();
Brian O'Connorc4f351d2015-03-10 20:53:11 -0700256 }
Madan Jampanicd48bfd2015-03-25 18:06:22 -0700257 logConfig("Reconfigured");
258 }
259
260 private void registerMessageHandlers(ExecutorService executor) {
261
262 clusterCommunicator.addSubscriber(APPLY_BATCH_FLOWS, new OnStoreBatch(local), executor);
263
264 clusterCommunicator.addSubscriber(REMOTE_APPLY_COMPLETED, new ClusterMessageHandler() {
265 @Override
266 public void handle(ClusterMessage message) {
267 FlowRuleBatchEvent event = SERIALIZER.decode(message.payload());
268 log.trace("received completed notification for {}", event);
269 notifyDelegate(event);
270 }
271 }, executor);
272
273 clusterCommunicator.addSubscriber(GET_FLOW_ENTRY, new ClusterMessageHandler() {
274
275 @Override
276 public void handle(ClusterMessage message) {
277 FlowRule rule = SERIALIZER.decode(message.payload());
278 log.trace("received get flow entry request for {}", rule);
279 FlowEntry flowEntry = flowTable.getFlowEntry(rule); //getFlowEntryInternal(rule);
280 try {
281 message.respond(SERIALIZER.encode(flowEntry));
282 } catch (IOException e) {
283 log.error("Failed to respond back", e);
284 }
285 }
286 }, executor);
287
288 clusterCommunicator.addSubscriber(GET_DEVICE_FLOW_ENTRIES, new ClusterMessageHandler() {
289
290 @Override
291 public void handle(ClusterMessage message) {
292 DeviceId deviceId = SERIALIZER.decode(message.payload());
293 log.trace("Received get flow entries request for {} from {}", deviceId, message.sender());
294 Set<FlowEntry> flowEntries = flowTable.getFlowEntries(deviceId);
295 try {
296 message.respond(SERIALIZER.encode(flowEntries));
297 } catch (IOException e) {
298 log.error("Failed to respond to peer's getFlowEntries request", e);
299 }
300 }
301 }, executor);
302
303 clusterCommunicator.addSubscriber(REMOVE_FLOW_ENTRY, new ClusterMessageHandler() {
304
305 @Override
306 public void handle(ClusterMessage message) {
307 FlowEntry rule = SERIALIZER.decode(message.payload());
308 log.trace("received get flow entry request for {}", rule);
309 FlowRuleEvent event = removeFlowRuleInternal(rule);
310 try {
311 message.respond(SERIALIZER.encode(event));
312 } catch (IOException e) {
313 log.error("Failed to respond back", e);
314 }
315 }
316 }, executor);
317 }
318
319 private void unregisterMessageHandlers() {
320 clusterCommunicator.removeSubscriber(REMOVE_FLOW_ENTRY);
321 clusterCommunicator.removeSubscriber(GET_DEVICE_FLOW_ENTRIES);
322 clusterCommunicator.removeSubscriber(GET_FLOW_ENTRY);
323 clusterCommunicator.removeSubscriber(APPLY_BATCH_FLOWS);
324 clusterCommunicator.removeSubscriber(REMOTE_APPLY_COMPLETED);
Brian O'Connorc4f351d2015-03-10 20:53:11 -0700325 }
326
327 private void logConfig(String prefix) {
328 log.info("{} with msgHandlerPoolSize = {}; backupEnabled = {}",
329 prefix, msgHandlerPoolSize, backupEnabled);
330 }
alshabib339a3d92014-09-26 17:54:32 -0700331
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700332
Brian O'Connor44008532014-12-04 16:41:36 -0800333 // This is not a efficient operation on a distributed sharded
Madan Jampani117aaae2014-10-23 10:04:05 -0700334 // flow store. We need to revisit the need for this operation or at least
335 // make it device specific.
alshabib339a3d92014-09-26 17:54:32 -0700336 @Override
tom9b4030d2014-10-06 10:39:03 -0700337 public int getFlowRuleCount() {
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700338 // implementing in-efficient operation for debugging purpose.
339 int sum = 0;
340 for (Device device : deviceService.getDevices()) {
341 final DeviceId did = device.id();
342 sum += Iterables.size(getFlowEntries(did));
343 }
344 return sum;
tom9b4030d2014-10-06 10:39:03 -0700345 }
346
347 @Override
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800348 public FlowEntry getFlowEntry(FlowRule rule) {
Madan Jampani117aaae2014-10-23 10:04:05 -0700349 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(rule.deviceId());
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700350
351 if (!replicaInfo.master().isPresent()) {
Yuta HIGUCHI6b98ab62014-12-03 16:08:08 -0800352 log.warn("Failed to getFlowEntry: No master for {}", rule.deviceId());
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800353 return null;
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700354 }
355
Madan Jampani117aaae2014-10-23 10:04:05 -0700356 if (replicaInfo.master().get().equals(clusterService.getLocalNode().id())) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800357 return flowTable.getFlowEntry(rule);
Madan Jampani117aaae2014-10-23 10:04:05 -0700358 }
359
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800360 log.trace("Forwarding getFlowEntry to {}, which is the primary (master) for device {}",
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800361 replicaInfo.master().orNull(), rule.deviceId());
Madan Jampani117aaae2014-10-23 10:04:05 -0700362
363 ClusterMessage message = new ClusterMessage(
364 clusterService.getLocalNode().id(),
365 FlowStoreMessageSubjects.GET_FLOW_ENTRY,
366 SERIALIZER.encode(rule));
367
368 try {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700369 Future<byte[]> responseFuture = clusterCommunicator.sendAndReceive(message, replicaInfo.master().get());
370 return SERIALIZER.decode(responseFuture.get(FLOW_RULE_STORE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
371 } catch (IOException | TimeoutException | ExecutionException | InterruptedException e) {
Brian O'Connor44008532014-12-04 16:41:36 -0800372 log.warn("Unable to fetch flow store contents from {}", replicaInfo.master().get());
Madan Jampani117aaae2014-10-23 10:04:05 -0700373 }
Brian O'Connor44008532014-12-04 16:41:36 -0800374 return null;
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700375 }
376
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800377
alshabib339a3d92014-09-26 17:54:32 -0700378
379 @Override
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800380 public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) {
Madan Jampanif5fdef02014-10-23 21:58:10 -0700381
382 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(deviceId);
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700383
384 if (!replicaInfo.master().isPresent()) {
Yuta HIGUCHI6b98ab62014-12-03 16:08:08 -0800385 log.warn("Failed to getFlowEntries: No master for {}", deviceId);
Yuta HIGUCHI2c1d8472014-10-31 14:13:38 -0700386 return Collections.emptyList();
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700387 }
388
Madan Jampanif5fdef02014-10-23 21:58:10 -0700389 if (replicaInfo.master().get().equals(clusterService.getLocalNode().id())) {
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700390 return flowTable.getFlowEntries(deviceId);
Madan Jampanif5fdef02014-10-23 21:58:10 -0700391 }
392
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800393 log.trace("Forwarding getFlowEntries to {}, which is the primary (master) for device {}",
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800394 replicaInfo.master().orNull(), deviceId);
Madan Jampanif5fdef02014-10-23 21:58:10 -0700395
396 ClusterMessage message = new ClusterMessage(
397 clusterService.getLocalNode().id(),
398 GET_DEVICE_FLOW_ENTRIES,
399 SERIALIZER.encode(deviceId));
400
401 try {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700402 Future<byte[]> responseFuture = clusterCommunicator.sendAndReceive(message, replicaInfo.master().get());
403 return SERIALIZER.decode(responseFuture.get(FLOW_RULE_STORE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
404 } catch (IOException | TimeoutException | ExecutionException | InterruptedException e) {
Brian O'Connor44008532014-12-04 16:41:36 -0800405 log.warn("Unable to fetch flow store contents from {}", replicaInfo.master().get());
Madan Jampanif5fdef02014-10-23 21:58:10 -0700406 }
Yuta HIGUCHI24f79eb2014-12-12 15:46:43 -0800407 return Collections.emptyList();
Madan Jampanif5fdef02014-10-23 21:58:10 -0700408 }
409
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800410
alshabib339a3d92014-09-26 17:54:32 -0700411
412 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700413 public void storeFlowRule(FlowRule rule) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800414 storeBatch(new FlowRuleBatchOperation(
415 Arrays.asList(new FlowRuleBatchEntry(FlowRuleOperation.ADD, rule)),
416 rule.deviceId(), idGenerator.getNewId()));
Madan Jampani117aaae2014-10-23 10:04:05 -0700417 }
418
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700419 @Override
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800420 public void storeBatch(FlowRuleBatchOperation operation) {
421
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700422
Madan Jampani117aaae2014-10-23 10:04:05 -0700423 if (operation.getOperations().isEmpty()) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800424
425 notifyDelegate(FlowRuleBatchEvent.completed(
426 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
427 new CompletedBatchOperation(true, Collections.emptySet(),
428 operation.deviceId())));
429 return;
alshabib339a3d92014-09-26 17:54:32 -0700430 }
Madan Jampani38b250d2014-10-17 11:02:38 -0700431
alshabib371abe82015-02-13 10:44:17 -0800432 DeviceId deviceId = operation.deviceId();
Madan Jampani117aaae2014-10-23 10:04:05 -0700433
434 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(deviceId);
435
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700436 if (!replicaInfo.master().isPresent()) {
alshabib371abe82015-02-13 10:44:17 -0800437 log.warn("No master for {} : flows will be marked for removal", deviceId);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800438
alshabib371abe82015-02-13 10:44:17 -0800439 updateStoreInternal(operation);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800440
441 notifyDelegate(FlowRuleBatchEvent.completed(
442 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
alshabib371abe82015-02-13 10:44:17 -0800443 new CompletedBatchOperation(true, Collections.emptySet(), operation.deviceId())));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800444 return;
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700445 }
446
447 final NodeId local = clusterService.getLocalNode().id();
448 if (replicaInfo.master().get().equals(local)) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800449 storeBatchInternal(operation);
450 return;
Madan Jampani117aaae2014-10-23 10:04:05 -0700451 }
452
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800453 log.trace("Forwarding storeBatch to {}, which is the primary (master) for device {}",
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800454 replicaInfo.master().orNull(), deviceId);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700455
Madan Jampani38b250d2014-10-17 11:02:38 -0700456 ClusterMessage message = new ClusterMessage(
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700457 local,
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700458 APPLY_BATCH_FLOWS,
Madan Jampani117aaae2014-10-23 10:04:05 -0700459 SERIALIZER.encode(operation));
Madan Jampani38b250d2014-10-17 11:02:38 -0700460
alshabib371abe82015-02-13 10:44:17 -0800461
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800462 if (!clusterCommunicator.unicast(message, replicaInfo.master().get())) {
463 log.warn("Failed to storeBatch: {} to {}", message, replicaInfo.master());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800464
465 Set<FlowRule> allFailures = operation.getOperations().stream()
Ray Milkeyf7329c72015-02-17 11:37:01 -0800466 .map(op -> op.target())
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800467 .collect(Collectors.toSet());
468
469 notifyDelegate(FlowRuleBatchEvent.completed(
470 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
471 new CompletedBatchOperation(false, allFailures, deviceId)));
472 return;
Madan Jampani38b250d2014-10-17 11:02:38 -0700473 }
474 }
475
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800476 private void storeBatchInternal(FlowRuleBatchOperation operation) {
Yuta HIGUCHIe9b2b002014-11-04 12:25:47 -0800477
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800478 final DeviceId did = operation.deviceId();
479 //final Collection<FlowEntry> ft = flowTable.getFlowEntries(did);
alshabib371abe82015-02-13 10:44:17 -0800480 Set<FlowRuleBatchEntry> currentOps = updateStoreInternal(operation);
481 if (currentOps.isEmpty()) {
482 batchOperationComplete(FlowRuleBatchEvent.completed(
483 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
484 new CompletedBatchOperation(true, Collections.emptySet(), did)));
485 return;
486 }
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700487 updateBackup(did, currentOps);
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700488
alshabib371abe82015-02-13 10:44:17 -0800489 notifyDelegate(FlowRuleBatchEvent.requested(new
490 FlowRuleBatchRequest(operation.id(),
491 currentOps), operation.deviceId()));
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700492
alshabib371abe82015-02-13 10:44:17 -0800493 }
494
495 private Set<FlowRuleBatchEntry> updateStoreInternal(FlowRuleBatchOperation operation) {
496 return operation.getOperations().stream().map(
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800497 op -> {
498 StoredFlowEntry entry;
Ray Milkeyf7329c72015-02-17 11:37:01 -0800499 switch (op.operator()) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800500 case ADD:
Ray Milkeyf7329c72015-02-17 11:37:01 -0800501 entry = new DefaultFlowEntry(op.target());
Madan Jampani2af244a2015-02-22 13:12:01 -0800502 // always add requested FlowRule
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800503 // Note: 2 equal FlowEntry may have different treatment
504 flowTable.remove(entry.deviceId(), entry);
505 flowTable.add(entry);
506
507 return op;
508 case REMOVE:
509 entry = flowTable.getFlowEntry(op.target());
510 if (entry != null) {
511 entry.setState(FlowEntryState.PENDING_REMOVE);
512 return op;
513 }
514 break;
515 case MODIFY:
516 //TODO: figure this out at some point
517 break;
518 default:
Ray Milkeyf7329c72015-02-17 11:37:01 -0800519 log.warn("Unknown flow operation operator: {}", op.operator());
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800520 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800521 return null;
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800522 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800523 ).filter(op -> op != null).collect(Collectors.toSet());
alshabib339a3d92014-09-26 17:54:32 -0700524 }
525
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700526 private void updateBackup(DeviceId deviceId, final Set<FlowRuleBatchEntry> entries) {
527 if (!backupEnabled) {
528 return;
529 }
530
531 Future<?> backup = backupExecutors.submit(new UpdateBackup(deviceId, entries));
532
533 if (syncBackup) {
534 // wait for backup to complete
535 try {
536 backup.get();
537 } catch (InterruptedException | ExecutionException e) {
538 log.error("Failed to create backups", e);
539 }
540 }
541 }
542
alshabib339a3d92014-09-26 17:54:32 -0700543 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700544 public void deleteFlowRule(FlowRule rule) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800545 storeBatch(
546 new FlowRuleBatchOperation(
547 Arrays.asList(
548 new FlowRuleBatchEntry(
549 FlowRuleOperation.REMOVE,
550 rule)), rule.deviceId(), idGenerator.getNewId()));
alshabib339a3d92014-09-26 17:54:32 -0700551 }
552
553 @Override
Madan Jampani38b250d2014-10-17 11:02:38 -0700554 public FlowRuleEvent addOrUpdateFlowRule(FlowEntry rule) {
555 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(rule.deviceId());
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700556 final NodeId localId = clusterService.getLocalNode().id();
557 if (localId.equals(replicaInfo.master().orNull())) {
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700558 return addOrUpdateFlowRuleInternal(rule);
Madan Jampani38b250d2014-10-17 11:02:38 -0700559 }
560
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800561 log.warn("Tried to update FlowRule {} state,"
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800562 + " while the Node was not the master.", rule);
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700563 return null;
Madan Jampani38b250d2014-10-17 11:02:38 -0700564 }
565
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700566 private FlowRuleEvent addOrUpdateFlowRuleInternal(FlowEntry rule) {
567 final DeviceId did = rule.deviceId();
568
569
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800570 // check if this new rule is an update to an existing entry
571 StoredFlowEntry stored = flowTable.getFlowEntry(rule);
572 if (stored != null) {
573 stored.setBytes(rule.bytes());
574 stored.setLife(rule.life());
575 stored.setPackets(rule.packets());
576 if (stored.state() == FlowEntryState.PENDING_ADD) {
577 stored.setState(FlowEntryState.ADDED);
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700578 FlowRuleBatchEntry entry =
579 new FlowRuleBatchEntry(FlowRuleOperation.ADD, stored);
580 updateBackup(did, Sets.newHashSet(entry));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800581 return new FlowRuleEvent(Type.RULE_ADDED, rule);
582 }
583 return new FlowRuleEvent(Type.RULE_UPDATED, rule);
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800584 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800585
586 // TODO: Confirm if this behavior is correct. See SimpleFlowRuleStore
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700587 // TODO: also update backup if the behavior is correct.
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800588 flowTable.add(rule);
589
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700590
alshabib1c319ff2014-10-04 20:29:09 -0700591 return null;
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700592
alshabib339a3d92014-09-26 17:54:32 -0700593 }
594
595 @Override
Madan Jampani38b250d2014-10-17 11:02:38 -0700596 public FlowRuleEvent removeFlowRule(FlowEntry rule) {
Yuta HIGUCHIb6eb9142014-11-26 16:18:13 -0800597 final DeviceId deviceId = rule.deviceId();
598 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(deviceId);
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700599
600 final NodeId localId = clusterService.getLocalNode().id();
601 if (localId.equals(replicaInfo.master().orNull())) {
Madan Jampani38b250d2014-10-17 11:02:38 -0700602 // bypass and handle it locally
603 return removeFlowRuleInternal(rule);
604 }
605
Yuta HIGUCHIb6eb9142014-11-26 16:18:13 -0800606 if (!replicaInfo.master().isPresent()) {
Yuta HIGUCHI6b98ab62014-12-03 16:08:08 -0800607 log.warn("Failed to removeFlowRule: No master for {}", deviceId);
Yuta HIGUCHIb6eb9142014-11-26 16:18:13 -0800608 // TODO: revisit if this should be null (="no-op") or Exception
609 return null;
610 }
611
Yuta HIGUCHIdfa45c12014-11-24 18:38:53 -0800612 log.trace("Forwarding removeFlowRule to {}, which is the primary (master) for device {}",
Yuta HIGUCHIb6eb9142014-11-26 16:18:13 -0800613 replicaInfo.master().orNull(), deviceId);
Yuta HIGUCHIdfa45c12014-11-24 18:38:53 -0800614
615 ClusterMessage message = new ClusterMessage(
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800616 clusterService.getLocalNode().id(),
617 REMOVE_FLOW_ENTRY,
618 SERIALIZER.encode(rule));
Yuta HIGUCHIdfa45c12014-11-24 18:38:53 -0800619
620 try {
621 Future<byte[]> responseFuture = clusterCommunicator.sendAndReceive(message, replicaInfo.master().get());
622 return SERIALIZER.decode(responseFuture.get(FLOW_RULE_STORE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
623 } catch (IOException | TimeoutException | ExecutionException | InterruptedException e) {
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800624 // TODO: Retry against latest master or throw a FlowStoreException
Yuta HIGUCHIdfa45c12014-11-24 18:38:53 -0800625 throw new RuntimeException(e);
626 }
Madan Jampani38b250d2014-10-17 11:02:38 -0700627 }
628
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800629 private FlowRuleEvent removeFlowRuleInternal(FlowEntry rule) {
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700630 final DeviceId deviceId = rule.deviceId();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800631 // This is where one could mark a rule as removed and still keep it in the store.
632 final boolean removed = flowTable.remove(deviceId, rule); //flowEntries.remove(deviceId, rule);
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700633 FlowRuleBatchEntry entry =
634 new FlowRuleBatchEntry(FlowRuleOperation.REMOVE, rule);
635 updateBackup(deviceId, Sets.newHashSet(entry));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800636 if (removed) {
637 return new FlowRuleEvent(RULE_REMOVED, rule);
638 } else {
639 return null;
alshabib339a3d92014-09-26 17:54:32 -0700640 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800641
alshabib339a3d92014-09-26 17:54:32 -0700642 }
Madan Jampani117aaae2014-10-23 10:04:05 -0700643
644 @Override
645 public void batchOperationComplete(FlowRuleBatchEvent event) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800646 //FIXME: need a per device pending response
647
648 NodeId nodeId = pendingResponses.remove(event.subject().batchId());
649 if (nodeId == null) {
650 notifyDelegate(event);
651 } else {
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800652 ClusterMessage message = new ClusterMessage(
653 clusterService.getLocalNode().id(),
654 REMOTE_APPLY_COMPLETED,
655 SERIALIZER.encode(event));
656 // TODO check unicast return value
657 clusterCommunicator.unicast(message, nodeId);
658 //error log: log.warn("Failed to respond to peer for batch operation result");
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700659 }
Madan Jampani117aaae2014-10-23 10:04:05 -0700660 }
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700661
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700662 private void loadFromBackup(final DeviceId did) {
663 if (!backupEnabled) {
664 return;
665 }
666 log.info("We are now the master for {}. Will load flow rules from backup", did);
667 try {
668 log.debug("Loading FlowRules for {} from backups", did);
669 SMap<FlowId, ImmutableList<StoredFlowEntry>> backupFlowTable = smaps.get(did);
670 for (Entry<FlowId, ImmutableList<StoredFlowEntry>> e
671 : backupFlowTable.entrySet()) {
672
673 log.trace("loading {}", e.getValue());
674 for (StoredFlowEntry entry : e.getValue()) {
675 flowTable.getFlowEntriesById(entry).remove(entry);
676 flowTable.getFlowEntriesById(entry).add(entry);
677
678
679 }
680 }
681 } catch (ExecutionException e) {
682 log.error("Failed to load backup flowtable for {}", did, e);
683 }
684 }
685
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800686 private void removeFromPrimary(final DeviceId did) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800687 flowTable.clearDevice(did);
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700688 }
689
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700690
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700691 private final class OnStoreBatch implements ClusterMessageHandler {
692 private final NodeId local;
693
694 private OnStoreBatch(NodeId local) {
695 this.local = local;
696 }
697
698 @Override
699 public void handle(final ClusterMessage message) {
700 FlowRuleBatchOperation operation = SERIALIZER.decode(message.payload());
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800701 log.debug("received batch request {}", operation);
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700702
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800703 final DeviceId deviceId = operation.deviceId();
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700704 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(deviceId);
705 if (!local.equals(replicaInfo.master().orNull())) {
706
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700707 Set<FlowRule> failures = new HashSet<>(operation.size());
708 for (FlowRuleBatchEntry op : operation.getOperations()) {
709 failures.add(op.target());
710 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800711 CompletedBatchOperation allFailed = new CompletedBatchOperation(false, failures, deviceId);
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700712 // This node is no longer the master, respond as all failed.
713 // TODO: we might want to wrap response in envelope
714 // to distinguish sw programming failure and hand over
715 // it make sense in the latter case to retry immediately.
716 try {
717 message.respond(SERIALIZER.encode(allFailed));
718 } catch (IOException e) {
719 log.error("Failed to respond back", e);
720 }
721 return;
722 }
723
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700724
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800725 pendingResponses.put(operation.id(), message.sender());
726 storeBatchInternal(operation);
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700727
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700728 }
729 }
730
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700731 private final class SMapLoader
732 extends CacheLoader<DeviceId, SMap<FlowId, ImmutableList<StoredFlowEntry>>> {
733
734 @Override
735 public SMap<FlowId, ImmutableList<StoredFlowEntry>> load(DeviceId id)
736 throws Exception {
737 IMap<byte[], byte[]> map = theInstance.getMap("flowtable_" + id.toString());
738 return new SMap<FlowId, ImmutableList<StoredFlowEntry>>(map, SERIALIZER);
739 }
740 }
741
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700742 private final class InternalReplicaInfoEventListener
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800743 implements ReplicaInfoEventListener {
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700744
745 @Override
746 public void event(ReplicaInfoEvent event) {
747 final NodeId local = clusterService.getLocalNode().id();
748 final DeviceId did = event.subject();
749 final ReplicaInfo rInfo = event.replicaInfo();
750
751 switch (event.type()) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800752 case MASTER_CHANGED:
753 if (local.equals(rInfo.master().orNull())) {
754 // This node is the new master, populate local structure
755 // from backup
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700756 loadFromBackup(did);
alshabib93cb57f2015-02-12 17:43:26 -0800757 }
758 //else {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800759 // This node is no longer the master holder,
760 // clean local structure
alshabib93cb57f2015-02-12 17:43:26 -0800761 //removeFromPrimary(did);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800762 // TODO: probably should stop pending backup activities in
763 // executors to avoid overwriting with old value
alshabib93cb57f2015-02-12 17:43:26 -0800764 //}
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800765 break;
766 default:
767 break;
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700768
769 }
770 }
771 }
772
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700773 // Task to update FlowEntries in backup HZ store
774 private final class UpdateBackup implements Runnable {
775
776 private final DeviceId deviceId;
777 private final Set<FlowRuleBatchEntry> ops;
778
779
780 public UpdateBackup(DeviceId deviceId,
781 Set<FlowRuleBatchEntry> ops) {
782 this.deviceId = checkNotNull(deviceId);
783 this.ops = checkNotNull(ops);
784
785 }
786
787 @Override
788 public void run() {
789 try {
790 log.trace("update backup {} {}", deviceId, ops
791 );
792 final SMap<FlowId, ImmutableList<StoredFlowEntry>> backupFlowTable = smaps.get(deviceId);
793
794
795 ops.stream().forEach(
796 op -> {
797 final FlowRule entry = op.target();
798 final FlowId id = entry.id();
799 ImmutableList<StoredFlowEntry> original = backupFlowTable.get(id);
800 List<StoredFlowEntry> list = new ArrayList<>();
801 if (original != null) {
802 list.addAll(original);
803 }
804 list.remove(op.target());
805 if (op.operator() == FlowRuleOperation.ADD) {
806 list.add((StoredFlowEntry) entry);
807 }
808
809 ImmutableList<StoredFlowEntry> newValue = ImmutableList.copyOf(list);
810 boolean success;
811 if (original == null) {
812 success = (backupFlowTable.putIfAbsent(id, newValue) == null);
813 } else {
814 success = backupFlowTable.replace(id, original, newValue);
815 }
816 if (!success) {
817 log.error("Updating backup failed.");
818 }
819
820 }
821 );
822 } catch (ExecutionException e) {
823 log.error("Failed to write to backups", e);
824 }
825
826 }
827 }
828
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800829 private class InternalFlowTable {
830
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700831 /*
832 TODO: This needs to be cleaned up. Perhaps using the eventually consistent
833 map when it supports distributed to a sequence of instances.
834 */
835
836
837 private final ConcurrentMap<DeviceId, ConcurrentMap<FlowId, Set<StoredFlowEntry>>>
838 flowEntries = new ConcurrentHashMap<>();
839
840
841 private NewConcurrentHashMap<FlowId, Set<StoredFlowEntry>> lazyEmptyFlowTable() {
842 return NewConcurrentHashMap.<FlowId, Set<StoredFlowEntry>>ifNeeded();
843 }
Madan Jampanie1356282015-03-10 19:05:36 -0700844
845 /**
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700846 * Returns the flow table for specified device.
847 *
848 * @param deviceId identifier of the device
849 * @return Map representing Flow Table of given device.
Madan Jampanie1356282015-03-10 19:05:36 -0700850 */
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700851 private ConcurrentMap<FlowId, Set<StoredFlowEntry>> getFlowTable(DeviceId deviceId) {
852 return createIfAbsentUnchecked(flowEntries,
853 deviceId, lazyEmptyFlowTable());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800854 }
855
856 private Set<StoredFlowEntry> getFlowEntriesInternal(DeviceId deviceId, FlowId flowId) {
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700857 final ConcurrentMap<FlowId, Set<StoredFlowEntry>> flowTable = getFlowTable(deviceId);
858 Set<StoredFlowEntry> r = flowTable.get(flowId);
859 if (r == null) {
860 final Set<StoredFlowEntry> concurrentlyAdded;
861 r = new CopyOnWriteArraySet<>();
862 concurrentlyAdded = flowTable.putIfAbsent(flowId, r);
863 if (concurrentlyAdded != null) {
864 return concurrentlyAdded;
865 }
866 }
867 return r;
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800868 }
869
870 private StoredFlowEntry getFlowEntryInternal(FlowRule rule) {
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700871 for (StoredFlowEntry f : getFlowEntriesInternal(rule.deviceId(), rule.id())) {
872 if (f.equals(rule)) {
873 return f;
874 }
875 }
876 return null;
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800877 }
878
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700879 private Set<FlowEntry> getFlowEntriesInternal(DeviceId deviceId) {
880 return getFlowTable(deviceId).values().stream()
881 .flatMap((list -> list.stream())).collect(Collectors.toSet());
882
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800883 }
884
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700885
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800886 public StoredFlowEntry getFlowEntry(FlowRule rule) {
887 return getFlowEntryInternal(rule);
888 }
889
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700890 public Set<FlowEntry> getFlowEntries(DeviceId deviceId) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800891 return getFlowEntriesInternal(deviceId);
892 }
893
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700894 public Set<StoredFlowEntry> getFlowEntriesById(FlowEntry entry) {
895 return getFlowEntriesInternal(entry.deviceId(), entry.id());
896 }
897
898 public void add(FlowEntry rule) {
899 ((CopyOnWriteArraySet)
900 getFlowEntriesInternal(rule.deviceId(), rule.id())).add(rule);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800901 }
902
903 public boolean remove(DeviceId deviceId, FlowEntry rule) {
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700904 return ((CopyOnWriteArraySet)
905 getFlowEntriesInternal(deviceId, rule.id())).remove(rule);
906 //return flowEntries.remove(deviceId, rule);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800907 }
908
909 public void clearDevice(DeviceId did) {
910 flowEntries.remove(did);
911 }
912 }
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700913
914
Madan Jampanie1356282015-03-10 19:05:36 -0700915}