PicaPipeline.java 21.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
/*
 * Copyright 2015 Open Networking Laboratory
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.onosproject.driver.pipeline;

import org.onlab.osgi.ServiceDirectory;
import org.onlab.packet.Ethernet;
import org.onlab.packet.IPv4;
import org.onlab.packet.MacAddress;
import org.onlab.packet.VlanId;
import org.onlab.util.KryoNamespace;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.CoreService;
import org.onosproject.net.DeviceId;
import org.onosproject.net.PortNumber;
import org.onosproject.net.behaviour.NextGroup;
import org.onosproject.net.behaviour.Pipeliner;
import org.onosproject.net.behaviour.PipelinerContext;
import org.onosproject.net.driver.AbstractHandlerBehaviour;
import org.onosproject.net.flow.DefaultFlowRule;
import org.onosproject.net.flow.DefaultTrafficSelector;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.FlowRule;
import org.onosproject.net.flow.FlowRuleOperations;
import org.onosproject.net.flow.FlowRuleOperationsContext;
import org.onosproject.net.flow.FlowRuleService;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.flow.criteria.Criteria;
import org.onosproject.net.flow.criteria.Criterion;
import org.onosproject.net.flow.criteria.EthCriterion;
import org.onosproject.net.flow.criteria.EthTypeCriterion;
import org.onosproject.net.flow.criteria.IPCriterion;
import org.onosproject.net.flow.criteria.IPProtocolCriterion;
import org.onosproject.net.flow.criteria.PortCriterion;
import org.onosproject.net.flow.criteria.VlanIdCriterion;
import org.onosproject.net.flow.instructions.Instruction;
import org.onosproject.net.flow.instructions.L2ModificationInstruction;
import org.onosproject.net.flowobjective.FilteringObjective;
import org.onosproject.net.flowobjective.FlowObjectiveStore;
import org.onosproject.net.flowobjective.ForwardingObjective;
import org.onosproject.net.flowobjective.NextObjective;
import org.onosproject.net.flowobjective.Objective;
import org.onosproject.net.flowobjective.ObjectiveError;
import org.onosproject.store.serializers.KryoNamespaces;
import org.slf4j.Logger;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * Pica pipeline handler.
 */
public class PicaPipeline extends AbstractHandlerBehaviour implements Pipeliner {

    protected static final int IP_UNICAST_TABLE = 252;
    protected static final int ACL_TABLE = 0;

    //private static final int CONTROLLER_PRIORITY = 255;
    private static final int DROP_PRIORITY = 0;
    private static final int HIGHEST_PRIORITY = 0xffff;

    private final Logger log = getLogger(getClass());

    private ServiceDirectory serviceDirectory;
    private FlowRuleService flowRuleService;
    private CoreService coreService;
    private FlowObjectiveStore flowObjectiveStore;
    private DeviceId deviceId;
    private ApplicationId appId;
    private Collection<Filter> filters;
    private Collection<ForwardingObjective> pendingVersatiles;

    private KryoNamespace appKryo = new KryoNamespace.Builder()
            .register(KryoNamespaces.API)
            .register(PicaGroup.class)
            .register(byte[].class)
            .build();

    @Override
    public void init(DeviceId deviceId, PipelinerContext context) {
        this.serviceDirectory = context.directory();
        this.deviceId = deviceId;

        coreService = serviceDirectory.get(CoreService.class);
        flowRuleService = serviceDirectory.get(FlowRuleService.class);
        flowObjectiveStore = context.store();
        filters = Collections.newSetFromMap(new ConcurrentHashMap<Filter, Boolean>());
        pendingVersatiles = Collections.newSetFromMap(
            new ConcurrentHashMap<ForwardingObjective, Boolean>());
        appId = coreService.registerApplication(
                "org.onosproject.driver.OVSPicaPipeline");

        initializePipeline();
    }

