blob: f1ac1f8ca6765461fa725e66c02bdd1ee4d3e34e [file] [log] [blame]
Madan Jampanib0a3dd62015-03-17 13:41:27 -07001 /*
Ray Milkey34c95902015-04-15 09:47:53 -07002 * Copyright 2014-2015 Open Networking Laboratory
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -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 */
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 Jampani2bfa94c2015-04-11 05:03:49 -070025import com.google.common.util.concurrent.Futures;
Madan Jampanib0a3dd62015-03-17 13:41:27 -070026import com.hazelcast.core.IMap;
27
alshabib339a3d92014-09-26 17:54:32 -070028import org.apache.felix.scr.annotations.Activate;
29import org.apache.felix.scr.annotations.Component;
30import org.apache.felix.scr.annotations.Deactivate;
Brian O'Connorc4f351d2015-03-10 20:53:11 -070031import org.apache.felix.scr.annotations.Modified;
32import org.apache.felix.scr.annotations.Property;
Madan Jampani38b250d2014-10-17 11:02:38 -070033import org.apache.felix.scr.annotations.Reference;
34import org.apache.felix.scr.annotations.ReferenceCardinality;
alshabib339a3d92014-09-26 17:54:32 -070035import org.apache.felix.scr.annotations.Service;
Madan Jampanib0a3dd62015-03-17 13:41:27 -070036import org.onlab.util.BoundedThreadPool;
Jonathan Hart4fb5cde2014-12-22 12:09:07 -080037import org.onlab.util.KryoNamespace;
Madan Jampanib0a3dd62015-03-17 13:41:27 -070038import org.onlab.util.NewConcurrentHashMap;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070039import org.onlab.util.Tools;
Brian O'Connorc4f351d2015-03-10 20:53:11 -070040import org.onosproject.cfg.ComponentConfigService;
Brian O'Connorabafb502014-12-02 22:26:20 -080041import org.onosproject.cluster.ClusterService;
42import org.onosproject.cluster.NodeId;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080043import org.onosproject.core.CoreService;
44import org.onosproject.core.IdGenerator;
Brian O'Connorabafb502014-12-02 22:26:20 -080045import org.onosproject.net.Device;
46import org.onosproject.net.DeviceId;
47import org.onosproject.net.device.DeviceService;
48import org.onosproject.net.flow.CompletedBatchOperation;
49import org.onosproject.net.flow.DefaultFlowEntry;
50import org.onosproject.net.flow.FlowEntry;
51import org.onosproject.net.flow.FlowEntry.FlowEntryState;
52import org.onosproject.net.flow.FlowId;
53import org.onosproject.net.flow.FlowRule;
54import org.onosproject.net.flow.FlowRuleBatchEntry;
Jonathan Hart4fb5cde2014-12-22 12:09:07 -080055import org.onosproject.net.flow.FlowRuleBatchEntry.FlowRuleOperation;
Brian O'Connorabafb502014-12-02 22:26:20 -080056import org.onosproject.net.flow.FlowRuleBatchEvent;
57import org.onosproject.net.flow.FlowRuleBatchOperation;
58import org.onosproject.net.flow.FlowRuleBatchRequest;
59import org.onosproject.net.flow.FlowRuleEvent;
Brian O'Connorabafb502014-12-02 22:26:20 -080060import org.onosproject.net.flow.FlowRuleEvent.Type;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080061import org.onosproject.net.flow.FlowRuleService;
Brian O'Connorabafb502014-12-02 22:26:20 -080062import org.onosproject.net.flow.FlowRuleStore;
63import org.onosproject.net.flow.FlowRuleStoreDelegate;
64import org.onosproject.net.flow.StoredFlowEntry;
65import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
66import org.onosproject.store.cluster.messaging.ClusterMessage;
67import org.onosproject.store.cluster.messaging.ClusterMessageHandler;
68import org.onosproject.store.flow.ReplicaInfo;
69import org.onosproject.store.flow.ReplicaInfoEvent;
70import org.onosproject.store.flow.ReplicaInfoEventListener;
71import org.onosproject.store.flow.ReplicaInfoService;
Madan Jampanib0a3dd62015-03-17 13:41:27 -070072import org.onosproject.store.hz.AbstractHazelcastStore;
73import org.onosproject.store.hz.SMap;
Brian O'Connorabafb502014-12-02 22:26:20 -080074import org.onosproject.store.serializers.KryoSerializer;
75import org.onosproject.store.serializers.StoreSerializer;
76import org.onosproject.store.serializers.impl.DistributedStoreSerializers;
Brian O'Connorc4f351d2015-03-10 20:53:11 -070077import org.osgi.service.component.ComponentContext;
alshabib339a3d92014-09-26 17:54:32 -070078import org.slf4j.Logger;
79
Madan Jampanib0a3dd62015-03-17 13:41:27 -070080import java.util.ArrayList;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080081import java.util.Arrays;
82import java.util.Collections;
Brian O'Connorc4f351d2015-03-10 20:53:11 -070083import java.util.Dictionary;
Madan Jampanib0a3dd62015-03-17 13:41:27 -070084import java.util.HashSet;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080085import java.util.List;
86import java.util.Map;
Madan Jampanib0a3dd62015-03-17 13:41:27 -070087import java.util.Map.Entry;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080088import java.util.Set;
89import java.util.concurrent.ConcurrentHashMap;
90import java.util.concurrent.ConcurrentMap;
91import java.util.concurrent.CopyOnWriteArraySet;
92import java.util.concurrent.ExecutionException;
93import java.util.concurrent.ExecutorService;
94import java.util.concurrent.Executors;
95import java.util.concurrent.Future;
96import java.util.concurrent.TimeUnit;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080097import 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 */
Madan Jampani86940d92015-05-06 11:47:57 -0700111@Component(immediate = false, enabled = false)
alshabib339a3d92014-09-26 17:54:32 -0700112@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);
Madan Jampanic26eede2015-04-16 11:42:16 -0700280 message.respond(SERIALIZER.encode(flowEntry));
Madan Jampanicd48bfd2015-03-25 18:06:22 -0700281 }
282 }, executor);
283
284 clusterCommunicator.addSubscriber(GET_DEVICE_FLOW_ENTRIES, new ClusterMessageHandler() {
285
286 @Override
287 public void handle(ClusterMessage message) {
288 DeviceId deviceId = SERIALIZER.decode(message.payload());
289 log.trace("Received get flow entries request for {} from {}", deviceId, message.sender());
290 Set<FlowEntry> flowEntries = flowTable.getFlowEntries(deviceId);
Madan Jampanic26eede2015-04-16 11:42:16 -0700291 message.respond(SERIALIZER.encode(flowEntries));
Madan Jampanicd48bfd2015-03-25 18:06:22 -0700292 }
293 }, executor);
294
295 clusterCommunicator.addSubscriber(REMOVE_FLOW_ENTRY, new ClusterMessageHandler() {
296
297 @Override
298 public void handle(ClusterMessage message) {
299 FlowEntry rule = SERIALIZER.decode(message.payload());
300 log.trace("received get flow entry request for {}", rule);
301 FlowRuleEvent event = removeFlowRuleInternal(rule);
Madan Jampanic26eede2015-04-16 11:42:16 -0700302 message.respond(SERIALIZER.encode(event));
Madan Jampanicd48bfd2015-03-25 18:06:22 -0700303 }
304 }, executor);
305 }
306
307 private void unregisterMessageHandlers() {
308 clusterCommunicator.removeSubscriber(REMOVE_FLOW_ENTRY);
309 clusterCommunicator.removeSubscriber(GET_DEVICE_FLOW_ENTRIES);
310 clusterCommunicator.removeSubscriber(GET_FLOW_ENTRY);
311 clusterCommunicator.removeSubscriber(APPLY_BATCH_FLOWS);
312 clusterCommunicator.removeSubscriber(REMOTE_APPLY_COMPLETED);
Brian O'Connorc4f351d2015-03-10 20:53:11 -0700313 }
314
315 private void logConfig(String prefix) {
316 log.info("{} with msgHandlerPoolSize = {}; backupEnabled = {}",
317 prefix, msgHandlerPoolSize, backupEnabled);
318 }
alshabib339a3d92014-09-26 17:54:32 -0700319
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700320
Brian O'Connor44008532014-12-04 16:41:36 -0800321 // This is not a efficient operation on a distributed sharded
Madan Jampani117aaae2014-10-23 10:04:05 -0700322 // flow store. We need to revisit the need for this operation or at least
323 // make it device specific.
alshabib339a3d92014-09-26 17:54:32 -0700324 @Override
tom9b4030d2014-10-06 10:39:03 -0700325 public int getFlowRuleCount() {
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700326 // implementing in-efficient operation for debugging purpose.
327 int sum = 0;
328 for (Device device : deviceService.getDevices()) {
329 final DeviceId did = device.id();
330 sum += Iterables.size(getFlowEntries(did));
331 }
332 return sum;
tom9b4030d2014-10-06 10:39:03 -0700333 }
334
335 @Override
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800336 public FlowEntry getFlowEntry(FlowRule rule) {
Madan Jampani117aaae2014-10-23 10:04:05 -0700337 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(rule.deviceId());
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700338
339 if (!replicaInfo.master().isPresent()) {
Yuta HIGUCHI6b98ab62014-12-03 16:08:08 -0800340 log.warn("Failed to getFlowEntry: No master for {}", rule.deviceId());
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800341 return null;
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700342 }
343
Madan Jampani117aaae2014-10-23 10:04:05 -0700344 if (replicaInfo.master().get().equals(clusterService.getLocalNode().id())) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800345 return flowTable.getFlowEntry(rule);
Madan Jampani117aaae2014-10-23 10:04:05 -0700346 }
347
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800348 log.trace("Forwarding getFlowEntry to {}, which is the primary (master) for device {}",
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800349 replicaInfo.master().orNull(), rule.deviceId());
Madan Jampani117aaae2014-10-23 10:04:05 -0700350
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700351 return Tools.futureGetOrElse(clusterCommunicator.sendAndReceive(rule,
352 FlowStoreMessageSubjects.GET_FLOW_ENTRY,
353 SERIALIZER::encode,
354 SERIALIZER::decode,
355 replicaInfo.master().get()),
356 FLOW_RULE_STORE_TIMEOUT_MILLIS,
357 TimeUnit.MILLISECONDS,
358 null);
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700359 }
360
alshabib339a3d92014-09-26 17:54:32 -0700361 @Override
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800362 public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) {
Madan Jampanif5fdef02014-10-23 21:58:10 -0700363
364 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(deviceId);
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700365
366 if (!replicaInfo.master().isPresent()) {
Yuta HIGUCHI6b98ab62014-12-03 16:08:08 -0800367 log.warn("Failed to getFlowEntries: No master for {}", deviceId);
Yuta HIGUCHI2c1d8472014-10-31 14:13:38 -0700368 return Collections.emptyList();
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700369 }
370
Madan Jampanif5fdef02014-10-23 21:58:10 -0700371 if (replicaInfo.master().get().equals(clusterService.getLocalNode().id())) {
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700372 return flowTable.getFlowEntries(deviceId);
Madan Jampanif5fdef02014-10-23 21:58:10 -0700373 }
374
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800375 log.trace("Forwarding getFlowEntries to {}, which is the primary (master) for device {}",
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800376 replicaInfo.master().orNull(), deviceId);
Madan Jampanif5fdef02014-10-23 21:58:10 -0700377
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700378 return Tools.futureGetOrElse(clusterCommunicator.sendAndReceive(deviceId,
379 FlowStoreMessageSubjects.GET_DEVICE_FLOW_ENTRIES,
380 SERIALIZER::encode,
381 SERIALIZER::decode,
382 replicaInfo.master().get()),
383 FLOW_RULE_STORE_TIMEOUT_MILLIS,
384 TimeUnit.MILLISECONDS,
385 Collections.emptyList());
Madan Jampanif5fdef02014-10-23 21:58:10 -0700386 }
387
alshabib339a3d92014-09-26 17:54:32 -0700388 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700389 public void storeFlowRule(FlowRule rule) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800390 storeBatch(new FlowRuleBatchOperation(
391 Arrays.asList(new FlowRuleBatchEntry(FlowRuleOperation.ADD, rule)),
392 rule.deviceId(), idGenerator.getNewId()));
Madan Jampani117aaae2014-10-23 10:04:05 -0700393 }
394
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700395 @Override
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800396 public void storeBatch(FlowRuleBatchOperation operation) {
397
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700398
Madan Jampani117aaae2014-10-23 10:04:05 -0700399 if (operation.getOperations().isEmpty()) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800400
401 notifyDelegate(FlowRuleBatchEvent.completed(
402 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
403 new CompletedBatchOperation(true, Collections.emptySet(),
404 operation.deviceId())));
405 return;
alshabib339a3d92014-09-26 17:54:32 -0700406 }
Madan Jampani38b250d2014-10-17 11:02:38 -0700407
alshabib371abe82015-02-13 10:44:17 -0800408 DeviceId deviceId = operation.deviceId();
Madan Jampani117aaae2014-10-23 10:04:05 -0700409
410 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(deviceId);
411
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700412 if (!replicaInfo.master().isPresent()) {
alshabib371abe82015-02-13 10:44:17 -0800413 log.warn("No master for {} : flows will be marked for removal", deviceId);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800414
alshabib371abe82015-02-13 10:44:17 -0800415 updateStoreInternal(operation);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800416
417 notifyDelegate(FlowRuleBatchEvent.completed(
418 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
alshabib371abe82015-02-13 10:44:17 -0800419 new CompletedBatchOperation(true, Collections.emptySet(), operation.deviceId())));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800420 return;
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700421 }
422
423 final NodeId local = clusterService.getLocalNode().id();
424 if (replicaInfo.master().get().equals(local)) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800425 storeBatchInternal(operation);
426 return;
Madan Jampani117aaae2014-10-23 10:04:05 -0700427 }
428
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800429 log.trace("Forwarding storeBatch to {}, which is the primary (master) for device {}",
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800430 replicaInfo.master().orNull(), deviceId);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700431
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700432 if (!clusterCommunicator.unicast(operation,
433 APPLY_BATCH_FLOWS, SERIALIZER::encode,
434 replicaInfo.master().get())) {
435 log.warn("Failed to storeBatch: {} to {}", operation, replicaInfo.master());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800436
437 Set<FlowRule> allFailures = operation.getOperations().stream()
Ray Milkeyf7329c72015-02-17 11:37:01 -0800438 .map(op -> op.target())
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800439 .collect(Collectors.toSet());
440
441 notifyDelegate(FlowRuleBatchEvent.completed(
442 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
443 new CompletedBatchOperation(false, allFailures, deviceId)));
444 return;
Madan Jampani38b250d2014-10-17 11:02:38 -0700445 }
446 }
447
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800448 private void storeBatchInternal(FlowRuleBatchOperation operation) {
Yuta HIGUCHIe9b2b002014-11-04 12:25:47 -0800449
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800450 final DeviceId did = operation.deviceId();
451 //final Collection<FlowEntry> ft = flowTable.getFlowEntries(did);
alshabib371abe82015-02-13 10:44:17 -0800452 Set<FlowRuleBatchEntry> currentOps = updateStoreInternal(operation);
453 if (currentOps.isEmpty()) {
454 batchOperationComplete(FlowRuleBatchEvent.completed(
455 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
456 new CompletedBatchOperation(true, Collections.emptySet(), did)));
457 return;
458 }
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700459 updateBackup(did, currentOps);
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700460
alshabib371abe82015-02-13 10:44:17 -0800461 notifyDelegate(FlowRuleBatchEvent.requested(new
462 FlowRuleBatchRequest(operation.id(),
463 currentOps), operation.deviceId()));
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700464
alshabib371abe82015-02-13 10:44:17 -0800465 }
466
467 private Set<FlowRuleBatchEntry> updateStoreInternal(FlowRuleBatchOperation operation) {
468 return operation.getOperations().stream().map(
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800469 op -> {
470 StoredFlowEntry entry;
Ray Milkeyf7329c72015-02-17 11:37:01 -0800471 switch (op.operator()) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800472 case ADD:
Ray Milkeyf7329c72015-02-17 11:37:01 -0800473 entry = new DefaultFlowEntry(op.target());
Madan Jampani2af244a2015-02-22 13:12:01 -0800474 // always add requested FlowRule
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800475 // Note: 2 equal FlowEntry may have different treatment
476 flowTable.remove(entry.deviceId(), entry);
477 flowTable.add(entry);
478
479 return op;
480 case REMOVE:
481 entry = flowTable.getFlowEntry(op.target());
482 if (entry != null) {
483 entry.setState(FlowEntryState.PENDING_REMOVE);
484 return op;
485 }
486 break;
487 case MODIFY:
488 //TODO: figure this out at some point
489 break;
490 default:
Ray Milkeyf7329c72015-02-17 11:37:01 -0800491 log.warn("Unknown flow operation operator: {}", op.operator());
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800492 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800493 return null;
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800494 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800495 ).filter(op -> op != null).collect(Collectors.toSet());
alshabib339a3d92014-09-26 17:54:32 -0700496 }
497
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700498 private void updateBackup(DeviceId deviceId, final Set<FlowRuleBatchEntry> entries) {
499 if (!backupEnabled) {
500 return;
501 }
502
503 Future<?> backup = backupExecutors.submit(new UpdateBackup(deviceId, entries));
504
505 if (syncBackup) {
506 // wait for backup to complete
507 try {
508 backup.get();
509 } catch (InterruptedException | ExecutionException e) {
510 log.error("Failed to create backups", e);
511 }
512 }
513 }
514
alshabib339a3d92014-09-26 17:54:32 -0700515 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700516 public void deleteFlowRule(FlowRule rule) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800517 storeBatch(
518 new FlowRuleBatchOperation(
519 Arrays.asList(
520 new FlowRuleBatchEntry(
521 FlowRuleOperation.REMOVE,
522 rule)), rule.deviceId(), idGenerator.getNewId()));
alshabib339a3d92014-09-26 17:54:32 -0700523 }
524
525 @Override
Madan Jampani38b250d2014-10-17 11:02:38 -0700526 public FlowRuleEvent addOrUpdateFlowRule(FlowEntry rule) {
527 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(rule.deviceId());
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700528 final NodeId localId = clusterService.getLocalNode().id();
529 if (localId.equals(replicaInfo.master().orNull())) {
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700530 return addOrUpdateFlowRuleInternal(rule);
Madan Jampani38b250d2014-10-17 11:02:38 -0700531 }
532
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800533 log.warn("Tried to update FlowRule {} state,"
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800534 + " while the Node was not the master.", rule);
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700535 return null;
Madan Jampani38b250d2014-10-17 11:02:38 -0700536 }
537
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700538 private FlowRuleEvent addOrUpdateFlowRuleInternal(FlowEntry rule) {
539 final DeviceId did = rule.deviceId();
540
541
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800542 // check if this new rule is an update to an existing entry
543 StoredFlowEntry stored = flowTable.getFlowEntry(rule);
544 if (stored != null) {
545 stored.setBytes(rule.bytes());
546 stored.setLife(rule.life());
547 stored.setPackets(rule.packets());
548 if (stored.state() == FlowEntryState.PENDING_ADD) {
549 stored.setState(FlowEntryState.ADDED);
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700550 FlowRuleBatchEntry entry =
551 new FlowRuleBatchEntry(FlowRuleOperation.ADD, stored);
552 updateBackup(did, Sets.newHashSet(entry));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800553 return new FlowRuleEvent(Type.RULE_ADDED, rule);
554 }
555 return new FlowRuleEvent(Type.RULE_UPDATED, rule);
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800556 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800557
558 // TODO: Confirm if this behavior is correct. See SimpleFlowRuleStore
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700559 // TODO: also update backup if the behavior is correct.
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800560 flowTable.add(rule);
561
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700562
alshabib1c319ff2014-10-04 20:29:09 -0700563 return null;
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700564
alshabib339a3d92014-09-26 17:54:32 -0700565 }
566
567 @Override
Madan Jampani38b250d2014-10-17 11:02:38 -0700568 public FlowRuleEvent removeFlowRule(FlowEntry rule) {
Yuta HIGUCHIb6eb9142014-11-26 16:18:13 -0800569 final DeviceId deviceId = rule.deviceId();
570 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(deviceId);
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700571
572 final NodeId localId = clusterService.getLocalNode().id();
573 if (localId.equals(replicaInfo.master().orNull())) {
Madan Jampani38b250d2014-10-17 11:02:38 -0700574 // bypass and handle it locally
575 return removeFlowRuleInternal(rule);
576 }
577
Yuta HIGUCHIb6eb9142014-11-26 16:18:13 -0800578 if (!replicaInfo.master().isPresent()) {
Yuta HIGUCHI6b98ab62014-12-03 16:08:08 -0800579 log.warn("Failed to removeFlowRule: No master for {}", deviceId);
Yuta HIGUCHIb6eb9142014-11-26 16:18:13 -0800580 // TODO: revisit if this should be null (="no-op") or Exception
581 return null;
582 }
583
Yuta HIGUCHIdfa45c12014-11-24 18:38:53 -0800584 log.trace("Forwarding removeFlowRule to {}, which is the primary (master) for device {}",
Yuta HIGUCHIb6eb9142014-11-26 16:18:13 -0800585 replicaInfo.master().orNull(), deviceId);
Yuta HIGUCHIdfa45c12014-11-24 18:38:53 -0800586
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700587 return Futures.get(clusterCommunicator.sendAndReceive(
588 rule,
589 REMOVE_FLOW_ENTRY,
590 SERIALIZER::encode,
591 SERIALIZER::decode,
592 replicaInfo.master().get()),
593 FLOW_RULE_STORE_TIMEOUT_MILLIS,
594 TimeUnit.MILLISECONDS,
595 RuntimeException.class);
Madan Jampani38b250d2014-10-17 11:02:38 -0700596 }
597
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800598 private FlowRuleEvent removeFlowRuleInternal(FlowEntry rule) {
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700599 final DeviceId deviceId = rule.deviceId();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800600 // This is where one could mark a rule as removed and still keep it in the store.
601 final boolean removed = flowTable.remove(deviceId, rule); //flowEntries.remove(deviceId, rule);
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700602 FlowRuleBatchEntry entry =
603 new FlowRuleBatchEntry(FlowRuleOperation.REMOVE, rule);
604 updateBackup(deviceId, Sets.newHashSet(entry));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800605 if (removed) {
606 return new FlowRuleEvent(RULE_REMOVED, rule);
607 } else {
608 return null;
alshabib339a3d92014-09-26 17:54:32 -0700609 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800610
alshabib339a3d92014-09-26 17:54:32 -0700611 }
Madan Jampani117aaae2014-10-23 10:04:05 -0700612
613 @Override
614 public void batchOperationComplete(FlowRuleBatchEvent event) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800615 //FIXME: need a per device pending response
616
617 NodeId nodeId = pendingResponses.remove(event.subject().batchId());
618 if (nodeId == null) {
619 notifyDelegate(event);
620 } else {
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800621 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700622 clusterCommunicator.unicast(event, REMOTE_APPLY_COMPLETED, SERIALIZER::encode, nodeId);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800623 //error log: log.warn("Failed to respond to peer for batch operation result");
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700624 }
Madan Jampani117aaae2014-10-23 10:04:05 -0700625 }
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700626
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700627 private void loadFromBackup(final DeviceId did) {
628 if (!backupEnabled) {
629 return;
630 }
631 log.info("We are now the master for {}. Will load flow rules from backup", did);
632 try {
633 log.debug("Loading FlowRules for {} from backups", did);
634 SMap<FlowId, ImmutableList<StoredFlowEntry>> backupFlowTable = smaps.get(did);
635 for (Entry<FlowId, ImmutableList<StoredFlowEntry>> e
636 : backupFlowTable.entrySet()) {
637
638 log.trace("loading {}", e.getValue());
639 for (StoredFlowEntry entry : e.getValue()) {
640 flowTable.getFlowEntriesById(entry).remove(entry);
641 flowTable.getFlowEntriesById(entry).add(entry);
642
643
644 }
645 }
646 } catch (ExecutionException e) {
647 log.error("Failed to load backup flowtable for {}", did, e);
648 }
649 }
650
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800651 private void removeFromPrimary(final DeviceId did) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800652 flowTable.clearDevice(did);
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700653 }
654
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700655
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700656 private final class OnStoreBatch implements ClusterMessageHandler {
657 private final NodeId local;
658
659 private OnStoreBatch(NodeId local) {
660 this.local = local;
661 }
662
663 @Override
664 public void handle(final ClusterMessage message) {
665 FlowRuleBatchOperation operation = SERIALIZER.decode(message.payload());
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800666 log.debug("received batch request {}", operation);
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700667
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800668 final DeviceId deviceId = operation.deviceId();
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700669 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(deviceId);
670 if (!local.equals(replicaInfo.master().orNull())) {
671
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700672 Set<FlowRule> failures = new HashSet<>(operation.size());
673 for (FlowRuleBatchEntry op : operation.getOperations()) {
674 failures.add(op.target());
675 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800676 CompletedBatchOperation allFailed = new CompletedBatchOperation(false, failures, deviceId);
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700677 // This node is no longer the master, respond as all failed.
678 // TODO: we might want to wrap response in envelope
679 // to distinguish sw programming failure and hand over
680 // it make sense in the latter case to retry immediately.
Madan Jampanic26eede2015-04-16 11:42:16 -0700681 message.respond(SERIALIZER.encode(allFailed));
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700682 return;
683 }
684
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700685
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800686 pendingResponses.put(operation.id(), message.sender());
687 storeBatchInternal(operation);
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700688
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700689 }
690 }
691
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700692 private final class SMapLoader
693 extends CacheLoader<DeviceId, SMap<FlowId, ImmutableList<StoredFlowEntry>>> {
694
695 @Override
696 public SMap<FlowId, ImmutableList<StoredFlowEntry>> load(DeviceId id)
697 throws Exception {
698 IMap<byte[], byte[]> map = theInstance.getMap("flowtable_" + id.toString());
699 return new SMap<FlowId, ImmutableList<StoredFlowEntry>>(map, SERIALIZER);
700 }
701 }
702
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700703 private final class InternalReplicaInfoEventListener
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800704 implements ReplicaInfoEventListener {
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700705
706 @Override
707 public void event(ReplicaInfoEvent event) {
708 final NodeId local = clusterService.getLocalNode().id();
709 final DeviceId did = event.subject();
710 final ReplicaInfo rInfo = event.replicaInfo();
711
712 switch (event.type()) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800713 case MASTER_CHANGED:
714 if (local.equals(rInfo.master().orNull())) {
715 // This node is the new master, populate local structure
716 // from backup
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700717 loadFromBackup(did);
alshabib93cb57f2015-02-12 17:43:26 -0800718 }
719 //else {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800720 // This node is no longer the master holder,
721 // clean local structure
alshabib93cb57f2015-02-12 17:43:26 -0800722 //removeFromPrimary(did);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800723 // TODO: probably should stop pending backup activities in
724 // executors to avoid overwriting with old value
alshabib93cb57f2015-02-12 17:43:26 -0800725 //}
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800726 break;
727 default:
728 break;
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700729
730 }
731 }
732 }
733
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700734 // Task to update FlowEntries in backup HZ store
735 private final class UpdateBackup implements Runnable {
736
737 private final DeviceId deviceId;
738 private final Set<FlowRuleBatchEntry> ops;
739
740
741 public UpdateBackup(DeviceId deviceId,
742 Set<FlowRuleBatchEntry> ops) {
743 this.deviceId = checkNotNull(deviceId);
744 this.ops = checkNotNull(ops);
745
746 }
747
748 @Override
749 public void run() {
750 try {
751 log.trace("update backup {} {}", deviceId, ops
752 );
753 final SMap<FlowId, ImmutableList<StoredFlowEntry>> backupFlowTable = smaps.get(deviceId);
754
755
756 ops.stream().forEach(
757 op -> {
758 final FlowRule entry = op.target();
759 final FlowId id = entry.id();
760 ImmutableList<StoredFlowEntry> original = backupFlowTable.get(id);
761 List<StoredFlowEntry> list = new ArrayList<>();
762 if (original != null) {
763 list.addAll(original);
764 }
765 list.remove(op.target());
766 if (op.operator() == FlowRuleOperation.ADD) {
767 list.add((StoredFlowEntry) entry);
768 }
769
770 ImmutableList<StoredFlowEntry> newValue = ImmutableList.copyOf(list);
771 boolean success;
772 if (original == null) {
773 success = (backupFlowTable.putIfAbsent(id, newValue) == null);
774 } else {
775 success = backupFlowTable.replace(id, original, newValue);
776 }
777 if (!success) {
778 log.error("Updating backup failed.");
779 }
780
781 }
782 );
783 } catch (ExecutionException e) {
784 log.error("Failed to write to backups", e);
785 }
786
787 }
788 }
789
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800790 private class InternalFlowTable {
791
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700792 /*
793 TODO: This needs to be cleaned up. Perhaps using the eventually consistent
794 map when it supports distributed to a sequence of instances.
795 */
796
797
798 private final ConcurrentMap<DeviceId, ConcurrentMap<FlowId, Set<StoredFlowEntry>>>
799 flowEntries = new ConcurrentHashMap<>();
800
801
802 private NewConcurrentHashMap<FlowId, Set<StoredFlowEntry>> lazyEmptyFlowTable() {
803 return NewConcurrentHashMap.<FlowId, Set<StoredFlowEntry>>ifNeeded();
804 }
Madan Jampanie1356282015-03-10 19:05:36 -0700805
806 /**
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700807 * Returns the flow table for specified device.
808 *
809 * @param deviceId identifier of the device
810 * @return Map representing Flow Table of given device.
Madan Jampanie1356282015-03-10 19:05:36 -0700811 */
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700812 private ConcurrentMap<FlowId, Set<StoredFlowEntry>> getFlowTable(DeviceId deviceId) {
813 return createIfAbsentUnchecked(flowEntries,
814 deviceId, lazyEmptyFlowTable());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800815 }
816
817 private Set<StoredFlowEntry> getFlowEntriesInternal(DeviceId deviceId, FlowId flowId) {
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700818 final ConcurrentMap<FlowId, Set<StoredFlowEntry>> flowTable = getFlowTable(deviceId);
819 Set<StoredFlowEntry> r = flowTable.get(flowId);
820 if (r == null) {
821 final Set<StoredFlowEntry> concurrentlyAdded;
822 r = new CopyOnWriteArraySet<>();
823 concurrentlyAdded = flowTable.putIfAbsent(flowId, r);
824 if (concurrentlyAdded != null) {
825 return concurrentlyAdded;
826 }
827 }
828 return r;
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800829 }
830
831 private StoredFlowEntry getFlowEntryInternal(FlowRule rule) {
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700832 for (StoredFlowEntry f : getFlowEntriesInternal(rule.deviceId(), rule.id())) {
833 if (f.equals(rule)) {
834 return f;
835 }
836 }
837 return null;
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800838 }
839
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700840 private Set<FlowEntry> getFlowEntriesInternal(DeviceId deviceId) {
841 return getFlowTable(deviceId).values().stream()
842 .flatMap((list -> list.stream())).collect(Collectors.toSet());
843
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800844 }
845
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700846
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800847 public StoredFlowEntry getFlowEntry(FlowRule rule) {
848 return getFlowEntryInternal(rule);
849 }
850
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700851 public Set<FlowEntry> getFlowEntries(DeviceId deviceId) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800852 return getFlowEntriesInternal(deviceId);
853 }
854
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700855 public Set<StoredFlowEntry> getFlowEntriesById(FlowEntry entry) {
856 return getFlowEntriesInternal(entry.deviceId(), entry.id());
857 }
858
859 public void add(FlowEntry rule) {
860 ((CopyOnWriteArraySet)
861 getFlowEntriesInternal(rule.deviceId(), rule.id())).add(rule);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800862 }
863
864 public boolean remove(DeviceId deviceId, FlowEntry rule) {
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700865 return ((CopyOnWriteArraySet)
866 getFlowEntriesInternal(deviceId, rule.id())).remove(rule);
867 //return flowEntries.remove(deviceId, rule);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800868 }
869
870 public void clearDevice(DeviceId did) {
871 flowEntries.remove(did);
872 }
873 }
Madan Jampanib0a3dd62015-03-17 13:41:27 -0700874
875
Madan Jampanie1356282015-03-10 19:05:36 -0700876}