blob: 3d66386abca6b98cc6bf24ea3d1183496f8efd62 [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
2 * 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
Brian O'Connor72cb19a2015-01-16 16:14:41 -080018import com.google.common.cache.CacheBuilder;
19import com.google.common.cache.CacheLoader;
20import com.google.common.cache.LoadingCache;
21import com.google.common.collect.ImmutableList;
22import com.google.common.collect.Iterables;
23import com.google.common.collect.Maps;
24import com.google.common.collect.Sets;
25import com.google.common.util.concurrent.ListenableFuture;
26import com.hazelcast.core.IMap;
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;
Madan Jampani38b250d2014-10-17 11:02:38 -070030import org.apache.felix.scr.annotations.Reference;
31import org.apache.felix.scr.annotations.ReferenceCardinality;
alshabib339a3d92014-09-26 17:54:32 -070032import org.apache.felix.scr.annotations.Service;
Jonathan Hart4fb5cde2014-12-22 12:09:07 -080033import org.onlab.util.KryoNamespace;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080034import org.onlab.util.NewConcurrentHashMap;
Brian O'Connorabafb502014-12-02 22:26:20 -080035import org.onosproject.cluster.ClusterService;
36import org.onosproject.cluster.NodeId;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080037import org.onosproject.core.CoreService;
38import org.onosproject.core.IdGenerator;
Brian O'Connorabafb502014-12-02 22:26:20 -080039import org.onosproject.net.Device;
40import org.onosproject.net.DeviceId;
41import org.onosproject.net.device.DeviceService;
42import org.onosproject.net.flow.CompletedBatchOperation;
43import org.onosproject.net.flow.DefaultFlowEntry;
44import org.onosproject.net.flow.FlowEntry;
45import org.onosproject.net.flow.FlowEntry.FlowEntryState;
46import org.onosproject.net.flow.FlowId;
47import org.onosproject.net.flow.FlowRule;
48import org.onosproject.net.flow.FlowRuleBatchEntry;
Jonathan Hart4fb5cde2014-12-22 12:09:07 -080049import org.onosproject.net.flow.FlowRuleBatchEntry.FlowRuleOperation;
Brian O'Connorabafb502014-12-02 22:26:20 -080050import org.onosproject.net.flow.FlowRuleBatchEvent;
51import org.onosproject.net.flow.FlowRuleBatchOperation;
52import org.onosproject.net.flow.FlowRuleBatchRequest;
53import org.onosproject.net.flow.FlowRuleEvent;
Brian O'Connorabafb502014-12-02 22:26:20 -080054import org.onosproject.net.flow.FlowRuleEvent.Type;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080055import org.onosproject.net.flow.FlowRuleService;
Brian O'Connorabafb502014-12-02 22:26:20 -080056import org.onosproject.net.flow.FlowRuleStore;
57import org.onosproject.net.flow.FlowRuleStoreDelegate;
58import org.onosproject.net.flow.StoredFlowEntry;
59import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
60import org.onosproject.store.cluster.messaging.ClusterMessage;
61import org.onosproject.store.cluster.messaging.ClusterMessageHandler;
62import org.onosproject.store.flow.ReplicaInfo;
63import org.onosproject.store.flow.ReplicaInfoEvent;
64import org.onosproject.store.flow.ReplicaInfoEventListener;
65import org.onosproject.store.flow.ReplicaInfoService;
66import org.onosproject.store.hz.AbstractHazelcastStore;
67import org.onosproject.store.hz.SMap;
Brian O'Connorabafb502014-12-02 22:26:20 -080068import org.onosproject.store.serializers.KryoSerializer;
69import org.onosproject.store.serializers.StoreSerializer;
70import org.onosproject.store.serializers.impl.DistributedStoreSerializers;
alshabib339a3d92014-09-26 17:54:32 -070071import org.slf4j.Logger;
72
Brian O'Connor72cb19a2015-01-16 16:14:41 -080073import java.io.IOException;
74import java.util.ArrayList;
75import java.util.Arrays;
76import java.util.Collections;
77import java.util.HashSet;
78import java.util.List;
79import java.util.Map;
80import java.util.Map.Entry;
81import java.util.Set;
82import java.util.concurrent.ConcurrentHashMap;
83import java.util.concurrent.ConcurrentMap;
84import java.util.concurrent.CopyOnWriteArraySet;
85import java.util.concurrent.ExecutionException;
86import java.util.concurrent.ExecutorService;
87import java.util.concurrent.Executors;
88import java.util.concurrent.Future;
89import java.util.concurrent.TimeUnit;
90import java.util.concurrent.TimeoutException;
91import java.util.stream.Collectors;
92
93import static com.google.common.base.Preconditions.checkNotNull;
94import static org.apache.commons.lang3.concurrent.ConcurrentUtils.createIfAbsentUnchecked;
95import static org.onlab.util.Tools.namedThreads;
96import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_REMOVED;
97import static org.onosproject.store.flow.impl.FlowStoreMessageSubjects.*;
98import static org.slf4j.LoggerFactory.getLogger;
alshabib339a3d92014-09-26 17:54:32 -070099
100/**
Madan Jampani38b250d2014-10-17 11:02:38 -0700101 * Manages inventory of flow rules using a distributed state management protocol.
alshabib339a3d92014-09-26 17:54:32 -0700102 */
alshabib339a3d92014-09-26 17:54:32 -0700103@Component(immediate = true)
104@Service
105public class DistributedFlowRuleStore
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700106 extends AbstractHazelcastStore<FlowRuleBatchEvent, FlowRuleStoreDelegate>
alshabib1c319ff2014-10-04 20:29:09 -0700107 implements FlowRuleStore {
alshabib339a3d92014-09-26 17:54:32 -0700108
109 private final Logger log = getLogger(getClass());
110
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800111 private InternalFlowTable flowTable = new InternalFlowTable();
112
113 /*private final ConcurrentMap<DeviceId, ConcurrentMap<FlowId, Set<StoredFlowEntry>>>
114 flowEntries = new ConcurrentHashMap<>();*/
alshabib339a3d92014-09-26 17:54:32 -0700115
Madan Jampani38b250d2014-10-17 11:02:38 -0700116 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700117 protected ReplicaInfoService replicaInfoManager;
Madan Jampani38b250d2014-10-17 11:02:38 -0700118
119 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700120 protected ClusterCommunicationService clusterCommunicator;
Madan Jampani38b250d2014-10-17 11:02:38 -0700121
122 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700123 protected ClusterService clusterService;
124
125 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
126 protected DeviceService deviceService;
127
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800128 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
129 protected CoreService coreService;
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700130
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800131 private Map<Long, NodeId> pendingResponses = Maps.newConcurrentMap();
Yuta HIGUCHIbf89c742014-10-27 15:10:02 -0700132
Yuta HIGUCHIe9b2b002014-11-04 12:25:47 -0800133 // Cache of SMaps used for backup data. each SMap contain device flow table
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700134 private LoadingCache<DeviceId, SMap<FlowId, ImmutableList<StoredFlowEntry>>> smaps;
135
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700136
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700137 private final ExecutorService backupExecutors =
Thomas Vachuska9ea3e6f2015-01-23 16:34:22 -0800138 Executors.newSingleThreadExecutor(namedThreads("onos-async-backups"));
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700139
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700140 private boolean syncBackup = false;
Madan Jampani38b250d2014-10-17 11:02:38 -0700141
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700142 protected static final StoreSerializer SERIALIZER = new KryoSerializer() {
Madan Jampani38b250d2014-10-17 11:02:38 -0700143 @Override
144 protected void setupKryoPool() {
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -0700145 serializerPool = KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800146 .register(DistributedStoreSerializers.STORE_COMMON)
147 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
Yuta HIGUCHI2f158332014-11-25 13:32:06 -0800148 .register(FlowRuleEvent.class)
Jonathan Hart4fb5cde2014-12-22 12:09:07 -0800149 .register(FlowRuleEvent.Type.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800150 .build();
Madan Jampani38b250d2014-10-17 11:02:38 -0700151 }
152 };
153
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700154 private static final long FLOW_RULE_STORE_TIMEOUT_MILLIS = 5000;
Madan Jampani38b250d2014-10-17 11:02:38 -0700155
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700156 private ReplicaInfoEventListener replicaInfoEventListener;
157
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800158 private IdGenerator idGenerator;
159
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700160 @Override
alshabib339a3d92014-09-26 17:54:32 -0700161 @Activate
162 public void activate() {
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700163
164 super.serializer = SERIALIZER;
165 super.theInstance = storeService.getHazelcastInstance();
166
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800167 idGenerator = coreService.getIdGenerator(FlowRuleService.FLOW_OP_TOPIC);
168
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700169 // Cache to create SMap on demand
170 smaps = CacheBuilder.newBuilder()
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800171 .softValues()
172 .build(new SMapLoader());
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700173
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700174 final NodeId local = clusterService.getLocalNode().id();
175
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700176 clusterCommunicator.addSubscriber(APPLY_BATCH_FLOWS, new OnStoreBatch(local));
Madan Jampani117aaae2014-10-23 10:04:05 -0700177
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800178 clusterCommunicator.addSubscriber(REMOTE_APPLY_COMPLETED, new ClusterMessageHandler() {
179 @Override
180 public void handle(ClusterMessage message) {
181 FlowRuleBatchEvent event = SERIALIZER.decode(message.payload());
182 log.trace("received completed notification for {}", event);
183 notifyDelegate(event);
184 }
185 });
186
Madan Jampani117aaae2014-10-23 10:04:05 -0700187 clusterCommunicator.addSubscriber(GET_FLOW_ENTRY, new ClusterMessageHandler() {
188
189 @Override
190 public void handle(ClusterMessage message) {
191 FlowRule rule = SERIALIZER.decode(message.payload());
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800192 log.trace("received get flow entry request for {}", rule);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800193 FlowEntry flowEntry = flowTable.getFlowEntry(rule); //getFlowEntryInternal(rule);
Madan Jampani117aaae2014-10-23 10:04:05 -0700194 try {
195 message.respond(SERIALIZER.encode(flowEntry));
196 } catch (IOException e) {
197 log.error("Failed to respond back", e);
198 }
199 }
200 });
201
Madan Jampanif5fdef02014-10-23 21:58:10 -0700202 clusterCommunicator.addSubscriber(GET_DEVICE_FLOW_ENTRIES, new ClusterMessageHandler() {
203
204 @Override
205 public void handle(ClusterMessage message) {
206 DeviceId deviceId = SERIALIZER.decode(message.payload());
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800207 log.trace("Received get flow entries request for {} from {}", deviceId, message.sender());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800208 Set<FlowEntry> flowEntries = flowTable.getFlowEntries(deviceId);
Madan Jampanif5fdef02014-10-23 21:58:10 -0700209 try {
210 message.respond(SERIALIZER.encode(flowEntries));
211 } catch (IOException e) {
212 log.error("Failed to respond to peer's getFlowEntries request", e);
213 }
214 }
215 });
216
Yuta HIGUCHIdfa45c12014-11-24 18:38:53 -0800217 clusterCommunicator.addSubscriber(REMOVE_FLOW_ENTRY, new ClusterMessageHandler() {
218
219 @Override
220 public void handle(ClusterMessage message) {
221 FlowEntry rule = SERIALIZER.decode(message.payload());
222 log.trace("received get flow entry request for {}", rule);
223 FlowRuleEvent event = removeFlowRuleInternal(rule);
224 try {
225 message.respond(SERIALIZER.encode(event));
226 } catch (IOException e) {
227 log.error("Failed to respond back", e);
228 }
229 }
230 });
231
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700232 replicaInfoEventListener = new InternalReplicaInfoEventListener();
233
234 replicaInfoManager.addListener(replicaInfoEventListener);
235
alshabib339a3d92014-09-26 17:54:32 -0700236 log.info("Started");
237 }
238
239 @Deactivate
240 public void deactivate() {
Yuta HIGUCHIdfa45c12014-11-24 18:38:53 -0800241 clusterCommunicator.removeSubscriber(REMOVE_FLOW_ENTRY);
242 clusterCommunicator.removeSubscriber(GET_DEVICE_FLOW_ENTRIES);
243 clusterCommunicator.removeSubscriber(GET_FLOW_ENTRY);
244 clusterCommunicator.removeSubscriber(APPLY_BATCH_FLOWS);
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700245 replicaInfoManager.removeListener(replicaInfoEventListener);
alshabib339a3d92014-09-26 17:54:32 -0700246 log.info("Stopped");
247 }
248
249
Brian O'Connor44008532014-12-04 16:41:36 -0800250 // This is not a efficient operation on a distributed sharded
Madan Jampani117aaae2014-10-23 10:04:05 -0700251 // flow store. We need to revisit the need for this operation or at least
252 // make it device specific.
alshabib339a3d92014-09-26 17:54:32 -0700253 @Override
tom9b4030d2014-10-06 10:39:03 -0700254 public int getFlowRuleCount() {
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700255 // implementing in-efficient operation for debugging purpose.
256 int sum = 0;
257 for (Device device : deviceService.getDevices()) {
258 final DeviceId did = device.id();
259 sum += Iterables.size(getFlowEntries(did));
260 }
261 return sum;
tom9b4030d2014-10-06 10:39:03 -0700262 }
263
264 @Override
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800265 public FlowEntry getFlowEntry(FlowRule rule) {
Madan Jampani117aaae2014-10-23 10:04:05 -0700266 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(rule.deviceId());
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700267
268 if (!replicaInfo.master().isPresent()) {
Yuta HIGUCHI6b98ab62014-12-03 16:08:08 -0800269 log.warn("Failed to getFlowEntry: No master for {}", rule.deviceId());
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800270 return null;
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700271 }
272
Madan Jampani117aaae2014-10-23 10:04:05 -0700273 if (replicaInfo.master().get().equals(clusterService.getLocalNode().id())) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800274 return flowTable.getFlowEntry(rule);
Madan Jampani117aaae2014-10-23 10:04:05 -0700275 }
276
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800277 log.trace("Forwarding getFlowEntry to {}, which is the primary (master) for device {}",
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800278 replicaInfo.master().orNull(), rule.deviceId());
Madan Jampani117aaae2014-10-23 10:04:05 -0700279
280 ClusterMessage message = new ClusterMessage(
281 clusterService.getLocalNode().id(),
282 FlowStoreMessageSubjects.GET_FLOW_ENTRY,
283 SERIALIZER.encode(rule));
284
285 try {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700286 Future<byte[]> responseFuture = clusterCommunicator.sendAndReceive(message, replicaInfo.master().get());
287 return SERIALIZER.decode(responseFuture.get(FLOW_RULE_STORE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
288 } catch (IOException | TimeoutException | ExecutionException | InterruptedException e) {
Brian O'Connor44008532014-12-04 16:41:36 -0800289 log.warn("Unable to fetch flow store contents from {}", replicaInfo.master().get());
Madan Jampani117aaae2014-10-23 10:04:05 -0700290 }
Brian O'Connor44008532014-12-04 16:41:36 -0800291 return null;
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700292 }
293
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800294
alshabib339a3d92014-09-26 17:54:32 -0700295
296 @Override
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800297 public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) {
Madan Jampanif5fdef02014-10-23 21:58:10 -0700298
299 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(deviceId);
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700300
301 if (!replicaInfo.master().isPresent()) {
Yuta HIGUCHI6b98ab62014-12-03 16:08:08 -0800302 log.warn("Failed to getFlowEntries: No master for {}", deviceId);
Yuta HIGUCHI2c1d8472014-10-31 14:13:38 -0700303 return Collections.emptyList();
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700304 }
305
Madan Jampanif5fdef02014-10-23 21:58:10 -0700306 if (replicaInfo.master().get().equals(clusterService.getLocalNode().id())) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800307 return flowTable.getFlowEntries(deviceId);
Madan Jampanif5fdef02014-10-23 21:58:10 -0700308 }
309
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800310 log.trace("Forwarding getFlowEntries to {}, which is the primary (master) for device {}",
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800311 replicaInfo.master().orNull(), deviceId);
Madan Jampanif5fdef02014-10-23 21:58:10 -0700312
313 ClusterMessage message = new ClusterMessage(
314 clusterService.getLocalNode().id(),
315 GET_DEVICE_FLOW_ENTRIES,
316 SERIALIZER.encode(deviceId));
317
318 try {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700319 Future<byte[]> responseFuture = clusterCommunicator.sendAndReceive(message, replicaInfo.master().get());
320 return SERIALIZER.decode(responseFuture.get(FLOW_RULE_STORE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
321 } catch (IOException | TimeoutException | ExecutionException | InterruptedException e) {
Brian O'Connor44008532014-12-04 16:41:36 -0800322 log.warn("Unable to fetch flow store contents from {}", replicaInfo.master().get());
Madan Jampanif5fdef02014-10-23 21:58:10 -0700323 }
Yuta HIGUCHI24f79eb2014-12-12 15:46:43 -0800324 return Collections.emptyList();
Madan Jampanif5fdef02014-10-23 21:58:10 -0700325 }
326
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800327
alshabib339a3d92014-09-26 17:54:32 -0700328
329 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700330 public void storeFlowRule(FlowRule rule) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800331 storeBatch(new FlowRuleBatchOperation(
332 Arrays.asList(new FlowRuleBatchEntry(FlowRuleOperation.ADD, rule)),
333 rule.deviceId(), idGenerator.getNewId()));
Madan Jampani117aaae2014-10-23 10:04:05 -0700334 }
335
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700336 @Override
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800337 public void storeBatch(FlowRuleBatchOperation operation) {
338
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700339
Madan Jampani117aaae2014-10-23 10:04:05 -0700340 if (operation.getOperations().isEmpty()) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800341
342 notifyDelegate(FlowRuleBatchEvent.completed(
343 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
344 new CompletedBatchOperation(true, Collections.emptySet(),
345 operation.deviceId())));
346 return;
alshabib339a3d92014-09-26 17:54:32 -0700347 }
Madan Jampani38b250d2014-10-17 11:02:38 -0700348
Sho SHIMIZUaba9d002015-01-29 14:51:04 -0800349 DeviceId deviceId = operation.getOperations().get(0).target().deviceId();
Madan Jampani117aaae2014-10-23 10:04:05 -0700350
351 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(deviceId);
352
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700353 if (!replicaInfo.master().isPresent()) {
Yuta HIGUCHI6b98ab62014-12-03 16:08:08 -0800354 log.warn("Failed to storeBatch: No master for {}", deviceId);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800355
356 Set<FlowRule> allFailures = operation.getOperations().stream()
357 .map(op -> op.getTarget())
358 .collect(Collectors.toSet());
359
360 notifyDelegate(FlowRuleBatchEvent.completed(
361 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
362 new CompletedBatchOperation(false, allFailures, operation.deviceId())));
363 return;
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700364 }
365
366 final NodeId local = clusterService.getLocalNode().id();
367 if (replicaInfo.master().get().equals(local)) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800368 storeBatchInternal(operation);
369 return;
Madan Jampani117aaae2014-10-23 10:04:05 -0700370 }
371
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800372 log.trace("Forwarding storeBatch to {}, which is the primary (master) for device {}",
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800373 replicaInfo.master().orNull(), deviceId);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700374
Madan Jampani38b250d2014-10-17 11:02:38 -0700375 ClusterMessage message = new ClusterMessage(
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700376 local,
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700377 APPLY_BATCH_FLOWS,
Madan Jampani117aaae2014-10-23 10:04:05 -0700378 SERIALIZER.encode(operation));
Madan Jampani38b250d2014-10-17 11:02:38 -0700379
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800380 //CompletedBatchOperation response;
Madan Jampani38b250d2014-10-17 11:02:38 -0700381 try {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700382 ListenableFuture<byte[]> responseFuture =
383 clusterCommunicator.sendAndReceive(message, replicaInfo.master().get());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800384 /*response =
385 Futures.transform(responseFuture,
386 new DecodeTo<CompletedBatchOperation>(SERIALIZER))
387 .get(500 * operation.size(), TimeUnit.MILLISECONDS);
388
389 notifyDelegate(FlowRuleBatchEvent.completed(
390 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()), response));*/
391
392 } catch (IOException /*| InterruptedException | ExecutionException | TimeoutException*/ e) {
393 log.warn("Failed to storeBatch: {}", e.getMessage());
394
395 Set<FlowRule> allFailures = operation.getOperations().stream()
396 .map(op -> op.getTarget())
397 .collect(Collectors.toSet());
398
399 notifyDelegate(FlowRuleBatchEvent.completed(
400 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
401 new CompletedBatchOperation(false, allFailures, deviceId)));
402 return;
Madan Jampani38b250d2014-10-17 11:02:38 -0700403 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800404
Madan Jampani38b250d2014-10-17 11:02:38 -0700405 }
406
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800407 private void storeBatchInternal(FlowRuleBatchOperation operation) {
Yuta HIGUCHIe9b2b002014-11-04 12:25:47 -0800408
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800409 final DeviceId did = operation.deviceId();
410 //final Collection<FlowEntry> ft = flowTable.getFlowEntries(did);
411 Set<FlowRuleBatchEntry> currentOps;
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700412
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700413
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800414 currentOps = operation.getOperations().stream().map(
415 op -> {
416 StoredFlowEntry entry;
417 switch (op.getOperator()) {
418 case ADD:
419 entry = new DefaultFlowEntry(op.getTarget());
420 // always add requested FlowRule

421 // Note: 2 equal FlowEntry may have different treatment
422 flowTable.remove(entry.deviceId(), entry);
423 flowTable.add(entry);
424
425 return op;
426 case REMOVE:
427 entry = flowTable.getFlowEntry(op.target());
428 if (entry != null) {
429 entry.setState(FlowEntryState.PENDING_REMOVE);
430 return op;
431 }
432 break;
433 case MODIFY:
434 //TODO: figure this out at some point
435 break;
436 default:
437 log.warn("Unknown flow operation operator: {}", op.getOperator());
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800438 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800439 return null;
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800440 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800441 ).filter(op -> op != null).collect(Collectors.toSet());
442 if (currentOps.isEmpty()) {
443 batchOperationComplete(FlowRuleBatchEvent.completed(
444 new FlowRuleBatchRequest(operation.id(), Collections.emptySet()),
445 new CompletedBatchOperation(true, Collections.emptySet(), did)));
446 return;
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800447 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800448 updateBackup(did, currentOps);
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700449
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700450
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800451 notifyDelegate(FlowRuleBatchEvent.requested(new
452 FlowRuleBatchRequest(operation.id(), currentOps), operation.deviceId()));
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700453
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800454
alshabib339a3d92014-09-26 17:54:32 -0700455 }
456
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800457 private void updateBackup(DeviceId deviceId, final Set<FlowRuleBatchEntry> entries) {
458 Future<?> backup = backupExecutors.submit(new UpdateBackup(deviceId, entries));
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700459
460 if (syncBackup) {
461 // wait for backup to complete
462 try {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800463 backup.get();
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700464 } catch (InterruptedException | ExecutionException e) {
465 log.error("Failed to create backups", e);
466 }
467 }
468 }
469
alshabib339a3d92014-09-26 17:54:32 -0700470 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700471 public void deleteFlowRule(FlowRule rule) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800472 storeBatch(
473 new FlowRuleBatchOperation(
474 Arrays.asList(
475 new FlowRuleBatchEntry(
476 FlowRuleOperation.REMOVE,
477 rule)), rule.deviceId(), idGenerator.getNewId()));
alshabib339a3d92014-09-26 17:54:32 -0700478 }
479
480 @Override
Madan Jampani38b250d2014-10-17 11:02:38 -0700481 public FlowRuleEvent addOrUpdateFlowRule(FlowEntry rule) {
482 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(rule.deviceId());
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700483 final NodeId localId = clusterService.getLocalNode().id();
484 if (localId.equals(replicaInfo.master().orNull())) {
Madan Jampani38b250d2014-10-17 11:02:38 -0700485 return addOrUpdateFlowRuleInternal(rule);
486 }
487
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800488 log.warn("Tried to update FlowRule {} state,"
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800489 + " while the Node was not the master.", rule);
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700490 return null;
Madan Jampani38b250d2014-10-17 11:02:38 -0700491 }
492
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800493 private FlowRuleEvent addOrUpdateFlowRuleInternal(FlowEntry rule) {
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700494 final DeviceId did = rule.deviceId();
alshabib339a3d92014-09-26 17:54:32 -0700495
alshabib339a3d92014-09-26 17:54:32 -0700496
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800497 // check if this new rule is an update to an existing entry
498 StoredFlowEntry stored = flowTable.getFlowEntry(rule);
499 if (stored != null) {
500 stored.setBytes(rule.bytes());
501 stored.setLife(rule.life());
502 stored.setPackets(rule.packets());
503 if (stored.state() == FlowEntryState.PENDING_ADD) {
504 stored.setState(FlowEntryState.ADDED);
505 FlowRuleBatchEntry entry =
506 new FlowRuleBatchEntry(FlowRuleOperation.ADD, stored);
507 updateBackup(did, Sets.newHashSet(entry));
508 return new FlowRuleEvent(Type.RULE_ADDED, rule);
509 }
510 return new FlowRuleEvent(Type.RULE_UPDATED, rule);
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800511 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800512
513 // TODO: Confirm if this behavior is correct. See SimpleFlowRuleStore
514 // TODO: also update backup if the behavior is correct.
515 flowTable.add(rule);
516
517
alshabib1c319ff2014-10-04 20:29:09 -0700518 return null;
Madan Jampani38b250d2014-10-17 11:02:38 -0700519
alshabib339a3d92014-09-26 17:54:32 -0700520 }
521
522 @Override
Madan Jampani38b250d2014-10-17 11:02:38 -0700523 public FlowRuleEvent removeFlowRule(FlowEntry rule) {
Yuta HIGUCHIb6eb9142014-11-26 16:18:13 -0800524 final DeviceId deviceId = rule.deviceId();
525 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(deviceId);
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700526
527 final NodeId localId = clusterService.getLocalNode().id();
528 if (localId.equals(replicaInfo.master().orNull())) {
Madan Jampani38b250d2014-10-17 11:02:38 -0700529 // bypass and handle it locally
530 return removeFlowRuleInternal(rule);
531 }
532
Yuta HIGUCHIb6eb9142014-11-26 16:18:13 -0800533 if (!replicaInfo.master().isPresent()) {
Yuta HIGUCHI6b98ab62014-12-03 16:08:08 -0800534 log.warn("Failed to removeFlowRule: No master for {}", deviceId);
Yuta HIGUCHIb6eb9142014-11-26 16:18:13 -0800535 // TODO: revisit if this should be null (="no-op") or Exception
536 return null;
537 }
538
Yuta HIGUCHIdfa45c12014-11-24 18:38:53 -0800539 log.trace("Forwarding removeFlowRule to {}, which is the primary (master) for device {}",
Yuta HIGUCHIb6eb9142014-11-26 16:18:13 -0800540 replicaInfo.master().orNull(), deviceId);
Yuta HIGUCHIdfa45c12014-11-24 18:38:53 -0800541
542 ClusterMessage message = new ClusterMessage(
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800543 clusterService.getLocalNode().id(),
544 REMOVE_FLOW_ENTRY,
545 SERIALIZER.encode(rule));
Yuta HIGUCHIdfa45c12014-11-24 18:38:53 -0800546
547 try {
548 Future<byte[]> responseFuture = clusterCommunicator.sendAndReceive(message, replicaInfo.master().get());
549 return SERIALIZER.decode(responseFuture.get(FLOW_RULE_STORE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
550 } catch (IOException | TimeoutException | ExecutionException | InterruptedException e) {
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800551 // TODO: Retry against latest master or throw a FlowStoreException
Yuta HIGUCHIdfa45c12014-11-24 18:38:53 -0800552 throw new RuntimeException(e);
553 }
Madan Jampani38b250d2014-10-17 11:02:38 -0700554 }
555
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800556 private FlowRuleEvent removeFlowRuleInternal(FlowEntry rule) {
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700557 final DeviceId deviceId = rule.deviceId();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800558 // This is where one could mark a rule as removed and still keep it in the store.
559 final boolean removed = flowTable.remove(deviceId, rule); //flowEntries.remove(deviceId, rule);
560 FlowRuleBatchEntry entry =
561 new FlowRuleBatchEntry(FlowRuleOperation.REMOVE, rule);
562 updateBackup(deviceId, Sets.newHashSet(entry));
563 if (removed) {
564 return new FlowRuleEvent(RULE_REMOVED, rule);
565 } else {
566 return null;
alshabib339a3d92014-09-26 17:54:32 -0700567 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800568
alshabib339a3d92014-09-26 17:54:32 -0700569 }
Madan Jampani117aaae2014-10-23 10:04:05 -0700570
571 @Override
572 public void batchOperationComplete(FlowRuleBatchEvent event) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800573 //FIXME: need a per device pending response
574
575 NodeId nodeId = pendingResponses.remove(event.subject().batchId());
576 if (nodeId == null) {
577 notifyDelegate(event);
578 } else {
579 try {
580 ClusterMessage message = new ClusterMessage(
581 clusterService.getLocalNode().id(),
582 REMOTE_APPLY_COMPLETED,
583 SERIALIZER.encode(event));
584 clusterCommunicator.sendAndReceive(message, nodeId);
585 } catch (IOException e) {
586 log.warn("Failed to respond to peer for batch operation result");
587 }
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700588 }
Madan Jampani117aaae2014-10-23 10:04:05 -0700589 }
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700590
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800591 private void loadFromBackup(final DeviceId did) {
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700592
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800593
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700594 try {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800595 log.debug("Loading FlowRules for {} from backups", did);
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700596 SMap<FlowId, ImmutableList<StoredFlowEntry>> backupFlowTable = smaps.get(did);
597 for (Entry<FlowId, ImmutableList<StoredFlowEntry>> e
598 : backupFlowTable.entrySet()) {
599
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800600 log.trace("loading {}", e.getValue());
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700601 for (StoredFlowEntry entry : e.getValue()) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800602 flowTable.getFlowEntriesById(entry).remove(entry);
603 flowTable.getFlowEntriesById(entry).add(entry);
604
605
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700606 }
607 }
608 } catch (ExecutionException e) {
609 log.error("Failed to load backup flowtable for {}", did, e);
610 }
611 }
612
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800613 private void removeFromPrimary(final DeviceId did) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800614 flowTable.clearDevice(did);
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700615 }
616
Yuta HIGUCHIf1ccee82014-11-11 20:39:58 -0800617
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700618 private final class OnStoreBatch implements ClusterMessageHandler {
619 private final NodeId local;
620
621 private OnStoreBatch(NodeId local) {
622 this.local = local;
623 }
624
625 @Override
626 public void handle(final ClusterMessage message) {
627 FlowRuleBatchOperation operation = SERIALIZER.decode(message.payload());
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800628 log.debug("received batch request {}", operation);
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700629
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800630 final DeviceId deviceId = operation.deviceId();
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700631 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(deviceId);
632 if (!local.equals(replicaInfo.master().orNull())) {
633
634 Set<FlowRule> failures = new HashSet<>(operation.size());
635 for (FlowRuleBatchEntry op : operation.getOperations()) {
Sho SHIMIZUaba9d002015-01-29 14:51:04 -0800636 failures.add(op.target());
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700637 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800638 CompletedBatchOperation allFailed = new CompletedBatchOperation(false, failures, deviceId);
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700639 // This node is no longer the master, respond as all failed.
640 // TODO: we might want to wrap response in envelope
641 // to distinguish sw programming failure and hand over
642 // it make sense in the latter case to retry immediately.
643 try {
644 message.respond(SERIALIZER.encode(allFailed));
645 } catch (IOException e) {
646 log.error("Failed to respond back", e);
647 }
648 return;
649 }
650
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700651
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800652 pendingResponses.put(operation.id(), message.sender());
653 storeBatchInternal(operation);
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700654
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700655 }
656 }
657
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700658 private final class SMapLoader
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800659 extends CacheLoader<DeviceId, SMap<FlowId, ImmutableList<StoredFlowEntry>>> {
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700660
661 @Override
662 public SMap<FlowId, ImmutableList<StoredFlowEntry>> load(DeviceId id)
663 throws Exception {
664 IMap<byte[], byte[]> map = theInstance.getMap("flowtable_" + id.toString());
665 return new SMap<FlowId, ImmutableList<StoredFlowEntry>>(map, SERIALIZER);
666 }
667 }
668
669 private final class InternalReplicaInfoEventListener
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800670 implements ReplicaInfoEventListener {
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700671
672 @Override
673 public void event(ReplicaInfoEvent event) {
674 final NodeId local = clusterService.getLocalNode().id();
675 final DeviceId did = event.subject();
676 final ReplicaInfo rInfo = event.replicaInfo();
677
678 switch (event.type()) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800679 case MASTER_CHANGED:
680 if (local.equals(rInfo.master().orNull())) {
681 // This node is the new master, populate local structure
682 // from backup
683 loadFromBackup(did);
684 } else {
685 // This node is no longer the master holder,
686 // clean local structure
687 removeFromPrimary(did);
688 // TODO: probably should stop pending backup activities in
689 // executors to avoid overwriting with old value
690 }
691 break;
692 default:
693 break;
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700694
695 }
696 }
697 }
698
699 // Task to update FlowEntries in backup HZ store
700 private final class UpdateBackup implements Runnable {
701
702 private final DeviceId deviceId;
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800703 private final Set<FlowRuleBatchEntry> ops;
704
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700705
706 public UpdateBackup(DeviceId deviceId,
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800707 Set<FlowRuleBatchEntry> ops) {
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700708 this.deviceId = checkNotNull(deviceId);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800709 this.ops = checkNotNull(ops);
710
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700711 }
712
713 @Override
714 public void run() {
715 try {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800716 log.trace("update backup {} {}", deviceId, ops
717 );
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700718 final SMap<FlowId, ImmutableList<StoredFlowEntry>> backupFlowTable = smaps.get(deviceId);
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700719
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700720
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800721 ops.stream().forEach(
722 op -> {
723 final FlowRule entry = op.getTarget();
724 final FlowId id = entry.id();
725 ImmutableList<StoredFlowEntry> original = backupFlowTable.get(id);
726 List<StoredFlowEntry> list = new ArrayList<>();
727 if (original != null) {
728 list.addAll(original);
729 }
730 list.remove(op.getTarget());
731 if (op.getOperator() == FlowRuleOperation.ADD) {
732 list.add((StoredFlowEntry) entry);
733 }
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700734
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800735 ImmutableList<StoredFlowEntry> newValue = ImmutableList.copyOf(list);
736 boolean success;
737 if (original == null) {
738 success = (backupFlowTable.putIfAbsent(id, newValue) == null);
739 } else {
740 success = backupFlowTable.replace(id, original, newValue);
741 }
742 if (!success) {
743 log.error("Updating backup failed.");
744 }
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700745
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800746 }
747 );
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700748 } catch (ExecutionException e) {
749 log.error("Failed to write to backups", e);
750 }
751
752 }
753 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800754
755 private class InternalFlowTable {
756
757 /*
758 TODO: This needs to be cleaned up. Perhaps using the eventually consistent
759 map when it supports distributed to a sequence of instances.
760 */
761
762
763 private final ConcurrentMap<DeviceId, ConcurrentMap<FlowId, Set<StoredFlowEntry>>>
764 flowEntries = new ConcurrentHashMap<>();
765
766
767 private NewConcurrentHashMap<FlowId, Set<StoredFlowEntry>> lazyEmptyFlowTable() {
768 return NewConcurrentHashMap.<FlowId, Set<StoredFlowEntry>>ifNeeded();
769 }
770
771 /**
772 * Returns the flow table for specified device.
773 *
774 * @param deviceId identifier of the device
775 * @return Map representing Flow Table of given device.
776 */
777 private ConcurrentMap<FlowId, Set<StoredFlowEntry>> getFlowTable(DeviceId deviceId) {
778 return createIfAbsentUnchecked(flowEntries,
779 deviceId, lazyEmptyFlowTable());
780 }
781
782 private Set<StoredFlowEntry> getFlowEntriesInternal(DeviceId deviceId, FlowId flowId) {
783 final ConcurrentMap<FlowId, Set<StoredFlowEntry>> flowTable = getFlowTable(deviceId);
784 Set<StoredFlowEntry> r = flowTable.get(flowId);
785 if (r == null) {
786 final Set<StoredFlowEntry> concurrentlyAdded;
787 r = new CopyOnWriteArraySet<>();
788 concurrentlyAdded = flowTable.putIfAbsent(flowId, r);
789 if (concurrentlyAdded != null) {
790 return concurrentlyAdded;
791 }
792 }
793 return r;
794 }
795
796 private StoredFlowEntry getFlowEntryInternal(FlowRule rule) {
797 for (StoredFlowEntry f : getFlowEntriesInternal(rule.deviceId(), rule.id())) {
798 if (f.equals(rule)) {
799 return f;
800 }
801 }
802 return null;
803 }
804
805 private Set<FlowEntry> getFlowEntriesInternal(DeviceId deviceId) {
806 return getFlowTable(deviceId).values().stream()
807 .flatMap((list -> list.stream())).collect(Collectors.toSet());
808
809 }
810
811
812 public StoredFlowEntry getFlowEntry(FlowRule rule) {
813 return getFlowEntryInternal(rule);
814 }
815
816 public Set<FlowEntry> getFlowEntries(DeviceId deviceId) {
817 return getFlowEntriesInternal(deviceId);
818 }
819
820 public Set<StoredFlowEntry> getFlowEntriesById(FlowEntry entry) {
821 return getFlowEntriesInternal(entry.deviceId(), entry.id());
822 }
823
824 public void add(FlowEntry rule) {
825 ((CopyOnWriteArraySet)
826 getFlowEntriesInternal(rule.deviceId(), rule.id())).add(rule);
827 }
828
829 public boolean remove(DeviceId deviceId, FlowEntry rule) {
830 return ((CopyOnWriteArraySet)
831 getFlowEntriesInternal(deviceId, rule.id())).remove(rule);
832 //return flowEntries.remove(deviceId, rule);
833 }
834
835 public void clearDevice(DeviceId did) {
836 flowEntries.remove(did);
837 }
838 }
839
840
alshabib339a3d92014-09-26 17:54:32 -0700841}