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