    @Override
    public void filter(FilteringObjective filteringObjective) {
        if (filteringObjective.type() == FilteringObjective.Type.PERMIT) {
            processFilter(filteringObjective,
                          filteringObjective.op() == Objective.Operation.ADD,
                          filteringObjective.appId());
        } else {
            fail(filteringObjective, ObjectiveError.UNSUPPORTED);
        }
    }

    @Override
    public void forward(ForwardingObjective fwd) {
        Collection<FlowRule> rules;
        FlowRuleOperations.Builder flowBuilder = FlowRuleOperations.builder();

        rules = processForward(fwd);
        switch (fwd.op()) {
            case ADD:
                rules.stream()
                        .filter(rule -> rule != null)
                        .forEach(flowBuilder::add);
                break;
            case REMOVE:
                rules.stream()
                        .filter(rule -> rule != null)
                        .forEach(flowBuilder::remove);
                break;
            default:
                fail(fwd, ObjectiveError.UNKNOWN);
                log.warn("Unknown forwarding type {}", fwd.op());
        }


        flowRuleService.apply(flowBuilder.build(new FlowRuleOperationsContext() {
            @Override
            public void onSuccess(FlowRuleOperations ops) {
                pass(fwd);
            }

            @Override
            public void onError(FlowRuleOperations ops) {
                fail(fwd, ObjectiveError.FLOWINSTALLATIONFAILED);
            }
        }));

    }

    @Override
    public void next(NextObjective nextObjective) {
        switch (nextObjective.type()) {
            case SIMPLE:
                Collection<TrafficTreatment> treatments = nextObjective.next();
                if (treatments.size() != 1) {
                    log.error("Next Objectives of type Simple should only have a "
                            + "single Traffic Treatment. Next Objective Id:{}", nextObjective.id());
                   fail(nextObjective, ObjectiveError.BADPARAMS);
                   return;
                }
                TrafficTreatment treatment = treatments.iterator().next();
                TrafficTreatment.Builder filteredTreatment = DefaultTrafficTreatment.builder();
                VlanId modVlanId;
                for (Instruction ins : treatment.allInstructions()) {
                    if (ins.type() == Instruction.Type.L2MODIFICATION) {
                        L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
                        switch (l2ins.subtype()) {
                            case ETH_DST:
                                filteredTreatment.setEthDst(
                                        ((L2ModificationInstruction.ModEtherInstruction) l2ins).mac());
                                break;
                            case ETH_SRC:
                                filteredTreatment.setEthSrc(
                                        ((L2ModificationInstruction.ModEtherInstruction) l2ins).mac());
                                break;
                            case VLAN_ID:
                                modVlanId = ((L2ModificationInstruction.ModVlanIdInstruction) l2ins).vlanId();
                                filteredTreatment.setVlanId(modVlanId);
                                break;
                            default:
                                break;
                        }
                    } else if (ins.type() == Instruction.Type.OUTPUT) {
                        //long portNum = ((Instructions.OutputInstruction) ins).port().toLong();
                        filteredTreatment.add(ins);
                    } else {
                        // Ignore the vlan_pcp action since it's does matter much.
                        log.warn("Driver does not handle this type of TrafficTreatment"
                                + " instruction in nextObjectives:  {}", ins.type());
                    }
                }
                // store for future use
                flowObjectiveStore.putNextGroup(nextObjective.id(),
                                                new PicaGroup(filteredTreatment.build()));
                break;
            case HASHED:
            case BROADCAST:
            case FAILOVER:
                fail(nextObjective, ObjectiveError.UNSUPPORTED);
                log.warn("Unsupported next objective type {}", nextObjective.type());
                break;
            default:
                fail(nextObjective, ObjectiveError.UNKNOWN);
                log.warn("Unknown next objective type {}", nextObjective.type());
        }

    }

    private Collection<FlowRule> processForward(ForwardingObjective fwd) {
        switch (fwd.flag()) {
            case SPECIFIC:
                return processSpecific(fwd);
            case VERSATILE:
                return processVersatile(fwd);
            default:
                fail(fwd, ObjectiveError.UNKNOWN);
                log.warn("Unknown forwarding flag {}", fwd.flag());
        }
        return Collections.emptySet();
    }

