Java Code Examples for org.onosproject.net.flow.FlowRuleService#getFlowEntries()

The following examples show how to use org.onosproject.net.flow.FlowRuleService#getFlowEntries() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FlowsWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Gets all flow entries. Returns array of all flow rules in the system.
 *
 * @return 200 OK with a collection of flows
 * @onos.rsModel FlowEntries
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getFlows() {
    ObjectNode root = mapper().createObjectNode();
    ArrayNode flowsNode = root.putArray(FLOWS);
    FlowRuleService service = get(FlowRuleService.class);
    Iterable<Device> devices = get(DeviceService.class).getDevices();
    for (Device device : devices) {
        Iterable<FlowEntry> flowEntries = service.getFlowEntries(device.id());
        if (flowEntries != null) {
            for (FlowEntry entry : flowEntries) {
                flowsNode.add(codec(FlowEntry.class).encode(entry, this));
            }
        }
    }

    return ok(root).build();
}
 
Example 2
Source File: FlowsWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Gets all pending flow entries. Returns array of all pending flow rules in the system.
 *
 * @return 200 OK with a collection of flows
 * @onos.rsModel FlowEntries
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("pending")
public Response getPendingFlows() {
    ObjectNode root = mapper().createObjectNode();
    ArrayNode flowsNode = root.putArray(FLOWS);
    FlowRuleService service = get(FlowRuleService.class);
    Iterable<Device> devices = get(DeviceService.class).getDevices();
    for (Device device : devices) {
        Iterable<FlowEntry> flowEntries = service.getFlowEntries(device.id());
        if (flowEntries != null) {
            for (FlowEntry entry : flowEntries) {
                if ((entry.state() == FlowEntry.FlowEntryState.PENDING_ADD) ||
                   (entry.state() == FlowEntry.FlowEntryState.PENDING_REMOVE)) {
                   flowsNode.add(codec(FlowEntry.class).encode(entry, this));
                }
            }
        }
    }

    return ok(root).build();
}
 
Example 3
Source File: FlowsWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Gets all flow entries for a table. Returns array of all flow rules for a table.
 * @param tableId table identifier
 * @return 200 OK with a collection of flows
 * @onos.rsModel FlowEntries
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("table/{tableId}")
public Response getTableFlows(@PathParam("tableId") int tableId) {
    ObjectNode root = mapper().createObjectNode();
    ArrayNode flowsNode = root.putArray(FLOWS);
    FlowRuleService service = get(FlowRuleService.class);
    Iterable<Device> devices = get(DeviceService.class).getDevices();
    for (Device device : devices) {
        Iterable<FlowEntry> flowEntries = service.getFlowEntries(device.id());
        if (flowEntries != null) {
            for (FlowEntry entry : flowEntries) {
                if (((IndexTableId) entry.table()).id() == tableId) {
                   flowsNode.add(codec(FlowEntry.class).encode(entry, this));
                }
            }
        }
    }

    return ok(root).build();
}
 
Example 4
Source File: FlowsWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Gets flow entries of a device. Returns array of all flow rules for the
 * specified device.
 *
 * @param deviceId device identifier
 * @return 200 OK with a collection of flows of given device
 * @onos.rsModel FlowEntries
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
// TODO: we need to add "/device" suffix to the path to differentiate with appId
@Path("{deviceId}")
public Response getFlowByDeviceId(@PathParam("deviceId") String deviceId) {
    FlowRuleService service = get(FlowRuleService.class);
    ObjectNode root = mapper().createObjectNode();
    ArrayNode flowsNode = root.putArray(FLOWS);
    Iterable<FlowEntry> flowEntries =
            service.getFlowEntries(DeviceId.deviceId(deviceId));

    if (flowEntries == null || !flowEntries.iterator().hasNext()) {
        throw new ItemNotFoundException(DEVICE_NOT_FOUND);
    }
    for (FlowEntry entry : flowEntries) {
        flowsNode.add(codec(FlowEntry.class).encode(entry, this));
    }
    return ok(root).build();
}
 
