Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2014-2015 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 | */ |
| 16 | package org.onosproject.store.flow.impl; |
| 17 | |
Brian O'Connor | a3e5cd5 | 2015-12-05 15:59:19 -0800 | [diff] [blame] | 18 | import com.google.common.collect.ImmutableList; |
| 19 | import com.google.common.collect.ImmutableMap; |
| 20 | import com.google.common.collect.Iterables; |
| 21 | import com.google.common.collect.Maps; |
| 22 | import com.google.common.collect.Sets; |
| 23 | import com.google.common.util.concurrent.Futures; |
| 24 | import org.apache.felix.scr.annotations.Activate; |
| 25 | import org.apache.felix.scr.annotations.Component; |
| 26 | import org.apache.felix.scr.annotations.Deactivate; |
| 27 | import org.apache.felix.scr.annotations.Modified; |
| 28 | import org.apache.felix.scr.annotations.Property; |
| 29 | import org.apache.felix.scr.annotations.Reference; |
| 30 | import org.apache.felix.scr.annotations.ReferenceCardinality; |
| 31 | import org.apache.felix.scr.annotations.Service; |
| 32 | import org.onlab.util.KryoNamespace; |
| 33 | import org.onlab.util.Tools; |
| 34 | import org.onosproject.cfg.ComponentConfigService; |
| 35 | import org.onosproject.cluster.ClusterService; |
| 36 | import org.onosproject.cluster.NodeId; |
| 37 | import org.onosproject.core.CoreService; |
| 38 | import org.onosproject.core.IdGenerator; |
| 39 | import org.onosproject.mastership.MastershipService; |
| 40 | import org.onosproject.net.DeviceId; |
| 41 | import org.onosproject.net.device.DeviceService; |
| 42 | import org.onosproject.net.flow.CompletedBatchOperation; |
| 43 | import org.onosproject.net.flow.DefaultFlowEntry; |
| 44 | import org.onosproject.net.flow.FlowEntry; |
| 45 | import org.onosproject.net.flow.FlowEntry.FlowEntryState; |
| 46 | import org.onosproject.net.flow.FlowId; |
| 47 | import org.onosproject.net.flow.FlowRule; |
| 48 | import org.onosproject.net.flow.FlowRuleBatchEntry; |
| 49 | import org.onosproject.net.flow.FlowRuleBatchEntry.FlowRuleOperation; |
| 50 | import org.onosproject.net.flow.FlowRuleBatchEvent; |
| 51 | import org.onosproject.net.flow.FlowRuleBatchOperation; |
| 52 | import org.onosproject.net.flow.FlowRuleBatchRequest; |
| 53 | import org.onosproject.net.flow.FlowRuleEvent; |
| 54 | import org.onosproject.net.flow.FlowRuleEvent.Type; |
| 55 | import org.onosproject.net.flow.FlowRuleService; |
| 56 | import org.onosproject.net.flow.FlowRuleStore; |
| 57 | import org.onosproject.net.flow.FlowRuleStoreDelegate; |
| 58 | import org.onosproject.net.flow.StoredFlowEntry; |
| 59 | import org.onosproject.net.flow.TableStatisticsEntry; |
| 60 | import org.onosproject.persistence.PersistenceService; |
| 61 | import org.onosproject.store.AbstractStore; |
| 62 | import org.onosproject.store.cluster.messaging.ClusterCommunicationService; |
| 63 | import org.onosproject.store.cluster.messaging.ClusterMessage; |
| 64 | import org.onosproject.store.cluster.messaging.ClusterMessageHandler; |
| 65 | import org.onosproject.store.flow.ReplicaInfoEvent; |
| 66 | import org.onosproject.store.flow.ReplicaInfoEventListener; |
| 67 | import org.onosproject.store.flow.ReplicaInfoService; |
| 68 | import org.onosproject.store.impl.MastershipBasedTimestamp; |
| 69 | import org.onosproject.store.serializers.KryoNamespaces; |
| 70 | import org.onosproject.store.serializers.KryoSerializer; |
| 71 | import org.onosproject.store.serializers.StoreSerializer; |
| 72 | import org.onosproject.store.serializers.custom.DistributedStoreSerializers; |
| 73 | import org.onosproject.store.service.EventuallyConsistentMap; |
| 74 | import org.onosproject.store.service.EventuallyConsistentMapEvent; |
| 75 | import org.onosproject.store.service.EventuallyConsistentMapListener; |
| 76 | import org.onosproject.store.service.Serializer; |
| 77 | import org.onosproject.store.service.StorageService; |
| 78 | import org.onosproject.store.service.WallClockTimestamp; |
| 79 | import org.osgi.service.component.ComponentContext; |
| 80 | import org.slf4j.Logger; |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 81 | |
Brian O'Connor | a3e5cd5 | 2015-12-05 15:59:19 -0800 | [diff] [blame] | 82 | import java.util.Collections; |
| 83 | import java.util.Dictionary; |
| 84 | import java.util.HashSet; |
| 85 | import java.util.List; |
| 86 | import java.util.Map; |
Sho SHIMIZU | 828bc16 | 2016-01-13 23:10:43 -0800 | [diff] [blame] | 87 | import java.util.Objects; |
Brian O'Connor | a3e5cd5 | 2015-12-05 15:59:19 -0800 | [diff] [blame] | 88 | import java.util.Set; |
| 89 | import java.util.concurrent.ExecutorService; |
| 90 | import java.util.concurrent.Executors; |
| 91 | import java.util.concurrent.ScheduledExecutorService; |
| 92 | import java.util.concurrent.ScheduledFuture; |
| 93 | import java.util.concurrent.TimeUnit; |
| 94 | import java.util.concurrent.atomic.AtomicInteger; |
| 95 | import java.util.concurrent.atomic.AtomicReference; |
| 96 | import java.util.stream.Collectors; |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 97 | |
Brian O'Connor | a3e5cd5 | 2015-12-05 15:59:19 -0800 | [diff] [blame] | 98 | import static com.google.common.base.Strings.isNullOrEmpty; |
| 99 | import static org.onlab.util.Tools.get; |
| 100 | import static org.onlab.util.Tools.groupedThreads; |
| 101 | import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_REMOVED; |
| 102 | import static org.onosproject.store.flow.impl.FlowStoreMessageSubjects.*; |
| 103 | import static org.slf4j.LoggerFactory.getLogger; |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 104 | |
| 105 | /** |
| 106 | * Manages inventory of flow rules using a distributed state management protocol. |
| 107 | */ |
| 108 | @Component(immediate = true, enabled = true) |
| 109 | @Service |
| 110 | public class NewDistributedFlowRuleStore |
| 111 | extends AbstractStore<FlowRuleBatchEvent, FlowRuleStoreDelegate> |
| 112 | implements FlowRuleStore { |
| 113 | |
| 114 | private final Logger log = getLogger(getClass()); |
| 115 | |
| 116 | private static final int MESSAGE_HANDLER_THREAD_POOL_SIZE = 8; |
| 117 | private static final boolean DEFAULT_BACKUP_ENABLED = true; |
Aaron Kruglikov | a62fdbb | 2015-10-27 16:32:06 -0700 | [diff] [blame] | 118 | private static final boolean DEFAULT_PERSISTENCE_ENABLED = false; |
Madan Jampani | 08bf17b | 2015-05-06 16:25:26 -0700 | [diff] [blame] | 119 | private static final int DEFAULT_BACKUP_PERIOD_MILLIS = 2000; |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 120 | private static final long FLOW_RULE_STORE_TIMEOUT_MILLIS = 5000; |
Madan Jampani | adea890 | 2015-06-04 17:39:45 -0700 | [diff] [blame] | 121 | // number of devices whose flow entries will be backed up in one communication round |
| 122 | private static final int FLOW_TABLE_BACKUP_BATCH_SIZE = 1; |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 123 | |
| 124 | @Property(name = "msgHandlerPoolSize", intValue = MESSAGE_HANDLER_THREAD_POOL_SIZE, |
| 125 | label = "Number of threads in the message handler pool") |
| 126 | private int msgHandlerPoolSize = MESSAGE_HANDLER_THREAD_POOL_SIZE; |
| 127 | |
| 128 | @Property(name = "backupEnabled", boolValue = DEFAULT_BACKUP_ENABLED, |
| 129 | label = "Indicates whether backups are enabled or not") |
| 130 | private boolean backupEnabled = DEFAULT_BACKUP_ENABLED; |
| 131 | |
Madan Jampani | 08bf17b | 2015-05-06 16:25:26 -0700 | [diff] [blame] | 132 | @Property(name = "backupPeriod", intValue = DEFAULT_BACKUP_PERIOD_MILLIS, |
| 133 | label = "Delay in ms between successive backup runs") |
| 134 | private int backupPeriod = DEFAULT_BACKUP_PERIOD_MILLIS; |
Aaron Kruglikov | a62fdbb | 2015-10-27 16:32:06 -0700 | [diff] [blame] | 135 | @Property(name = "persistenceEnabled", boolValue = false, |
| 136 | label = "Indicates whether or not changes in the flow table should be persisted to disk.") |
| 137 | private boolean persistenceEnabled = DEFAULT_PERSISTENCE_ENABLED; |
Madan Jampani | 08bf17b | 2015-05-06 16:25:26 -0700 | [diff] [blame] | 138 | |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 139 | private InternalFlowTable flowTable = new InternalFlowTable(); |
| 140 | |
| 141 | @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) |
| 142 | protected ReplicaInfoService replicaInfoManager; |
| 143 | |
| 144 | @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) |
| 145 | protected ClusterCommunicationService clusterCommunicator; |
| 146 | |
| 147 | @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) |
| 148 | protected ClusterService clusterService; |
| 149 | |
| 150 | @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) |
| 151 | protected DeviceService deviceService; |
| 152 | |
| 153 | @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) |
| 154 | protected CoreService coreService; |
| 155 | |
| 156 | @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) |
| 157 | protected ComponentConfigService configService; |
| 158 | |
| 159 | @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) |
| 160 | protected MastershipService mastershipService; |
| 161 | |
Aaron Kruglikov | a62fdbb | 2015-10-27 16:32:06 -0700 | [diff] [blame] | 162 | @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) |
| 163 | protected PersistenceService persistenceService; |
| 164 | |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 165 | private Map<Long, NodeId> pendingResponses = Maps.newConcurrentMap(); |
| 166 | private ExecutorService messageHandlingExecutor; |
| 167 | |
Madan Jampani | 08bf17b | 2015-05-06 16:25:26 -0700 | [diff] [blame] | 168 | private ScheduledFuture<?> backupTask; |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 169 | private final ScheduledExecutorService backupSenderExecutor = |
| 170 | Executors.newSingleThreadScheduledExecutor(groupedThreads("onos/flow", "backup-sender")); |
| 171 | |
Srikanth Vavilapalli | 95810f5 | 2015-09-14 15:49:56 -0700 | [diff] [blame] | 172 | private EventuallyConsistentMap<DeviceId, List<TableStatisticsEntry>> deviceTableStats; |
| 173 | private final EventuallyConsistentMapListener<DeviceId, List<TableStatisticsEntry>> tableStatsListener = |
| 174 | new InternalTableStatsListener(); |
| 175 | |
| 176 | @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) |
| 177 | protected StorageService storageService; |
| 178 | |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 179 | protected static final StoreSerializer SERIALIZER = new KryoSerializer() { |
| 180 | @Override |
| 181 | protected void setupKryoPool() { |
| 182 | serializerPool = KryoNamespace.newBuilder() |
| 183 | .register(DistributedStoreSerializers.STORE_COMMON) |
| 184 | .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN) |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 185 | .build(); |
| 186 | } |
| 187 | }; |
| 188 | |
Srikanth Vavilapalli | 95810f5 | 2015-09-14 15:49:56 -0700 | [diff] [blame] | 189 | protected static final KryoNamespace.Builder SERIALIZER_BUILDER = KryoNamespace.newBuilder() |
| 190 | .register(KryoNamespaces.API) |
| 191 | .register(MastershipBasedTimestamp.class); |
| 192 | |
| 193 | |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 194 | private IdGenerator idGenerator; |
| 195 | private NodeId local; |
| 196 | |
| 197 | @Activate |
| 198 | public void activate(ComponentContext context) { |
| 199 | configService.registerProperties(getClass()); |
| 200 | |
| 201 | idGenerator = coreService.getIdGenerator(FlowRuleService.FLOW_OP_TOPIC); |
| 202 | |
| 203 | local = clusterService.getLocalNode().id(); |
| 204 | |
| 205 | messageHandlingExecutor = Executors.newFixedThreadPool( |
| 206 | msgHandlerPoolSize, groupedThreads("onos/store/flow", "message-handlers")); |
| 207 | |
| 208 | registerMessageHandlers(messageHandlingExecutor); |
| 209 | |
Madan Jampani | 08bf17b | 2015-05-06 16:25:26 -0700 | [diff] [blame] | 210 | if (backupEnabled) { |
Madan Jampani | f7536ab | 2015-05-07 23:23:23 -0700 | [diff] [blame] | 211 | replicaInfoManager.addListener(flowTable); |
Madan Jampani | 08bf17b | 2015-05-06 16:25:26 -0700 | [diff] [blame] | 212 | backupTask = backupSenderExecutor.scheduleWithFixedDelay( |
| 213 | flowTable::backup, |
| 214 | 0, |
| 215 | backupPeriod, |
| 216 | TimeUnit.MILLISECONDS); |
| 217 | } |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 218 | |
Srikanth Vavilapalli | 95810f5 | 2015-09-14 15:49:56 -0700 | [diff] [blame] | 219 | deviceTableStats = storageService.<DeviceId, List<TableStatisticsEntry>>eventuallyConsistentMapBuilder() |
| 220 | .withName("onos-flow-table-stats") |
| 221 | .withSerializer(SERIALIZER_BUILDER) |
| 222 | .withAntiEntropyPeriod(5, TimeUnit.SECONDS) |
| 223 | .withTimestampProvider((k, v) -> new WallClockTimestamp()) |
| 224 | .withTombstonesDisabled() |
| 225 | .build(); |
| 226 | deviceTableStats.addListener(tableStatsListener); |
| 227 | |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 228 | logConfig("Started"); |
| 229 | } |
| 230 | |
| 231 | @Deactivate |
| 232 | public void deactivate(ComponentContext context) { |
Madan Jampani | f7536ab | 2015-05-07 23:23:23 -0700 | [diff] [blame] | 233 | if (backupEnabled) { |
| 234 | replicaInfoManager.removeListener(flowTable); |
| 235 | backupTask.cancel(true); |
| 236 | } |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 237 | configService.unregisterProperties(getClass(), false); |
| 238 | unregisterMessageHandlers(); |
Srikanth Vavilapalli | 95810f5 | 2015-09-14 15:49:56 -0700 | [diff] [blame] | 239 | deviceTableStats.removeListener(tableStatsListener); |
| 240 | deviceTableStats.destroy(); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 241 | messageHandlingExecutor.shutdownNow(); |
| 242 | backupSenderExecutor.shutdownNow(); |
| 243 | log.info("Stopped"); |
| 244 | } |
| 245 | |
| 246 | @SuppressWarnings("rawtypes") |
| 247 | @Modified |
| 248 | public void modified(ComponentContext context) { |
| 249 | if (context == null) { |
| 250 | backupEnabled = DEFAULT_BACKUP_ENABLED; |
| 251 | logConfig("Default config"); |
| 252 | return; |
| 253 | } |
| 254 | |
| 255 | Dictionary properties = context.getProperties(); |
| 256 | int newPoolSize; |
| 257 | boolean newBackupEnabled; |
Madan Jampani | 08bf17b | 2015-05-06 16:25:26 -0700 | [diff] [blame] | 258 | int newBackupPeriod; |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 259 | try { |
| 260 | String s = get(properties, "msgHandlerPoolSize"); |
| 261 | newPoolSize = isNullOrEmpty(s) ? msgHandlerPoolSize : Integer.parseInt(s.trim()); |
| 262 | |
| 263 | s = get(properties, "backupEnabled"); |
| 264 | newBackupEnabled = isNullOrEmpty(s) ? backupEnabled : Boolean.parseBoolean(s.trim()); |
| 265 | |
Madan Jampani | 08bf17b | 2015-05-06 16:25:26 -0700 | [diff] [blame] | 266 | s = get(properties, "backupPeriod"); |
| 267 | newBackupPeriod = isNullOrEmpty(s) ? backupPeriod : Integer.parseInt(s.trim()); |
| 268 | |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 269 | } catch (NumberFormatException | ClassCastException e) { |
| 270 | newPoolSize = MESSAGE_HANDLER_THREAD_POOL_SIZE; |
| 271 | newBackupEnabled = DEFAULT_BACKUP_ENABLED; |
Madan Jampani | 08bf17b | 2015-05-06 16:25:26 -0700 | [diff] [blame] | 272 | newBackupPeriod = DEFAULT_BACKUP_PERIOD_MILLIS; |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 273 | } |
| 274 | |
Madan Jampani | 08bf17b | 2015-05-06 16:25:26 -0700 | [diff] [blame] | 275 | boolean restartBackupTask = false; |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 276 | if (newBackupEnabled != backupEnabled) { |
| 277 | backupEnabled = newBackupEnabled; |
Madan Jampani | f7536ab | 2015-05-07 23:23:23 -0700 | [diff] [blame] | 278 | if (!backupEnabled) { |
| 279 | replicaInfoManager.removeListener(flowTable); |
| 280 | if (backupTask != null) { |
| 281 | backupTask.cancel(false); |
| 282 | backupTask = null; |
| 283 | } |
| 284 | } else { |
| 285 | replicaInfoManager.addListener(flowTable); |
Madan Jampani | 08bf17b | 2015-05-06 16:25:26 -0700 | [diff] [blame] | 286 | } |
| 287 | restartBackupTask = backupEnabled; |
| 288 | } |
| 289 | if (newBackupPeriod != backupPeriod) { |
| 290 | backupPeriod = newBackupPeriod; |
| 291 | restartBackupTask = backupEnabled; |
| 292 | } |
| 293 | if (restartBackupTask) { |
| 294 | if (backupTask != null) { |
| 295 | // cancel previously running task |
| 296 | backupTask.cancel(false); |
| 297 | } |
| 298 | backupTask = backupSenderExecutor.scheduleWithFixedDelay( |
| 299 | flowTable::backup, |
| 300 | 0, |
| 301 | backupPeriod, |
| 302 | TimeUnit.MILLISECONDS); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 303 | } |
| 304 | if (newPoolSize != msgHandlerPoolSize) { |
| 305 | msgHandlerPoolSize = newPoolSize; |
| 306 | ExecutorService oldMsgHandler = messageHandlingExecutor; |
| 307 | messageHandlingExecutor = Executors.newFixedThreadPool( |
| 308 | msgHandlerPoolSize, groupedThreads("onos/store/flow", "message-handlers")); |
| 309 | |
| 310 | // replace previously registered handlers. |
| 311 | registerMessageHandlers(messageHandlingExecutor); |
| 312 | oldMsgHandler.shutdown(); |
| 313 | } |
| 314 | logConfig("Reconfigured"); |
| 315 | } |
| 316 | |
| 317 | private void registerMessageHandlers(ExecutorService executor) { |
| 318 | |
| 319 | clusterCommunicator.addSubscriber(APPLY_BATCH_FLOWS, new OnStoreBatch(), executor); |
| 320 | clusterCommunicator.<FlowRuleBatchEvent>addSubscriber( |
| 321 | REMOTE_APPLY_COMPLETED, SERIALIZER::decode, this::notifyDelegate, executor); |
| 322 | clusterCommunicator.addSubscriber( |
| 323 | GET_FLOW_ENTRY, SERIALIZER::decode, flowTable::getFlowEntry, SERIALIZER::encode, executor); |
| 324 | clusterCommunicator.addSubscriber( |
| 325 | GET_DEVICE_FLOW_ENTRIES, SERIALIZER::decode, flowTable::getFlowEntries, SERIALIZER::encode, executor); |
| 326 | clusterCommunicator.addSubscriber( |
| 327 | REMOVE_FLOW_ENTRY, SERIALIZER::decode, this::removeFlowRuleInternal, SERIALIZER::encode, executor); |
| 328 | clusterCommunicator.addSubscriber( |
| 329 | REMOVE_FLOW_ENTRY, SERIALIZER::decode, this::removeFlowRuleInternal, SERIALIZER::encode, executor); |
| 330 | clusterCommunicator.addSubscriber( |
Madan Jampani | 654b58a | 2015-05-22 11:28:11 -0700 | [diff] [blame] | 331 | FLOW_TABLE_BACKUP, SERIALIZER::decode, flowTable::onBackupReceipt, SERIALIZER::encode, executor); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 332 | } |
| 333 | |
| 334 | private void unregisterMessageHandlers() { |
| 335 | clusterCommunicator.removeSubscriber(REMOVE_FLOW_ENTRY); |
| 336 | clusterCommunicator.removeSubscriber(GET_DEVICE_FLOW_ENTRIES); |
| 337 | clusterCommunicator.removeSubscriber(GET_FLOW_ENTRY); |
| 338 | clusterCommunicator.removeSubscriber(APPLY_BATCH_FLOWS); |
| 339 | clusterCommunicator.removeSubscriber(REMOTE_APPLY_COMPLETED); |
| 340 | clusterCommunicator.removeSubscriber(FLOW_TABLE_BACKUP); |
| 341 | } |
| 342 | |
| 343 | private void logConfig(String prefix) { |
Madan Jampani | 08bf17b | 2015-05-06 16:25:26 -0700 | [diff] [blame] | 344 | log.info("{} with msgHandlerPoolSize = {}; backupEnabled = {}, backupPeriod = {}", |
| 345 | prefix, msgHandlerPoolSize, backupEnabled, backupPeriod); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 346 | } |
| 347 | |
| 348 | // This is not a efficient operation on a distributed sharded |
| 349 | // flow store. We need to revisit the need for this operation or at least |
| 350 | // make it device specific. |
| 351 | @Override |
| 352 | public int getFlowRuleCount() { |
| 353 | AtomicInteger sum = new AtomicInteger(0); |
| 354 | deviceService.getDevices().forEach(device -> sum.addAndGet(Iterables.size(getFlowEntries(device.id())))); |
| 355 | return sum.get(); |
| 356 | } |
| 357 | |
| 358 | @Override |
| 359 | public FlowEntry getFlowEntry(FlowRule rule) { |
Madan Jampani | 6bd2d9f | 2015-05-14 14:10:42 -0700 | [diff] [blame] | 360 | NodeId master = mastershipService.getMasterFor(rule.deviceId()); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 361 | |
| 362 | if (master == null) { |
Thomas Vachuska | 88fd690 | 2015-08-04 10:08:34 -0700 | [diff] [blame] | 363 | log.debug("Failed to getFlowEntry: No master for {}", rule.deviceId()); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 364 | return null; |
| 365 | } |
| 366 | |
Sho SHIMIZU | 828bc16 | 2016-01-13 23:10:43 -0800 | [diff] [blame] | 367 | if (Objects.equals(local, master)) { |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 368 | return flowTable.getFlowEntry(rule); |
| 369 | } |
| 370 | |
| 371 | log.trace("Forwarding getFlowEntry to {}, which is the primary (master) for device {}", |
| 372 | master, rule.deviceId()); |
| 373 | |
| 374 | return Tools.futureGetOrElse(clusterCommunicator.sendAndReceive(rule, |
| 375 | FlowStoreMessageSubjects.GET_FLOW_ENTRY, |
| 376 | SERIALIZER::encode, |
| 377 | SERIALIZER::decode, |
| 378 | master), |
| 379 | FLOW_RULE_STORE_TIMEOUT_MILLIS, |
| 380 | TimeUnit.MILLISECONDS, |
| 381 | null); |
| 382 | } |
| 383 | |
| 384 | @Override |
| 385 | public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) { |
Madan Jampani | 6bd2d9f | 2015-05-14 14:10:42 -0700 | [diff] [blame] | 386 | NodeId master = mastershipService.getMasterFor(deviceId); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 387 | |
| 388 | if (master == null) { |
Thomas Vachuska | 88fd690 | 2015-08-04 10:08:34 -0700 | [diff] [blame] | 389 | log.debug("Failed to getFlowEntries: No master for {}", deviceId); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 390 | return Collections.emptyList(); |
| 391 | } |
| 392 | |
Sho SHIMIZU | 828bc16 | 2016-01-13 23:10:43 -0800 | [diff] [blame] | 393 | if (Objects.equals(local, master)) { |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 394 | return flowTable.getFlowEntries(deviceId); |
| 395 | } |
| 396 | |
| 397 | log.trace("Forwarding getFlowEntries to {}, which is the primary (master) for device {}", |
| 398 | master, deviceId); |
| 399 | |
| 400 | return Tools.futureGetOrElse(clusterCommunicator.sendAndReceive(deviceId, |
| 401 | FlowStoreMessageSubjects.GET_DEVICE_FLOW_ENTRIES, |
| 402 | SERIALIZER::encode, |
| 403 | SERIALIZER::decode, |
| 404 | master), |
| 405 | FLOW_RULE_STORE_TIMEOUT_MILLIS, |
| 406 | TimeUnit.MILLISECONDS, |
| 407 | Collections.emptyList()); |
| 408 | } |
| 409 | |
| 410 | @Override |
| 411 | public void storeFlowRule(FlowRule rule) { |
| 412 | storeBatch(new FlowRuleBatchOperation( |
Sho SHIMIZU | 98ffca8 | 2015-05-11 08:39:24 -0700 | [diff] [blame] | 413 | Collections.singletonList(new FlowRuleBatchEntry(FlowRuleOperation.ADD, rule)), |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 414 | rule.deviceId(), idGenerator.getNewId())); |
| 415 | } |
| 416 | |
| 417 | @Override |
| 418 | public void storeBatch(FlowRuleBatchOperation operation) { |
| 419 | if (operation.getOperations().isEmpty()) { |
| 420 | notifyDelegate(FlowRuleBatchEvent.completed( |
| 421 | new FlowRuleBatchRequest(operation.id(), Collections.emptySet()), |
| 422 | new CompletedBatchOperation(true, Collections.emptySet(), operation.deviceId()))); |
| 423 | return; |
| 424 | } |
| 425 | |
| 426 | DeviceId deviceId = operation.deviceId(); |
Madan Jampani | 6bd2d9f | 2015-05-14 14:10:42 -0700 | [diff] [blame] | 427 | NodeId master = mastershipService.getMasterFor(deviceId); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 428 | |
| 429 | if (master == null) { |
| 430 | log.warn("No master for {} : flows will be marked for removal", deviceId); |
| 431 | |
| 432 | updateStoreInternal(operation); |
| 433 | |
| 434 | notifyDelegate(FlowRuleBatchEvent.completed( |
| 435 | new FlowRuleBatchRequest(operation.id(), Collections.emptySet()), |
| 436 | new CompletedBatchOperation(true, Collections.emptySet(), operation.deviceId()))); |
| 437 | return; |
| 438 | } |
| 439 | |
Sho SHIMIZU | 828bc16 | 2016-01-13 23:10:43 -0800 | [diff] [blame] | 440 | if (Objects.equals(local, master)) { |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 441 | storeBatchInternal(operation); |
| 442 | return; |
| 443 | } |
| 444 | |
| 445 | log.trace("Forwarding storeBatch to {}, which is the primary (master) for device {}", |
| 446 | master, deviceId); |
| 447 | |
Madan Jampani | 175e8fd | 2015-05-20 14:10:45 -0700 | [diff] [blame] | 448 | clusterCommunicator.unicast(operation, |
| 449 | APPLY_BATCH_FLOWS, |
| 450 | SERIALIZER::encode, |
| 451 | master) |
| 452 | .whenComplete((result, error) -> { |
Thomas Vachuska | a267ce4 | 2015-05-27 16:14:23 -0700 | [diff] [blame] | 453 | if (error != null) { |
Madan Jampani | 15f1bc4 | 2015-05-28 10:51:52 -0700 | [diff] [blame] | 454 | log.warn("Failed to storeBatch: {} to {}", operation, master, error); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 455 | |
Thomas Vachuska | a267ce4 | 2015-05-27 16:14:23 -0700 | [diff] [blame] | 456 | Set<FlowRule> allFailures = operation.getOperations() |
| 457 | .stream() |
| 458 | .map(op -> op.target()) |
| 459 | .collect(Collectors.toSet()); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 460 | |
Thomas Vachuska | a267ce4 | 2015-05-27 16:14:23 -0700 | [diff] [blame] | 461 | notifyDelegate(FlowRuleBatchEvent.completed( |
| 462 | new FlowRuleBatchRequest(operation.id(), Collections.emptySet()), |
| 463 | new CompletedBatchOperation(false, allFailures, deviceId))); |
| 464 | } |
Madan Jampani | 175e8fd | 2015-05-20 14:10:45 -0700 | [diff] [blame] | 465 | }); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 466 | } |
| 467 | |
| 468 | private void storeBatchInternal(FlowRuleBatchOperation operation) { |
| 469 | |
| 470 | final DeviceId did = operation.deviceId(); |
| 471 | //final Collection<FlowEntry> ft = flowTable.getFlowEntries(did); |
| 472 | Set<FlowRuleBatchEntry> currentOps = updateStoreInternal(operation); |
| 473 | if (currentOps.isEmpty()) { |
| 474 | batchOperationComplete(FlowRuleBatchEvent.completed( |
| 475 | new FlowRuleBatchRequest(operation.id(), Collections.emptySet()), |
| 476 | new CompletedBatchOperation(true, Collections.emptySet(), did))); |
| 477 | return; |
| 478 | } |
| 479 | |
| 480 | notifyDelegate(FlowRuleBatchEvent.requested(new |
| 481 | FlowRuleBatchRequest(operation.id(), |
| 482 | currentOps), operation.deviceId())); |
| 483 | } |
| 484 | |
| 485 | private Set<FlowRuleBatchEntry> updateStoreInternal(FlowRuleBatchOperation operation) { |
| 486 | return operation.getOperations().stream().map( |
| 487 | op -> { |
| 488 | StoredFlowEntry entry; |
| 489 | switch (op.operator()) { |
| 490 | case ADD: |
| 491 | entry = new DefaultFlowEntry(op.target()); |
| 492 | // always add requested FlowRule |
| 493 | // Note: 2 equal FlowEntry may have different treatment |
| 494 | flowTable.remove(entry.deviceId(), entry); |
| 495 | flowTable.add(entry); |
| 496 | |
| 497 | return op; |
| 498 | case REMOVE: |
| 499 | entry = flowTable.getFlowEntry(op.target()); |
| 500 | if (entry != null) { |
Brian O'Connor | a3e5cd5 | 2015-12-05 15:59:19 -0800 | [diff] [blame] | 501 | //FIXME modification of "stored" flow entry outside of flow table |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 502 | entry.setState(FlowEntryState.PENDING_REMOVE); |
Brian O'Connor | a3e5cd5 | 2015-12-05 15:59:19 -0800 | [diff] [blame] | 503 | log.debug("Setting state of rule to pending remove: {}", entry); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 504 | return op; |
| 505 | } |
| 506 | break; |
| 507 | case MODIFY: |
| 508 | //TODO: figure this out at some point |
| 509 | break; |
| 510 | default: |
| 511 | log.warn("Unknown flow operation operator: {}", op.operator()); |
| 512 | } |
| 513 | return null; |
| 514 | } |
Sho SHIMIZU | 828bc16 | 2016-01-13 23:10:43 -0800 | [diff] [blame] | 515 | ).filter(Objects::nonNull).collect(Collectors.toSet()); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 516 | } |
| 517 | |
| 518 | @Override |
| 519 | public void deleteFlowRule(FlowRule rule) { |
| 520 | storeBatch( |
| 521 | new FlowRuleBatchOperation( |
Sho SHIMIZU | 98ffca8 | 2015-05-11 08:39:24 -0700 | [diff] [blame] | 522 | Collections.singletonList( |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 523 | new FlowRuleBatchEntry( |
| 524 | FlowRuleOperation.REMOVE, |
| 525 | rule)), rule.deviceId(), idGenerator.getNewId())); |
| 526 | } |
| 527 | |
| 528 | @Override |
| 529 | public FlowRuleEvent addOrUpdateFlowRule(FlowEntry rule) { |
Madan Jampani | 6bd2d9f | 2015-05-14 14:10:42 -0700 | [diff] [blame] | 530 | NodeId master = mastershipService.getMasterFor(rule.deviceId()); |
Sho SHIMIZU | 828bc16 | 2016-01-13 23:10:43 -0800 | [diff] [blame] | 531 | if (Objects.equals(local, master)) { |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 532 | return addOrUpdateFlowRuleInternal(rule); |
| 533 | } |
| 534 | |
| 535 | log.warn("Tried to update FlowRule {} state," |
| 536 | + " while the Node was not the master.", rule); |
| 537 | return null; |
| 538 | } |
| 539 | |
| 540 | private FlowRuleEvent addOrUpdateFlowRuleInternal(FlowEntry rule) { |
| 541 | // check if this new rule is an update to an existing entry |
| 542 | StoredFlowEntry stored = flowTable.getFlowEntry(rule); |
| 543 | if (stored != null) { |
Brian O'Connor | a3e5cd5 | 2015-12-05 15:59:19 -0800 | [diff] [blame] | 544 | //FIXME modification of "stored" flow entry outside of flow table |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 545 | stored.setBytes(rule.bytes()); |
| 546 | stored.setLife(rule.life()); |
| 547 | stored.setPackets(rule.packets()); |
Jonathan Hart | 89e981f | 2016-01-04 13:59:55 -0800 | [diff] [blame] | 548 | stored.setLastSeen(); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 549 | if (stored.state() == FlowEntryState.PENDING_ADD) { |
| 550 | stored.setState(FlowEntryState.ADDED); |
| 551 | return new FlowRuleEvent(Type.RULE_ADDED, rule); |
| 552 | } |
| 553 | return new FlowRuleEvent(Type.RULE_UPDATED, rule); |
| 554 | } |
| 555 | |
| 556 | // TODO: Confirm if this behavior is correct. See SimpleFlowRuleStore |
| 557 | // TODO: also update backup if the behavior is correct. |
| 558 | flowTable.add(rule); |
| 559 | return null; |
| 560 | } |
| 561 | |
| 562 | @Override |
| 563 | public FlowRuleEvent removeFlowRule(FlowEntry rule) { |
| 564 | final DeviceId deviceId = rule.deviceId(); |
Madan Jampani | 6bd2d9f | 2015-05-14 14:10:42 -0700 | [diff] [blame] | 565 | NodeId master = mastershipService.getMasterFor(deviceId); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 566 | |
Sho SHIMIZU | 828bc16 | 2016-01-13 23:10:43 -0800 | [diff] [blame] | 567 | if (Objects.equals(local, master)) { |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 568 | // bypass and handle it locally |
| 569 | return removeFlowRuleInternal(rule); |
| 570 | } |
| 571 | |
| 572 | if (master == null) { |
| 573 | log.warn("Failed to removeFlowRule: No master for {}", deviceId); |
| 574 | // TODO: revisit if this should be null (="no-op") or Exception |
| 575 | return null; |
| 576 | } |
| 577 | |
| 578 | log.trace("Forwarding removeFlowRule to {}, which is the master for device {}", |
| 579 | master, deviceId); |
| 580 | |
| 581 | return Futures.get(clusterCommunicator.sendAndReceive( |
| 582 | rule, |
| 583 | REMOVE_FLOW_ENTRY, |
| 584 | SERIALIZER::encode, |
| 585 | SERIALIZER::decode, |
| 586 | master), |
| 587 | FLOW_RULE_STORE_TIMEOUT_MILLIS, |
| 588 | TimeUnit.MILLISECONDS, |
| 589 | RuntimeException.class); |
| 590 | } |
| 591 | |
| 592 | private FlowRuleEvent removeFlowRuleInternal(FlowEntry rule) { |
| 593 | final DeviceId deviceId = rule.deviceId(); |
| 594 | // This is where one could mark a rule as removed and still keep it in the store. |
Brian O'Connor | a3e5cd5 | 2015-12-05 15:59:19 -0800 | [diff] [blame] | 595 | final FlowEntry removed = flowTable.remove(deviceId, rule); |
| 596 | // rule may be partial rule that is missing treatment, we should use rule from store instead |
| 597 | return removed != null ? new FlowRuleEvent(RULE_REMOVED, removed) : null; |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 598 | } |
| 599 | |
| 600 | @Override |
| 601 | public void batchOperationComplete(FlowRuleBatchEvent event) { |
| 602 | //FIXME: need a per device pending response |
| 603 | NodeId nodeId = pendingResponses.remove(event.subject().batchId()); |
| 604 | if (nodeId == null) { |
| 605 | notifyDelegate(event); |
| 606 | } else { |
| 607 | // TODO check unicast return value |
| 608 | clusterCommunicator.unicast(event, REMOTE_APPLY_COMPLETED, SERIALIZER::encode, nodeId); |
| 609 | //error log: log.warn("Failed to respond to peer for batch operation result"); |
| 610 | } |
| 611 | } |
| 612 | |
| 613 | private final class OnStoreBatch implements ClusterMessageHandler { |
| 614 | |
| 615 | @Override |
| 616 | public void handle(final ClusterMessage message) { |
| 617 | FlowRuleBatchOperation operation = SERIALIZER.decode(message.payload()); |
| 618 | log.debug("received batch request {}", operation); |
| 619 | |
| 620 | final DeviceId deviceId = operation.deviceId(); |
Madan Jampani | 6bd2d9f | 2015-05-14 14:10:42 -0700 | [diff] [blame] | 621 | NodeId master = mastershipService.getMasterFor(deviceId); |
Sho SHIMIZU | 828bc16 | 2016-01-13 23:10:43 -0800 | [diff] [blame] | 622 | if (!Objects.equals(local, master)) { |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 623 | Set<FlowRule> failures = new HashSet<>(operation.size()); |
| 624 | for (FlowRuleBatchEntry op : operation.getOperations()) { |
| 625 | failures.add(op.target()); |
| 626 | } |
| 627 | CompletedBatchOperation allFailed = new CompletedBatchOperation(false, failures, deviceId); |
| 628 | // This node is no longer the master, respond as all failed. |
| 629 | // TODO: we might want to wrap response in envelope |
| 630 | // to distinguish sw programming failure and hand over |
| 631 | // it make sense in the latter case to retry immediately. |
| 632 | message.respond(SERIALIZER.encode(allFailed)); |
| 633 | return; |
| 634 | } |
| 635 | |
| 636 | pendingResponses.put(operation.id(), message.sender()); |
| 637 | storeBatchInternal(operation); |
| 638 | } |
| 639 | } |
| 640 | |
Madan Jampani | f7536ab | 2015-05-07 23:23:23 -0700 | [diff] [blame] | 641 | private class InternalFlowTable implements ReplicaInfoEventListener { |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 642 | |
Brian O'Connor | a3e5cd5 | 2015-12-05 15:59:19 -0800 | [diff] [blame] | 643 | //TODO replace the Map<V,V> with ExtendedSet |
| 644 | private final Map<DeviceId, Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>> |
Madan Jampani | 5c3766c | 2015-06-02 15:54:41 -0700 | [diff] [blame] | 645 | flowEntries = Maps.newConcurrentMap(); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 646 | |
| 647 | private final Map<DeviceId, Long> lastBackupTimes = Maps.newConcurrentMap(); |
| 648 | private final Map<DeviceId, Long> lastUpdateTimes = Maps.newConcurrentMap(); |
| 649 | private final Map<DeviceId, NodeId> lastBackupNodes = Maps.newConcurrentMap(); |
| 650 | |
Madan Jampani | f7536ab | 2015-05-07 23:23:23 -0700 | [diff] [blame] | 651 | @Override |
| 652 | public void event(ReplicaInfoEvent event) { |
Madan Jampani | a98bf93 | 2015-06-02 12:01:36 -0700 | [diff] [blame] | 653 | if (!backupEnabled) { |
| 654 | return; |
| 655 | } |
Madan Jampani | f7536ab | 2015-05-07 23:23:23 -0700 | [diff] [blame] | 656 | if (event.type() == ReplicaInfoEvent.Type.BACKUPS_CHANGED) { |
| 657 | DeviceId deviceId = event.subject(); |
Madan Jampani | 6bd2d9f | 2015-05-14 14:10:42 -0700 | [diff] [blame] | 658 | NodeId master = mastershipService.getMasterFor(deviceId); |
Sho SHIMIZU | 828bc16 | 2016-01-13 23:10:43 -0800 | [diff] [blame] | 659 | if (!Objects.equals(local, master)) { |
Madan Jampani | f7536ab | 2015-05-07 23:23:23 -0700 | [diff] [blame] | 660 | // ignore since this event is for a device this node does not manage. |
| 661 | return; |
| 662 | } |
Madan Jampani | 7267c55 | 2015-05-20 22:39:17 -0700 | [diff] [blame] | 663 | NodeId newBackupNode = getBackupNode(deviceId); |
| 664 | NodeId currentBackupNode = lastBackupNodes.get(deviceId); |
Sho SHIMIZU | 828bc16 | 2016-01-13 23:10:43 -0800 | [diff] [blame] | 665 | if (Objects.equals(newBackupNode, currentBackupNode)) { |
Madan Jampani | f7536ab | 2015-05-07 23:23:23 -0700 | [diff] [blame] | 666 | // ignore since backup location hasn't changed. |
| 667 | return; |
| 668 | } |
Madan Jampani | 7267c55 | 2015-05-20 22:39:17 -0700 | [diff] [blame] | 669 | if (currentBackupNode != null && newBackupNode == null) { |
| 670 | // Current backup node is most likely down and no alternate backup node |
| 671 | // has been chosen. Clear current backup location so that we can resume |
| 672 | // backups when either current backup comes online or a different backup node |
| 673 | // is chosen. |
| 674 | log.warn("Lost backup location {} for deviceId {} and no alternate backup node exists. " |
| 675 | + "Flows can be lost if the master goes down", currentBackupNode, deviceId); |
| 676 | lastBackupNodes.remove(deviceId); |
| 677 | lastBackupTimes.remove(deviceId); |
| 678 | return; |
| 679 | // TODO: Pick any available node as backup and ensure hand-off occurs when |
| 680 | // a new master is elected. |
| 681 | } |
Madan Jampani | 44839b8 | 2015-06-12 13:57:41 -0700 | [diff] [blame] | 682 | log.debug("Backup location for {} has changed from {} to {}.", |
Madan Jampani | 7267c55 | 2015-05-20 22:39:17 -0700 | [diff] [blame] | 683 | deviceId, currentBackupNode, newBackupNode); |
| 684 | backupSenderExecutor.schedule(() -> backupFlowEntries(newBackupNode, Sets.newHashSet(deviceId)), |
Madan Jampani | 0306268 | 2015-05-19 17:57:51 -0700 | [diff] [blame] | 685 | 0, |
| 686 | TimeUnit.SECONDS); |
Madan Jampani | f7536ab | 2015-05-07 23:23:23 -0700 | [diff] [blame] | 687 | } |
| 688 | } |
| 689 | |
Madan Jampani | adea890 | 2015-06-04 17:39:45 -0700 | [diff] [blame] | 690 | private void sendBackups(NodeId nodeId, Set<DeviceId> deviceIds) { |
| 691 | // split up the devices into smaller batches and send them separately. |
| 692 | Iterables.partition(deviceIds, FLOW_TABLE_BACKUP_BATCH_SIZE) |
| 693 | .forEach(ids -> backupFlowEntries(nodeId, Sets.newHashSet(ids))); |
| 694 | } |
| 695 | |
Madan Jampani | f7536ab | 2015-05-07 23:23:23 -0700 | [diff] [blame] | 696 | private void backupFlowEntries(NodeId nodeId, Set<DeviceId> deviceIds) { |
Madan Jampani | adea890 | 2015-06-04 17:39:45 -0700 | [diff] [blame] | 697 | if (deviceIds.isEmpty()) { |
| 698 | return; |
| 699 | } |
Madan Jampani | f7536ab | 2015-05-07 23:23:23 -0700 | [diff] [blame] | 700 | log.debug("Sending flowEntries for devices {} to {} as backup.", deviceIds, nodeId); |
Brian O'Connor | a3e5cd5 | 2015-12-05 15:59:19 -0800 | [diff] [blame] | 701 | Map<DeviceId, Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>> |
| 702 | deviceFlowEntries = Maps.newConcurrentMap(); |
Madan Jampani | 85a9b0d | 2015-06-03 17:15:44 -0700 | [diff] [blame] | 703 | deviceIds.forEach(id -> deviceFlowEntries.put(id, ImmutableMap.copyOf(getFlowTable(id)))); |
Brian O'Connor | a3e5cd5 | 2015-12-05 15:59:19 -0800 | [diff] [blame] | 704 | clusterCommunicator.<Map<DeviceId, |
| 705 | Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>>, |
| 706 | Set<DeviceId>> |
| 707 | sendAndReceive(deviceFlowEntries, |
| 708 | FLOW_TABLE_BACKUP, |
| 709 | SERIALIZER::encode, |
| 710 | SERIALIZER::decode, |
| 711 | nodeId) |
| 712 | .whenComplete((backedupDevices, error) -> { |
| 713 | Set<DeviceId> devicesNotBackedup = error != null ? |
| 714 | deviceFlowEntries.keySet() : |
| 715 | Sets.difference(deviceFlowEntries.keySet(), backedupDevices); |
| 716 | if (devicesNotBackedup.size() > 0) { |
| 717 | log.warn("Failed to backup devices: {}. Reason: {}", |
| 718 | devicesNotBackedup, error.getMessage()); |
| 719 | } |
| 720 | if (backedupDevices != null) { |
| 721 | backedupDevices.forEach(id -> { |
| 722 | lastBackupTimes.put(id, System.currentTimeMillis()); |
| 723 | lastBackupNodes.put(id, nodeId); |
| 724 | }); |
| 725 | } |
| 726 | }); |
Madan Jampani | f7536ab | 2015-05-07 23:23:23 -0700 | [diff] [blame] | 727 | } |
| 728 | |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 729 | /** |
| 730 | * Returns the flow table for specified device. |
| 731 | * |
| 732 | * @param deviceId identifier of the device |
| 733 | * @return Map representing Flow Table of given device. |
| 734 | */ |
Brian O'Connor | a3e5cd5 | 2015-12-05 15:59:19 -0800 | [diff] [blame] | 735 | private Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> getFlowTable(DeviceId deviceId) { |
Aaron Kruglikov | a62fdbb | 2015-10-27 16:32:06 -0700 | [diff] [blame] | 736 | if (persistenceEnabled) { |
| 737 | return flowEntries.computeIfAbsent(deviceId, id -> persistenceService |
Brian O'Connor | a3e5cd5 | 2015-12-05 15:59:19 -0800 | [diff] [blame] | 738 | .<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>persistentMapBuilder() |
Aaron Kruglikov | a62fdbb | 2015-10-27 16:32:06 -0700 | [diff] [blame] | 739 | .withName("FlowTable:" + deviceId.toString()) |
| 740 | .withSerializer(new Serializer() { |
| 741 | @Override |
| 742 | public <T> byte[] encode(T object) { |
| 743 | return SERIALIZER.encode(object); |
| 744 | } |
| 745 | |
| 746 | @Override |
| 747 | public <T> T decode(byte[] bytes) { |
| 748 | return SERIALIZER.decode(bytes); |
| 749 | } |
| 750 | }) |
| 751 | .build()); |
| 752 | } else { |
| 753 | return flowEntries.computeIfAbsent(deviceId, id -> Maps.newConcurrentMap()); |
| 754 | } |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 755 | } |
| 756 | |
Brian O'Connor | a3e5cd5 | 2015-12-05 15:59:19 -0800 | [diff] [blame] | 757 | private Map<StoredFlowEntry, StoredFlowEntry> getFlowEntriesInternal(DeviceId deviceId, FlowId flowId) { |
| 758 | return getFlowTable(deviceId).computeIfAbsent(flowId, id -> Maps.newConcurrentMap()); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 759 | } |
| 760 | |
| 761 | private StoredFlowEntry getFlowEntryInternal(FlowRule rule) { |
Brian O'Connor | a3e5cd5 | 2015-12-05 15:59:19 -0800 | [diff] [blame] | 762 | return getFlowEntriesInternal(rule.deviceId(), rule.id()).get(rule); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 763 | } |
| 764 | |
| 765 | private Set<FlowEntry> getFlowEntriesInternal(DeviceId deviceId) { |
Brian O'Connor | a3e5cd5 | 2015-12-05 15:59:19 -0800 | [diff] [blame] | 766 | return getFlowTable(deviceId).values().stream() |
| 767 | .flatMap(m -> m.values().stream()) |
| 768 | .collect(Collectors.toSet()); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 769 | } |
| 770 | |
| 771 | public StoredFlowEntry getFlowEntry(FlowRule rule) { |
| 772 | return getFlowEntryInternal(rule); |
| 773 | } |
| 774 | |
| 775 | public Set<FlowEntry> getFlowEntries(DeviceId deviceId) { |
| 776 | return getFlowEntriesInternal(deviceId); |
| 777 | } |
| 778 | |
| 779 | public void add(FlowEntry rule) { |
Brian O'Connor | a3e5cd5 | 2015-12-05 15:59:19 -0800 | [diff] [blame] | 780 | getFlowEntriesInternal(rule.deviceId(), rule.id()) |
| 781 | .compute((StoredFlowEntry) rule, (k, stored) -> { |
| 782 | //TODO compare stored and rule timestamps |
| 783 | //TODO the key is not updated |
| 784 | return (StoredFlowEntry) rule; |
| 785 | }); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 786 | lastUpdateTimes.put(rule.deviceId(), System.currentTimeMillis()); |
| 787 | } |
| 788 | |
Brian O'Connor | a3e5cd5 | 2015-12-05 15:59:19 -0800 | [diff] [blame] | 789 | public FlowEntry remove(DeviceId deviceId, FlowEntry rule) { |
| 790 | final AtomicReference<FlowEntry> removedRule = new AtomicReference<>(); |
| 791 | getFlowEntriesInternal(rule.deviceId(), rule.id()) |
| 792 | .computeIfPresent((StoredFlowEntry) rule, (k, stored) -> { |
| 793 | if (rule instanceof DefaultFlowEntry) { |
| 794 | DefaultFlowEntry toRemove = (DefaultFlowEntry) rule; |
| 795 | if (stored instanceof DefaultFlowEntry) { |
| 796 | DefaultFlowEntry storedEntry = (DefaultFlowEntry) stored; |
| 797 | if (toRemove.created() < storedEntry.created()) { |
| 798 | log.debug("Trying to remove more recent flow entry {} (stored: {})", |
| 799 | toRemove, stored); |
| 800 | // the key is not updated, removedRule remains null |
| 801 | return stored; |
| 802 | } |
| 803 | } |
| 804 | } |
| 805 | removedRule.set(stored); |
| 806 | return null; |
| 807 | }); |
| 808 | |
| 809 | if (removedRule.get() != null) { |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 810 | lastUpdateTimes.put(deviceId, System.currentTimeMillis()); |
Brian O'Connor | a3e5cd5 | 2015-12-05 15:59:19 -0800 | [diff] [blame] | 811 | return removedRule.get(); |
| 812 | } else { |
| 813 | return null; |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 814 | } |
| 815 | } |
| 816 | |
| 817 | private NodeId getBackupNode(DeviceId deviceId) { |
| 818 | List<NodeId> deviceStandbys = replicaInfoManager.getReplicaInfoFor(deviceId).backups(); |
| 819 | // pick the standby which is most likely to become next master |
| 820 | return deviceStandbys.isEmpty() ? null : deviceStandbys.get(0); |
| 821 | } |
| 822 | |
| 823 | private void backup() { |
Madan Jampani | 08bf17b | 2015-05-06 16:25:26 -0700 | [diff] [blame] | 824 | if (!backupEnabled) { |
| 825 | return; |
| 826 | } |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 827 | try { |
| 828 | // determine the set of devices that we need to backup during this run. |
| 829 | Set<DeviceId> devicesToBackup = mastershipService.getDevicesOf(local) |
| 830 | .stream() |
| 831 | .filter(deviceId -> { |
| 832 | Long lastBackupTime = lastBackupTimes.get(deviceId); |
| 833 | Long lastUpdateTime = lastUpdateTimes.get(deviceId); |
| 834 | NodeId lastBackupNode = lastBackupNodes.get(deviceId); |
Madan Jampani | 7267c55 | 2015-05-20 22:39:17 -0700 | [diff] [blame] | 835 | NodeId newBackupNode = getBackupNode(deviceId); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 836 | return lastBackupTime == null |
Sho SHIMIZU | 828bc16 | 2016-01-13 23:10:43 -0800 | [diff] [blame] | 837 | || !Objects.equals(lastBackupNode, newBackupNode) |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 838 | || (lastUpdateTime != null && lastUpdateTime > lastBackupTime); |
| 839 | }) |
| 840 | .collect(Collectors.toSet()); |
| 841 | |
| 842 | // compute a mapping from node to the set of devices whose flow entries it should backup |
| 843 | Map<NodeId, Set<DeviceId>> devicesToBackupByNode = Maps.newHashMap(); |
| 844 | devicesToBackup.forEach(deviceId -> { |
| 845 | NodeId backupLocation = getBackupNode(deviceId); |
| 846 | if (backupLocation != null) { |
| 847 | devicesToBackupByNode.computeIfAbsent(backupLocation, nodeId -> Sets.newHashSet()) |
| 848 | .add(deviceId); |
| 849 | } |
| 850 | }); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 851 | // send the device flow entries to their respective backup nodes |
Madan Jampani | adea890 | 2015-06-04 17:39:45 -0700 | [diff] [blame] | 852 | devicesToBackupByNode.forEach(this::sendBackups); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 853 | } catch (Exception e) { |
| 854 | log.error("Backup failed.", e); |
| 855 | } |
| 856 | } |
| 857 | |
Brian O'Connor | a3e5cd5 | 2015-12-05 15:59:19 -0800 | [diff] [blame] | 858 | private Set<DeviceId> onBackupReceipt(Map<DeviceId, |
| 859 | Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>>> flowTables) { |
Madan Jampani | 7267c55 | 2015-05-20 22:39:17 -0700 | [diff] [blame] | 860 | log.debug("Received flowEntries for {} to backup", flowTables.keySet()); |
Madan Jampani | 654b58a | 2015-05-22 11:28:11 -0700 | [diff] [blame] | 861 | Set<DeviceId> backedupDevices = Sets.newHashSet(); |
| 862 | try { |
Madan Jampani | a98bf93 | 2015-06-02 12:01:36 -0700 | [diff] [blame] | 863 | flowTables.forEach((deviceId, deviceFlowTable) -> { |
| 864 | // Only process those devices are that not managed by the local node. |
Sho SHIMIZU | 828bc16 | 2016-01-13 23:10:43 -0800 | [diff] [blame] | 865 | if (!Objects.equals(local, mastershipService.getMasterFor(deviceId))) { |
Brian O'Connor | a3e5cd5 | 2015-12-05 15:59:19 -0800 | [diff] [blame] | 866 | Map<FlowId, Map<StoredFlowEntry, StoredFlowEntry>> backupFlowTable = |
| 867 | getFlowTable(deviceId); |
Madan Jampani | a98bf93 | 2015-06-02 12:01:36 -0700 | [diff] [blame] | 868 | backupFlowTable.clear(); |
| 869 | backupFlowTable.putAll(deviceFlowTable); |
| 870 | backedupDevices.add(deviceId); |
| 871 | } |
Madan Jampani | 08bf17b | 2015-05-06 16:25:26 -0700 | [diff] [blame] | 872 | }); |
Madan Jampani | 654b58a | 2015-05-22 11:28:11 -0700 | [diff] [blame] | 873 | } catch (Exception e) { |
| 874 | log.warn("Failure processing backup request", e); |
| 875 | } |
| 876 | return backedupDevices; |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 877 | } |
| 878 | } |
Srikanth Vavilapalli | 95810f5 | 2015-09-14 15:49:56 -0700 | [diff] [blame] | 879 | |
| 880 | @Override |
| 881 | public FlowRuleEvent updateTableStatistics(DeviceId deviceId, |
| 882 | List<TableStatisticsEntry> tableStats) { |
| 883 | deviceTableStats.put(deviceId, tableStats); |
| 884 | return null; |
| 885 | } |
| 886 | |
| 887 | @Override |
| 888 | public Iterable<TableStatisticsEntry> getTableStatistics(DeviceId deviceId) { |
| 889 | NodeId master = mastershipService.getMasterFor(deviceId); |
| 890 | |
| 891 | if (master == null) { |
| 892 | log.debug("Failed to getTableStats: No master for {}", deviceId); |
| 893 | return Collections.emptyList(); |
| 894 | } |
| 895 | |
| 896 | List<TableStatisticsEntry> tableStats = deviceTableStats.get(deviceId); |
| 897 | if (tableStats == null) { |
| 898 | return Collections.emptyList(); |
| 899 | } |
| 900 | return ImmutableList.copyOf(tableStats); |
| 901 | } |
| 902 | |
| 903 | private class InternalTableStatsListener |
| 904 | implements EventuallyConsistentMapListener<DeviceId, List<TableStatisticsEntry>> { |
| 905 | @Override |
| 906 | public void event(EventuallyConsistentMapEvent<DeviceId, |
| 907 | List<TableStatisticsEntry>> event) { |
| 908 | //TODO: Generate an event to listeners (do we need?) |
| 909 | } |
| 910 | } |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 911 | } |