blob: 7d5af6aa8904eb99df9de27031d261be24e81969 [file] [log] [blame]
pierventre30368ab2021-02-24 23:23:22 +01001/*
2 * Copyright 2021-present Open Networking Foundation
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 */
16package org.onosproject.segmentrouting.policy.impl;
17
18import com.google.common.collect.ImmutableSet;
19import com.google.common.collect.Lists;
20import com.google.common.collect.Maps;
21import com.google.common.hash.HashFunction;
22import com.google.common.hash.Hashing;
Wailok Shume2ab3d62021-05-27 04:40:38 +080023
pierventre30368ab2021-02-24 23:23:22 +010024import org.glassfish.jersey.internal.guava.Sets;
pierventre4f68ffa2021-03-09 22:52:14 +010025import org.onlab.packet.MacAddress;
pierventre30368ab2021-02-24 23:23:22 +010026import org.onlab.util.KryoNamespace;
27import org.onlab.util.PredictableExecutor;
28import org.onosproject.cluster.ClusterService;
29import org.onosproject.cluster.NodeId;
Wailok Shumee90c132021-03-11 21:00:11 +080030import org.onosproject.codec.CodecService;
pierventre30368ab2021-02-24 23:23:22 +010031import org.onosproject.core.ApplicationId;
32import org.onosproject.core.CoreService;
pierventre4f68ffa2021-03-09 22:52:14 +010033import org.onosproject.net.ConnectPoint;
Wailok Shume2ab3d62021-05-27 04:40:38 +080034import org.onosproject.net.config.NetworkConfigEvent;
35import org.onosproject.net.config.NetworkConfigListener;
36import org.onosproject.net.config.NetworkConfigRegistry;
37import org.onosproject.net.device.DeviceService;
pierventre30368ab2021-02-24 23:23:22 +010038import org.onosproject.net.DeviceId;
pierventre4f68ffa2021-03-09 22:52:14 +010039import org.onosproject.net.Link;
40import org.onosproject.net.flow.DefaultTrafficSelector;
pierventre30368ab2021-02-24 23:23:22 +010041import org.onosproject.net.flow.DefaultTrafficTreatment;
pierventre4f68ffa2021-03-09 22:52:14 +010042import org.onosproject.net.flow.TrafficSelector;
pierventre30368ab2021-02-24 23:23:22 +010043import org.onosproject.net.flow.TrafficTreatment;
44import org.onosproject.net.flowobjective.DefaultForwardingObjective;
pierventre4f68ffa2021-03-09 22:52:14 +010045import org.onosproject.net.flowobjective.DefaultNextObjective;
pierventre30368ab2021-02-24 23:23:22 +010046import org.onosproject.net.flowobjective.DefaultObjectiveContext;
47import org.onosproject.net.flowobjective.FlowObjectiveService;
48import org.onosproject.net.flowobjective.ForwardingObjective;
pierventre4f68ffa2021-03-09 22:52:14 +010049import org.onosproject.net.flowobjective.NextObjective;
pierventre30368ab2021-02-24 23:23:22 +010050import org.onosproject.net.flowobjective.Objective;
51import org.onosproject.net.flowobjective.ObjectiveContext;
52import org.onosproject.net.intent.WorkPartitionService;
pierventre4f68ffa2021-03-09 22:52:14 +010053import org.onosproject.net.link.LinkService;
pierventre30368ab2021-02-24 23:23:22 +010054import org.onosproject.segmentrouting.policy.api.DropPolicy;
55import org.onosproject.segmentrouting.policy.api.Policy;
pierventre30368ab2021-02-24 23:23:22 +010056import org.onosproject.segmentrouting.policy.api.PolicyData;
57import org.onosproject.segmentrouting.policy.api.PolicyId;
58import org.onosproject.segmentrouting.policy.api.PolicyService;
59import org.onosproject.segmentrouting.policy.api.PolicyState;
pierventre4f68ffa2021-03-09 22:52:14 +010060import org.onosproject.segmentrouting.policy.api.RedirectPolicy;
pierventre30368ab2021-02-24 23:23:22 +010061import org.onosproject.segmentrouting.policy.api.TrafficMatch;
62import org.onosproject.segmentrouting.policy.api.TrafficMatchData;
63import org.onosproject.segmentrouting.policy.api.TrafficMatchId;
Wailok Shum37dd29a2021-04-27 18:13:55 +080064import org.onosproject.segmentrouting.policy.api.TrafficMatchPriority;
pierventre30368ab2021-02-24 23:23:22 +010065import org.onosproject.segmentrouting.policy.api.TrafficMatchState;
pierventreb37a11a2021-03-18 16:50:04 +010066import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
Wailok Shume2ab3d62021-05-27 04:40:38 +080067import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
pierventreb37a11a2021-03-18 16:50:04 +010068import org.onosproject.segmentrouting.policy.api.Policy.PolicyType;
pierventre30368ab2021-02-24 23:23:22 +010069import org.onosproject.store.serializers.KryoNamespaces;
70import org.onosproject.store.service.ConsistentMap;
71import org.onosproject.store.service.MapEvent;
72import org.onosproject.store.service.MapEventListener;
73import org.onosproject.store.service.Serializer;
74import org.onosproject.store.service.StorageException;
75import org.onosproject.store.service.StorageService;
76import org.onosproject.store.service.Versioned;
77import org.osgi.service.component.annotations.Activate;
78import org.osgi.service.component.annotations.Component;
79import org.osgi.service.component.annotations.Deactivate;
80import org.osgi.service.component.annotations.Reference;
81import org.osgi.service.component.annotations.ReferenceCardinality;
82import org.slf4j.Logger;
83
Wailok Shume2ab3d62021-05-27 04:40:38 +080084import java.util.ArrayList;
pierventre30368ab2021-02-24 23:23:22 +010085import java.util.List;
86import java.util.Map;
87import java.util.Optional;
88import java.util.Set;
89import java.util.concurrent.CompletableFuture;
Wailok Shume2ab3d62021-05-27 04:40:38 +080090import java.util.concurrent.ExecutorService;
91import java.util.concurrent.Executors;
pierventre30368ab2021-02-24 23:23:22 +010092import java.util.stream.Collectors;
93
94import static org.onlab.util.Tools.groupedThreads;
pierventree9261c92021-08-27 13:12:06 +020095import static org.onosproject.segmentrouting.metadata.SRObjectiveMetadata.EDGE_PORT;
pierventre30368ab2021-02-24 23:23:22 +010096import static org.slf4j.LoggerFactory.getLogger;
97
98/**
99 * Implementation of the policy service interface.
100 */
101@Component(immediate = true, service = PolicyService.class)
102public class PolicyManager implements PolicyService {
103
104 // App related things
105 private static final String APP_NAME = "org.onosproject.segmentrouting.policy";
106 private ApplicationId appId;
107 private Logger log = getLogger(getClass());
108 static final String KEY_SEPARATOR = "|";
109
pierventre4f68ffa2021-03-09 22:52:14 +0100110 // Supported policies
pierventreb37a11a2021-03-18 16:50:04 +0100111 private static final Set<PolicyType> SUPPORTED_POLICIES = ImmutableSet.of(
pierventre4f68ffa2021-03-09 22:52:14 +0100112 PolicyType.DROP, PolicyType.REDIRECT);
113
pierventre30368ab2021-02-24 23:23:22 +0100114 // Policy/TrafficMatch store related objects. We use these consistent maps to keep track of the
115 // lifecycle of a policy/traffic match. These are decomposed in multiple operations which have
116 // to be performed on multiple devices in order to have a policy/traffic match in ADDED state.
pierventre4f68ffa2021-03-09 22:52:14 +0100117 // TODO Consider to add store and delegate
pierventre30368ab2021-02-24 23:23:22 +0100118 private static final String POLICY_STORE = "sr-policy-store";
119 private ConsistentMap<PolicyId, PolicyRequest> policies;
120 private MapEventListener<PolicyId, PolicyRequest> mapPolListener = new InternalPolMapEventListener();
121 private Map<PolicyId, PolicyRequest> policiesMap;
122
123 private static final String OPS_STORE = "sr-ops-store";
124 private ConsistentMap<String, Operation> operations;
125 private MapEventListener<String, Operation> mapOpsListener = new InternalOpsMapEventListener();
126 private Map<String, Operation> opsMap;
127
128 private static final String TRAFFIC_MATCH_STORE = "sr-tmatch-store";
129 private ConsistentMap<TrafficMatchId, TrafficMatchRequest> trafficMatches;
130 private MapEventListener<TrafficMatchId, TrafficMatchRequest> mapTMatchListener =
131 new InternalTMatchMapEventListener();
132 private Map<TrafficMatchId, TrafficMatchRequest> trafficMatchesMap;
133
134 // Leadership related objects - consistent hashing
135 private static final HashFunction HASH_FN = Hashing.md5();
136 // Read only cache of the Policy leader
137 private Map<PolicyId, NodeId> policyLeaderCache;
138
139 // Worker threads for policy and traffic match related ops
140 private static final int DEFAULT_THREADS = 4;
141 protected PredictableExecutor workers;
142
143 // Serializers and ONOS services
144 private static final KryoNamespace.Builder APP_KRYO_BUILDER = KryoNamespace.newBuilder()
145 .register(KryoNamespaces.API)
146 .register(PolicyId.class)
147 .register(PolicyType.class)
148 .register(DropPolicy.class)
pierventre4f68ffa2021-03-09 22:52:14 +0100149 .register(RedirectPolicy.class)
pierventre30368ab2021-02-24 23:23:22 +0100150 .register(PolicyState.class)
151 .register(PolicyRequest.class)
152 .register(TrafficMatchId.class)
153 .register(TrafficMatchState.class)
Wailok Shum37dd29a2021-04-27 18:13:55 +0800154 .register(TrafficMatchPriority.class)
pierventre30368ab2021-02-24 23:23:22 +0100155 .register(TrafficMatch.class)
156 .register(TrafficMatchRequest.class)
157 .register(Operation.class);
158 private Serializer serializer = Serializer.using(Lists.newArrayList(APP_KRYO_BUILDER.build()));
159
160 @Reference(cardinality = ReferenceCardinality.MANDATORY)
161 private CoreService coreService;
162
163 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Wailok Shumee90c132021-03-11 21:00:11 +0800164 private CodecService codecService;
165
166 @Reference(cardinality = ReferenceCardinality.MANDATORY)
pierventre30368ab2021-02-24 23:23:22 +0100167 private StorageService storageService;
168
169 @Reference(cardinality = ReferenceCardinality.MANDATORY)
170 private ClusterService clusterService;
171
172 @Reference(cardinality = ReferenceCardinality.MANDATORY)
pierventre4f68ffa2021-03-09 22:52:14 +0100173 private WorkPartitionService workPartitionService;
pierventre30368ab2021-02-24 23:23:22 +0100174
Wailok Shumee90c132021-03-11 21:00:11 +0800175 @Reference(cardinality = ReferenceCardinality.MANDATORY)
pierventre4f68ffa2021-03-09 22:52:14 +0100176 private FlowObjectiveService flowObjectiveService;
177
178 @Reference(cardinality = ReferenceCardinality.MANDATORY)
179 private LinkService linkService;
pierventre30368ab2021-02-24 23:23:22 +0100180
Wailok Shume2ab3d62021-05-27 04:40:38 +0800181 @Reference(cardinality = ReferenceCardinality.MANDATORY)
182 private NetworkConfigRegistry cfgService;
183
184 @Reference(cardinality = ReferenceCardinality.MANDATORY)
185 private DeviceService deviceService;
186
187 // Netcfg listener
188 private final InternalConfigListener cfgListener = new InternalConfigListener();
189 // EventExecutor for netcfg event
190 private ExecutorService eventExecutor;
191
pierventre30368ab2021-02-24 23:23:22 +0100192 @Activate
193 public void activate() {
194 appId = coreService.registerApplication(APP_NAME);
195
Wailok Shumee90c132021-03-11 21:00:11 +0800196 codecService.registerCodec(DropPolicy.class, new DropPolicyCodec());
197 codecService.registerCodec(RedirectPolicy.class, new RedirectPolicyCodec());
198 codecService.registerCodec(TrafficMatch.class, new TrafficMatchCodec());
199
Wailok Shume2ab3d62021-05-27 04:40:38 +0800200 cfgService.addListener(cfgListener);
201
pierventre30368ab2021-02-24 23:23:22 +0100202 policies = storageService.<PolicyId, PolicyRequest>consistentMapBuilder()
203 .withName(POLICY_STORE)
204 .withSerializer(serializer).build();
205 policies.addListener(mapPolListener);
206 policiesMap = policies.asJavaMap();
207
208 trafficMatches = storageService.<TrafficMatchId, TrafficMatchRequest>consistentMapBuilder()
209 .withName(TRAFFIC_MATCH_STORE)
210 .withSerializer(serializer).build();
211 trafficMatches.addListener(mapTMatchListener);
212 trafficMatchesMap = trafficMatches.asJavaMap();
213
214 operations = storageService.<String, Operation>consistentMapBuilder()
215 .withName(OPS_STORE)
216 .withSerializer(serializer).build();
217 operations.addListener(mapOpsListener);
218 opsMap = operations.asJavaMap();
219
220 policyLeaderCache = Maps.newConcurrentMap();
221
222 workers = new PredictableExecutor(DEFAULT_THREADS,
223 groupedThreads("sr-policy", "worker-%d", log));
224
Wailok Shume2ab3d62021-05-27 04:40:38 +0800225 eventExecutor = Executors.newSingleThreadExecutor();
226
pierventre30368ab2021-02-24 23:23:22 +0100227 log.info("Started");
228 }
229
230 @Deactivate
231 public void deactivate() {
232 // Teardown everything
Wailok Shumee90c132021-03-11 21:00:11 +0800233 codecService.unregisterCodec(DropPolicy.class);
234 codecService.unregisterCodec(RedirectPolicy.class);
235 codecService.unregisterCodec(TrafficMatch.class);
Wailok Shume2ab3d62021-05-27 04:40:38 +0800236 cfgService.removeListener(cfgListener);
pierventre30368ab2021-02-24 23:23:22 +0100237 policies.removeListener(mapPolListener);
238 policies.destroy();
239 policiesMap.clear();
240 trafficMatches.removeListener(mapTMatchListener);
241 trafficMatches.destroy();
242 trafficMatchesMap.clear();
243 operations.removeListener(mapOpsListener);
244 operations.destroy();
245 operations.clear();
246 workers.shutdown();
Wailok Shume2ab3d62021-05-27 04:40:38 +0800247 eventExecutor.shutdown();
pierventre30368ab2021-02-24 23:23:22 +0100248
249 log.info("Stopped");
250 }
251
252 @Override
253 //FIXME update does not work well
254 public PolicyId addOrUpdatePolicy(Policy policy) {
255 PolicyId policyId = policy.policyId();
256 try {
257 policies.put(policyId, new PolicyRequest(policy));
258 } catch (StorageException e) {
259 log.error("{} thrown a storage exception: {}", e.getStackTrace()[0].getMethodName(),
260 e.getMessage(), e);
261 policyId = null;
262 }
263 return policyId;
264 }
265
266 @Override
267 public boolean removePolicy(PolicyId policyId) {
268 boolean result;
pierventre4f68ffa2021-03-09 22:52:14 +0100269 if (dependingTrafficMatches(policyId).isPresent()) {
270 if (log.isDebugEnabled()) {
271 log.debug("Found depending traffic matches");
272 }
273 return false;
274 }
pierventre30368ab2021-02-24 23:23:22 +0100275 try {
276 result = Versioned.valueOrNull(policies.computeIfPresent(policyId, (k, v) -> {
277 if (v.policyState() != PolicyState.PENDING_REMOVE) {
278 v.policyState(PolicyState.PENDING_REMOVE);
279 }
280 return v;
281 })) != null;
282 } catch (StorageException e) {
283 log.error("{} thrown a storage exception: {}", e.getStackTrace()[0].getMethodName(),
284 e.getMessage(), e);
285 result = false;
286 }
287 return result;
288 }
289
290 @Override
291 public Set<PolicyData> policies(Set<PolicyType> filter) {
292 Set<PolicyData> policyData = Sets.newHashSet();
Wailok Shume2ab3d62021-05-27 04:40:38 +0800293 List<DeviceId> edgeDeviceIds = getEdgeDeviceIds();
pierventre30368ab2021-02-24 23:23:22 +0100294 Set<PolicyRequest> policyRequests;
295 if (filter.isEmpty()) {
296 policyRequests = ImmutableSet.copyOf(policiesMap.values());
297 } else {
298 policyRequests = policiesMap.values().stream()
299 .filter(policyRequest -> filter.contains(policyRequest.policyType()))
300 .collect(Collectors.toSet());
301 }
302 PolicyKey policyKey;
303 List<String> ops;
304 for (PolicyRequest policyRequest : policyRequests) {
305 ops = Lists.newArrayList();
306 for (DeviceId deviceId : edgeDeviceIds) {
307 policyKey = new PolicyKey(deviceId, policyRequest.policyId());
308 Operation operation = Versioned.valueOrNull(operations.get(policyKey.toString()));
309 if (operation != null) {
310 ops.add(deviceId + " -> " + operation.toStringMinimal());
311 }
312 }
313 policyData.add(new PolicyData(policyRequest.policyState(), policyRequest.policy(), ops));
314 }
315 return policyData;
316 }
317
318 @Override
319 //FIXME update does not work well
320 public TrafficMatchId addOrUpdateTrafficMatch(TrafficMatch trafficMatch) {
321 TrafficMatchId trafficMatchId = trafficMatch.trafficMatchId();
322 try {
323 trafficMatches.put(trafficMatchId, new TrafficMatchRequest(trafficMatch));
324 } catch (StorageException e) {
325 log.error("{} thrown a storage exception: {}", e.getStackTrace()[0].getMethodName(),
326 e.getMessage(), e);
327 trafficMatchId = null;
328 }
329 return trafficMatchId;
330 }
331
332 @Override
333 public boolean removeTrafficMatch(TrafficMatchId trafficMatchId) {
334 boolean result;
335 try {
336 result = Versioned.valueOrNull(trafficMatches.computeIfPresent(trafficMatchId, (k, v) -> {
337 if (v.trafficMatchState() != TrafficMatchState.PENDING_REMOVE) {
338 v.trafficMatchState(TrafficMatchState.PENDING_REMOVE);
339 }
340 return v;
341 })) != null;
342 } catch (StorageException e) {
343 log.error("{} thrown a storage exception: {}", e.getStackTrace()[0].getMethodName(),
344 e.getMessage(), e);
345 result = false;
346 }
347 return result;
348 }
349
350 @Override
351 public Set<TrafficMatchData> trafficMatches() {
352 Set<TrafficMatchData> trafficMatchData = Sets.newHashSet();
Wailok Shume2ab3d62021-05-27 04:40:38 +0800353 List<DeviceId> edgeDeviceIds = getEdgeDeviceIds();
pierventre30368ab2021-02-24 23:23:22 +0100354 Set<TrafficMatchRequest> trafficMatchRequests = ImmutableSet.copyOf(trafficMatchesMap.values());
355 TrafficMatchKey trafficMatchKey;
356 List<String> ops;
357 for (TrafficMatchRequest trafficMatchRequest : trafficMatchRequests) {
358 ops = Lists.newArrayList();
359 for (DeviceId deviceId : edgeDeviceIds) {
360 trafficMatchKey = new TrafficMatchKey(deviceId, trafficMatchRequest.trafficMatch().trafficMatchId());
361 Operation operation = Versioned.valueOrNull(operations.get(trafficMatchKey.toString()));
362 if (operation != null) {
363 ops.add(deviceId + " -> " + operation.toStringMinimal());
364 }
365 }
366 trafficMatchData.add(new TrafficMatchData(trafficMatchRequest.trafficMatchState(),
367 trafficMatchRequest.trafficMatch(), ops));
368 }
369 return trafficMatchData;
370 }
371
372 // Install/remove the policies on the edge devices
373 private void sendPolicy(Policy policy, boolean install) {
374 if (!isLeader(policy.policyId())) {
375 if (log.isDebugEnabled()) {
376 log.debug("Instance is not leader for policy {}", policy.policyId());
377 }
378 return;
379 }
380 // We know that we are the leader, offloads to the workers the remaining
381 // part: issue fobj installation/removal and update the maps
Wailok Shume2ab3d62021-05-27 04:40:38 +0800382 List<DeviceId> edgeDeviceIds = getEdgeDeviceIds();
pierventre30368ab2021-02-24 23:23:22 +0100383 for (DeviceId deviceId : edgeDeviceIds) {
384 workers.execute(() -> {
385 if (install) {
386 installPolicyInDevice(deviceId, policy);
387 } else {
388 removePolicyInDevice(deviceId, policy);
389 }
390 }, deviceId.hashCode());
391 }
392 }
393
394 // Orchestrate policy installation according to the type
395 private void installPolicyInDevice(DeviceId deviceId, Policy policy) {
pierventre4f68ffa2021-03-09 22:52:14 +0100396 if (!SUPPORTED_POLICIES.contains(policy.policyType())) {
pierventre30368ab2021-02-24 23:23:22 +0100397 log.warn("Policy {} type {} not yet supported",
398 policy.policyId(), policy.policyType());
pierventre4f68ffa2021-03-09 22:52:14 +0100399 return;
400 }
401 PolicyKey policyKey;
402 Operation.Builder operation;
403 if (log.isDebugEnabled()) {
404 log.debug("Installing {} policy {} for dev: {}",
405 policy.policyType(), policy.policyId(), deviceId);
406 }
407 policyKey = new PolicyKey(deviceId, policy.policyId());
Wailok Shume2ab3d62021-05-27 04:40:38 +0800408 // Prevent duplicate installation of the policies. With the current
409 // implementation is not possible to update a policy since a change
410 // in the params will create a new policy. Thus, there is no need to
411 // check the equality like we do for the TM
412 Operation oldPolicyOp = Versioned.valueOrNull(operations.get(policyKey.toString()));
413 if (oldPolicyOp != null && oldPolicyOp.isInstall()) {
414 if (log.isDebugEnabled()) {
415 log.debug("There is already an install operation for policy {}", policy.policyId());
416 }
Wailok Shum4df59312021-06-08 21:44:00 +0800417 // If we add or submit a policy multiple times
418 // We skip the installation update the policy state directly
419 updatePolicy(policy.policyId(), true);
Wailok Shume2ab3d62021-05-27 04:40:38 +0800420 return;
421 }
pierventre4f68ffa2021-03-09 22:52:14 +0100422 operation = Operation.builder()
423 .isInstall(true)
424 .policy(policy);
425 // TODO To better handle different policy types consider the abstraction of a compiler (subtypes ?)
426 if (policy.policyType() == PolicyType.DROP) {
427 // DROP policies do not need the next objective installation phase
428 // we can update directly the map and signal the ops as done
429 operation.isDone(true);
Wailok Shum4df59312021-06-08 21:44:00 +0800430 operations.put(policyKey.toString(), operation.build());
pierventre4f68ffa2021-03-09 22:52:14 +0100431 } else if (policy.policyType() == PolicyType.REDIRECT) {
432 // REDIRECT Uses next objective context to update the ops as done when
433 // it returns successfully. In the other cases leaves the ops as undone
434 // and the relative policy will remain in pending.
435 operations.put(policyKey.toString(), operation.build());
436 NextObjective.Builder builder = redirectPolicyNextObjective(deviceId, (RedirectPolicy) policy);
437 // Handle error here - leave the operation as undone and pending
438 if (builder != null) {
439 CompletableFuture<Objective> future = new CompletableFuture<>();
440 if (log.isDebugEnabled()) {
441 log.debug("Installing REDIRECT next objective for dev: {}", deviceId);
442 }
443 ObjectiveContext context = new DefaultObjectiveContext(
444 (objective) -> {
445 if (log.isDebugEnabled()) {
446 log.debug("REDIRECT next objective for policy {} installed in dev: {}",
447 policy.policyId(), deviceId);
448 }
449 future.complete(objective);
450 },
451 (objective, error) -> {
452 log.warn("Failed to install REDIRECT next objective for policy {}: {} in dev: {}",
453 policy.policyId(), error, deviceId);
454 future.complete(null);
455 });
456 // Context is not serializable
457 NextObjective serializableObjective = builder.add();
458 flowObjectiveService.next(deviceId, builder.add(context));
459 future.whenComplete((objective, ex) -> {
460 if (ex != null) {
461 log.error("Exception installing REDIRECT next objective", ex);
462 } else if (objective != null) {
463 operations.computeIfPresent(policyKey.toString(), (k, v) -> {
464 if (!v.isDone() && v.isInstall()) {
465 v.isDone(true);
466 v.objectiveOperation(serializableObjective);
467 }
468 return v;
469 });
470 }
471 });
472 }
pierventre30368ab2021-02-24 23:23:22 +0100473 }
474 }
475
476 // Remove policy in a device according to the type
477 private void removePolicyInDevice(DeviceId deviceId, Policy policy) {
pierventre30368ab2021-02-24 23:23:22 +0100478 PolicyKey policyKey = new PolicyKey(deviceId, policy.policyId());
479 Operation operation = Versioned.valueOrNull(operations.get(policyKey.toString()));
480 // Policy might be still in pending or not present anymore
481 if (operation == null || operation.objectiveOperation() == null) {
482 log.warn("There are no ops associated with {}", policyKey);
483 operation = Operation.builder()
484 .isDone(true)
485 .isInstall(false)
486 .policy(policy)
487 .build();
488 operations.put(policyKey.toString(), operation);
489 } else {
pierventre4f68ffa2021-03-09 22:52:14 +0100490 if (log.isDebugEnabled()) {
491 log.debug("Removing {} policy {} in device {}", policy.policyType(), policy.policyId(), deviceId);
492 }
493 Operation.Builder operationBuilder = Operation.builder()
494 .isInstall(false)
495 .policy(policy);
pierventre30368ab2021-02-24 23:23:22 +0100496 if (policy.policyType() == PolicyType.DROP) {
pierventre4f68ffa2021-03-09 22:52:14 +0100497 operationBuilder.isDone(true);
498 operations.put(policyKey.toString(), operationBuilder.build());
pierventre30368ab2021-02-24 23:23:22 +0100499 } else if (policy.policyType() == PolicyType.REDIRECT) {
pierventre4f68ffa2021-03-09 22:52:14 +0100500 // REDIRECT has to remove the next objective first
501 NextObjective oldObj = (NextObjective) operation.objectiveOperation();
502 operations.put(policyKey.toString(), operationBuilder.build());
503 NextObjective.Builder builder = oldObj.copy();
504 CompletableFuture<Objective> future = new CompletableFuture<>();
pierventre30368ab2021-02-24 23:23:22 +0100505 if (log.isDebugEnabled()) {
pierventre4f68ffa2021-03-09 22:52:14 +0100506 log.debug("Removing REDIRECT next objective for dev: {}", deviceId);
pierventre30368ab2021-02-24 23:23:22 +0100507 }
pierventre4f68ffa2021-03-09 22:52:14 +0100508 ObjectiveContext context = new DefaultObjectiveContext(
509 (objective) -> {
510 if (log.isDebugEnabled()) {
511 log.debug("REDIRECT next objective for policy {} removed in dev: {}",
512 policy.policyId(), deviceId);
513 }
514 future.complete(objective);
515 },
516 (objective, error) -> {
517 log.warn("Failed to remove REDIRECT next objective for policy {}: {} in dev: {}",
518 policy.policyId(), error, deviceId);
519 future.complete(null);
520 });
521 NextObjective serializableObjective = builder.remove();
522 flowObjectiveService.next(deviceId, builder.remove(context));
523 future.whenComplete((objective, ex) -> {
524 if (ex != null) {
525 log.error("Exception Removing REDIRECT next objective", ex);
526 } else if (objective != null) {
527 operations.computeIfPresent(policyKey.toString(), (k, v) -> {
528 if (!v.isDone() && !v.isInstall()) {
529 v.isDone(true);
530 v.objectiveOperation(serializableObjective);
531 }
532 return v;
533 });
534 }
535 });
pierventre30368ab2021-02-24 23:23:22 +0100536 }
537 }
538 }
539
540 // Updates policy status if all the pending ops are done
541 private void updatePolicy(PolicyId policyId, boolean install) {
542 if (!isLeader(policyId)) {
543 if (log.isDebugEnabled()) {
544 log.debug("Instance is not leader for policy {}", policyId);
545 }
546 return;
547 }
548 workers.execute(() -> updatePolicyInternal(policyId, install), policyId.hashCode());
549 }
550
551 private void updatePolicyInternal(PolicyId policyId, boolean install) {
552 // If there are no more pending ops we are ready to go; potentially we can check
553 // if the id is contained. Updates policies only if they are still present
554 Optional<Map.Entry<String, Versioned<Operation>>> notYetDone = operations.entrySet().stream()
555 .filter(entry -> entry.getValue().value().policy().isPresent())
556 .filter(entry -> PolicyKey.fromString(entry.getKey()).policyId().equals(policyId))
557 .filter(entry -> !entry.getValue().value().isDone() && entry.getValue().value().isInstall() == install)
558 .findFirst();
559 if (notYetDone.isEmpty()) {
560 PolicyRequest policyRequest = Versioned.valueOrNull(policies.computeIfPresent(policyId, (k, v) -> {
561 if (v.policyState() == PolicyState.PENDING_ADD && install) {
562 if (log.isDebugEnabled()) {
563 log.debug("Policy {} is ready", policyId);
564 }
565 v.policyState(PolicyState.ADDED);
566 } else if (v.policyState() == PolicyState.PENDING_REMOVE && !install) {
567 if (log.isDebugEnabled()) {
568 log.debug("Policy {} is removed", policyId);
569 }
570 v = null;
571 }
572 return v;
573 }));
574 // Greedy check for pending traffic matches
575 if (policyRequest != null && policyRequest.policyState() == PolicyState.ADDED) {
576 updatePendingTrafficMatches(policyRequest.policyId());
577 }
578 }
579 }
580
581 // Install/remove the traffic match on the edge devices
582 private void sendTrafficMatch(TrafficMatch trafficMatch, boolean install) {
583 if (!isLeader(trafficMatch.policyId())) {
584 if (log.isDebugEnabled()) {
585 log.debug("Instance is not leader for policy {}", trafficMatch.policyId());
586 }
587 return;
588 }
589 // We know that we are the leader, offloads to the workers the remaining
590 // part: issue fobj installation/removal and update the maps
Wailok Shume2ab3d62021-05-27 04:40:38 +0800591 List<DeviceId> edgeDeviceIds = getEdgeDeviceIds();
pierventre30368ab2021-02-24 23:23:22 +0100592 for (DeviceId deviceId : edgeDeviceIds) {
593 workers.execute(() -> {
594 if (install) {
595 installTrafficMatchToDevice(deviceId, trafficMatch);
596 } else {
597 removeTrafficMatchInDevice(deviceId, trafficMatch);
598 }
599 }, deviceId.hashCode());
600 }
601 }
602
603 // Orchestrate traffic match installation according to the type
604 private void installTrafficMatchToDevice(DeviceId deviceId, TrafficMatch trafficMatch) {
605 if (log.isDebugEnabled()) {
606 log.debug("Installing traffic match {} associated to policy {}",
607 trafficMatch.trafficMatchId(), trafficMatch.policyId());
608 }
pierventre30368ab2021-02-24 23:23:22 +0100609 TrafficMatchKey trafficMatchKey = new TrafficMatchKey(deviceId, trafficMatch.trafficMatchId());
Wailok Shum6f71cd92021-05-06 20:05:29 +0800610 Operation oldTrafficOperation = Versioned.valueOrNull(operations.get(trafficMatchKey.toString()));
611 if (oldTrafficOperation != null && oldTrafficOperation.isInstall()) {
612 if (trafficMatch.equals(oldTrafficOperation.trafficMatch().orElse(null))) {
613 if (log.isDebugEnabled()) {
614 log.debug("There is already an install operation for traffic match {} associated to policy {} " +
615 "for device {}",
616 trafficMatch.trafficMatchId(), trafficMatch.policyId(), deviceId);
617 }
Wailok Shum4df59312021-06-08 21:44:00 +0800618 // If we add or submit a trafficMatch multiple times
619 // We skip the installation and update the state directly
620 updateTrafficMatch(trafficMatch, true);
Wailok Shum6f71cd92021-05-06 20:05:29 +0800621 return;
622 } else {
623 if (log.isDebugEnabled()) {
624 log.debug("Starts updating traffic match {} associated to policy {} " +
625 "for device {}",
626 trafficMatch.trafficMatchId(), trafficMatch.policyId(), deviceId);
627 }
pierventre4f68ffa2021-03-09 22:52:14 +0100628 }
pierventre4f68ffa2021-03-09 22:52:14 +0100629 }
pierventre30368ab2021-02-24 23:23:22 +0100630 // For the DROP policy we need to set an ACL drop in the fwd objective. The other
631 // policies require to retrieve the next Id and sets the next step.
632 PolicyKey policyKey = new PolicyKey(deviceId, trafficMatch.policyId());
633 Operation policyOperation = Versioned.valueOrNull(operations.get(policyKey.toString()));
634 if (policyOperation == null || !policyOperation.isDone() ||
pierventre4f68ffa2021-03-09 22:52:14 +0100635 !policyOperation.isInstall() || policyOperation.policy().isEmpty() ||
636 (policyOperation.policy().get().policyType() == PolicyType.REDIRECT &&
637 policyOperation.objectiveOperation() == null)) {
pierventre30368ab2021-02-24 23:23:22 +0100638 log.info("Deferring traffic match {} installation on device {}. Policy {} not yet installed",
639 trafficMatch.trafficMatchId(), deviceId, trafficMatch.policyId());
640 return;
641 }
pierventre4f68ffa2021-03-09 22:52:14 +0100642 // Updates the store and then send the versatile fwd objective to the pipeliner
Wailok Shum6f71cd92021-05-06 20:05:29 +0800643 Operation newTrafficOperation = Operation.builder()
pierventre4f68ffa2021-03-09 22:52:14 +0100644 .isInstall(true)
645 .trafficMatch(trafficMatch)
646 .build();
Wailok Shum6f71cd92021-05-06 20:05:29 +0800647 operations.put(trafficMatchKey.toString(), newTrafficOperation);
pierventre30368ab2021-02-24 23:23:22 +0100648 Policy policy = policyOperation.policy().get();
pierventre4f68ffa2021-03-09 22:52:14 +0100649 ForwardingObjective.Builder builder = trafficMatchFwdObjective(trafficMatch, policy.policyType());
pierventre30368ab2021-02-24 23:23:22 +0100650 if (policy.policyType() == PolicyType.DROP) {
pierventre4f68ffa2021-03-09 22:52:14 +0100651 // Firstly builds the fwd objective with the wipeDeferred action.
pierventre30368ab2021-02-24 23:23:22 +0100652 TrafficTreatment dropTreatment = DefaultTrafficTreatment.builder()
653 .wipeDeferred()
654 .build();
655 builder.withTreatment(dropTreatment);
pierventre4f68ffa2021-03-09 22:52:14 +0100656 } else if (policy.policyType() == PolicyType.REDIRECT) {
657
658 // Here we need to set only the next step
659 builder.nextStep(policyOperation.objectiveOperation().id());
pierventre30368ab2021-02-24 23:23:22 +0100660 }
pierventre4f68ffa2021-03-09 22:52:14 +0100661 // Once, the fwd objective has completed its execution, we update the policiesOps map
Wailok Shum6f71cd92021-05-06 20:05:29 +0800662 CompletableFuture<Objective> addNewFuture = new CompletableFuture<>();
663 CompletableFuture<Objective> removeOldFuture = new CompletableFuture<>();
pierventre4f68ffa2021-03-09 22:52:14 +0100664 if (log.isDebugEnabled()) {
665 log.debug("Installing forwarding objective for dev: {}", deviceId);
666 }
Wailok Shum6f71cd92021-05-06 20:05:29 +0800667 ObjectiveContext addNewContext = new DefaultObjectiveContext(
pierventre4f68ffa2021-03-09 22:52:14 +0100668 (objective) -> {
669 if (log.isDebugEnabled()) {
670 log.debug("Forwarding objective for policy {} installed", trafficMatch.policyId());
671 }
Wailok Shum6f71cd92021-05-06 20:05:29 +0800672 addNewFuture.complete(objective);
pierventre4f68ffa2021-03-09 22:52:14 +0100673 },
674 (objective, error) -> {
675 log.warn("Failed to install forwarding objective for policy {}: {}",
676 trafficMatch.policyId(), error);
Wailok Shum6f71cd92021-05-06 20:05:29 +0800677 addNewFuture.complete(null);
pierventre4f68ffa2021-03-09 22:52:14 +0100678 });
Wailok Shum6f71cd92021-05-06 20:05:29 +0800679 ObjectiveContext removeOldContext = new DefaultObjectiveContext(
680 (objective) -> {
681 if (log.isDebugEnabled()) {
682 log.debug("Old forwarding objective for policy {} removed, update finished",
683 trafficMatch.policyId());
684 }
685 removeOldFuture.complete(objective);
686 },
687 (objective, error) -> {
688 log.warn("Failed to remove old forwarding objective for policy {}: {}",
689 trafficMatch.policyId(), error);
690 removeOldFuture.complete(null);
691 });
pierventre4f68ffa2021-03-09 22:52:14 +0100692 // Context is not serializable
693 ForwardingObjective serializableObjective = builder.add();
Wailok Shum6f71cd92021-05-06 20:05:29 +0800694 flowObjectiveService.forward(deviceId, builder.add(addNewContext));
695 addNewFuture.whenComplete((objective, ex) -> {
pierventre4f68ffa2021-03-09 22:52:14 +0100696 if (ex != null) {
697 log.error("Exception installing forwarding objective", ex);
698 } else if (objective != null) {
Wailok Shum4df59312021-06-08 21:44:00 +0800699 // Remove existing flow after new flow is installed
700 // base on priority, selector and metadata change
Wailok Shum6f71cd92021-05-06 20:05:29 +0800701 if (oldTrafficOperation != null && oldTrafficOperation.objectiveOperation() != null
702 && oldTrafficOperation.isInstall()
Wailok Shum4df59312021-06-08 21:44:00 +0800703 && (oldTrafficOperation.objectiveOperation().priority() != serializableObjective.priority()
704 || !((ForwardingObjective) oldTrafficOperation.objectiveOperation()).selector()
705 .equals(serializableObjective.selector())
706 || !((ForwardingObjective) oldTrafficOperation.objectiveOperation()).meta()
707 .equals(serializableObjective.meta()))) {
Wailok Shum6f71cd92021-05-06 20:05:29 +0800708 ForwardingObjective oldFwdObj = (ForwardingObjective) oldTrafficOperation.objectiveOperation();
709 ForwardingObjective.Builder oldBuilder = DefaultForwardingObjective.builder(oldFwdObj);
710 flowObjectiveService.forward(deviceId, oldBuilder.remove(removeOldContext));
711 } else {
712 operations.computeIfPresent(trafficMatchKey.toString(), (k, v) -> {
713 if (!v.isDone() && v.isInstall()) {
714 v.isDone(true);
715 v.objectiveOperation(serializableObjective);
716 }
717 return v;
718 });
719 }
720 }
721 });
722 removeOldFuture.whenComplete((objective, ex) -> {
723 if (ex != null) {
724 log.error("Exception removing old forwarding objective", ex);
725 } else if (objective != null) {
pierventre4f68ffa2021-03-09 22:52:14 +0100726 operations.computeIfPresent(trafficMatchKey.toString(), (k, v) -> {
727 if (!v.isDone() && v.isInstall()) {
728 v.isDone(true);
729 v.objectiveOperation(serializableObjective);
730 }
731 return v;
732 });
733 }
734 });
pierventre30368ab2021-02-24 23:23:22 +0100735 }
736
737 // Updates traffic match status if all the pending ops are done
738 private void updateTrafficMatch(TrafficMatch trafficMatch, boolean install) {
739 if (!isLeader(trafficMatch.policyId())) {
740 if (log.isDebugEnabled()) {
741 log.debug("Instance is not leader for policy {}", trafficMatch.policyId());
742 }
743 return;
744 }
745 workers.execute(() -> updateTrafficMatchInternal(trafficMatch.trafficMatchId(), install),
746 trafficMatch.policyId().hashCode());
747 }
748
749 private void updateTrafficMatchInternal(TrafficMatchId trafficMatchId, boolean install) {
750 // If there are no more pending ops we are ready to go; potentially we can check
751 // if the id is contained. Updates traffic matches only if they are still present
752 Optional<Map.Entry<String, Versioned<Operation>>> notYetDone = operations.entrySet().stream()
753 .filter(entry -> entry.getValue().value().trafficMatch().isPresent())
754 .filter(entry -> TrafficMatchKey.fromString(entry.getKey()).trafficMatchId().equals(trafficMatchId))
755 .filter(entry -> !entry.getValue().value().isDone() && entry.getValue().value().isInstall() == install)
756 .findFirst();
757 if (notYetDone.isEmpty()) {
758 trafficMatches.computeIfPresent(trafficMatchId, (k, v) -> {
759 if (v.trafficMatchState() == TrafficMatchState.PENDING_ADD && install) {
760 if (log.isDebugEnabled()) {
761 log.debug("Traffic match {} is ready", trafficMatchId);
762 }
763 v.trafficMatchState(TrafficMatchState.ADDED);
764 } else if (v.trafficMatchState() == TrafficMatchState.PENDING_REMOVE && !install) {
765 if (log.isDebugEnabled()) {
766 log.debug("Traffic match {} is removed", trafficMatchId);
767 }
768 v = null;
769 }
770 return v;
771 });
772 }
773 }
774
775 // Look for any pending traffic match waiting for the policy
776 private void updatePendingTrafficMatches(PolicyId policyId) {
777 Set<TrafficMatchRequest> pendingTrafficMatches = trafficMatches.stream()
778 .filter(trafficMatchEntry -> trafficMatchEntry.getValue().value().policyId().equals(policyId) &&
779 trafficMatchEntry.getValue().value().trafficMatchState() == TrafficMatchState.PENDING_ADD)
780 .map(trafficMatchEntry -> trafficMatchEntry.getValue().value())
781 .collect(Collectors.toSet());
782 for (TrafficMatchRequest trafficMatch : pendingTrafficMatches) {
783 sendTrafficMatch(trafficMatch.trafficMatch(), true);
784 }
785 }
786
787 // Traffic match removal in a device
788 private void removeTrafficMatchInDevice(DeviceId deviceId, TrafficMatch trafficMatch) {
789 if (log.isDebugEnabled()) {
790 log.debug("Removing traffic match {} associated to policy {}",
791 trafficMatch.trafficMatchId(), trafficMatch.policyId());
792 }
793 TrafficMatchKey trafficMatchKey = new TrafficMatchKey(deviceId, trafficMatch.trafficMatchId());
794 Operation operation = Versioned.valueOrNull(operations.get(trafficMatchKey.toString()));
795 if (operation == null || operation.objectiveOperation() == null) {
796 log.warn("There are no ops associated with {}", trafficMatchKey);
797 operation = Operation.builder()
798 .isDone(true)
799 .isInstall(false)
800 .trafficMatch(trafficMatch)
801 .build();
802 operations.put(trafficMatchKey.toString(), operation);
pierventre4f68ffa2021-03-09 22:52:14 +0100803 } else if (!operation.isInstall()) {
804 if (log.isDebugEnabled()) {
805 log.debug("There is already an uninstall operation for traffic match {} associated to policy {}" +
806 " for device {}", trafficMatch.trafficMatchId(), trafficMatch.policyId(), deviceId);
807 }
pierventre30368ab2021-02-24 23:23:22 +0100808 } else {
809 ForwardingObjective oldObj = (ForwardingObjective) operation.objectiveOperation();
810 operation = Operation.builder(operation)
pierventre30368ab2021-02-24 23:23:22 +0100811 .isInstall(false)
812 .build();
813 operations.put(trafficMatchKey.toString(), operation);
814 ForwardingObjective.Builder builder = DefaultForwardingObjective.builder(oldObj);
815 CompletableFuture<Objective> future = new CompletableFuture<>();
816 if (log.isDebugEnabled()) {
pierventre4f68ffa2021-03-09 22:52:14 +0100817 log.debug("Removing forwarding objectives for dev: {}", deviceId);
pierventre30368ab2021-02-24 23:23:22 +0100818 }
819 ObjectiveContext context = new DefaultObjectiveContext(
820 (objective) -> {
821 if (log.isDebugEnabled()) {
pierventre4f68ffa2021-03-09 22:52:14 +0100822 log.debug("Forwarding objective for policy {} removed", trafficMatch.policyId());
pierventre30368ab2021-02-24 23:23:22 +0100823 }
824 future.complete(objective);
825 },
826 (objective, error) -> {
pierventre4f68ffa2021-03-09 22:52:14 +0100827 log.warn("Failed to remove forwarding objective for policy {}: {}",
828 trafficMatch.policyId(), error);
pierventre30368ab2021-02-24 23:23:22 +0100829 future.complete(null);
830 });
831 ForwardingObjective serializableObjective = builder.remove();
832 flowObjectiveService.forward(deviceId, builder.remove(context));
833 future.whenComplete((objective, ex) -> {
834 if (ex != null) {
pierventre4f68ffa2021-03-09 22:52:14 +0100835 log.error("Exception removing forwarding objective", ex);
pierventre30368ab2021-02-24 23:23:22 +0100836 } else if (objective != null) {
837 operations.computeIfPresent(trafficMatchKey.toString(), (k, v) -> {
838 if (!v.isDone() && !v.isInstall()) {
839 v.isDone(true);
840 v.objectiveOperation(serializableObjective);
841 }
842 return v;
843 });
844 }
845 });
846 }
847 }
848
pierventre4f68ffa2021-03-09 22:52:14 +0100849 // It is used when a policy has been removed but there are still traffic matches depending on it
850 private Optional<TrafficMatchRequest> dependingTrafficMatches(PolicyId policyId) {
851 return trafficMatches.stream()
pierventre30368ab2021-02-24 23:23:22 +0100852 .filter(trafficMatchEntry -> trafficMatchEntry.getValue().value().policyId().equals(policyId) &&
853 trafficMatchEntry.getValue().value().trafficMatchState() == TrafficMatchState.ADDED)
854 .map(trafficMatchEntry -> trafficMatchEntry.getValue().value())
pierventre4f68ffa2021-03-09 22:52:14 +0100855 .findFirst();
pierventre30368ab2021-02-24 23:23:22 +0100856 }
857
858 // Utility that removes operations related to a policy or to a traffic match.
859 private void removeOperations(PolicyId policyId, Optional<TrafficMatchId> trafficMatchId) {
860 if (!isLeader(policyId)) {
861 if (log.isDebugEnabled()) {
862 log.debug("Instance is not leader for policy {}", policyId);
863 }
864 return;
865 }
Wailok Shume2ab3d62021-05-27 04:40:38 +0800866 List<DeviceId> edgeDeviceIds = getEdgeDeviceIds();
pierventre30368ab2021-02-24 23:23:22 +0100867 for (DeviceId deviceId : edgeDeviceIds) {
868 workers.execute(() -> {
869 String key;
870 if (trafficMatchId.isPresent()) {
871 key = new TrafficMatchKey(deviceId, trafficMatchId.get()).toString();
872 } else {
873 key = new PolicyKey(deviceId, policyId).toString();
874 }
875 operations.remove(key);
876 }, deviceId.hashCode());
877 }
878 }
879
pierventre4f68ffa2021-03-09 22:52:14 +0100880 private ForwardingObjective.Builder trafficMatchFwdObjective(TrafficMatch trafficMatch, PolicyType policyType) {
881 TrafficSelector.Builder metaBuilder = DefaultTrafficSelector.builder(trafficMatch.trafficSelector());
pierventree9261c92021-08-27 13:12:06 +0200882 // Driver should use this meta to match ig_port_type field in the ACL table
pierventre4f68ffa2021-03-09 22:52:14 +0100883 if (policyType == PolicyType.REDIRECT) {
884 metaBuilder.matchMetadata(EDGE_PORT);
885 }
pierventre30368ab2021-02-24 23:23:22 +0100886 return DefaultForwardingObjective.builder()
Wailok Shum37dd29a2021-04-27 18:13:55 +0800887 .withPriority(trafficMatch.trafficMatchPriority().priority())
pierventre30368ab2021-02-24 23:23:22 +0100888 .withSelector(trafficMatch.trafficSelector())
pierventre4f68ffa2021-03-09 22:52:14 +0100889 .withMeta(metaBuilder.build())
pierventre30368ab2021-02-24 23:23:22 +0100890 .fromApp(appId)
891 .withFlag(ForwardingObjective.Flag.VERSATILE)
892 .makePermanent();
893 }
894
pierventre4f68ffa2021-03-09 22:52:14 +0100895 private NextObjective.Builder redirectPolicyNextObjective(DeviceId srcDevice, RedirectPolicy redirectPolicy) {
896 Set<Link> egressLinks = linkService.getDeviceEgressLinks(srcDevice);
897 Map<ConnectPoint, DeviceId> egressPortsToEnforce = Maps.newHashMap();
Wailok Shume2ab3d62021-05-27 04:40:38 +0800898 List<DeviceId> edgeDevices = getEdgeDeviceIds();
pierventre4f68ffa2021-03-09 22:52:14 +0100899 egressLinks.stream()
900 .filter(link -> redirectPolicy.spinesToEnforce().contains(link.dst().deviceId()) &&
901 !edgeDevices.contains(link.dst().deviceId()))
902 .forEach(link -> egressPortsToEnforce.put(link.src(), link.dst().deviceId()));
903 // No ports no friend
904 if (egressPortsToEnforce.isEmpty()) {
905 log.warn("There are no port available for the REDIRECT policy {}", redirectPolicy.policyId());
906 return null;
907 }
908 // We need to add a treatment for each valid egress port. The treatment
909 // requires to set src and dst mac address and set the egress port. We are
910 // deliberately not providing the metadata to prevent the programming of
911 // some tables which are already controlled by SegmentRouting or are unnecessary
912 int nextId = flowObjectiveService.allocateNextId();
913 DefaultNextObjective.Builder builder = DefaultNextObjective.builder()
914 .withId(nextId)
915 .withType(NextObjective.Type.HASHED)
916 .fromApp(appId);
917 MacAddress srcDeviceMac;
918 try {
Wailok Shume2ab3d62021-05-27 04:40:38 +0800919 srcDeviceMac = getDeviceMacAddress(srcDevice);
pierventre4f68ffa2021-03-09 22:52:14 +0100920 } catch (DeviceConfigNotFoundException e) {
921 log.warn(e.getMessage() + " Aborting installation REDIRECT policy {}", redirectPolicy.policyId());
922 return null;
923 }
924 MacAddress neigborDeviceMac;
925 TrafficTreatment.Builder tBuilder;
926 for (Map.Entry<ConnectPoint, DeviceId> entry : egressPortsToEnforce.entrySet()) {
927 try {
Wailok Shume2ab3d62021-05-27 04:40:38 +0800928 neigborDeviceMac = getDeviceMacAddress(entry.getValue());
pierventre4f68ffa2021-03-09 22:52:14 +0100929 } catch (DeviceConfigNotFoundException e) {
930 log.warn(e.getMessage() + " Aborting installation REDIRECT policy {}", redirectPolicy.policyId());
931 return null;
932 }
933 tBuilder = DefaultTrafficTreatment.builder()
934 .setEthSrc(srcDeviceMac)
935 .setEthDst(neigborDeviceMac)
936 .setOutput(entry.getKey().port());
937 builder.addTreatment(tBuilder.build());
938 }
939 return builder;
940 }
941
pierventre30368ab2021-02-24 23:23:22 +0100942 // Each map has an event listener enabling the events distribution across the cluster
943 private class InternalPolMapEventListener implements MapEventListener<PolicyId, PolicyRequest> {
944 @Override
945 public void event(MapEvent<PolicyId, PolicyRequest> event) {
946 Versioned<PolicyRequest> value = event.type() == MapEvent.Type.REMOVE ?
947 event.oldValue() : event.newValue();
948 PolicyRequest policyRequest = value.value();
949 Policy policy = policyRequest.policy();
950 switch (event.type()) {
951 case INSERT:
952 case UPDATE:
953 switch (policyRequest.policyState()) {
954 case PENDING_ADD:
955 sendPolicy(policy, true);
956 break;
957 case PENDING_REMOVE:
958 sendPolicy(policy, false);
959 break;
960 case ADDED:
961 break;
962 default:
963 log.warn("Unknown policy state type {}", policyRequest.policyState());
964 }
965 break;
966 case REMOVE:
967 removeOperations(policy.policyId(), Optional.empty());
pierventre30368ab2021-02-24 23:23:22 +0100968 break;
969 default:
970 log.warn("Unknown event type {}", event.type());
971
972 }
973 }
974 }
975
976 private class InternalTMatchMapEventListener implements MapEventListener<TrafficMatchId, TrafficMatchRequest> {
977 @Override
978 public void event(MapEvent<TrafficMatchId, TrafficMatchRequest> event) {
979 Versioned<TrafficMatchRequest> value = event.type() == MapEvent.Type.REMOVE ?
980 event.oldValue() : event.newValue();
981 TrafficMatchRequest trafficMatchRequest = value.value();
982 TrafficMatch trafficMatch = trafficMatchRequest.trafficMatch();
983 switch (event.type()) {
984 case INSERT:
985 case UPDATE:
986 switch (trafficMatchRequest.trafficMatchState()) {
987 case PENDING_ADD:
988 sendTrafficMatch(trafficMatch, true);
989 break;
990 case PENDING_REMOVE:
991 sendTrafficMatch(trafficMatch, false);
992 break;
993 case ADDED:
994 break;
995 default:
996 log.warn("Unknown traffic match state type {}", trafficMatchRequest.trafficMatchState());
997 }
998 break;
999 case REMOVE:
1000 removeOperations(trafficMatch.policyId(), Optional.of(trafficMatch.trafficMatchId()));
1001 break;
1002 default:
1003 log.warn("Unknown event type {}", event.type());
1004 }
1005 }
1006 }
1007
1008 private class InternalOpsMapEventListener implements MapEventListener<String, Operation> {
1009 @Override
1010 public void event(MapEvent<String, Operation> event) {
1011 String key = event.key();
1012 Versioned<Operation> value = event.type() == MapEvent.Type.REMOVE ?
1013 event.oldValue() : event.newValue();
1014 Operation operation = value.value();
1015 switch (event.type()) {
1016 case INSERT:
1017 case UPDATE:
1018 if (operation.isDone()) {
1019 if (operation.policy().isPresent()) {
1020 PolicyKey policyKey = PolicyKey.fromString(key);
1021 updatePolicy(policyKey.policyId(), operation.isInstall());
1022 } else if (operation.trafficMatch().isPresent()) {
1023 updateTrafficMatch(operation.trafficMatch().get(), operation.isInstall());
1024 } else {
1025 log.warn("Unknown pending operation");
1026 }
1027 }
1028 break;
1029 case REMOVE:
1030 break;
1031 default:
1032 log.warn("Unknown event type {}", event.type());
1033 }
1034 }
1035 }
1036
1037 // Using the work partition service defines who is in charge of a given policy.
1038 private boolean isLeader(PolicyId policyId) {
1039 final NodeId currentNodeId = clusterService.getLocalNode().id();
1040 final NodeId leader = workPartitionService.getLeader(policyId, this::hasher);
1041 if (leader == null) {
1042 log.error("Fail to elect a leader for {}.", policyId);
1043 return false;
1044 }
1045 policyLeaderCache.put(policyId, leader);
1046 return currentNodeId.equals(leader);
1047 }
1048
1049 private Long hasher(PolicyId policyId) {
1050 return HASH_FN.newHasher()
1051 .putUnencodedChars(policyId.toString())
1052 .hash()
1053 .asLong();
1054 }
1055
pierventre4f68ffa2021-03-09 22:52:14 +01001056 // TODO Periodic checker, consider to add store and delegates.
1057
pierventre30368ab2021-02-24 23:23:22 +01001058 // Check periodically for any issue and try to resolve automatically if possible
1059 private final class PolicyChecker implements Runnable {
1060 @Override
1061 public void run() {
1062 }
1063 }
Wailok Shume2ab3d62021-05-27 04:40:38 +08001064
1065 // Netcfg event listener
1066 private class InternalConfigListener implements NetworkConfigListener {
1067 @Override
1068 public void event(NetworkConfigEvent event) {
1069 eventExecutor.execute(() -> {
1070 switch (event.type()) {
1071 case CONFIG_ADDED:
1072 case CONFIG_UPDATED:
1073 if (event.configClass() == SegmentRoutingDeviceConfig.class) {
1074 // Reset all policy state to PENDING_ADD
1075 ImmutableSet<PolicyId> policyIds = ImmutableSet.copyOf(policies.keySet());
1076 policyIds.forEach((policyId) -> {
1077 policies.computeIfPresent(policyId, (k, v) -> {
1078 v.policyState(PolicyState.PENDING_ADD);
1079 return v;
1080 });
1081 });
1082 // Reset all TrafficMatch state to PENDING_ADD
1083 ImmutableSet<TrafficMatchId> trafficMatchIds = ImmutableSet.copyOf(trafficMatches.keySet());
1084 trafficMatchIds.forEach((trafficMatchId) -> {
1085 trafficMatches.computeIfPresent(trafficMatchId, (k, v) -> {
1086 v.trafficMatchState(TrafficMatchState.PENDING_ADD);
1087 return v;
1088 });
1089 });
1090 }
1091 break;
1092 default:
1093 break;
1094 }
1095 });
1096 }
1097 }
1098
1099 private List<DeviceId> getEdgeDeviceIds() {
1100 List<DeviceId> edges = new ArrayList<>();
1101 deviceService.getDevices().forEach((device) -> {
1102 DeviceId deviceId = device.id();
1103 SegmentRoutingDeviceConfig srDevCfg = cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
1104 if (srDevCfg != null && srDevCfg.isEdgeRouter()) {
1105 edges.add(deviceId);
1106 }
1107 });
1108 return edges;
1109 }
1110
1111 private MacAddress getDeviceMacAddress(DeviceId deviceId) throws DeviceConfigNotFoundException {
1112 SegmentRoutingDeviceConfig srDevCfg = cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
1113 if (srDevCfg != null) {
1114 return srDevCfg.routerMac();
1115 } else {
1116 throw new DeviceConfigNotFoundException("Config for device: " + deviceId.toString() + " not found");
1117 }
1118 }
pierventre30368ab2021-02-24 23:23:22 +01001119}