    private Collection<FlowRule> processVersatile(ForwardingObjective fwd) {
        log.debug("Processing versatile forwarding objective");
        TrafficSelector selector = fwd.selector();

        EthTypeCriterion ethType =
                (EthTypeCriterion) selector.getCriterion(Criterion.Type.ETH_TYPE);
        if (ethType == null) {
            log.error("Versatile forwarding objective must include ethType");
            fail(fwd, ObjectiveError.UNKNOWN);
            return Collections.emptySet();
        }

        if (ethType.ethType().toShort() == Ethernet.TYPE_ARP) {
            if (filters.isEmpty()) {
                pendingVersatiles.add(fwd);
                return Collections.emptySet();
            }
            Collection<FlowRule> flowrules = new ArrayList<FlowRule>();
            for (Filter filter : filters) {
                flowrules.addAll(processVersatilesWithFilters(filter, fwd));
            }
            return flowrules;
        } else if (ethType.ethType().toShort() == Ethernet.TYPE_LLDP ||
                ethType.ethType().toShort() == Ethernet.TYPE_BSN) {
            log.warn("Driver currently does not currently handle LLDP packets");
            fail(fwd, ObjectiveError.UNSUPPORTED);
            return Collections.emptySet();
        } else if (ethType.ethType().toShort() == Ethernet.TYPE_IPV4) {
            IPCriterion ipSrc = (IPCriterion) selector
                    .getCriterion(Criterion.Type.IPV4_SRC);
            IPCriterion ipDst = (IPCriterion) selector
                    .getCriterion(Criterion.Type.IPV4_DST);
            IPProtocolCriterion ipProto = (IPProtocolCriterion) selector
                    .getCriterion(Criterion.Type.IP_PROTO);
            if (ipSrc != null) {
                log.warn("Driver does not currently handle matching Src IP");
                fail(fwd, ObjectiveError.UNSUPPORTED);
                return Collections.emptySet();
            }
            if (ipDst != null) {
                log.error("Driver handles Dst IP matching as specific forwarding "
                        + "objective, not versatile");
                fail(fwd, ObjectiveError.UNSUPPORTED);
                return Collections.emptySet();
            }
            if (ipProto != null && ipProto.protocol() == IPv4.PROTOCOL_TCP) {
                log.warn("Driver automatically punts all packets reaching the "
                        + "ACL table to the controller");
                pass(fwd);
                return Collections.emptySet();
            }
        }

        log.warn("Driver does not support given versatile forwarding objective");
        fail(fwd, ObjectiveError.UNSUPPORTED);
        return Collections.emptySet();
    }

    private Collection<FlowRule> processVersatilesWithFilters(
                Filter filt, ForwardingObjective fwd) {
        Collection<FlowRule> flows = new ArrayList<FlowRule>();

        // rule for ARP replies
        log.debug("adding ARP rule in ACL table");
        TrafficSelector.Builder sel = DefaultTrafficSelector.builder();
        TrafficTreatment.Builder treat = DefaultTrafficTreatment.builder();
        sel.matchInPort(filt.port());
        sel.matchVlanId(filt.vlanId());
        sel.matchEthDst(filt.mac());
        sel.matchEthType(Ethernet.TYPE_ARP);
        treat.setOutput(PortNumber.CONTROLLER);
        FlowRule rule = DefaultFlowRule.builder()
                .forDevice(deviceId)
                .withSelector(sel.build())
                .withTreatment(treat.build())
                .withPriority(HIGHEST_PRIORITY)
                .fromApp(appId)
                .makePermanent()
                .forTable(ACL_TABLE).build();
        flows.add(rule);

        // rule for ARP Broadcast
        sel = DefaultTrafficSelector.builder();
        treat = DefaultTrafficTreatment.builder();
        sel.matchInPort(filt.port());
        sel.matchVlanId(filt.vlanId());
        sel.matchEthDst(MacAddress.BROADCAST);
        sel.matchEthType(Ethernet.TYPE_ARP);
        treat.setOutput(PortNumber.CONTROLLER);
        rule = DefaultFlowRule.builder()
                .forDevice(deviceId)
                .withSelector(sel.build())
                .withTreatment(treat.build())
                .withPriority(HIGHEST_PRIORITY)
                .fromApp(appId)
                .makePermanent()
                .forTable(ACL_TABLE).build();
        flows.add(rule);

        return flows;
    }


