blob: b9543056d9b71237df2dbc991c845faa38cc2e8d [file] [log] [blame]
Ray Milkey661c38c2016-02-26 17:12:17 -08001/*
2 * Copyright 2016 Open Networking Laboratory
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.net.intent.impl.compiler;
17
18import java.util.Collections;
19import java.util.HashMap;
20import java.util.Iterator;
21import java.util.List;
22import java.util.Map;
23import java.util.Optional;
24import java.util.Set;
25import java.util.stream.Collectors;
26import java.util.stream.Stream;
27
Michele Santuari6096acd2016-02-09 17:00:37 +010028import org.onlab.packet.EthType;
29import org.onlab.packet.Ethernet;
30import org.onlab.packet.MplsLabel;
Ray Milkey661c38c2016-02-26 17:12:17 -080031import org.onlab.packet.VlanId;
32import org.onosproject.net.ConnectPoint;
33import org.onosproject.net.DeviceId;
34import org.onosproject.net.Link;
35import org.onosproject.net.LinkKey;
36import org.onosproject.net.flow.DefaultTrafficSelector;
37import org.onosproject.net.flow.DefaultTrafficTreatment;
38import org.onosproject.net.flow.TrafficSelector;
39import org.onosproject.net.flow.TrafficTreatment;
40import org.onosproject.net.flow.criteria.Criterion;
Michele Santuari6096acd2016-02-09 17:00:37 +010041import org.onosproject.net.flow.criteria.EthTypeCriterion;
42import org.onosproject.net.flow.criteria.MplsCriterion;
Ray Milkey661c38c2016-02-26 17:12:17 -080043import org.onosproject.net.flow.criteria.VlanIdCriterion;
Michele Santuari6096acd2016-02-09 17:00:37 +010044import org.onosproject.net.flow.instructions.Instruction;
Ray Milkey661c38c2016-02-26 17:12:17 -080045import org.onosproject.net.flow.instructions.L2ModificationInstruction;
46import org.onosproject.net.intent.PathIntent;
47import org.onosproject.net.intent.constraint.EncapsulationConstraint;
48import org.onosproject.net.intent.impl.IntentCompilationException;
Sho SHIMIZUe18cb122016-02-22 21:04:56 -080049import org.onosproject.net.resource.Resource;
50import org.onosproject.net.resource.ResourceAllocation;
51import org.onosproject.net.resource.ResourceService;
52import org.onosproject.net.resource.Resources;
Ray Milkey661c38c2016-02-26 17:12:17 -080053import org.slf4j.Logger;
54
55import com.google.common.collect.ImmutableList;
56import com.google.common.collect.Sets;
57
58import static org.onosproject.net.LinkKey.linkKey;
59
60/**
61 * Shared APIs and implementations for path compilers.
62 */
63
64public class PathCompiler<T> {
65
66 /**
67 * Defines methods used to create objects representing flows.
68 */
69 public interface PathCompilerCreateFlow<T> {
70
71 void createFlow(TrafficSelector originalSelector,
72 TrafficTreatment originalTreatment,
73 ConnectPoint ingress, ConnectPoint egress,
74 int priority,
75 boolean applyTreatment,
76 List<T> flows,
77 List<DeviceId> devices);
78
79 Logger log();
80
81 ResourceService resourceService();
82 }
83
84 private boolean isLast(List<Link> links, int i) {
85 return i == links.size() - 2;
86 }
87
88 private Map<LinkKey, VlanId> assignVlanId(PathCompilerCreateFlow creator, PathIntent intent) {
89 Set<LinkKey> linkRequest =
90 Sets.newHashSetWithExpectedSize(intent.path()
91 .links().size() - 2);
92 for (int i = 1; i <= intent.path().links().size() - 2; i++) {
93 LinkKey link = linkKey(intent.path().links().get(i));
94 linkRequest.add(link);
95 // add the inverse link. I want that the VLANID is reserved both for
96 // the direct and inverse link
97 linkRequest.add(linkKey(link.dst(), link.src()));
98 }
99
100 Map<LinkKey, VlanId> vlanIds = findVlanIds(creator, linkRequest);
101 if (vlanIds.isEmpty()) {
102 creator.log().warn("No VLAN IDs available");
103 return Collections.emptyMap();
104 }
105
106 //same VLANID is used for both directions
107 Set<Resource> resources = vlanIds.entrySet().stream()
108 .flatMap(x -> Stream.of(
109 Resources.discrete(x.getKey().src().deviceId(), x.getKey().src().port(), x.getValue())
110 .resource(),
111 Resources.discrete(x.getKey().dst().deviceId(), x.getKey().dst().port(), x.getValue())
112 .resource()
113 ))
114 .collect(Collectors.toSet());
Sho SHIMIZUe18cb122016-02-22 21:04:56 -0800115 List<ResourceAllocation> allocations =
Ray Milkey661c38c2016-02-26 17:12:17 -0800116 creator.resourceService().allocate(intent.id(), ImmutableList.copyOf(resources));
117 if (allocations.isEmpty()) {
118 Collections.emptyMap();
119 }
120
121 return vlanIds;
122 }
123
124 private Map<LinkKey, VlanId> findVlanIds(PathCompilerCreateFlow creator, Set<LinkKey> links) {
125 Map<LinkKey, VlanId> vlanIds = new HashMap<>();
126 for (LinkKey link : links) {
127 Set<VlanId> forward = findVlanId(creator, link.src());
128 Set<VlanId> backward = findVlanId(creator, link.dst());
129 Set<VlanId> common = Sets.intersection(forward, backward);
130 if (common.isEmpty()) {
131 continue;
132 }
133 vlanIds.put(link, common.iterator().next());
134 }
135 return vlanIds;
136 }
137
138 private Set<VlanId> findVlanId(PathCompilerCreateFlow creator, ConnectPoint cp) {
139 return creator.resourceService().getAvailableResourceValues(
140 Resources.discrete(cp.deviceId(), cp.port()).id(),
141 VlanId.class);
142 }
143
144 private void manageVlanEncap(PathCompilerCreateFlow<T> creator, List<T> flows,
145 List<DeviceId> devices,
146 PathIntent intent) {
147 Map<LinkKey, VlanId> vlanIds = assignVlanId(creator, intent);
148
149 Iterator<Link> links = intent.path().links().iterator();
150 Link srcLink = links.next();
151
152 Link link = links.next();
153
154 // Ingress traffic
155 VlanId vlanId = vlanIds.get(linkKey(link));
156 if (vlanId == null) {
157 throw new IntentCompilationException("No available VLAN ID for " + link);
158 }
159 VlanId prevVlanId = vlanId;
160
161 Optional<VlanIdCriterion> vlanCriterion = intent.selector().criteria()
162 .stream().filter(criterion -> criterion.type() == Criterion.Type.VLAN_VID)
163 .map(criterion -> (VlanIdCriterion) criterion)
164 .findAny();
165
166 //Push VLAN if selector does not include VLAN
167 TrafficTreatment.Builder treatBuilder = DefaultTrafficTreatment.builder();
168 if (!vlanCriterion.isPresent()) {
169 treatBuilder.pushVlan();
170 }
171 //Tag the traffic with the new encapsulation VLAN
172 treatBuilder.setVlanId(vlanId);
173 creator.createFlow(intent.selector(), treatBuilder.build(),
174 srcLink.dst(), link.src(), intent.priority(), true,
175 flows, devices);
176
177 ConnectPoint prev = link.dst();
178
179 while (links.hasNext()) {
180
181 link = links.next();
182
183 if (links.hasNext()) {
184 // Transit traffic
185 VlanId egressVlanId = vlanIds.get(linkKey(link));
186 if (egressVlanId == null) {
187 throw new IntentCompilationException("No available VLAN ID for " + link);
188 }
189 prevVlanId = egressVlanId;
190
191 TrafficSelector transitSelector = DefaultTrafficSelector.builder()
192 .matchInPort(prev.port())
193 .matchVlanId(prevVlanId).build();
194
195 TrafficTreatment.Builder transitTreat = DefaultTrafficTreatment.builder();
196
197 // Set the new vlanId only if the previous one is different
198 if (!prevVlanId.equals(egressVlanId)) {
199 transitTreat.setVlanId(egressVlanId);
200 }
201 creator.createFlow(transitSelector,
202 transitTreat.build(), prev, link.src(),
203 intent.priority(), true, flows, devices);
204 prev = link.dst();
205 } else {
206 // Egress traffic
207 TrafficSelector egressSelector = DefaultTrafficSelector.builder()
208 .matchInPort(prev.port())
209 .matchVlanId(prevVlanId).build();
210 TrafficTreatment.Builder egressTreat = DefaultTrafficTreatment.builder(intent.treatment());
211
212 Optional<L2ModificationInstruction.ModVlanIdInstruction> modVlanIdInstruction = intent.treatment()
213 .allInstructions().stream().filter(
214 instruction -> instruction instanceof L2ModificationInstruction.ModVlanIdInstruction)
215 .map(x -> (L2ModificationInstruction.ModVlanIdInstruction) x).findAny();
216
217 Optional<L2ModificationInstruction.PopVlanInstruction> popVlanInstruction = intent.treatment()
218 .allInstructions().stream().filter(
219 instruction -> instruction instanceof L2ModificationInstruction.PopVlanInstruction)
220 .map(x -> (L2ModificationInstruction.PopVlanInstruction) x).findAny();
221
222 if (!modVlanIdInstruction.isPresent() && !popVlanInstruction.isPresent()) {
223 if (vlanCriterion.isPresent()) {
224 egressTreat.setVlanId(vlanCriterion.get().vlanId());
225 } else {
226 egressTreat.popVlan();
227 }
228 }
229
230 creator.createFlow(egressSelector,
231 egressTreat.build(), prev, link.src(),
232 intent.priority(), true, flows, devices);
233 }
234 }
235 }
236
Michele Santuari6096acd2016-02-09 17:00:37 +0100237 private Map<LinkKey, MplsLabel> assignMplsLabel(PathCompilerCreateFlow creator, PathIntent intent) {
238 Set<LinkKey> linkRequest =
239 Sets.newHashSetWithExpectedSize(intent.path()
240 .links().size() - 2);
241 for (int i = 1; i <= intent.path().links().size() - 2; i++) {
242 LinkKey link = linkKey(intent.path().links().get(i));
243 linkRequest.add(link);
244 // add the inverse link. I want that the VLANID is reserved both for
245 // the direct and inverse link
246 linkRequest.add(linkKey(link.dst(), link.src()));
247 }
248
249 Map<LinkKey, MplsLabel> labels = findMplsLabels(creator, linkRequest);
250 if (labels.isEmpty()) {
251 throw new IntentCompilationException("No available MPLS Label");
252 }
253
254 // for short term solution: same label is used for both directions
255 // TODO: introduce the concept of Tx and Rx resources of a port
256 Set<Resource> resources = labels.entrySet().stream()
257 .flatMap(x -> Stream.of(
258 Resources.discrete(x.getKey().src().deviceId(), x.getKey().src().port(), x.getValue())
259 .resource(),
260 Resources.discrete(x.getKey().dst().deviceId(), x.getKey().dst().port(), x.getValue())
261 .resource()
262 ))
263 .collect(Collectors.toSet());
264 List<ResourceAllocation> allocations =
265 creator.resourceService().allocate(intent.id(), ImmutableList.copyOf(resources));
266 if (allocations.isEmpty()) {
267 Collections.emptyMap();
268 }
269
270 return labels;
271 }
272
273 private Map<LinkKey, MplsLabel> findMplsLabels(PathCompilerCreateFlow creator, Set<LinkKey> links) {
274 Map<LinkKey, MplsLabel> labels = new HashMap<>();
275 for (LinkKey link : links) {
276 Set<MplsLabel> forward = findMplsLabel(creator, link.src());
277 Set<MplsLabel> backward = findMplsLabel(creator, link.dst());
278 Set<MplsLabel> common = Sets.intersection(forward, backward);
279 if (common.isEmpty()) {
280 continue;
281 }
282 labels.put(link, common.iterator().next());
283 }
284
285 return labels;
286 }
287
288 private Set<MplsLabel> findMplsLabel(PathCompilerCreateFlow creator, ConnectPoint cp) {
289 return creator.resourceService().getAvailableResourceValues(
290 Resources.discrete(cp.deviceId(), cp.port()).id(),
291 MplsLabel.class);
292 }
293
294 private void manageMplsEncap(PathCompilerCreateFlow<T> creator, List<T> flows,
295 List<DeviceId> devices,
296 PathIntent intent) {
297 Map<LinkKey, MplsLabel> mplsLabels = assignMplsLabel(creator, intent);
298
299 Iterator<Link> links = intent.path().links().iterator();
300 Link srcLink = links.next();
301
302 Link link = links.next();
303 // List of flow rules to be installed
304
305 // Ingress traffic
306 MplsLabel mplsLabel = mplsLabels.get(linkKey(link));
307 if (mplsLabel == null) {
308 throw new IntentCompilationException("No available MPLS Label for " + link);
309 }
310 MplsLabel prevMplsLabel = mplsLabel;
311
312 Optional<MplsCriterion> mplsCriterion = intent.selector().criteria()
313 .stream().filter(criterion -> criterion.type() == Criterion.Type.MPLS_LABEL)
314 .map(criterion -> (MplsCriterion) criterion)
315 .findAny();
316
317 //Push MPLS if selector does not include MPLS
318 TrafficTreatment.Builder treatBuilder = DefaultTrafficTreatment.builder();
319 if (!mplsCriterion.isPresent()) {
320 treatBuilder.pushMpls();
321 }
322 //Tag the traffic with the new encapsulation MPLS label
323 treatBuilder.setMpls(mplsLabel);
324 creator.createFlow(intent.selector(), treatBuilder.build(),
325 srcLink.dst(), link.src(), intent.priority(), true, flows, devices);
326
327 ConnectPoint prev = link.dst();
328
329 while (links.hasNext()) {
330
331 link = links.next();
332
333 if (links.hasNext()) {
334 // Transit traffic
335 MplsLabel transitMplsLabel = mplsLabels.get(linkKey(link));
336 if (transitMplsLabel == null) {
337 throw new IntentCompilationException("No available MPLS label for " + link);
338 }
339 prevMplsLabel = transitMplsLabel;
340
341 TrafficSelector transitSelector = DefaultTrafficSelector.builder()
342 .matchInPort(prev.port())
343 .matchEthType(Ethernet.MPLS_UNICAST)
344 .matchMplsLabel(prevMplsLabel).build();
345
346 TrafficTreatment.Builder transitTreat = DefaultTrafficTreatment.builder();
347
348 // Set the new MPLS Label only if the previous one is different
349 if (!prevMplsLabel.equals(transitMplsLabel)) {
350 transitTreat.setMpls(transitMplsLabel);
351 }
352 creator.createFlow(transitSelector,
353 transitTreat.build(), prev, link.src(), intent.priority(), true, flows, devices);
354 prev = link.dst();
355 } else {
356 TrafficSelector.Builder egressSelector = DefaultTrafficSelector.builder()
357 .matchInPort(prev.port())
358 .matchEthType(Ethernet.MPLS_UNICAST)
359 .matchMplsLabel(prevMplsLabel);
360 TrafficTreatment.Builder egressTreat = DefaultTrafficTreatment.builder(intent.treatment());
361
362 // Egress traffic
363 // check if the treatement is popVlan or setVlan (rewrite),
364 // than selector needs to match any VlanId
365 for (Instruction instruct : intent.treatment().allInstructions()) {
366 if (instruct instanceof L2ModificationInstruction) {
367 L2ModificationInstruction l2Mod = (L2ModificationInstruction) instruct;
368 if (l2Mod.subtype() == L2ModificationInstruction.L2SubType.VLAN_PUSH) {
369 break;
370 }
371 if (l2Mod.subtype() == L2ModificationInstruction.L2SubType.VLAN_POP ||
372 l2Mod.subtype() == L2ModificationInstruction.L2SubType.VLAN_ID) {
373 egressSelector.matchVlanId(VlanId.ANY);
374 }
375 }
376 }
377
378 if (mplsCriterion.isPresent()) {
379 egressTreat.setMpls(mplsCriterion.get().label());
380 } else {
381 egressTreat.popMpls(outputEthType(intent.selector()));
382 }
383
384
385 if (mplsCriterion.isPresent()) {
386 egressTreat.setMpls(mplsCriterion.get().label());
387 } else {
388 egressTreat.popVlan();
389 }
390
391 creator.createFlow(egressSelector.build(),
392 egressTreat.build(), prev, link.src(), intent.priority(), true, flows, devices);
393 }
394
395 }
396
397 }
398
399 private MplsLabel getMplsLabel(Map<LinkKey, MplsLabel> labels, LinkKey link) {
400 return labels.get(link);
401 }
402
403 // if the ingress ethertype is defined, the egress traffic
404 // will be use that value, otherwise the IPv4 ethertype is used.
405 private EthType outputEthType(TrafficSelector selector) {
406 Criterion c = selector.getCriterion(Criterion.Type.ETH_TYPE);
407 if (c != null && c instanceof EthTypeCriterion) {
408 EthTypeCriterion ethertype = (EthTypeCriterion) c;
409 return ethertype.ethType();
410 } else {
411 return EthType.EtherType.IPV4.ethType();
412 }
413 }
414
415
Ray Milkey661c38c2016-02-26 17:12:17 -0800416 /**
417 * Compiles an intent down to flows.
418 *
419 * @param creator how to create the flows
420 * @param intent intent to process
421 * @param flows list of generated flows
422 * @param devices list of devices that correspond to the flows
423 */
424 public void compile(PathCompilerCreateFlow<T> creator,
425 PathIntent intent,
426 List<T> flows,
427 List<DeviceId> devices) {
428 // Note: right now recompile is not considered
429 // TODO: implement recompile behavior
430
431 List<Link> links = intent.path().links();
432
433 Optional<EncapsulationConstraint> encapConstraint = intent.constraints().stream()
434 .filter(constraint -> constraint instanceof EncapsulationConstraint)
435 .map(x -> (EncapsulationConstraint) x).findAny();
436 //if no encapsulation or is involved only a single switch use the default behaviour
437 if (!encapConstraint.isPresent() || links.size() == 1) {
438 for (int i = 0; i < links.size() - 1; i++) {
439 ConnectPoint ingress = links.get(i).dst();
440 ConnectPoint egress = links.get(i + 1).src();
441 creator.createFlow(intent.selector(), intent.treatment(),
442 ingress, egress, intent.priority(),
443 isLast(links, i), flows, devices);
444 }
445 }
446
447 encapConstraint.map(EncapsulationConstraint::encapType)
448 .map(type -> {
449 switch (type) {
450 case VLAN:
451 manageVlanEncap(creator, flows, devices, intent);
Michele Santuari6096acd2016-02-09 17:00:37 +0100452 break;
453 case MPLS:
454 manageMplsEncap(creator, flows, devices, intent);
455 break;
Ray Milkey661c38c2016-02-26 17:12:17 -0800456 default:
457 // Nothing to do
458 }
459 return 0;
460 });
461 }
462
463}