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