Example 5
Source File: FlowsWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Gets flow rules. Returns the flow entry specified by the device id and
 * flow rule id.
 *
 * @param deviceId device identifier
 * @param flowId   flow rule identifier
 * @return 200 OK with a collection of flows of given device and flow
 * @onos.rsModel FlowEntries
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{deviceId}/{flowId}")
public Response getFlowByDeviceIdAndFlowId(@PathParam("deviceId") String deviceId,
                                           @PathParam("flowId") long flowId) {
    FlowRuleService service = get(FlowRuleService.class);
    ObjectNode root = mapper().createObjectNode();
    ArrayNode flowsNode = root.putArray(FLOWS);
    Iterable<FlowEntry> flowEntries =
            service.getFlowEntries(DeviceId.deviceId(deviceId));

    if (flowEntries == null || !flowEntries.iterator().hasNext()) {
        throw new ItemNotFoundException(DEVICE_NOT_FOUND);
    }
    for (FlowEntry entry : flowEntries) {
        if (entry.id().value() == flowId) {
            flowsNode.add(codec(FlowEntry.class).encode(entry, this));
        }
    }
    return ok(root).build();
}
 
Example 6
Source File: FlowsWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Removes flow rule. Removes the specified flow rule.
 *
 * @param deviceId device identifier
 * @param flowId   flow rule identifier
 * @return 204 NO CONTENT
 */
@DELETE
@Path("{deviceId}/{flowId}")
public Response deleteFlowByDeviceIdAndFlowId(@PathParam("deviceId") String deviceId,
                                              @PathParam("flowId") long flowId) {
    FlowRuleService service = get(FlowRuleService.class);
    Iterable<FlowEntry> flowEntries =
            service.getFlowEntries(DeviceId.deviceId(deviceId));

    if (!flowEntries.iterator().hasNext()) {
        throw new ItemNotFoundException(DEVICE_NOT_FOUND);
    }

    StreamSupport.stream(flowEntries.spliterator(), false)
            .filter(entry -> entry.id().value() == flowId)
            .forEach(service::removeFlowRules);
    return Response.noContent().build();
}
 
Example 7
Source File: FlowViewMessageHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected void populateTable(TableModel tm, ObjectNode payload) {
    String uri = string(payload, DEV_ID);
    if (!Strings.isNullOrEmpty(uri)) {
        DeviceId deviceId = DeviceId.deviceId(uri);
        Map<Short, ApplicationId> lookup = appShortMap();
        FlowRuleService frs = get(FlowRuleService.class);

        for (FlowEntry flow : frs.getFlowEntries(deviceId)) {
            populateRow(tm.addRow(), flow, lookup);
        }
    }
}
 
Example 8
Source File: OplinkPowerConfigUtil.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Find matching flow on device.
 *
 * @param portNum the port number
 * @param och channel signal
 * @return flow entry
 */
private FlowEntry findFlow(PortNumber portNum, OchSignal och) {
    final DriverHandler handler = behaviour.handler();
    FlowRuleService service = handler.get(FlowRuleService.class);
    Iterable<FlowEntry> flowEntries = service.getFlowEntries(handler.data().deviceId());

    // Return first matching flow
    for (FlowEntry entry : flowEntries) {
        TrafficSelector selector = entry.selector();
        OchSignalCriterion entrySigid =
                (OchSignalCriterion) selector.getCriterion(Criterion.Type.OCH_SIGID);
        // Check channel
        if (entrySigid != null && och.equals(entrySigid.lambda())) {
            // Check input port
            PortCriterion entryPort =
                    (PortCriterion) selector.getCriterion(Criterion.Type.IN_PORT);
            if (entryPort != null && portNum.equals(entryPort.port())) {
                return entry;
            }

            // Check output port
            TrafficTreatment treatment = entry.treatment();
            for (Instruction instruction : treatment.allInstructions()) {
                if (instruction.type() == Instruction.Type.OUTPUT &&
                    ((Instructions.OutputInstruction) instruction).port().equals(portNum)) {
                    return entry;
                }
            }
        }
    }
    log.warn("No matching flow found");
    return null;
}
 
