blob: 44583302ea0ce26c00a01b2fb06dd80009701fd5 [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 */
alshabib339a3d92014-09-26 17:54:32 -070016package org.onlab.onos.store.flow.impl;
17
Yuta HIGUCHI92891d12014-10-27 20:04:38 -070018import static com.google.common.base.Preconditions.checkNotNull;
alshabib339a3d92014-09-26 17:54:32 -070019import static org.onlab.onos.net.flow.FlowRuleEvent.Type.RULE_REMOVED;
20import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -070021import static org.onlab.onos.store.flow.impl.FlowStoreMessageSubjects.*;
Yuta HIGUCHI9def0472014-10-23 15:51:10 -070022import static org.onlab.util.Tools.namedThreads;
alshabib339a3d92014-09-26 17:54:32 -070023
Madan Jampani38b250d2014-10-17 11:02:38 -070024import java.io.IOException;
Madan Jampani117aaae2014-10-23 10:04:05 -070025import java.util.ArrayList;
26import java.util.Arrays;
alshabib339a3d92014-09-26 17:54:32 -070027import java.util.Collection;
28import java.util.Collections;
Yuta HIGUCHI4b524442014-10-28 22:23:57 -070029import java.util.HashSet;
Yuta HIGUCHI92891d12014-10-27 20:04:38 -070030import java.util.Map.Entry;
Madan Jampanif5fdef02014-10-23 21:58:10 -070031import java.util.Set;
Madan Jampani24f9efb2014-10-24 18:56:23 -070032import java.util.concurrent.ExecutionException;
Yuta HIGUCHI9def0472014-10-23 15:51:10 -070033import java.util.concurrent.ExecutorService;
34import java.util.concurrent.Executors;
Madan Jampani117aaae2014-10-23 10:04:05 -070035import java.util.concurrent.Future;
Madan Jampani38b250d2014-10-17 11:02:38 -070036import java.util.concurrent.TimeUnit;
37import java.util.concurrent.TimeoutException;
Yuta HIGUCHI9def0472014-10-23 15:51:10 -070038import java.util.concurrent.atomic.AtomicInteger;
Yuta HIGUCHI885868f2014-11-13 19:12:07 -080039import java.util.concurrent.locks.ReentrantReadWriteLock;
Madan Jampani117aaae2014-10-23 10:04:05 -070040import java.util.List;
alshabib339a3d92014-09-26 17:54:32 -070041
42import org.apache.felix.scr.annotations.Activate;
43import org.apache.felix.scr.annotations.Component;
44import org.apache.felix.scr.annotations.Deactivate;
Madan Jampani38b250d2014-10-17 11:02:38 -070045import org.apache.felix.scr.annotations.Reference;
46import org.apache.felix.scr.annotations.ReferenceCardinality;
alshabib339a3d92014-09-26 17:54:32 -070047import org.apache.felix.scr.annotations.Service;
Madan Jampani38b250d2014-10-17 11:02:38 -070048import org.onlab.onos.cluster.ClusterService;
Yuta HIGUCHI92891d12014-10-27 20:04:38 -070049import org.onlab.onos.cluster.NodeId;
Yuta HIGUCHI9def0472014-10-23 15:51:10 -070050import org.onlab.onos.net.Device;
alshabib339a3d92014-09-26 17:54:32 -070051import org.onlab.onos.net.DeviceId;
Yuta HIGUCHI9def0472014-10-23 15:51:10 -070052import org.onlab.onos.net.device.DeviceService;
Madan Jampani117aaae2014-10-23 10:04:05 -070053import org.onlab.onos.net.flow.CompletedBatchOperation;
alshabib1c319ff2014-10-04 20:29:09 -070054import org.onlab.onos.net.flow.DefaultFlowEntry;
55import org.onlab.onos.net.flow.FlowEntry;
56import org.onlab.onos.net.flow.FlowEntry.FlowEntryState;
Yuta HIGUCHI92891d12014-10-27 20:04:38 -070057import org.onlab.onos.net.flow.FlowId;
alshabib339a3d92014-09-26 17:54:32 -070058import org.onlab.onos.net.flow.FlowRule;
Madan Jampani117aaae2014-10-23 10:04:05 -070059import org.onlab.onos.net.flow.FlowRuleBatchEntry;
60import org.onlab.onos.net.flow.FlowRuleBatchEvent;
61import org.onlab.onos.net.flow.FlowRuleBatchOperation;
62import org.onlab.onos.net.flow.FlowRuleBatchRequest;
alshabib339a3d92014-09-26 17:54:32 -070063import org.onlab.onos.net.flow.FlowRuleEvent;
Madan Jampani117aaae2014-10-23 10:04:05 -070064import org.onlab.onos.net.flow.FlowRuleBatchEntry.FlowRuleOperation;
alshabib339a3d92014-09-26 17:54:32 -070065import org.onlab.onos.net.flow.FlowRuleEvent.Type;
66import org.onlab.onos.net.flow.FlowRuleStore;
67import org.onlab.onos.net.flow.FlowRuleStoreDelegate;
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -070068import org.onlab.onos.net.flow.StoredFlowEntry;
Madan Jampani38b250d2014-10-17 11:02:38 -070069import org.onlab.onos.store.cluster.messaging.ClusterCommunicationService;
70import org.onlab.onos.store.cluster.messaging.ClusterMessage;
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -070071import org.onlab.onos.store.cluster.messaging.ClusterMessageHandler;
Madan Jampani38b250d2014-10-17 11:02:38 -070072import org.onlab.onos.store.flow.ReplicaInfo;
Yuta HIGUCHI92891d12014-10-27 20:04:38 -070073import org.onlab.onos.store.flow.ReplicaInfoEvent;
74import org.onlab.onos.store.flow.ReplicaInfoEventListener;
Yuta HIGUCHIfe280eb2014-10-17 12:10:43 -070075import org.onlab.onos.store.flow.ReplicaInfoService;
Yuta HIGUCHI92891d12014-10-27 20:04:38 -070076import org.onlab.onos.store.hz.AbstractHazelcastStore;
77import org.onlab.onos.store.hz.SMap;
Yuta HIGUCHIea150152014-10-28 22:55:14 -070078import org.onlab.onos.store.serializers.DecodeTo;
Madan Jampani38b250d2014-10-17 11:02:38 -070079import org.onlab.onos.store.serializers.KryoSerializer;
Yuta HIGUCHIea150152014-10-28 22:55:14 -070080import org.onlab.onos.store.serializers.StoreSerializer;
Yuta HIGUCHI60a190b2014-11-07 16:24:47 -080081import org.onlab.onos.store.serializers.impl.DistributedStoreSerializers;
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -070082import org.onlab.util.KryoNamespace;
alshabib339a3d92014-09-26 17:54:32 -070083import org.slf4j.Logger;
84
Yuta HIGUCHIbf89c742014-10-27 15:10:02 -070085import com.google.common.cache.Cache;
86import com.google.common.cache.CacheBuilder;
Yuta HIGUCHI92891d12014-10-27 20:04:38 -070087import com.google.common.cache.CacheLoader;
88import com.google.common.cache.LoadingCache;
Yuta HIGUCHIf1ccee82014-11-11 20:39:58 -080089import com.google.common.cache.RemovalListener;
90import com.google.common.cache.RemovalNotification;
alshabib339a3d92014-09-26 17:54:32 -070091import com.google.common.collect.ArrayListMultimap;
Yuta HIGUCHI92891d12014-10-27 20:04:38 -070092import com.google.common.collect.ImmutableList;
alshabib339a3d92014-09-26 17:54:32 -070093import com.google.common.collect.ImmutableSet;
Yuta HIGUCHI9def0472014-10-23 15:51:10 -070094import com.google.common.collect.Iterables;
alshabib339a3d92014-09-26 17:54:32 -070095import com.google.common.collect.Multimap;
Madan Jampani117aaae2014-10-23 10:04:05 -070096import com.google.common.util.concurrent.Futures;
Yuta HIGUCHI9def0472014-10-23 15:51:10 -070097import com.google.common.util.concurrent.ListenableFuture;
98import com.google.common.util.concurrent.SettableFuture;
Yuta HIGUCHI92891d12014-10-27 20:04:38 -070099import com.hazelcast.core.IMap;
alshabib339a3d92014-09-26 17:54:32 -0700100
101/**
Madan Jampani38b250d2014-10-17 11:02:38 -0700102 * Manages inventory of flow rules using a distributed state management protocol.
alshabib339a3d92014-09-26 17:54:32 -0700103 */
alshabib339a3d92014-09-26 17:54:32 -0700104@Component(immediate = true)
105@Service
106public class DistributedFlowRuleStore
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700107 extends AbstractHazelcastStore<FlowRuleBatchEvent, FlowRuleStoreDelegate>
alshabib1c319ff2014-10-04 20:29:09 -0700108 implements FlowRuleStore {
alshabib339a3d92014-09-26 17:54:32 -0700109
110 private final Logger log = getLogger(getClass());
111
Yuta HIGUCHIe9b2b002014-11-04 12:25:47 -0800112 // primary data:
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800113 // read/write needs to be locked
114 private final ReentrantReadWriteLock flowEntriesLock = new ReentrantReadWriteLock();
alshabib339a3d92014-09-26 17:54:32 -0700115 // store entries as a pile of rules, no info about device tables
Yuta HIGUCHIe9b2b002014-11-04 12:25:47 -0800116 private final Multimap<DeviceId, StoredFlowEntry> flowEntries
117 = ArrayListMultimap.<DeviceId, StoredFlowEntry>create();
alshabib339a3d92014-09-26 17:54:32 -0700118
Madan Jampani38b250d2014-10-17 11:02:38 -0700119 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700120 protected ReplicaInfoService replicaInfoManager;
Madan Jampani38b250d2014-10-17 11:02:38 -0700121
122 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700123 protected ClusterCommunicationService clusterCommunicator;
Madan Jampani38b250d2014-10-17 11:02:38 -0700124
125 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700126 protected ClusterService clusterService;
127
128 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
129 protected DeviceService deviceService;
130
131 private final AtomicInteger localBatchIdGen = new AtomicInteger();
132
Yuta HIGUCHIbf89c742014-10-27 15:10:02 -0700133 // TODO: make this configurable
134 private int pendingFutureTimeoutMinutes = 5;
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700135
Yuta HIGUCHIbf89c742014-10-27 15:10:02 -0700136 private Cache<Integer, SettableFuture<CompletedBatchOperation>> pendingFutures =
137 CacheBuilder.newBuilder()
138 .expireAfterWrite(pendingFutureTimeoutMinutes, TimeUnit.MINUTES)
Yuta HIGUCHIf1ccee82014-11-11 20:39:58 -0800139 .removalListener(new TimeoutFuture())
Yuta HIGUCHIbf89c742014-10-27 15:10:02 -0700140 .build();
141
Yuta HIGUCHIe9b2b002014-11-04 12:25:47 -0800142 // Cache of SMaps used for backup data. each SMap contain device flow table
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700143 private LoadingCache<DeviceId, SMap<FlowId, ImmutableList<StoredFlowEntry>>> smaps;
144
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700145
146 private final ExecutorService futureListeners =
147 Executors.newCachedThreadPool(namedThreads("flowstore-peer-responders"));
148
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700149 private final ExecutorService backupExecutors =
150 Executors.newSingleThreadExecutor(namedThreads("async-backups"));
151
152 // TODO make this configurable
153 private boolean syncBackup = false;
Madan Jampani38b250d2014-10-17 11:02:38 -0700154
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700155 protected static final StoreSerializer SERIALIZER = new KryoSerializer() {
Madan Jampani38b250d2014-10-17 11:02:38 -0700156 @Override
157 protected void setupKryoPool() {
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -0700158 serializerPool = KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800159 .register(DistributedStoreSerializers.STORE_COMMON)
160 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
Yuta HIGUCHI2f158332014-11-25 13:32:06 -0800161 .register(FlowRuleEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800162 .build();
Madan Jampani38b250d2014-10-17 11:02:38 -0700163 }
164 };
165
166 // TODO: make this configurable
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700167 private static final long FLOW_RULE_STORE_TIMEOUT_MILLIS = 5000;
Madan Jampani38b250d2014-10-17 11:02:38 -0700168
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700169 private ReplicaInfoEventListener replicaInfoEventListener;
170
171 @Override
alshabib339a3d92014-09-26 17:54:32 -0700172 @Activate
173 public void activate() {
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700174
175 super.serializer = SERIALIZER;
176 super.theInstance = storeService.getHazelcastInstance();
177
178 // Cache to create SMap on demand
179 smaps = CacheBuilder.newBuilder()
180 .softValues()
181 .build(new SMapLoader());
182
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700183 final NodeId local = clusterService.getLocalNode().id();
184
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700185 clusterCommunicator.addSubscriber(APPLY_BATCH_FLOWS, new OnStoreBatch(local));
Madan Jampani117aaae2014-10-23 10:04:05 -0700186
187 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);
Madan Jampani117aaae2014-10-23 10:04:05 -0700193 FlowEntry flowEntry = getFlowEntryInternal(rule);
194 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());
Madan Jampanif5fdef02014-10-23 21:58:10 -0700208 Set<FlowEntry> flowEntries = getFlowEntriesInternal(deviceId);
209 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
Madan Jampani117aaae2014-10-23 10:04:05 -0700250 // TODO: This is not a efficient operation on a distributed sharded
251 // 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()) {
269 log.warn("No master for {}", rule);
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800270 // TODO: should we try returning from backup?
271 return null;
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700272 }
273
Madan Jampani117aaae2014-10-23 10:04:05 -0700274 if (replicaInfo.master().get().equals(clusterService.getLocalNode().id())) {
275 return getFlowEntryInternal(rule);
276 }
277
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800278 log.trace("Forwarding getFlowEntry to {}, which is the primary (master) for device {}",
Madan Jampani117aaae2014-10-23 10:04:05 -0700279 replicaInfo.master().orNull(), rule.deviceId());
280
281 ClusterMessage message = new ClusterMessage(
282 clusterService.getLocalNode().id(),
283 FlowStoreMessageSubjects.GET_FLOW_ENTRY,
284 SERIALIZER.encode(rule));
285
286 try {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700287 Future<byte[]> responseFuture = clusterCommunicator.sendAndReceive(message, replicaInfo.master().get());
288 return SERIALIZER.decode(responseFuture.get(FLOW_RULE_STORE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
289 } catch (IOException | TimeoutException | ExecutionException | InterruptedException e) {
Madan Jampani117aaae2014-10-23 10:04:05 -0700290 // FIXME: throw a FlowStoreException
291 throw new RuntimeException(e);
292 }
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700293 }
294
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800295 private StoredFlowEntry getFlowEntryInternal(FlowRule rule) {
296 flowEntriesLock.readLock().lock();
297 try {
298 for (StoredFlowEntry f : flowEntries.get(rule.deviceId())) {
299 if (f.equals(rule)) {
300 return f;
301 }
alshabib339a3d92014-09-26 17:54:32 -0700302 }
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800303 } finally {
304 flowEntriesLock.readLock().unlock();
alshabib339a3d92014-09-26 17:54:32 -0700305 }
306 return null;
307 }
308
309 @Override
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800310 public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) {
Madan Jampanif5fdef02014-10-23 21:58:10 -0700311
312 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(deviceId);
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700313
314 if (!replicaInfo.master().isPresent()) {
315 log.warn("No master for {}", deviceId);
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800316 // TODO: should we try returning from backup?
Yuta HIGUCHI2c1d8472014-10-31 14:13:38 -0700317 return Collections.emptyList();
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700318 }
319
Madan Jampanif5fdef02014-10-23 21:58:10 -0700320 if (replicaInfo.master().get().equals(clusterService.getLocalNode().id())) {
321 return getFlowEntriesInternal(deviceId);
322 }
323
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800324 log.trace("Forwarding getFlowEntries to {}, which is the primary (master) for device {}",
Madan Jampanif5fdef02014-10-23 21:58:10 -0700325 replicaInfo.master().orNull(), deviceId);
326
327 ClusterMessage message = new ClusterMessage(
328 clusterService.getLocalNode().id(),
329 GET_DEVICE_FLOW_ENTRIES,
330 SERIALIZER.encode(deviceId));
331
332 try {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700333 Future<byte[]> responseFuture = clusterCommunicator.sendAndReceive(message, replicaInfo.master().get());
334 return SERIALIZER.decode(responseFuture.get(FLOW_RULE_STORE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
335 } catch (IOException | TimeoutException | ExecutionException | InterruptedException e) {
Madan Jampanif5fdef02014-10-23 21:58:10 -0700336 // FIXME: throw a FlowStoreException
337 throw new RuntimeException(e);
338 }
339 }
340
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800341 private Set<FlowEntry> getFlowEntriesInternal(DeviceId deviceId) {
342 flowEntriesLock.readLock().lock();
343 try {
344 Collection<? extends FlowEntry> rules = flowEntries.get(deviceId);
345 if (rules == null) {
346 return Collections.emptySet();
347 }
348 return ImmutableSet.copyOf(rules);
349 } finally {
350 flowEntriesLock.readLock().unlock();
alshabib339a3d92014-09-26 17:54:32 -0700351 }
alshabib339a3d92014-09-26 17:54:32 -0700352 }
353
354 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700355 public void storeFlowRule(FlowRule rule) {
356 storeBatch(new FlowRuleBatchOperation(Arrays.asList(new FlowRuleBatchEntry(FlowRuleOperation.ADD, rule))));
357 }
358
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700359 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700360 public Future<CompletedBatchOperation> storeBatch(FlowRuleBatchOperation operation) {
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700361
Madan Jampani117aaae2014-10-23 10:04:05 -0700362 if (operation.getOperations().isEmpty()) {
Brian O'Connor427a1762014-11-19 18:40:32 -0800363 return Futures.immediateFuture(new CompletedBatchOperation(true,
364 Collections.<FlowRule>emptySet()));
alshabib339a3d92014-09-26 17:54:32 -0700365 }
Madan Jampani38b250d2014-10-17 11:02:38 -0700366
Madan Jampani117aaae2014-10-23 10:04:05 -0700367 DeviceId deviceId = operation.getOperations().get(0).getTarget().deviceId();
368
369 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(deviceId);
370
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700371 if (!replicaInfo.master().isPresent()) {
372 log.warn("No master for {}", deviceId);
373 // TODO: revisit if this should be "success" from Future point of view
374 // with every FlowEntry failed
375 return Futures.immediateFailedFuture(new IOException("No master to forward to"));
376 }
377
378 final NodeId local = clusterService.getLocalNode().id();
379 if (replicaInfo.master().get().equals(local)) {
Madan Jampani117aaae2014-10-23 10:04:05 -0700380 return storeBatchInternal(operation);
381 }
382
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800383 log.trace("Forwarding storeBatch to {}, which is the primary (master) for device {}",
Madan Jampani117aaae2014-10-23 10:04:05 -0700384 replicaInfo.master().orNull(), deviceId);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700385
Madan Jampani38b250d2014-10-17 11:02:38 -0700386 ClusterMessage message = new ClusterMessage(
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700387 local,
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700388 APPLY_BATCH_FLOWS,
Madan Jampani117aaae2014-10-23 10:04:05 -0700389 SERIALIZER.encode(operation));
Madan Jampani38b250d2014-10-17 11:02:38 -0700390
391 try {
Madan Jampani24f9efb2014-10-24 18:56:23 -0700392 ListenableFuture<byte[]> responseFuture =
393 clusterCommunicator.sendAndReceive(message, replicaInfo.master().get());
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700394 return Futures.transform(responseFuture, new DecodeTo<CompletedBatchOperation>(SERIALIZER));
Madan Jampani24f9efb2014-10-24 18:56:23 -0700395 } catch (IOException e) {
396 return Futures.immediateFailedFuture(e);
Madan Jampani38b250d2014-10-17 11:02:38 -0700397 }
398 }
399
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800400 private ListenableFuture<CompletedBatchOperation>
Yuta HIGUCHIe9b2b002014-11-04 12:25:47 -0800401 storeBatchInternal(FlowRuleBatchOperation operation) {
402
Brian O'Connor427a1762014-11-19 18:40:32 -0800403 final List<FlowRuleBatchEntry> toRemove = new ArrayList<>();
404 final List<FlowRuleBatchEntry> toAdd = new ArrayList<>();
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700405 DeviceId did = null;
406
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700407
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800408 flowEntriesLock.writeLock().lock();
409 try {
410 for (FlowRuleBatchEntry batchEntry : operation.getOperations()) {
411 FlowRule flowRule = batchEntry.getTarget();
412 FlowRuleOperation op = batchEntry.getOperator();
413 if (did == null) {
414 did = flowRule.deviceId();
415 }
416 if (op.equals(FlowRuleOperation.REMOVE)) {
417 StoredFlowEntry entry = getFlowEntryInternal(flowRule);
418 if (entry != null) {
419 entry.setState(FlowEntryState.PENDING_REMOVE);
Brian O'Connor427a1762014-11-19 18:40:32 -0800420 toRemove.add(batchEntry);
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800421 }
422 } else if (op.equals(FlowRuleOperation.ADD)) {
423 StoredFlowEntry flowEntry = new DefaultFlowEntry(flowRule);
424 DeviceId deviceId = flowRule.deviceId();
425 if (!flowEntries.containsEntry(deviceId, flowEntry)) {
426 flowEntries.put(deviceId, flowEntry);
Brian O'Connor427a1762014-11-19 18:40:32 -0800427 toAdd.add(batchEntry);
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800428 }
429 }
430 }
431 if (toAdd.isEmpty() && toRemove.isEmpty()) {
432 return Futures.immediateFuture(new CompletedBatchOperation(true, Collections.<FlowRule>emptySet()));
433 }
434
435 // create remote backup copies
436 updateBackup(did, toAdd, toRemove);
437 } finally {
438 flowEntriesLock.writeLock().unlock();
439 }
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700440
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700441 SettableFuture<CompletedBatchOperation> r = SettableFuture.create();
442 final int batchId = localBatchIdGen.incrementAndGet();
443
444 pendingFutures.put(batchId, r);
445 notifyDelegate(FlowRuleBatchEvent.requested(new FlowRuleBatchRequest(batchId, toAdd, toRemove)));
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700446
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700447 return r;
alshabib339a3d92014-09-26 17:54:32 -0700448 }
449
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700450 private void updateBackup(final DeviceId deviceId,
Brian O'Connor427a1762014-11-19 18:40:32 -0800451 final List<FlowRuleBatchEntry> toAdd,
452 final List<FlowRuleBatchEntry> list) {
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700453
454 Future<?> submit = backupExecutors.submit(new UpdateBackup(deviceId, toAdd, list));
455
456 if (syncBackup) {
457 // wait for backup to complete
458 try {
459 submit.get();
460 } catch (InterruptedException | ExecutionException e) {
461 log.error("Failed to create backups", e);
462 }
463 }
464 }
465
Brian O'Connor427a1762014-11-19 18:40:32 -0800466 private void updateBackup(DeviceId deviceId, List<FlowRuleBatchEntry> toAdd) {
467
468 updateBackup(deviceId, toAdd, Collections.<FlowRuleBatchEntry>emptyList());
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700469 }
470
alshabib339a3d92014-09-26 17:54:32 -0700471 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700472 public void deleteFlowRule(FlowRule rule) {
473 storeBatch(new FlowRuleBatchOperation(Arrays.asList(new FlowRuleBatchEntry(FlowRuleOperation.REMOVE, rule))));
alshabib339a3d92014-09-26 17:54:32 -0700474 }
475
476 @Override
Madan Jampani38b250d2014-10-17 11:02:38 -0700477 public FlowRuleEvent addOrUpdateFlowRule(FlowEntry rule) {
478 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(rule.deviceId());
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700479 final NodeId localId = clusterService.getLocalNode().id();
480 if (localId.equals(replicaInfo.master().orNull())) {
Madan Jampani38b250d2014-10-17 11:02:38 -0700481 return addOrUpdateFlowRuleInternal(rule);
482 }
483
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800484 log.warn("Tried to update FlowRule {} state,"
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700485 + " while the Node was not the master.", rule);
486 return null;
Madan Jampani38b250d2014-10-17 11:02:38 -0700487 }
488
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800489 private FlowRuleEvent addOrUpdateFlowRuleInternal(FlowEntry rule) {
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700490 final DeviceId did = rule.deviceId();
alshabib339a3d92014-09-26 17:54:32 -0700491
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800492 flowEntriesLock.writeLock().lock();
493 try {
494 // check if this new rule is an update to an existing entry
495 StoredFlowEntry stored = getFlowEntryInternal(rule);
496 if (stored != null) {
497 stored.setBytes(rule.bytes());
498 stored.setLife(rule.life());
499 stored.setPackets(rule.packets());
500 if (stored.state() == FlowEntryState.PENDING_ADD) {
501 stored.setState(FlowEntryState.ADDED);
Brian O'Connor427a1762014-11-19 18:40:32 -0800502 FlowRuleBatchEntry entry =
503 new FlowRuleBatchEntry(FlowRuleOperation.ADD, stored);
504 updateBackup(did, Arrays.asList(entry));
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800505 return new FlowRuleEvent(Type.RULE_ADDED, rule);
506 }
507 return new FlowRuleEvent(Type.RULE_UPDATED, rule);
alshabib1c319ff2014-10-04 20:29:09 -0700508 }
alshabib339a3d92014-09-26 17:54:32 -0700509
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800510 // TODO: Confirm if this behavior is correct. See SimpleFlowRuleStore
511 // TODO: also update backup.
512 flowEntries.put(did, new DefaultFlowEntry(rule));
513 } finally {
514 flowEntriesLock.writeLock().unlock();
515 }
alshabib1c319ff2014-10-04 20:29:09 -0700516 return null;
Madan Jampani38b250d2014-10-17 11:02:38 -0700517
alshabib339a3d92014-09-26 17:54:32 -0700518 }
519
520 @Override
Madan Jampani38b250d2014-10-17 11:02:38 -0700521 public FlowRuleEvent removeFlowRule(FlowEntry rule) {
Yuta HIGUCHIb6eb9142014-11-26 16:18:13 -0800522 final DeviceId deviceId = rule.deviceId();
523 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(deviceId);
Yuta HIGUCHI4b524442014-10-28 22:23:57 -0700524
525 final NodeId localId = clusterService.getLocalNode().id();
526 if (localId.equals(replicaInfo.master().orNull())) {
Madan Jampani38b250d2014-10-17 11:02:38 -0700527 // bypass and handle it locally
528 return removeFlowRuleInternal(rule);
529 }
530
Yuta HIGUCHIb6eb9142014-11-26 16:18:13 -0800531 if (!replicaInfo.master().isPresent()) {
532 log.warn("No master for {}", deviceId);
533 // TODO: revisit if this should be null (="no-op") or Exception
534 return null;
535 }
536
Yuta HIGUCHIdfa45c12014-11-24 18:38:53 -0800537 log.trace("Forwarding removeFlowRule to {}, which is the primary (master) for device {}",
Yuta HIGUCHIb6eb9142014-11-26 16:18:13 -0800538 replicaInfo.master().orNull(), deviceId);
Yuta HIGUCHIdfa45c12014-11-24 18:38:53 -0800539
540 ClusterMessage message = new ClusterMessage(
541 clusterService.getLocalNode().id(),
542 REMOVE_FLOW_ENTRY,
543 SERIALIZER.encode(rule));
544
545 try {
546 Future<byte[]> responseFuture = clusterCommunicator.sendAndReceive(message, replicaInfo.master().get());
547 return SERIALIZER.decode(responseFuture.get(FLOW_RULE_STORE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
548 } catch (IOException | TimeoutException | ExecutionException | InterruptedException e) {
549 // FIXME: throw a FlowStoreException
550 throw new RuntimeException(e);
551 }
Madan Jampani38b250d2014-10-17 11:02:38 -0700552 }
553
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800554 private FlowRuleEvent removeFlowRuleInternal(FlowEntry rule) {
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700555 final DeviceId deviceId = rule.deviceId();
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800556 flowEntriesLock.writeLock().lock();
557 try {
558 // This is where one could mark a rule as removed and still keep it in the store.
559 final boolean removed = flowEntries.remove(deviceId, rule);
Brian O'Connor427a1762014-11-19 18:40:32 -0800560 FlowRuleBatchEntry entry =
561 new FlowRuleBatchEntry(FlowRuleOperation.REMOVE, rule);
562 updateBackup(deviceId, Collections.<FlowRuleBatchEntry>emptyList(), Arrays.asList(entry));
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800563 if (removed) {
564 return new FlowRuleEvent(RULE_REMOVED, rule);
565 } else {
566 return null;
567 }
568 } finally {
569 flowEntriesLock.writeLock().unlock();
alshabib339a3d92014-09-26 17:54:32 -0700570 }
alshabib339a3d92014-09-26 17:54:32 -0700571 }
Madan Jampani117aaae2014-10-23 10:04:05 -0700572
573 @Override
574 public void batchOperationComplete(FlowRuleBatchEvent event) {
Yuta HIGUCHIbf89c742014-10-27 15:10:02 -0700575 final Integer batchId = event.subject().batchId();
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700576 SettableFuture<CompletedBatchOperation> future
Yuta HIGUCHIbf89c742014-10-27 15:10:02 -0700577 = pendingFutures.getIfPresent(batchId);
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700578 if (future != null) {
579 future.set(event.result());
Yuta HIGUCHIbf89c742014-10-27 15:10:02 -0700580 pendingFutures.invalidate(batchId);
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700581 }
Madan Jampani117aaae2014-10-23 10:04:05 -0700582 notifyDelegate(event);
583 }
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700584
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800585 private void loadFromBackup(final DeviceId did) {
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700586
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800587 flowEntriesLock.writeLock().lock();
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700588 try {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800589 log.debug("Loading FlowRules for {} from backups", did);
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700590 SMap<FlowId, ImmutableList<StoredFlowEntry>> backupFlowTable = smaps.get(did);
591 for (Entry<FlowId, ImmutableList<StoredFlowEntry>> e
592 : backupFlowTable.entrySet()) {
593
594 // TODO: should we be directly updating internal structure or
595 // should we be triggering event?
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800596 log.trace("loading {}", e.getValue());
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700597 for (StoredFlowEntry entry : e.getValue()) {
598 flowEntries.remove(did, entry);
599 flowEntries.put(did, entry);
600 }
601 }
602 } catch (ExecutionException e) {
603 log.error("Failed to load backup flowtable for {}", did, e);
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800604 } finally {
605 flowEntriesLock.writeLock().unlock();
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700606 }
607 }
608
Yuta HIGUCHI885868f2014-11-13 19:12:07 -0800609 private void removeFromPrimary(final DeviceId did) {
610 Collection<StoredFlowEntry> removed = null;
611 flowEntriesLock.writeLock().lock();
612 try {
613 removed = flowEntries.removeAll(did);
614 } finally {
615 flowEntriesLock.writeLock().unlock();
616 }
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800617 log.trace("removedFromPrimary {}", removed);
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700618 }
619
Yuta HIGUCHIf1ccee82014-11-11 20:39:58 -0800620 private static final class TimeoutFuture
621 implements RemovalListener<Integer, SettableFuture<CompletedBatchOperation>> {
622 @Override
623 public void onRemoval(RemovalNotification<Integer, SettableFuture<CompletedBatchOperation>> notification) {
624 // wrapping in ExecutionException to support Future.get
625 notification.getValue()
626 .setException(new ExecutionException("Timed out",
627 new TimeoutException()));
628 }
629 }
630
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700631 private final class OnStoreBatch implements ClusterMessageHandler {
632 private final NodeId local;
633
634 private OnStoreBatch(NodeId local) {
635 this.local = local;
636 }
637
638 @Override
639 public void handle(final ClusterMessage message) {
640 FlowRuleBatchOperation operation = SERIALIZER.decode(message.payload());
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800641 log.debug("received batch request {}", operation);
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700642
643 final DeviceId deviceId = operation.getOperations().get(0).getTarget().deviceId();
644 ReplicaInfo replicaInfo = replicaInfoManager.getReplicaInfoFor(deviceId);
645 if (!local.equals(replicaInfo.master().orNull())) {
646
647 Set<FlowRule> failures = new HashSet<>(operation.size());
648 for (FlowRuleBatchEntry op : operation.getOperations()) {
649 failures.add(op.getTarget());
650 }
651 CompletedBatchOperation allFailed = new CompletedBatchOperation(false, failures);
652 // This node is no longer the master, respond as all failed.
653 // TODO: we might want to wrap response in envelope
654 // to distinguish sw programming failure and hand over
655 // it make sense in the latter case to retry immediately.
656 try {
657 message.respond(SERIALIZER.encode(allFailed));
658 } catch (IOException e) {
659 log.error("Failed to respond back", e);
660 }
661 return;
662 }
663
664 final ListenableFuture<CompletedBatchOperation> f = storeBatchInternal(operation);
665
666 f.addListener(new Runnable() {
667
668 @Override
669 public void run() {
Yuta HIGUCHIf1ccee82014-11-11 20:39:58 -0800670 CompletedBatchOperation result;
671 try {
672 result = f.get();
673 } catch (InterruptedException | ExecutionException e) {
674 log.error("Batch operation failed", e);
675 // create everything failed response
676 Set<FlowRule> failures = new HashSet<>(operation.size());
677 for (FlowRuleBatchEntry op : operation.getOperations()) {
678 failures.add(op.getTarget());
679 }
680 result = new CompletedBatchOperation(false, failures);
681 }
Yuta HIGUCHIea150152014-10-28 22:55:14 -0700682 try {
683 message.respond(SERIALIZER.encode(result));
684 } catch (IOException e) {
685 log.error("Failed to respond back", e);
686 }
687 }
688 }, futureListeners);
689 }
690 }
691
Yuta HIGUCHI92891d12014-10-27 20:04:38 -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
703 private final class InternalReplicaInfoEventListener
704 implements ReplicaInfoEventListener {
705
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()) {
713 case MASTER_CHANGED:
714 if (local.equals(rInfo.master().orNull())) {
715 // This node is the new master, populate local structure
716 // from backup
717 loadFromBackup(did);
718 } else {
719 // This node is no longer the master holder,
720 // clean local structure
721 removeFromPrimary(did);
722 // FIXME: probably should stop pending backup activities in
723 // executors to avoid overwriting with old value
724 }
725 break;
726 default:
727 break;
728
729 }
730 }
731 }
732
733 // Task to update FlowEntries in backup HZ store
Brian O'Connor427a1762014-11-19 18:40:32 -0800734 // TODO: Should be refactored to contain only one list and not
735 // toAdd and toRemove
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700736 private final class UpdateBackup implements Runnable {
737
738 private final DeviceId deviceId;
Brian O'Connor427a1762014-11-19 18:40:32 -0800739 private final List<FlowRuleBatchEntry> toAdd;
740 private final List<FlowRuleBatchEntry> toRemove;
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700741
742 public UpdateBackup(DeviceId deviceId,
Brian O'Connor427a1762014-11-19 18:40:32 -0800743 List<FlowRuleBatchEntry> toAdd,
744 List<FlowRuleBatchEntry> list) {
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700745 this.deviceId = checkNotNull(deviceId);
746 this.toAdd = checkNotNull(toAdd);
747 this.toRemove = checkNotNull(list);
748 }
749
750 @Override
751 public void run() {
752 try {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -0800753 log.trace("update backup {} +{} -{}", deviceId, toAdd, toRemove);
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700754 final SMap<FlowId, ImmutableList<StoredFlowEntry>> backupFlowTable = smaps.get(deviceId);
755 // Following should be rewritten using async APIs
Brian O'Connor427a1762014-11-19 18:40:32 -0800756 for (FlowRuleBatchEntry bEntry : toAdd) {
757 final FlowRule entry = bEntry.getTarget();
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700758 final FlowId id = entry.id();
759 ImmutableList<StoredFlowEntry> original = backupFlowTable.get(id);
760 List<StoredFlowEntry> list = new ArrayList<>();
761 if (original != null) {
762 list.addAll(original);
763 }
764
Brian O'Connor427a1762014-11-19 18:40:32 -0800765 list.remove(bEntry.getTarget());
766 list.add((StoredFlowEntry) entry);
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700767
768 ImmutableList<StoredFlowEntry> newValue = ImmutableList.copyOf(list);
769 boolean success;
770 if (original == null) {
771 success = (backupFlowTable.putIfAbsent(id, newValue) == null);
772 } else {
773 success = backupFlowTable.replace(id, original, newValue);
774 }
775 // TODO retry?
776 if (!success) {
777 log.error("Updating backup failed.");
778 }
779 }
Brian O'Connor427a1762014-11-19 18:40:32 -0800780 for (FlowRuleBatchEntry bEntry : toRemove) {
781 final FlowRule entry = bEntry.getTarget();
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700782 final FlowId id = entry.id();
783 ImmutableList<StoredFlowEntry> original = backupFlowTable.get(id);
784 List<StoredFlowEntry> list = new ArrayList<>();
785 if (original != null) {
786 list.addAll(original);
787 }
788
Brian O'Connor427a1762014-11-19 18:40:32 -0800789 list.remove(bEntry.getTarget());
Yuta HIGUCHI92891d12014-10-27 20:04:38 -0700790
791 ImmutableList<StoredFlowEntry> newValue = ImmutableList.copyOf(list);
792 boolean success;
793 if (original == null) {
794 success = (backupFlowTable.putIfAbsent(id, newValue) == null);
795 } else {
796 success = backupFlowTable.replace(id, original, newValue);
797 }
798 // TODO retry?
799 if (!success) {
800 log.error("Updating backup failed.");
801 }
802 }
803 } catch (ExecutionException e) {
804 log.error("Failed to write to backups", e);
805 }
806
807 }
808 }
alshabib339a3d92014-09-26 17:54:32 -0700809}