Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 1 | /* |
Brian O'Connor | a09fe5b | 2017-08-03 21:12:30 -0700 | [diff] [blame] | 2 | * Copyright 2014-present Open Networking Foundation |
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 | |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 18 | import com.google.common.collect.ImmutableList; |
| 19 | import com.google.common.collect.Iterables; |
| 20 | import com.google.common.collect.Maps; |
| 21 | import com.google.common.collect.Sets; |
Yuta HIGUCHI | baaf8dc | 2017-06-21 17:44:09 -0700 | [diff] [blame] | 22 | import com.google.common.collect.Streams; |
Yuta HIGUCHI | baaf8dc | 2017-06-21 17:44:09 -0700 | [diff] [blame] | 23 | import org.onlab.util.KryoNamespace; |
| 24 | import org.onlab.util.Tools; |
Yuta HIGUCHI | baaf8dc | 2017-06-21 17:44:09 -0700 | [diff] [blame] | 25 | import org.onosproject.cluster.ClusterService; |
| 26 | import org.onosproject.cluster.NodeId; |
| 27 | import org.onosproject.core.CoreService; |
| 28 | import org.onosproject.core.IdGenerator; |
| 29 | import org.onosproject.mastership.MastershipService; |
| 30 | import org.onosproject.net.DeviceId; |
| 31 | import org.onosproject.net.device.DeviceService; |
| 32 | import org.onosproject.net.flow.CompletedBatchOperation; |
| 33 | import org.onosproject.net.flow.DefaultFlowEntry; |
| 34 | import org.onosproject.net.flow.FlowEntry; |
| 35 | import org.onosproject.net.flow.FlowEntry.FlowEntryState; |
| 36 | import org.onosproject.net.flow.FlowId; |
| 37 | import org.onosproject.net.flow.FlowRule; |
Yuta HIGUCHI | baaf8dc | 2017-06-21 17:44:09 -0700 | [diff] [blame] | 38 | import org.onosproject.net.flow.FlowRuleEvent; |
| 39 | import org.onosproject.net.flow.FlowRuleEvent.Type; |
| 40 | import org.onosproject.net.flow.FlowRuleService; |
| 41 | import org.onosproject.net.flow.FlowRuleStore; |
| 42 | import org.onosproject.net.flow.FlowRuleStoreDelegate; |
| 43 | import org.onosproject.net.flow.StoredFlowEntry; |
| 44 | import org.onosproject.net.flow.TableStatisticsEntry; |
Ray Milkey | d84f89b | 2018-08-17 14:54:17 -0700 | [diff] [blame] | 45 | import org.onosproject.net.flow.oldbatch.FlowRuleBatchEntry; |
| 46 | import org.onosproject.net.flow.oldbatch.FlowRuleBatchEntry.FlowRuleOperation; |
| 47 | import org.onosproject.net.flow.oldbatch.FlowRuleBatchEvent; |
| 48 | import org.onosproject.net.flow.oldbatch.FlowRuleBatchOperation; |
| 49 | import org.onosproject.net.flow.oldbatch.FlowRuleBatchRequest; |
Yuta HIGUCHI | baaf8dc | 2017-06-21 17:44:09 -0700 | [diff] [blame] | 50 | import org.onosproject.store.AbstractStore; |
| 51 | import org.onosproject.store.cluster.messaging.ClusterCommunicationService; |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 52 | import org.onosproject.store.cluster.messaging.MessageSubject; |
Yuta HIGUCHI | baaf8dc | 2017-06-21 17:44:09 -0700 | [diff] [blame] | 53 | import org.onosproject.store.impl.MastershipBasedTimestamp; |
| 54 | import org.onosproject.store.serializers.KryoNamespaces; |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 55 | import org.onosproject.store.service.AsyncDocumentTree; |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 56 | import org.onosproject.store.service.DocumentPath; |
| 57 | import org.onosproject.store.service.DocumentTree; |
Yuta HIGUCHI | baaf8dc | 2017-06-21 17:44:09 -0700 | [diff] [blame] | 58 | import org.onosproject.store.service.EventuallyConsistentMap; |
| 59 | import org.onosproject.store.service.EventuallyConsistentMapEvent; |
| 60 | import org.onosproject.store.service.EventuallyConsistentMapListener; |
Jordan Halterman | f5295f6 | 2017-09-12 15:07:18 -0700 | [diff] [blame] | 61 | import org.onosproject.store.service.IllegalDocumentModificationException; |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 62 | import org.onosproject.store.service.NoSuchDocumentPathException; |
Yuta HIGUCHI | baaf8dc | 2017-06-21 17:44:09 -0700 | [diff] [blame] | 63 | import org.onosproject.store.service.Serializer; |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 64 | import org.onosproject.store.service.StorageException; |
Yuta HIGUCHI | baaf8dc | 2017-06-21 17:44:09 -0700 | [diff] [blame] | 65 | import org.onosproject.store.service.StorageService; |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 66 | import org.onosproject.store.service.Versioned; |
Yuta HIGUCHI | baaf8dc | 2017-06-21 17:44:09 -0700 | [diff] [blame] | 67 | import org.onosproject.store.service.WallClockTimestamp; |
Ray Milkey | d84f89b | 2018-08-17 14:54:17 -0700 | [diff] [blame] | 68 | import org.osgi.service.component.annotations.Activate; |
| 69 | import org.osgi.service.component.annotations.Component; |
| 70 | import org.osgi.service.component.annotations.Deactivate; |
| 71 | import org.osgi.service.component.annotations.Reference; |
| 72 | import org.osgi.service.component.annotations.ReferenceCardinality; |
Yuta HIGUCHI | baaf8dc | 2017-06-21 17:44:09 -0700 | [diff] [blame] | 73 | import org.slf4j.Logger; |
Ray Milkey | 2b6ff42 | 2016-08-26 13:03:15 -0700 | [diff] [blame] | 74 | |
Ray Milkey | d84f89b | 2018-08-17 14:54:17 -0700 | [diff] [blame] | 75 | import java.security.SecureRandom; |
| 76 | import java.util.Collections; |
| 77 | import java.util.List; |
| 78 | import java.util.Map; |
| 79 | import java.util.Objects; |
| 80 | import java.util.Random; |
| 81 | import java.util.Set; |
| 82 | import java.util.concurrent.CompletableFuture; |
| 83 | import java.util.concurrent.ExecutorService; |
| 84 | import java.util.concurrent.Executors; |
| 85 | import java.util.concurrent.ScheduledExecutorService; |
| 86 | import java.util.concurrent.TimeUnit; |
| 87 | import java.util.function.Supplier; |
| 88 | import java.util.stream.Collectors; |
| 89 | |
Yuta HIGUCHI | baaf8dc | 2017-06-21 17:44:09 -0700 | [diff] [blame] | 90 | import static org.onlab.util.Tools.groupedThreads; |
| 91 | import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_REMOVED; |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 92 | import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_UPDATED; |
Yuta HIGUCHI | baaf8dc | 2017-06-21 17:44:09 -0700 | [diff] [blame] | 93 | import static org.slf4j.LoggerFactory.getLogger; |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 94 | |
| 95 | /** |
| 96 | * Manages inventory of flow rules using a distributed state management protocol. |
Ray Milkey | ed9bace | 2018-03-20 10:05:56 -0700 | [diff] [blame] | 97 | * |
| 98 | * @deprecated in Nightingale Release (1.13) |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 99 | */ |
Ray Milkey | ed9bace | 2018-03-20 10:05:56 -0700 | [diff] [blame] | 100 | @Deprecated |
Ray Milkey | d84f89b | 2018-08-17 14:54:17 -0700 | [diff] [blame] | 101 | @Component(enabled = false, service = FlowRuleStore.class) |
Madan Jampani | 37d04c6 | 2016-04-25 15:53:55 -0700 | [diff] [blame] | 102 | public class DistributedFlowRuleStore |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 103 | extends AbstractStore<FlowRuleBatchEvent, FlowRuleStoreDelegate> |
| 104 | implements FlowRuleStore { |
| 105 | |
| 106 | private final Logger log = getLogger(getClass()); |
| 107 | |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 108 | // Constant exception used to indicate an atomic read-modify-write operation needs to be retried. |
| 109 | // We don't want to populate a stack trace every time an optimistic lock is retried. |
| 110 | private static final StorageException.ConcurrentModification RETRY; |
| 111 | |
| 112 | // Initialize retry exception with an empty stack trace. |
| 113 | static { |
| 114 | RETRY = new StorageException.ConcurrentModification(); |
| 115 | RETRY.setStackTrace(new StackTraceElement[0]); |
| 116 | } |
| 117 | |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 118 | private static final int SCHEDULED_THREAD_POOL_SIZE = 8; |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 119 | private static final int MESSAGE_HANDLER_THREAD_POOL_SIZE = 8; |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 120 | private static final int MAX_RETRY_DELAY_MILLIS = 50; |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 121 | |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 122 | private static final String FLOW_TABLE = "onos-flow-table"; |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 123 | |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 124 | private static final MessageSubject APPLY_BATCH_FLOWS = new MessageSubject("onos-flow-apply"); |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 125 | private static final MessageSubject COMPLETE_BATCH = new MessageSubject("onos-flow-batch-complete"); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 126 | |
Ray Milkey | d84f89b | 2018-08-17 14:54:17 -0700 | [diff] [blame] | 127 | @Reference(cardinality = ReferenceCardinality.MANDATORY) |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 128 | protected DeviceService deviceService; |
| 129 | |
Ray Milkey | d84f89b | 2018-08-17 14:54:17 -0700 | [diff] [blame] | 130 | @Reference(cardinality = ReferenceCardinality.MANDATORY) |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 131 | protected CoreService coreService; |
| 132 | |
Ray Milkey | d84f89b | 2018-08-17 14:54:17 -0700 | [diff] [blame] | 133 | @Reference(cardinality = ReferenceCardinality.MANDATORY) |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 134 | protected MastershipService mastershipService; |
| 135 | |
Ray Milkey | d84f89b | 2018-08-17 14:54:17 -0700 | [diff] [blame] | 136 | @Reference(cardinality = ReferenceCardinality.MANDATORY) |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 137 | protected ClusterCommunicationService clusterCommunicator; |
Aaron Kruglikov | a62fdbb | 2015-10-27 16:32:06 -0700 | [diff] [blame] | 138 | |
Ray Milkey | d84f89b | 2018-08-17 14:54:17 -0700 | [diff] [blame] | 139 | @Reference(cardinality = ReferenceCardinality.MANDATORY) |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 140 | protected ClusterService clusterService; |
Srikanth Vavilapalli | 95810f5 | 2015-09-14 15:49:56 -0700 | [diff] [blame] | 141 | |
Ray Milkey | d84f89b | 2018-08-17 14:54:17 -0700 | [diff] [blame] | 142 | @Reference(cardinality = ReferenceCardinality.MANDATORY) |
Srikanth Vavilapalli | 95810f5 | 2015-09-14 15:49:56 -0700 | [diff] [blame] | 143 | protected StorageService storageService; |
| 144 | |
Madan Jampani | 884d443 | 2016-08-23 10:46:55 -0700 | [diff] [blame] | 145 | protected final Serializer serializer = Serializer.using(KryoNamespaces.API); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 146 | |
Madan Jampani | 884d443 | 2016-08-23 10:46:55 -0700 | [diff] [blame] | 147 | protected final KryoNamespace.Builder serializerBuilder = KryoNamespace.newBuilder() |
Srikanth Vavilapalli | 95810f5 | 2015-09-14 15:49:56 -0700 | [diff] [blame] | 148 | .register(KryoNamespaces.API) |
| 149 | .register(MastershipBasedTimestamp.class); |
| 150 | |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 151 | private EventuallyConsistentMap<DeviceId, List<TableStatisticsEntry>> deviceTableStats; |
| 152 | private final EventuallyConsistentMapListener<DeviceId, List<TableStatisticsEntry>> tableStatsListener = |
| 153 | new InternalTableStatsListener(); |
Srikanth Vavilapalli | 95810f5 | 2015-09-14 15:49:56 -0700 | [diff] [blame] | 154 | |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 155 | private Set<Long> pendingBatches = Sets.newConcurrentHashSet(); |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 156 | private ScheduledExecutorService scheduledExecutor; |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 157 | private ExecutorService messageHandlingExecutor; |
Ray Milkey | b68bbbc | 2017-12-18 10:05:49 -0800 | [diff] [blame] | 158 | private final Random random = new SecureRandom(); |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 159 | |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 160 | private AsyncDocumentTree<Map<StoredFlowEntry, StoredFlowEntry>> asyncFlows; |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 161 | private DocumentTree<Map<StoredFlowEntry, StoredFlowEntry>> flows; |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 162 | private IdGenerator idGenerator; |
| 163 | private NodeId local; |
| 164 | |
| 165 | @Activate |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 166 | public void activate() { |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 167 | idGenerator = coreService.getIdGenerator(FlowRuleService.FLOW_OP_TOPIC); |
| 168 | |
| 169 | local = clusterService.getLocalNode().id(); |
| 170 | |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 171 | scheduledExecutor = Executors.newScheduledThreadPool( |
| 172 | SCHEDULED_THREAD_POOL_SIZE, |
| 173 | groupedThreads("onos/store/flow", "schedulers", log)); |
| 174 | |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 175 | messageHandlingExecutor = Executors.newFixedThreadPool( |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 176 | MESSAGE_HANDLER_THREAD_POOL_SIZE, |
| 177 | groupedThreads("onos/store/flow", "message-handlers", log)); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 178 | |
Srikanth Vavilapalli | 95810f5 | 2015-09-14 15:49:56 -0700 | [diff] [blame] | 179 | deviceTableStats = storageService.<DeviceId, List<TableStatisticsEntry>>eventuallyConsistentMapBuilder() |
| 180 | .withName("onos-flow-table-stats") |
Madan Jampani | 884d443 | 2016-08-23 10:46:55 -0700 | [diff] [blame] | 181 | .withSerializer(serializerBuilder) |
Srikanth Vavilapalli | 95810f5 | 2015-09-14 15:49:56 -0700 | [diff] [blame] | 182 | .withAntiEntropyPeriod(5, TimeUnit.SECONDS) |
| 183 | .withTimestampProvider((k, v) -> new WallClockTimestamp()) |
| 184 | .withTombstonesDisabled() |
| 185 | .build(); |
| 186 | deviceTableStats.addListener(tableStatsListener); |
| 187 | |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 188 | asyncFlows = storageService.<Map<StoredFlowEntry, StoredFlowEntry>>documentTreeBuilder() |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 189 | .withName(FLOW_TABLE) |
| 190 | .withSerializer(serializer) |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 191 | .buildDocumentTree(); |
| 192 | flows = asyncFlows.asDocumentTree(); |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 193 | |
| 194 | clusterCommunicator.addSubscriber( |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 195 | APPLY_BATCH_FLOWS, |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 196 | serializer::decode, |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 197 | this::applyBatchFlows, |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 198 | messageHandlingExecutor); |
| 199 | clusterCommunicator.addSubscriber( |
| 200 | COMPLETE_BATCH, |
| 201 | serializer::decode, |
| 202 | this::completeBatch, |
| 203 | messageHandlingExecutor); |
| 204 | |
| 205 | log.info("Started"); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 206 | } |
| 207 | |
| 208 | @Deactivate |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 209 | public void deactivate() { |
Srikanth Vavilapalli | 95810f5 | 2015-09-14 15:49:56 -0700 | [diff] [blame] | 210 | deviceTableStats.removeListener(tableStatsListener); |
| 211 | deviceTableStats.destroy(); |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 212 | clusterCommunicator.removeSubscriber(APPLY_BATCH_FLOWS); |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 213 | clusterCommunicator.removeSubscriber(COMPLETE_BATCH); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 214 | messageHandlingExecutor.shutdownNow(); |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 215 | scheduledExecutor.shutdownNow(); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 216 | log.info("Stopped"); |
| 217 | } |
| 218 | |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 219 | /** |
| 220 | * Retries the given supplier until successful. |
| 221 | * <p> |
| 222 | * This method retries the given supplier until no {@code ConcurrentModification} exceptions are thrown. In |
| 223 | * between retries, it waits a semi-random interval to attempt to avoid transaction conflicts with other processes. |
| 224 | * |
| 225 | * @param supplier the supplier to retry |
| 226 | * @param <T> the return type |
| 227 | * @return the return value of the given supplier once it runs successfully |
| 228 | */ |
| 229 | private <T> T retryUntilSuccess(Supplier<T> supplier) { |
| 230 | return Tools.retryable( |
| 231 | supplier, |
| 232 | StorageException.ConcurrentModification.class, |
| 233 | Integer.MAX_VALUE, |
| 234 | MAX_RETRY_DELAY_MILLIS) |
| 235 | .get(); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 236 | } |
| 237 | |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 238 | /** |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 239 | * Retries the given asynchronous supplier until successful. |
| 240 | * <p> |
| 241 | * This method retries the given supplier until no {@code ConcurrentModification} exceptions are thrown. In |
| 242 | * between retries, it waits a semi-random interval to attempt to avoid transaction conflicts with other processes. |
| 243 | * |
| 244 | * @param supplier the supplier to retry |
| 245 | * @param <T> the return type |
| 246 | * @return the return value of the given supplier once it runs successfully |
| 247 | */ |
| 248 | private <T> CompletableFuture<T> retryAsyncUntilSuccess(Supplier<CompletableFuture<T>> supplier) { |
| 249 | return retryAsyncUntilSuccess(supplier, new CompletableFuture<>()); |
| 250 | } |
| 251 | |
| 252 | /** |
| 253 | * Retries the given asynchronous supplier until successful. |
| 254 | * <p> |
| 255 | * This method retries the given supplier until no {@code ConcurrentModification} exceptions are thrown. In |
| 256 | * between retries, it waits a semi-random interval to attempt to avoid transaction conflicts with other processes. |
| 257 | * |
| 258 | * @param supplier the supplier to retry |
| 259 | * @param future future to be completed once the operation has been successful |
| 260 | * @param <T> the return type |
| 261 | * @return the return value of the given supplier once it runs successfully |
| 262 | */ |
| 263 | private <T> CompletableFuture<T> retryAsyncUntilSuccess( |
| 264 | Supplier<CompletableFuture<T>> supplier, |
| 265 | CompletableFuture<T> future) { |
| 266 | supplier.get().whenComplete((result, error) -> { |
| 267 | if (error == null) { |
| 268 | future.complete(result); |
| 269 | } else { |
| 270 | Throwable cause = error.getCause() != null ? error.getCause() : error; |
| 271 | if (cause instanceof StorageException.ConcurrentModification) { |
| 272 | scheduledExecutor.schedule( |
| 273 | () -> retryAsyncUntilSuccess(supplier, future), |
| 274 | random.nextInt(50), |
| 275 | TimeUnit.MILLISECONDS); |
| 276 | } else { |
| 277 | future.completeExceptionally(error); |
| 278 | } |
| 279 | } |
| 280 | }); |
| 281 | return future; |
| 282 | } |
| 283 | |
| 284 | /** |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 285 | * Return method for {@link #retryUntilSuccess(Supplier)} callbacks to indicate that the callback needs to be |
| 286 | * retried after a randomized delay. |
| 287 | * |
| 288 | * @param <T> the return type |
| 289 | * @return nothing |
| 290 | * @throws StorageException.ConcurrentModification to force a retry of the callback |
| 291 | */ |
| 292 | private <T> T retry() { |
| 293 | throw RETRY; |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 294 | } |
| 295 | |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 296 | /** |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 297 | * Handles a completed batch event received from the master node. |
| 298 | * <p> |
| 299 | * If this node is the source of the batch, notifies event listeners to complete the operations. |
| 300 | * |
| 301 | * @param event the event to handle |
| 302 | */ |
| 303 | private void completeBatch(FlowRuleBatchEvent event) { |
| 304 | if (pendingBatches.remove(event.subject().batchId())) { |
| 305 | notifyDelegate(event); |
| 306 | } |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 307 | } |
| 308 | |
| 309 | // This is not a efficient operation on a distributed sharded |
| 310 | // flow store. We need to revisit the need for this operation or at least |
| 311 | // make it device specific. |
| 312 | @Override |
| 313 | public int getFlowRuleCount() { |
Yuta HIGUCHI | 10e91fb | 2017-06-15 13:30:50 -0700 | [diff] [blame] | 314 | return Streams.stream(deviceService.getDevices()).parallel() |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 315 | .mapToInt(device -> Iterables.size(getFlowEntries(device.id()))) |
| 316 | .sum(); |
| 317 | } |
| 318 | |
| 319 | /** |
| 320 | * Returns the {@link DocumentPath} for the given {@link DeviceId}. |
| 321 | * |
| 322 | * @param deviceId the device identifier for which to return a path |
| 323 | * @return the path for the given device |
| 324 | */ |
| 325 | private DocumentPath getPathFor(DeviceId deviceId) { |
| 326 | return DocumentPath.from("root", deviceId.toString()); |
| 327 | } |
| 328 | |
| 329 | /** |
| 330 | * Returns the {@link DocumentPath} for the given {@link DeviceId} and {@link FlowId}. |
| 331 | * |
| 332 | * @param deviceId the device identifier for which to return the path |
| 333 | * @param flowId the flow identifier for which to return the path |
| 334 | * @return the path for the given device/flow |
| 335 | */ |
| 336 | private DocumentPath getPathFor(DeviceId deviceId, FlowId flowId) { |
| 337 | return DocumentPath.from("root", deviceId.toString(), flowId.toString()); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 338 | } |
| 339 | |
| 340 | @Override |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 341 | @SuppressWarnings("unchecked") |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 342 | public FlowEntry getFlowEntry(FlowRule rule) { |
Deepa Vaddireddy | 2e85cfc | 2017-11-07 12:58:00 +0000 | [diff] [blame] | 343 | DeviceId deviceId = rule.deviceId(); |
| 344 | if (mastershipService.getMasterFor(deviceId) != null) { |
| 345 | DocumentPath path = getPathFor(deviceId, rule.id()); |
| 346 | Versioned<Map<StoredFlowEntry, StoredFlowEntry>> flowEntries = flows.get(path); |
| 347 | return flowEntries != null ? flowEntries.value().get(rule) : null; |
| 348 | } else { |
| 349 | log.debug("Failed to getFlowEntries: No master for {}", deviceId); |
| 350 | return null; |
| 351 | } |
| 352 | |
| 353 | |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 354 | } |
| 355 | |
| 356 | @Override |
| 357 | public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) { |
Deepa Vaddireddy | 2e85cfc | 2017-11-07 12:58:00 +0000 | [diff] [blame] | 358 | if (mastershipService.getMasterFor(deviceId) != null) { |
| 359 | DocumentPath path = getPathFor(deviceId); |
| 360 | try { |
| 361 | return getFlowEntries(path); |
| 362 | } catch (NoSuchDocumentPathException e) { |
| 363 | return Collections.emptyList(); |
| 364 | } |
| 365 | } else { |
| 366 | log.debug("Failed to getFlowEntries: No master for {}", deviceId); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 367 | return Collections.emptyList(); |
| 368 | } |
Deepa Vaddireddy | 2e85cfc | 2017-11-07 12:58:00 +0000 | [diff] [blame] | 369 | |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 370 | } |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 371 | |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 372 | @SuppressWarnings("unchecked") |
| 373 | private Iterable<FlowEntry> getFlowEntries(DocumentPath path) { |
| 374 | return flows.getChildren(path) |
| 375 | .values() |
| 376 | .stream() |
| 377 | .flatMap(v -> v.value().values().stream()) |
| 378 | .collect(Collectors.toList()); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 379 | } |
| 380 | |
| 381 | @Override |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 382 | @SuppressWarnings("unchecked") |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 383 | public void storeFlowRule(FlowRule rule) { |
| 384 | storeBatch(new FlowRuleBatchOperation( |
Sho SHIMIZU | 98ffca8 | 2015-05-11 08:39:24 -0700 | [diff] [blame] | 385 | Collections.singletonList(new FlowRuleBatchEntry(FlowRuleOperation.ADD, rule)), |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 386 | rule.deviceId(), idGenerator.getNewId())); |
| 387 | } |
| 388 | |
| 389 | @Override |
| 390 | public void storeBatch(FlowRuleBatchOperation operation) { |
| 391 | if (operation.getOperations().isEmpty()) { |
| 392 | notifyDelegate(FlowRuleBatchEvent.completed( |
| 393 | new FlowRuleBatchRequest(operation.id(), Collections.emptySet()), |
| 394 | new CompletedBatchOperation(true, Collections.emptySet(), operation.deviceId()))); |
| 395 | return; |
| 396 | } |
| 397 | |
| 398 | DeviceId deviceId = operation.deviceId(); |
Madan Jampani | 6bd2d9f | 2015-05-14 14:10:42 -0700 | [diff] [blame] | 399 | NodeId master = mastershipService.getMasterFor(deviceId); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 400 | |
| 401 | if (master == null) { |
Sivachidambaram Subramanian | 605104e | 2017-06-21 07:40:04 +0530 | [diff] [blame] | 402 | log.warn("No master for {} ", deviceId); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 403 | |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 404 | updateStoreInternal(operation).whenComplete((result, error) -> { |
| 405 | notifyDelegate(FlowRuleBatchEvent.completed( |
| 406 | new FlowRuleBatchRequest(operation.id(), Collections.emptySet()), |
| 407 | new CompletedBatchOperation(true, Collections.emptySet(), operation.deviceId()))); |
| 408 | }); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 409 | return; |
| 410 | } |
| 411 | |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 412 | pendingBatches.add(operation.id()); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 413 | |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 414 | // If the local node is the master, apply the flows. Otherwise, send them to the master. |
| 415 | if (Objects.equals(local, master)) { |
| 416 | applyBatchFlows(operation); |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 417 | } else { |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 418 | log.trace("Forwarding storeBatch to {}, which is the primary (master) for device {}", master, deviceId); |
| 419 | clusterCommunicator.unicast( |
| 420 | operation, |
| 421 | APPLY_BATCH_FLOWS, |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 422 | serializer::encode, |
| 423 | master); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 424 | } |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 425 | } |
| 426 | |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 427 | /** |
| 428 | * Asynchronously applies a batch of flows to the store. |
| 429 | * <p> |
| 430 | * This operation is performed on the master node to ensure that events occur <em>after</em> flows have been stored |
| 431 | * and are visible to the master node. If a non-master node stores flows and then triggers events on the master, |
| 432 | * the flows may not yet be visible to the master node due to the nature of sequentially consistent reads on the |
| 433 | * underlying {@code DocumentTree} primitive. |
| 434 | */ |
| 435 | private void applyBatchFlows(FlowRuleBatchOperation operation) { |
| 436 | updateStoreInternal(operation).whenComplete((operations, error) -> { |
| 437 | if (error == null) { |
| 438 | if (operations.isEmpty()) { |
| 439 | batchOperationComplete(FlowRuleBatchEvent.completed( |
| 440 | new FlowRuleBatchRequest(operation.id(), Collections.emptySet()), |
| 441 | new CompletedBatchOperation(true, Collections.emptySet(), operation.deviceId()))); |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 442 | } else { |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 443 | notifyDelegate(FlowRuleBatchEvent.requested( |
| 444 | new FlowRuleBatchRequest(operation.id(), operations), |
| 445 | operation.deviceId())); |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 446 | } |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 447 | } |
| 448 | }); |
| 449 | } |
| 450 | |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 451 | private CompletableFuture<Set<FlowRuleBatchEntry>> updateStoreInternal(FlowRuleBatchOperation operation) { |
| 452 | return Tools.allOf(operation.getOperations().stream().map(op -> { |
| 453 | switch (op.operator()) { |
| 454 | case ADD: |
Yi Tseng | c29d882 | 2017-10-25 16:19:25 -0700 | [diff] [blame] | 455 | case MODIFY: |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 456 | return addBatchEntry(op).thenApply(succeeded -> succeeded ? op : null); |
| 457 | case REMOVE: |
| 458 | return removeBatchEntry(op).thenApply(succeeded -> succeeded ? op : null); |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 459 | default: |
| 460 | log.warn("Unknown flow operation operator: {}", op.operator()); |
| 461 | return CompletableFuture.<FlowRuleBatchEntry>completedFuture(null); |
| 462 | } |
| 463 | }).collect(Collectors.toList())) |
| 464 | .thenApply(results -> results.stream() |
| 465 | .filter(Objects::nonNull) |
| 466 | .collect(Collectors.toSet())); |
| 467 | } |
| 468 | |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 469 | @SuppressWarnings("unchecked") |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 470 | private CompletableFuture<Boolean> addBatchEntry(FlowRuleBatchEntry batchEntry) { |
| 471 | StoredFlowEntry entry = new DefaultFlowEntry(batchEntry.target()); |
| 472 | DocumentPath path = getPathFor(entry.deviceId(), entry.id()); |
| 473 | return retryAsyncUntilSuccess(() -> { |
| 474 | CompletableFuture<Boolean> future = new CompletableFuture<>(); |
| 475 | asyncFlows.get(path).whenComplete((value, getError) -> { |
| 476 | if (getError == null) { |
| 477 | if (value != null) { |
| 478 | Map<StoredFlowEntry, StoredFlowEntry> entries = Maps.newHashMap(value.value()); |
| 479 | entries.put(entry, entry); |
| 480 | asyncFlows.replace(path, entries, value.version()).whenComplete((succeeded, replaceError) -> { |
| 481 | if (replaceError == null) { |
| 482 | if (succeeded) { |
| 483 | log.trace("Stored new flow rule: {}", entry); |
| 484 | future.complete(true); |
| 485 | } else { |
| 486 | log.trace("Failed to store new flow rule: {}", entry); |
| 487 | future.completeExceptionally(RETRY); |
| 488 | } |
| 489 | } else { |
| 490 | future.completeExceptionally(replaceError); |
| 491 | } |
| 492 | }); |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 493 | } else { |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 494 | // If there are no entries stored for the device, initialize the device's flows. |
| 495 | Map<StoredFlowEntry, StoredFlowEntry> map = Maps.newHashMap(); |
| 496 | map.put(entry, entry); |
| 497 | asyncFlows.createRecursive(path, map).whenComplete((succeeded, createError) -> { |
| 498 | if (createError == null) { |
| 499 | if (succeeded) { |
| 500 | log.trace("Stored new flow rule: {}", entry); |
| 501 | future.complete(true); |
| 502 | } else { |
| 503 | log.trace("Failed to store new flow rule: {}", entry); |
| 504 | future.completeExceptionally(RETRY); |
| 505 | } |
| 506 | } else { |
| 507 | future.completeExceptionally(createError); |
| 508 | } |
| 509 | }); |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 510 | } |
| 511 | } else { |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 512 | future.completeExceptionally(getError); |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 513 | } |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 514 | }); |
| 515 | return future; |
| 516 | }); |
| 517 | } |
| 518 | |
| 519 | @SuppressWarnings("unchecked") |
| 520 | private CompletableFuture<Boolean> removeBatchEntry(FlowRuleBatchEntry batchEntry) { |
| 521 | FlowRule rule = batchEntry.target(); |
| 522 | DocumentPath path = getPathFor(rule.deviceId(), rule.id()); |
| 523 | return retryAsyncUntilSuccess(() -> { |
| 524 | CompletableFuture<Boolean> future = new CompletableFuture<>(); |
| 525 | asyncFlows.get(path).whenComplete((value, getError) -> { |
| 526 | if (getError == null) { |
| 527 | if (value != null) { |
| 528 | Map<StoredFlowEntry, StoredFlowEntry> entries = Maps.newHashMap(value.value()); |
| 529 | StoredFlowEntry entry = entries.get(rule); |
| 530 | if (entry != null) { |
| 531 | entry.setState(FlowEntryState.PENDING_REMOVE); |
| 532 | asyncFlows.replace(path, entries, value.version()).whenComplete((succeeded, error) -> { |
| 533 | if (error == null) { |
| 534 | if (succeeded) { |
| 535 | log.trace("Updated flow rule state to PENDING_REMOVE: {}", entry); |
| 536 | future.complete(true); |
| 537 | } else { |
| 538 | log.trace("Failed to update flow rule state to PENDING_REMOVE: {}", entry); |
| 539 | future.completeExceptionally(RETRY); |
| 540 | } |
| 541 | } else { |
| 542 | future.completeExceptionally(error); |
| 543 | } |
| 544 | }); |
| 545 | } else { |
| 546 | future.complete(false); |
| 547 | } |
| 548 | } else { |
| 549 | future.complete(false); |
| 550 | } |
| 551 | } else { |
| 552 | future.completeExceptionally(getError); |
| 553 | } |
| 554 | }); |
| 555 | return future; |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 556 | }); |
| 557 | } |
| 558 | |
| 559 | @Override |
| 560 | public void batchOperationComplete(FlowRuleBatchEvent event) { |
| 561 | if (pendingBatches.remove(event.subject().batchId())) { |
| 562 | notifyDelegate(event); |
| 563 | } else { |
| 564 | clusterCommunicator.broadcast(event, COMPLETE_BATCH, serializer::encode); |
| 565 | } |
| 566 | } |
| 567 | |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 568 | @Override |
| 569 | public void deleteFlowRule(FlowRule rule) { |
| 570 | storeBatch( |
| 571 | new FlowRuleBatchOperation( |
Sho SHIMIZU | 98ffca8 | 2015-05-11 08:39:24 -0700 | [diff] [blame] | 572 | Collections.singletonList( |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 573 | new FlowRuleBatchEntry( |
| 574 | FlowRuleOperation.REMOVE, |
| 575 | rule)), rule.deviceId(), idGenerator.getNewId())); |
| 576 | } |
| 577 | |
| 578 | @Override |
Charles Chan | 93fa727 | 2016-01-26 22:27:02 -0800 | [diff] [blame] | 579 | public FlowRuleEvent pendingFlowRule(FlowEntry rule) { |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 580 | DocumentPath path = getPathFor(rule.deviceId(), rule.id()); |
| 581 | return retryUntilSuccess(() -> { |
| 582 | Versioned<Map<StoredFlowEntry, StoredFlowEntry>> value = flows.get(path); |
| 583 | if (value != null) { |
| 584 | Map<StoredFlowEntry, StoredFlowEntry> entries = Maps.newHashMap(value.value()); |
| 585 | StoredFlowEntry entry = entries.get(rule); |
| 586 | if (entry != null && entry.state() != FlowEntryState.PENDING_ADD) { |
| 587 | entry.setState(FlowEntryState.PENDING_ADD); |
| 588 | if (flows.replace(path, entries, value.version())) { |
| 589 | log.trace("Updated flow rule state to PENDING_ADD: {}", entry); |
| 590 | return new FlowRuleEvent(RULE_UPDATED, rule); |
| 591 | } else { |
| 592 | log.trace("Failed to update flow rule state to PENDING_ADD: {}", entry); |
| 593 | return retry(); |
| 594 | } |
| 595 | } else { |
| 596 | return null; |
| 597 | } |
| 598 | } else { |
| 599 | return null; |
Charles Chan | 93fa727 | 2016-01-26 22:27:02 -0800 | [diff] [blame] | 600 | } |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 601 | }); |
Charles Chan | 93fa727 | 2016-01-26 22:27:02 -0800 | [diff] [blame] | 602 | } |
| 603 | |
| 604 | @Override |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 605 | @SuppressWarnings("unchecked") |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 606 | public FlowRuleEvent addOrUpdateFlowRule(FlowEntry rule) { |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 607 | DocumentPath path = getPathFor(rule.deviceId(), rule.id()); |
| 608 | return retryUntilSuccess(() -> { |
| 609 | Versioned<Map<StoredFlowEntry, StoredFlowEntry>> value = flows.get(path); |
| 610 | if (value != null) { |
| 611 | Map<StoredFlowEntry, StoredFlowEntry> entries = Maps.newHashMap(value.value()); |
| 612 | StoredFlowEntry entry = entries.get(rule); |
| 613 | if (entry != null) { |
| 614 | FlowRuleEvent event; |
| 615 | String message; |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 616 | |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 617 | entry.setBytes(rule.bytes()); |
| 618 | entry.setLife(rule.life(TimeUnit.NANOSECONDS), TimeUnit.NANOSECONDS); |
| 619 | entry.setLiveType(rule.liveType()); |
| 620 | entry.setPackets(rule.packets()); |
| 621 | entry.setLastSeen(); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 622 | |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 623 | // If the entry state is PENDING_ADD, set it to ADDED. Otherwise, just update the rule. |
| 624 | if (entry.state() == FlowEntryState.PENDING_ADD) { |
| 625 | entry.setState(FlowEntryState.ADDED); |
| 626 | event = new FlowRuleEvent(Type.RULE_ADDED, rule); |
| 627 | message = "Updated flow rule state to ADDED: {}"; |
| 628 | } else { |
| 629 | event = new FlowRuleEvent(Type.RULE_UPDATED, rule); |
| 630 | message = "Updated flow rule: {}"; |
| 631 | } |
| 632 | |
| 633 | if (flows.replace(path, entries, value.version())) { |
| 634 | log.trace(message, entry); |
| 635 | return event; |
| 636 | } else { |
| 637 | log.trace("Failed to update flow rule: {}", entry); |
| 638 | return retry(); |
| 639 | } |
| 640 | } else { |
| 641 | // If the rule does not exist, return null. Inserting the rule risks race conditions |
| 642 | // that can result in removed rules being retained. |
| 643 | return null; |
| 644 | } |
| 645 | } else { |
Jordan Halterman | 9b3a7ce | 2017-08-25 15:12:54 -0700 | [diff] [blame] | 646 | return null; |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 647 | } |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 648 | }); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 649 | } |
| 650 | |
| 651 | @Override |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 652 | @SuppressWarnings("unchecked") |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 653 | public FlowRuleEvent removeFlowRule(FlowEntry rule) { |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 654 | DocumentPath path = getPathFor(rule.deviceId(), rule.id()); |
| 655 | return retryUntilSuccess(() -> { |
| 656 | Versioned<Map<StoredFlowEntry, StoredFlowEntry>> value = flows.get(path); |
| 657 | if (value != null) { |
| 658 | Map<StoredFlowEntry, StoredFlowEntry> entries = Maps.newHashMap(value.value()); |
| 659 | StoredFlowEntry entry = entries.remove(rule); |
| 660 | if (entry != null) { |
| 661 | if (flows.replace(path, entries, value.version())) { |
| 662 | log.trace("Removed flow rule: {}", entry); |
| 663 | return new FlowRuleEvent(RULE_REMOVED, entry); |
| 664 | } else { |
| 665 | log.trace("Failed to remove flow rule: {}", entry); |
| 666 | return retry(); |
| 667 | } |
| 668 | } else { |
| 669 | return null; |
| 670 | } |
| 671 | } else { |
| 672 | return null; |
| 673 | } |
| 674 | }); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 675 | } |
| 676 | |
| 677 | @Override |
Charles Chan | 0c7c43b | 2016-01-14 17:39:20 -0800 | [diff] [blame] | 678 | public void purgeFlowRule(DeviceId deviceId) { |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 679 | DocumentPath path = getPathFor(deviceId); |
Jordan Halterman | f5295f6 | 2017-09-12 15:07:18 -0700 | [diff] [blame] | 680 | retryUntilSuccess(() -> { |
| 681 | try { |
| 682 | for (String flowId : flows.getChildren(path).keySet()) { |
| 683 | flows.removeNode(DocumentPath.from("root", deviceId.toString(), flowId)); |
| 684 | } |
| 685 | } catch (NoSuchDocumentPathException e) { |
| 686 | // Do nothing. There are no flows for the device. |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 687 | } |
Jordan Halterman | f5295f6 | 2017-09-12 15:07:18 -0700 | [diff] [blame] | 688 | |
| 689 | // New children may have been created since they were removed above. Catch |
| 690 | // IllegalDocumentModificationException and retry if necessary. |
| 691 | try { |
| 692 | flows.removeNode(path); |
| 693 | } catch (NoSuchDocumentPathException e) { |
| 694 | return null; |
| 695 | } catch (IllegalDocumentModificationException e) { |
| 696 | return retry(); |
| 697 | } |
| 698 | return null; |
| 699 | }); |
Charles Chan | 0c7c43b | 2016-01-14 17:39:20 -0800 | [diff] [blame] | 700 | } |
| 701 | |
| 702 | @Override |
Victor Silva | 139bca4 | 2016-08-18 11:46:35 -0300 | [diff] [blame] | 703 | public void purgeFlowRules() { |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 704 | try { |
| 705 | for (String deviceId : flows.getChildren(flows.root()).keySet()) { |
| 706 | purgeFlowRule(DeviceId.deviceId(deviceId)); |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 707 | } |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 708 | } catch (NoSuchDocumentPathException e) { |
Jordan Halterman | f5295f6 | 2017-09-12 15:07:18 -0700 | [diff] [blame] | 709 | // Do nothing if no children exist. |
Madan Jampani | 86940d9 | 2015-05-06 11:47:57 -0700 | [diff] [blame] | 710 | } |
| 711 | } |
Srikanth Vavilapalli | 95810f5 | 2015-09-14 15:49:56 -0700 | [diff] [blame] | 712 | |
| 713 | @Override |
| 714 | public FlowRuleEvent updateTableStatistics(DeviceId deviceId, |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 715 | List<TableStatisticsEntry> tableStats) { |
Srikanth Vavilapalli | 95810f5 | 2015-09-14 15:49:56 -0700 | [diff] [blame] | 716 | deviceTableStats.put(deviceId, tableStats); |
| 717 | return null; |
| 718 | } |
| 719 | |
| 720 | @Override |
| 721 | public Iterable<TableStatisticsEntry> getTableStatistics(DeviceId deviceId) { |
Deepa Vaddireddy | 2e85cfc | 2017-11-07 12:58:00 +0000 | [diff] [blame] | 722 | if (mastershipService.getMasterFor(deviceId) != null) { |
| 723 | List<TableStatisticsEntry> tableStats = deviceTableStats.get(deviceId); |
| 724 | if (tableStats == null) { |
| 725 | return Collections.emptyList(); |
| 726 | } |
| 727 | return ImmutableList.copyOf(tableStats); |
| 728 | } else { |
| 729 | log.debug("Failed to getTableStatistics: No master for {}", deviceId); |
Srikanth Vavilapalli | 95810f5 | 2015-09-14 15:49:56 -0700 | [diff] [blame] | 730 | return Collections.emptyList(); |
| 731 | } |
Deepa Vaddireddy | 2e85cfc | 2017-11-07 12:58:00 +0000 | [diff] [blame] | 732 | |
Srikanth Vavilapalli | 95810f5 | 2015-09-14 15:49:56 -0700 | [diff] [blame] | 733 | } |
| 734 | |
Patryk Konopka | 7e40c01 | 2017-06-06 13:38:06 +0200 | [diff] [blame] | 735 | @Override |
| 736 | public long getActiveFlowRuleCount(DeviceId deviceId) { |
Deepa Vaddireddy | 2e85cfc | 2017-11-07 12:58:00 +0000 | [diff] [blame] | 737 | if (mastershipService.getMasterFor(deviceId) != null) { |
| 738 | return Streams.stream(getTableStatistics(deviceId)) |
| 739 | .mapToLong(TableStatisticsEntry::activeFlowEntries) |
| 740 | .sum(); |
| 741 | } else { |
| 742 | log.debug("Failed to getActiveFlowRuleCount: No master for {}", deviceId); |
| 743 | return 0; |
| 744 | } |
Patryk Konopka | 7e40c01 | 2017-06-06 13:38:06 +0200 | [diff] [blame] | 745 | } |
| 746 | |
Srikanth Vavilapalli | 95810f5 | 2015-09-14 15:49:56 -0700 | [diff] [blame] | 747 | private class InternalTableStatsListener |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 748 | implements EventuallyConsistentMapListener<DeviceId, List<TableStatisticsEntry>> { |
Srikanth Vavilapalli | 95810f5 | 2015-09-14 15:49:56 -0700 | [diff] [blame] | 749 | @Override |
| 750 | public void event(EventuallyConsistentMapEvent<DeviceId, |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 751 | List<TableStatisticsEntry>> event) { |
Srikanth Vavilapalli | 95810f5 | 2015-09-14 15:49:56 -0700 | [diff] [blame] | 752 | //TODO: Generate an event to listeners (do we need?) |
| 753 | } |
| 754 | } |
Jordan Halterman | f755409 | 2017-07-30 15:05:51 -0700 | [diff] [blame] | 755 | } |