Example 9
Source File: OplinkOpticalPowerConfig.java    From onos with Apache License 2.0 5 votes vote down vote up
private boolean setChannelTargetPower(PortNumber port, OchSignal channel, long power) {
    log.debug("Set port{} channel{} attenuation.", port, channel.channelSpacing());
    FlowRuleService service = handler().get(FlowRuleService.class);
    Iterable<FlowEntry> entries = service.getFlowEntries(data().deviceId());
    for (FlowEntry entry : entries) {
        OplinkCrossConnect crossConnect = OplinkOpticalUtility.fromFlowRule(this, entry);
        // The channel port might be input port or output port.
        if ((port.equals(crossConnect.getInPort()) || port.equals(crossConnect.getOutPort())) &&
                channel.spacingMultiplier() == crossConnect.getChannel()) {
            log.debug("Flow is found, modify the flow with attenuation.");
            // Modify attenuation in treatment
            TrafficTreatment treatment = DefaultTrafficTreatment.builder()
                    .setOutput(crossConnect.getOutPort())
                    .extension(new OplinkAttenuation((int) power), data().deviceId())
                    .build();
            // Apply the new flow rule
            service.applyFlowRules(DefaultFlowRule.builder()
                    .forDevice(data().deviceId())
                    .makePermanent()
                    .withSelector(entry.selector())
                    .withTreatment(treatment)
                    .withPriority(entry.priority())
                    .withCookie(entry.id().value())
                    .build());
            return true;
        }
    }
    return false;
}
 
Example 10
Source File: FlowsListCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the list of devices sorted using the device ID URIs.
 *
 * @param deviceService device service
 * @param service flow rule service
 * @param coreService core service
 * @return sorted device list
 */
protected SortedMap<Device, List<FlowEntry>> getSortedFlows(DeviceService deviceService,
                                                      FlowRuleService service, CoreService coreService) {
    SortedMap<Device, List<FlowEntry>> flows = new TreeMap<>(Comparators.ELEMENT_COMPARATOR);
    List<FlowEntry> rules;

    Iterable<Device> devices = null;
    if (uri == null) {
        devices = deviceService.getDevices();
    } else {
        Device dev = deviceService.getDevice(DeviceId.deviceId(uri));
        devices = (dev == null) ? deviceService.getDevices()
                                : Collections.singletonList(dev);
    }

    for (Device d : devices) {
        if (predicate.equals(TRUE_PREDICATE)) {
            rules = newArrayList(service.getFlowEntries(d.id()));
        } else {
            rules = newArrayList();
            for (FlowEntry f : service.getFlowEntries(d.id())) {
                if (predicate.test(f)) {
                    rules.add(f);
                }
            }
        }
        rules.sort(Comparators.FLOW_RULE_COMPARATOR);

        if (suppressCoreOutput) {
            short coreAppId = coreService.getAppId("org.onosproject.core").id();
            rules = rules.stream()
                    .filter(f -> f.appId() != coreAppId)
                    .collect(Collectors.toList());
        }
        flows.put(d, rules);
    }
    return flows;
}
 
Example 11
Source File: VirtualFlowsListCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the list of devices sorted using the device ID URIs.
 *
 * @param deviceService device service
 * @param service flow rule service
 * @return sorted device list
 */
protected SortedMap<Device, List<FlowEntry>> getSortedFlows(DeviceService deviceService,
                                                      FlowRuleService service) {
    SortedMap<Device, List<FlowEntry>> flows = new TreeMap<>(Comparators.ELEMENT_COMPARATOR);
    List<FlowEntry> rules;

    Iterable<Device> devices = null;
    if (uri == null) {
        devices = deviceService.getDevices();
    } else {
        Device dev = deviceService.getDevice(DeviceId.deviceId(uri));
        devices = (dev == null) ? deviceService.getDevices()
                                : Collections.singletonList(dev);
    }

    for (Device d : devices) {
        if (predicate.equals(TRUE_PREDICATE)) {
            rules = newArrayList(service.getFlowEntries(d.id()));
        } else {
            rules = newArrayList();
            for (FlowEntry f : service.getFlowEntries(d.id())) {
                if (predicate.test(f)) {
                    rules.add(f);
                }
            }
        }
        rules.sort(Comparators.FLOW_RULE_COMPARATOR);

        flows.put(d, rules);
    }
    return flows;
}
 