    private Collection<FlowRule> processSpecific(ForwardingObjective fwd) {
        log.debug("Processing specific forwarding objective");
        TrafficSelector selector = fwd.selector();
        EthTypeCriterion ethType =
                (EthTypeCriterion) selector.getCriterion(Criterion.Type.ETH_TYPE);
        if (ethType == null || ethType.ethType().toShort() != Ethernet.TYPE_IPV4) {
            fail(fwd, ObjectiveError.UNSUPPORTED);
            return Collections.emptySet();
        }

        List<FlowRule> ipflows = new ArrayList<FlowRule>();
        for (Filter f: filters) {
            TrafficSelector filteredSelector =
                    DefaultTrafficSelector.builder()
                    .matchEthType(Ethernet.TYPE_IPV4)
                    .matchIPDst(
                                ((IPCriterion)
                                        selector.getCriterion(Criterion.Type.IPV4_DST)).ip())
                    .matchEthDst(f.mac())
                    .matchVlanId(f.vlanId())
                    .build();
            TrafficTreatment tt = null;
            if (fwd.nextId() != null) {
                NextGroup next = flowObjectiveStore.getNextGroup(fwd.nextId());
                if (next == null) {
                    log.error("next-id {} does not exist in store", fwd.nextId());
                    return Collections.emptySet();
                }
                tt = appKryo.deserialize(next.data());
                if (tt == null)  {
                    log.error("Error in deserializing next-id {}", fwd.nextId());
                    return Collections.emptySet();
                }
            }

            FlowRule.Builder ruleBuilder = DefaultFlowRule.builder()
                    .fromApp(fwd.appId())
                    .withPriority(fwd.priority())
                    .forDevice(deviceId)
                    .withSelector(filteredSelector)
                    .withTreatment(tt);
            if (fwd.permanent()) {
                ruleBuilder.makePermanent();
            } else {
                ruleBuilder.makeTemporary(fwd.timeout());
            }
            ruleBuilder.forTable(IP_UNICAST_TABLE);
            ipflows.add(ruleBuilder.build());
        }

        return ipflows;
    }

