blob: 2bb521c30956207f0a83040a1ef75ed2e5d72dda [file] [log] [blame]
Michele Santuari9a8d16d2016-03-24 10:37:58 -07001/*
2 * Copyright 2016-present 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 */
16
17package org.onosproject.drivers.corsa;
18
19import com.google.common.cache.Cache;
20import com.google.common.cache.CacheBuilder;
21import com.google.common.cache.RemovalCause;
22import com.google.common.cache.RemovalNotification;
23import org.onlab.osgi.ServiceDirectory;
24import org.onlab.packet.Ethernet;
25import org.onlab.util.KryoNamespace;
26import org.onosproject.core.ApplicationId;
27import org.onosproject.core.CoreService;
28import org.onosproject.net.DeviceId;
29import org.onosproject.net.behaviour.NextGroup;
30import org.onosproject.net.behaviour.Pipeliner;
31import org.onosproject.net.behaviour.PipelinerContext;
32import org.onosproject.net.device.DeviceService;
33import org.onosproject.net.driver.AbstractHandlerBehaviour;
34import org.onosproject.net.flow.DefaultFlowRule;
35import org.onosproject.net.flow.DefaultTrafficSelector;
36import org.onosproject.net.flow.DefaultTrafficTreatment;
37import org.onosproject.net.flow.FlowRule;
38import org.onosproject.net.flow.FlowRuleOperations;
39import org.onosproject.net.flow.FlowRuleOperationsContext;
40import org.onosproject.net.flow.FlowRuleService;
41import org.onosproject.net.flow.TrafficSelector;
42import org.onosproject.net.flow.TrafficTreatment;
43import org.onosproject.net.flow.criteria.Criteria;
44import org.onosproject.net.flow.criteria.Criterion;
45import org.onosproject.net.flow.criteria.EthCriterion;
46import org.onosproject.net.flow.criteria.EthTypeCriterion;
47import org.onosproject.net.flow.criteria.IPCriterion;
48import org.onosproject.net.flow.criteria.PortCriterion;
49import org.onosproject.net.flow.criteria.VlanIdCriterion;
50import org.onosproject.net.flowobjective.FilteringObjective;
51import org.onosproject.net.flowobjective.FlowObjectiveStore;
52import org.onosproject.net.flowobjective.ForwardingObjective;
53import org.onosproject.net.flowobjective.NextObjective;
54import org.onosproject.net.flowobjective.Objective;
55import org.onosproject.net.flowobjective.ObjectiveError;
56import org.onosproject.net.group.DefaultGroupBucket;
57import org.onosproject.net.group.DefaultGroupDescription;
58import org.onosproject.net.group.DefaultGroupKey;
59import org.onosproject.net.group.Group;
60import org.onosproject.net.group.GroupBucket;
61import org.onosproject.net.group.GroupBuckets;
62import org.onosproject.net.group.GroupDescription;
63import org.onosproject.net.group.GroupEvent;
64import org.onosproject.net.group.GroupKey;
65import org.onosproject.net.group.GroupListener;
66import org.onosproject.net.group.GroupService;
67import org.onosproject.net.meter.MeterService;
68import org.slf4j.Logger;
69
70import java.util.Collection;
71import java.util.Collections;
72import java.util.List;
73import java.util.Objects;
74import java.util.Set;
75import java.util.concurrent.Executors;
76import java.util.concurrent.ScheduledExecutorService;
77import java.util.concurrent.TimeUnit;
78import java.util.stream.Collectors;
79
80import static org.onlab.util.Tools.groupedThreads;
81import static org.onosproject.net.flow.FlowRule.Builder;
82import static org.slf4j.LoggerFactory.getLogger;
83
84/**
85 * Abstraction of the Corsa pipeline handler.
86 */
87public abstract class AbstractCorsaPipeline extends AbstractHandlerBehaviour implements Pipeliner {
88
89
90 private final Logger log = getLogger(getClass());
91
92 private ServiceDirectory serviceDirectory;
93 protected FlowRuleService flowRuleService;
94 private CoreService coreService;
95 private GroupService groupService;
96 protected MeterService meterService;
97 private FlowObjectiveStore flowObjectiveStore;
98 protected DeviceId deviceId;
99 protected ApplicationId appId;
100 protected DeviceService deviceService;
101
102 private KryoNamespace appKryo = new KryoNamespace.Builder()
103 .register(GroupKey.class)
104 .register(DefaultGroupKey.class)
105 .register(CorsaGroup.class)
106 .register(byte[].class)
107 .build();
108
109 private Cache<GroupKey, NextObjective> pendingGroups;
110
111 private ScheduledExecutorService groupChecker =
112 Executors.newScheduledThreadPool(2, groupedThreads("onos/pipeliner",
113 "ovs-corsa-%d"));
114
115 protected static final int CONTROLLER_PRIORITY = 255;
116 protected static final int DROP_PRIORITY = 0;
117 protected static final int HIGHEST_PRIORITY = 0xffff;
118 protected static final String APPID = "org.onosproject.drivers.corsa.CorsaPipeline";
119
120 @Override
121 public void init(DeviceId deviceId, PipelinerContext context) {
122 this.serviceDirectory = context.directory();
123 this.deviceId = deviceId;
124
125 pendingGroups = CacheBuilder.newBuilder()
126 .expireAfterWrite(20, TimeUnit.SECONDS)
127 .removalListener((RemovalNotification<GroupKey, NextObjective> notification) -> {
128 if (notification.getCause() == RemovalCause.EXPIRED) {
129 fail(notification.getValue(), ObjectiveError.GROUPINSTALLATIONFAILED);
130 }
131 }).build();
132
133 groupChecker.scheduleAtFixedRate(new GroupChecker(), 0, 500, TimeUnit.MILLISECONDS);
134
135 coreService = serviceDirectory.get(CoreService.class);
136 flowRuleService = serviceDirectory.get(FlowRuleService.class);
137 groupService = serviceDirectory.get(GroupService.class);
138 meterService = serviceDirectory.get(MeterService.class);
139 deviceService = serviceDirectory.get(DeviceService.class);
140 flowObjectiveStore = context.store();
141
142 groupService.addListener(new InnerGroupListener());
143
144 appId = coreService.registerApplication(APPID);
145
146 initializePipeline();
147 }
148
149 protected abstract void initializePipeline();
150
151 protected void pass(Objective obj) {
152 obj.context().ifPresent(context -> context.onSuccess(obj));
153 }
154
155 protected void fail(Objective obj, ObjectiveError error) {
156 obj.context().ifPresent(context -> context.onError(obj, error));
157 }
158
159 private class GroupChecker implements Runnable {
160
161 @Override
162 public void run() {
163 Set<GroupKey> keys = pendingGroups.asMap().keySet().stream()
164 .filter(key -> groupService.getGroup(deviceId, key) != null)
165 .collect(Collectors.toSet());
166
167 keys.stream().forEach(key -> {
168 NextObjective obj = pendingGroups.getIfPresent(key);
169 if (obj == null) {
170 return;
171 }
172 pass(obj);
173 pendingGroups.invalidate(key);
174 log.info("Heard back from group service for group {}. "
175 + "Applying pending forwarding objectives", obj.id());
176 flowObjectiveStore.putNextGroup(obj.id(), new CorsaGroup(key));
177 });
178 }
179 }
180
181 private class CorsaGroup implements NextGroup {
182
183 private final GroupKey key;
184
185 public CorsaGroup(GroupKey key) {
186 this.key = key;
187 }
188
189 public GroupKey key() {
190 return key;
191 }
192
193 @Override
194 public byte[] data() {
195 return appKryo.serialize(key);
196 }
197
198 }
199
200 @Override
201 public List<String> getNextMappings(NextGroup nextGroup) {
202 //TODO: to be implemented
203 return Collections.emptyList();
204 }
205
206 private class InnerGroupListener implements GroupListener {
207 @Override
208 public void event(GroupEvent event) {
209 if (event.type() == GroupEvent.Type.GROUP_ADDED) {
210 GroupKey key = event.subject().appCookie();
211
212 NextObjective obj = pendingGroups.getIfPresent(key);
213 if (obj != null) {
214 flowObjectiveStore.putNextGroup(obj.id(), new CorsaGroup(key));
215 pass(obj);
216 pendingGroups.invalidate(key);
217 }
218 }
219 }
220 }
221
222
223 @Override
224 public void filter(FilteringObjective filteringObjective) {
225 if (filteringObjective.type() == FilteringObjective.Type.PERMIT) {
226 processFilter(filteringObjective,
227 filteringObjective.op() == Objective.Operation.ADD,
228 filteringObjective.appId());
229 } else {
230 fail(filteringObjective, ObjectiveError.UNSUPPORTED);
231 }
232 }
233
234 private void processFilter(FilteringObjective filt, boolean install,
235 ApplicationId applicationId) {
236 // This driver only processes filtering criteria defined with switch
237 // ports as the key
238 PortCriterion port;
239 if (!filt.key().equals(Criteria.dummy()) &&
240 filt.key().type() == Criterion.Type.IN_PORT) {
241 port = (PortCriterion) filt.key();
242 } else {
243 log.warn("No key defined in filtering objective from app: {}. Not"
244 + "processing filtering objective", applicationId);
245 fail(filt, ObjectiveError.UNKNOWN);
246 return;
247 }
248 // convert filtering conditions for switch-intfs into flowrules
249 FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
250 for (Criterion c : filt.conditions()) {
251 if (c.type() == Criterion.Type.ETH_DST) {
252 EthCriterion eth = (EthCriterion) c;
253 FlowRule.Builder rule = processEthFiler(filt, eth, port);
254 rule.forDevice(deviceId)
255 .fromApp(applicationId);
256 ops = install ? ops.add(rule.build()) : ops.remove(rule.build());
257
258 } else if (c.type() == Criterion.Type.VLAN_VID) {
259 VlanIdCriterion vlan = (VlanIdCriterion) c;
260 FlowRule.Builder rule = processVlanFiler(filt, vlan, port);
261 rule.forDevice(deviceId)
262 .fromApp(applicationId);
263 ops = install ? ops.add(rule.build()) : ops.remove(rule.build());
264
265 } else if (c.type() == Criterion.Type.IPV4_DST) {
266 IPCriterion ip = (IPCriterion) c;
267 FlowRule.Builder rule = processIpFilter(filt, ip, port);
268 rule.forDevice(deviceId)
269 .fromApp(applicationId);
270 ops = install ? ops.add(rule.build()) : ops.remove(rule.build());
271
272 } else {
273 log.warn("Driver does not currently process filtering condition"
274 + " of type: {}", c.type());
275 fail(filt, ObjectiveError.UNSUPPORTED);
276 }
277 }
278 // apply filtering flow rules
279 flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
280 @Override
281 public void onSuccess(FlowRuleOperations ops) {
282 pass(filt);
283 log.info("Applied filtering rules");
284 }
285
286 @Override
287 public void onError(FlowRuleOperations ops) {
288 fail(filt, ObjectiveError.FLOWINSTALLATIONFAILED);
289 log.info("Failed to apply filtering rules");
290 }
291 }));
292 }
293
294 protected abstract Builder processEthFiler(FilteringObjective filt,
295 EthCriterion eth, PortCriterion port);
296
297 protected abstract Builder processVlanFiler(FilteringObjective filt,
298 VlanIdCriterion vlan, PortCriterion port);
299
300 protected abstract Builder processIpFilter(FilteringObjective filt,
301 IPCriterion ip, PortCriterion port);
302
303
304 @Override
305 public void forward(ForwardingObjective fwd) {
306 Collection<FlowRule> rules;
307 FlowRuleOperations.Builder flowBuilder = FlowRuleOperations.builder();
308
309 rules = processForward(fwd);
310 switch (fwd.op()) {
311 case ADD:
312 rules.stream()
313 .filter(Objects::nonNull)
314 .forEach(flowBuilder::add);
315 break;
316 case REMOVE:
317 rules.stream()
318 .filter(Objects::nonNull)
319 .forEach(flowBuilder::remove);
320 break;
321 default:
322 fail(fwd, ObjectiveError.UNKNOWN);
323 log.warn("Unknown forwarding type {}", fwd.op());
324 }
325
326 flowRuleService.apply(flowBuilder.build(new FlowRuleOperationsContext() {
327 @Override
328 public void onSuccess(FlowRuleOperations ops) {
329 pass(fwd);
330 }
331
332 @Override
333 public void onError(FlowRuleOperations ops) {
334 fail(fwd, ObjectiveError.FLOWINSTALLATIONFAILED);
335 }
336 }));
337
338 }
339
340 private Collection<FlowRule> processForward(ForwardingObjective fwd) {
341 switch (fwd.flag()) {
342 case SPECIFIC:
343 return processSpecific(fwd);
344 case VERSATILE:
345 return processVersatile(fwd);
346 default:
347 fail(fwd, ObjectiveError.UNKNOWN);
348 log.warn("Unknown forwarding flag {}", fwd.flag());
349 }
350 return Collections.emptySet();
351 }
352
353 private Collection<FlowRule> processSpecific(ForwardingObjective fwd) {
354 log.debug("Processing specific forwarding objective");
355 TrafficSelector selector = fwd.selector();
356 EthTypeCriterion ethType =
357 (EthTypeCriterion) selector.getCriterion(Criterion.Type.ETH_TYPE);
358 if (ethType != null) {
359 short et = ethType.ethType().toShort();
360 if (et == Ethernet.TYPE_IPV4) {
361 return processSpecificRoute(fwd);
362 } else if (et == Ethernet.TYPE_VLAN) {
363 /* The ForwardingObjective must specify VLAN ethtype in order to use the Transit Circuit */
364 return processSpecificSwitch(fwd);
365 }
366 }
367
368 fail(fwd, ObjectiveError.UNSUPPORTED);
369 return Collections.emptySet();
370 }
371
372 protected Collection<FlowRule> processSpecificSwitch(ForwardingObjective fwd) {
373 /* Not supported by until CorsaPipelineV3 */
374 log.warn("Vlan switching not supported in ovs-corsa driver");
375 fail(fwd, ObjectiveError.UNSUPPORTED);
376 return Collections.emptySet();
377 }
378
379 private Collection<FlowRule> processVersatile(ForwardingObjective fwd) {
380 log.debug("Processing vesatile forwarding objective");
381 TrafficSelector selector = fwd.selector();
382
383 EthTypeCriterion ethType =
384 (EthTypeCriterion) selector.getCriterion(Criterion.Type.ETH_TYPE);
385 if (ethType == null) {
386 log.error("Versatile forwarding objective must include ethType");
387 fail(fwd, ObjectiveError.UNKNOWN);
388 return Collections.emptySet();
389 }
390 Builder rule = DefaultFlowRule.builder()
391 .forDevice(deviceId)
392 .withSelector(fwd.selector())
393 .withTreatment(fwd.treatment())
394 .withPriority(fwd.priority())
395 .fromApp(fwd.appId())
396 .makePermanent();
397 if (ethType.ethType().toShort() == Ethernet.TYPE_ARP) {
398 return processArpTraffic(fwd, rule);
399 } else if (ethType.ethType().toShort() == Ethernet.TYPE_LLDP ||
400 ethType.ethType().toShort() == Ethernet.TYPE_BSN) {
401 return processLinkDiscovery(fwd, rule);
402 } else if (ethType.ethType().toShort() == Ethernet.TYPE_IPV4) {
403 return processIpTraffic(fwd, rule);
404 }
405 log.warn("Driver does not support given versatile forwarding objective");
406 fail(fwd, ObjectiveError.UNSUPPORTED);
407 return Collections.emptySet();
408 }
409
410 protected abstract Collection<FlowRule> processArpTraffic(ForwardingObjective fwd, Builder rule);
411
412 protected abstract Collection<FlowRule> processLinkDiscovery(ForwardingObjective fwd, Builder rule);
413
414 protected abstract Collection<FlowRule> processIpTraffic(ForwardingObjective fwd, Builder rule);
415
416 private Collection<FlowRule> processSpecificRoute(ForwardingObjective fwd) {
417 TrafficSelector filteredSelector =
418 DefaultTrafficSelector.builder()
419 .matchEthType(Ethernet.TYPE_IPV4)
420 .matchIPDst(
421 ((IPCriterion) fwd.selector().getCriterion(Criterion.Type.IPV4_DST)).ip())
422 .build();
423
424 TrafficTreatment.Builder tb = processSpecificRoutingTreatment();
425
426 if (fwd.nextId() != null) {
427 NextGroup next = flowObjectiveStore.getNextGroup(fwd.nextId());
428 GroupKey key = appKryo.deserialize(next.data());
429 Group group = groupService.getGroup(deviceId, key);
430 if (group == null) {
431 log.warn("The group left!");
432 fail(fwd, ObjectiveError.GROUPMISSING);
433 return Collections.emptySet();
434 }
435 tb.group(group.id());
436 }
437 Builder ruleBuilder = DefaultFlowRule.builder()
438 .fromApp(fwd.appId())
439 .withPriority(fwd.priority())
440 .forDevice(deviceId)
441 .withSelector(filteredSelector)
442 .withTreatment(tb.build());
443
444 ruleBuilder = processSpecificRoutingRule(ruleBuilder);
445
446 if (fwd.permanent()) {
447 ruleBuilder.makePermanent();
448 } else {
449 ruleBuilder.makeTemporary(fwd.timeout());
450 }
451 return Collections.singletonList(ruleBuilder.build());
452 }
453
454 //Hook for modifying Route traffic treatment
455 protected TrafficTreatment.Builder processSpecificRoutingTreatment() {
456 return DefaultTrafficTreatment.builder();
457 }
458
459 //Hook for modifying Route flow rule
460 protected abstract Builder processSpecificRoutingRule(Builder rb);
461
462 @Override
463 public void next(NextObjective nextObjective) {
464 switch (nextObjective.type()) {
465 case SIMPLE:
466 Collection<TrafficTreatment> treatments = nextObjective.next();
467 if (treatments.size() == 1) {
468 TrafficTreatment treatment = treatments.iterator().next();
469 treatment = processNextTreatment(treatment);
470 GroupBucket bucket =
471 DefaultGroupBucket.createIndirectGroupBucket(treatment);
472 final GroupKey key = new DefaultGroupKey(appKryo.serialize(nextObjective.id()));
473 GroupDescription groupDescription
474 = new DefaultGroupDescription(deviceId,
475 GroupDescription.Type.INDIRECT,
476 new GroupBuckets(Collections
477 .singletonList(bucket)),
478 key,
479 null, // let group service determine group id
480 nextObjective.appId());
481 groupService.addGroup(groupDescription);
482 pendingGroups.put(key, nextObjective);
483 }
484 break;
485 case HASHED:
486 case BROADCAST:
487 case FAILOVER:
488 fail(nextObjective, ObjectiveError.UNSUPPORTED);
489 log.warn("Unsupported next objective type {}", nextObjective.type());
490 break;
491 default:
492 fail(nextObjective, ObjectiveError.UNKNOWN);
493 log.warn("Unknown next objective type {}", nextObjective.type());
494 }
495
496 }
497
498 //Hook for altering the NextObjective treatment
499 protected TrafficTreatment processNextTreatment(TrafficTreatment treatment) {
500 return treatment;
501 }
502
503 //Init helper: Table Miss = Drop
504 protected void processTableMissDrop(boolean install, int table, String description) {
505 TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
506
507 TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
508 treatment.drop();
509
510 FlowRule rule = DefaultFlowRule.builder()
511 .forDevice(deviceId)
512 .withSelector(selector.build())
513 .withTreatment(treatment.build())
514 .withPriority(DROP_PRIORITY)
515 .fromApp(appId)
516 .makePermanent()
517 .forTable(table).build();
518
519 processFlowRule(install, rule, description);
520 }
521
522 //Init helper: Table Miss = GoTo
523 protected void processTableMissGoTo(boolean install, int table, int goTo, String description) {
524 TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
525
526 TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
527 treatment.transition(goTo);
528
529 FlowRule rule = DefaultFlowRule.builder()
530 .forDevice(deviceId)
531 .withSelector(selector.build())
532 .withTreatment(treatment.build())
533 .withPriority(DROP_PRIORITY)
534 .fromApp(appId)
535 .makePermanent()
536 .forTable(table).build();
537
538 processFlowRule(install, rule, description);
539 }
540
541 //Init helper: Apply flow rule
542 protected void processFlowRule(boolean install, FlowRule rule, String description) {
543 FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
544 ops = install ? ops.add(rule) : ops.remove(rule);
545
546 flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
547 @Override
548 public void onSuccess(FlowRuleOperations ops) {
549 log.info(description + " success: " + ops.toString() + ", " + rule.toString());
550 }
551
552 @Override
553 public void onError(FlowRuleOperations ops) {
554 log.info(description + " error: " + ops.toString() + ", " + rule.toString());
555 }
556 }));
557 }
558}