Example 12
Source File: FlowRuleJuniperImpl.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
    public Collection<FlowEntry> getFlowEntries() {

        DeviceId devId = checkNotNull(this.data().deviceId());
        NetconfSession session = lookupNetconfSession(devId);
        if (session == null) {
            return Collections.emptyList();
        }

        //Installed static routes
        String reply;
        try {
            reply = session.get(routingTableBuilder());
        } catch (NetconfException e) {
            throw new IllegalStateException(new NetconfException("Failed to retrieve configuration.",
                    e));
        }
        Collection<StaticRoute> devicesStaticRoutes =
                JuniperUtils.parseRoutingTable(loadXmlString(reply));

        //Expected FlowEntries installed
        FlowRuleService flowRuleService = this.handler().get(FlowRuleService.class);
        Iterable<FlowEntry> flowEntries = flowRuleService.getFlowEntries(devId);

        Collection<FlowEntry> installedRules = new HashSet<>();
        flowEntries.forEach(flowEntry -> {
            Optional<IPCriterion> ipCriterion = getIpCriterion(flowEntry);
            if (!ipCriterion.isPresent()) {
                return;
            }

            Optional<OutputInstruction> output = getOutput(flowEntry);
            if (!output.isPresent()) {
                return;
            }
            //convert FlowRule into static route
            getStaticRoute(devId, ipCriterion.get(), output.get(), flowEntry.priority()).ifPresent(staticRoute -> {
                //Two type of FlowRules:
                //1. FlowRules to forward to a remote subnet: they are translated into static route
                // configuration. So a removal request will be processed.
                //2. FlowRules to forward on a subnet directly attached to the router (Generally speaking called local):
                // those routes do not require any configuration because the router is already able to forward on
                // directly attached subnet. In this case, when the driver receive the request to remove,
                // it will report as removed.

                if (staticRoute.isLocalRoute()) {
                    //if the FlowRule is in PENDING_REMOVE or REMOVED, it is not reported.
                    if (flowEntry.state() == PENDING_REMOVE || flowEntry.state() == REMOVED) {
                        devicesStaticRoutes.remove(staticRoute);
                    } else {
                        //FlowRule is reported installed
                        installedRules.add(flowEntry);
                        devicesStaticRoutes.remove(staticRoute);
                    }

                } else {
                    //if the route is found in the device, the FlowRule is reported installed.
                    if (devicesStaticRoutes.contains(staticRoute)) {
                        installedRules.add(flowEntry);
                        devicesStaticRoutes.remove(staticRoute);
                    }
                }
            });
        });

        if (!devicesStaticRoutes.isEmpty()) {
            log.info("Found static routes on device {} not installed by ONOS: {}",
                    devId, devicesStaticRoutes);
//            FIXME: enable configuration to purge already installed flows.
//            It cannot be allowed by default because it may remove needed management routes
//            log.warn("Removing from device {} the FlowEntries not expected {}", deviceId, devicesStaticRoutes);
//            devicesStaticRoutes.forEach(staticRoute -> editRoute(session, REMOVE, staticRoute));
        }
        return installedRules;
    }
 