    private void processFilter(FilteringObjective filt, boolean install,
                                             ApplicationId applicationId) {
        // This driver only processes filtering criteria defined with switch
        // ports as the key
        PortCriterion p;
        if (!filt.key().equals(Criteria.dummy()) &&
                filt.key().type() == Criterion.Type.IN_PORT) {
            p = (PortCriterion) filt.key();
        } else {
            log.warn("No key defined in filtering objective from app: {}. Not"
                    + "processing filtering objective", applicationId);
            fail(filt, ObjectiveError.UNKNOWN);
            return;
        }

        EthCriterion e = null; VlanIdCriterion v = null;
        Collection<IPCriterion> ips = new ArrayList<IPCriterion>();
        // convert filtering conditions for switch-intfs into flowrules
        FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
        for (Criterion c : filt.conditions()) {
            if (c.type() == Criterion.Type.ETH_DST) {
                e = (EthCriterion) c;
            } else if (c.type() == Criterion.Type.VLAN_VID) {
                v = (VlanIdCriterion) c;
            } else if (c.type() == Criterion.Type.IPV4_DST) {
                ips.add((IPCriterion) c);
            } else {
                log.error("Unsupported filter {}", c);
                fail(filt, ObjectiveError.UNSUPPORTED);
                return;
            }
        }

        // cache for later use
        Filter filter = new Filter(p, e, v, ips);
        filters.add(filter);

        // apply any pending versatile forwarding objectives
        for (ForwardingObjective fwd : pendingVersatiles) {
            Collection<FlowRule> ret = processVersatilesWithFilters(filter, fwd);
            for (FlowRule fr : ret) {
                ops.add(fr);
            }
        }

        for (IPCriterion ipaddr : ips) {
            log.debug("adding IP filtering rules in ACL table: {}", ipaddr.ip());
            TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
            TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
            selector.matchInPort(p.port());
            selector.matchVlanId(v.vlanId());
            selector.matchEthDst(e.mac());
            selector.matchEthType(Ethernet.TYPE_IPV4);
            selector.matchIPDst(ipaddr.ip()); // router IPs to the controller
            treatment.setOutput(PortNumber.CONTROLLER);
            FlowRule rule = DefaultFlowRule.builder()
                    .forDevice(deviceId)
                    .withSelector(selector.build())
                    .withTreatment(treatment.build())
                    .withPriority(HIGHEST_PRIORITY)
                    .fromApp(applicationId)
                    .makePermanent()
                    .forTable(ACL_TABLE).build();
            ops =  ops.add(rule);
        }

        // apply filtering flow rules
        flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
            @Override
            public void onSuccess(FlowRuleOperations ops) {
                pass(filt);
                log.info("Applied filtering rules");
            }

            @Override
            public void onError(FlowRuleOperations ops) {
                fail(filt, ObjectiveError.FLOWINSTALLATIONFAILED);
                log.info("Failed to apply filtering rules");
            }
        }));
    }

    private void pass(Objective obj) {
        if (obj.context().isPresent()) {
            obj.context().get().onSuccess(obj);
        }
    }

    private void fail(Objective obj, ObjectiveError error) {
        if (obj.context().isPresent()) {
            obj.context().get().onError(obj, error);
        }
    }

    private void initializePipeline() {
        //processIpUnicastTable(true);
        processACLTable(true);
    }

    private void processACLTable(boolean install) {
        TrafficSelector.Builder selector;
        TrafficTreatment.Builder treatment;
        FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
        FlowRule rule;

        //Drop rule
        selector = DefaultTrafficSelector.builder();
        treatment = DefaultTrafficTreatment.builder();

        rule = DefaultFlowRule.builder()
                .forDevice(deviceId)
                .withSelector(selector.build())
                .withTreatment(treatment.build())
                .withPriority(DROP_PRIORITY)
                .fromApp(appId)
                .makePermanent()
                .forTable(ACL_TABLE).build();

        ops = install ? ops.add(rule) : ops.remove(rule);

        flowRuleService.apply(ops.build(new FlowRuleOperationsContext() {
            @Override
            public void onSuccess(FlowRuleOperations ops) {
                log.info("Provisioned ACL table");
            }

            @Override
            public void onError(FlowRuleOperations ops) {
                log.info("Failed to provision ACL table");
            }
        }));
    }

    private class Filter {
        private PortCriterion port;
        private VlanIdCriterion vlan;
        private EthCriterion eth;

        @SuppressWarnings("unused")
        private Collection<IPCriterion> ips;

        public Filter(PortCriterion p, EthCriterion e, VlanIdCriterion v,
                      Collection<IPCriterion> ips) {
            this.eth = e;
            this.port = p;
            this.vlan = v;
            this.ips = ips;
        }

        public PortNumber port() {
            return port.port();
        }

        public VlanId vlanId() {
            return vlan.vlanId();
        }

        public MacAddress mac() {
            return eth.mac();
        }
    }

    private class PicaGroup implements NextGroup {
        TrafficTreatment nextActions;

        public PicaGroup(TrafficTreatment next) {
            this.nextActions = next;
        }

        @Override
        public byte[] data() {
            return appKryo.serialize(nextActions);
        }

    }
}