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