Example 13
Source File: CzechLightFlowRuleProgrammable.java    From onos with Apache License 2.0 4 votes vote down vote up
private FlowRule asFlowRule(final Direction direction, final CzechLightRouting routing) {
    FlowRuleService service = handler().get(FlowRuleService.class);
    Iterable<FlowEntry> entries = service.getFlowEntries(data().deviceId());

    final var portIn = PortNumber.portNumber(direction == Direction.DROP ?
            CzechLightDiscovery.PORT_COMMON : routing.leafPort);
    final var portOut = PortNumber.portNumber(direction == Direction.ADD ?
            CzechLightDiscovery.PORT_COMMON : routing.leafPort);

    final var channelWidth = routing.channel.highMHz - routing.channel.lowMHz;
    final var channelCentralFreq = (int) (routing.channel.lowMHz + channelWidth / 2);

    for (FlowEntry entry : entries) {
        final var och = ochSignalFromFlow(entry);
        if (och.centralFrequency().asMHz() == channelCentralFreq
                && och.slotWidth().asMHz() == channelWidth
                && portIn.equals(inputPortFromFlow(entry))
                && portOut.equals(outputPortFromFlow(entry))) {
            return entry;
        }
    }

    final var channelSlotWidth = (int) (channelWidth / ChannelSpacing.CHL_12P5GHZ.frequency().asMHz());
    final var channelMultiplier = (int) ((channelCentralFreq - Spectrum.CENTER_FREQUENCY.asMHz())
            / ChannelSpacing.CHL_6P25GHZ.frequency().asMHz());

    TrafficSelector selector = DefaultTrafficSelector.builder()
            .matchInPort(portIn)
            .add(Criteria.matchOchSignalType(OchSignalType.FLEX_GRID))
            .add(Criteria.matchLambda(Lambda.ochSignal(GridType.FLEX, ChannelSpacing.CHL_6P25GHZ,
                    channelMultiplier, channelSlotWidth)))
            .build();
    TrafficTreatment treatment = DefaultTrafficTreatment.builder()
            .setOutput(portOut)
            .build();
    return DefaultFlowRule.builder()
            .forDevice(data().deviceId())
            .withSelector(selector)
            .withTreatment(treatment)
            // the concept of priorities does not make sense for a ROADM MC configuration,
            // but it's mandatory nonetheless
            .withPriority(666)
            .makePermanent()
            .fromApp(handler().get(CoreService.class).getAppId(DEFAULT_APP))
            .build();
}
 
Example 14
Source File: RoadmCrossConnectCommand.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * This function drops XC installed on the device, which is matching parsed criteria.
 * Takes as an input "global" parameters (passed by user through the console).
 * @return - returns number of the rules that were dropped.
 */
protected FlowId dropRule() {

    // Preparing parameters
    DeviceId device = DeviceId.deviceId(deviceId);
    PortNumber inPort = PortNumber.portNumber(srcPort);
    PortNumber outPort = PortNumber.portNumber(dstPort);

    // Creating some variables
    OchSignal ochSignal = null;
    PortNumber inputPortNumber = null;
    PortNumber outputPortNumber = null;

    // Main idea: Go over all flow rules (read out from the storage) of current device and
    // filter them based on input and output port with respect to OchSignal
    FlowRuleService fr = AbstractShellCommand.get(FlowRuleService.class);
    Iterable<FlowEntry> flowRules = fr.getFlowEntries(device);
    FlowId flowId = null;
    OchSignal referenceSignal = createOchSignal(freq, sw, gridType, channelSpacing);


    for (FlowEntry flowRule : flowRules) {

        // Taken from FlowRuleParser
        for (Criterion c : flowRule.selector().criteria()) {
            if (c instanceof OchSignalCriterion) {
                ochSignal = ((OchSignalCriterion) c).lambda();
            }
            if (c instanceof PortCriterion) {
                inputPortNumber = ((PortCriterion) c).port(); // obtain input port
            }
        }
        for (Instruction i : flowRule.treatment().immediate()) {
            if (i instanceof
                    L0ModificationInstruction.ModOchSignalInstruction) {
                ochSignal =
                        ((L0ModificationInstruction.ModOchSignalInstruction) i)
                                .lambda();
            }
            if (i instanceof Instructions.OutputInstruction) {
                outputPortNumber = ((Instructions.OutputInstruction) i).port(); // obtain output port
            }
        }

        // If we found match, then let's delete this rule
        if ((ochSignal.centralFrequency().equals(referenceSignal.centralFrequency()))
                & (ochSignal.slotWidth().equals(referenceSignal.slotWidth()))
                & (inputPortNumber.equals(inPort)) & (outputPortNumber.equals(outPort))) {
            flowId = flowRule.id();

            RoadmService manager = AbstractShellCommand.get(RoadmService.class);
            manager.removeConnection(device, flowId);
            print("Dropping existing XC from the device %s", deviceId);
            return flowId;
        }
    }

    return null;
}
 
Example 15
Source File: OFSwitchManager.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
public List<FlowEntry> getFlowEntries(NetworkId networkId, DeviceId deviceId) {
    FlowRuleService flowRuleService = virtualNetService.get(networkId, FlowRuleService.class);
    Iterable<FlowEntry> entries = flowRuleService.getFlowEntries(deviceId);
    return Lists.newArrayList(entries);
}