org.onlab.util.ImmutableByteSequence Java Examples

The following examples show how to use org.onlab.util.ImmutableByteSequence. 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: FabricBngProgrammable.java    From onos with Apache License 2.0 6 votes vote down vote up
private Set<Long> getLineIdsFromFlowRules(Iterable<? extends FlowRule> rules) {
    // Extract the line ID found in the flow rule selector.
    return StreamSupport.stream(rules.spliterator(), true)
            .map(f -> (PiCriterion) f.selector().getCriterion(Criterion.Type.PROTOCOL_INDEPENDENT))
            .filter(Objects::nonNull)
            .map(c -> c.fieldMatch(FabricConstants.HDR_LINE_ID))
            .filter(Optional::isPresent)
            .map(Optional::get)
            .filter(m -> m.type() == PiMatchType.EXACT)
            .map(m -> ((PiExactFieldMatch) m).value())
            .map(b -> {
                try {
                    return b.fit(Long.BYTES * 8);
                } catch (ImmutableByteSequence.ByteSequenceTrimException e) {
                    log.error("Invalid line ID found in flow rule: {} is bigger than a long! BUG?", b);
                    return null;
                }
            })
            .filter(Objects::nonNull)
            .map(b -> b.asReadOnlyBuffer().getLong())
            .collect(Collectors.toSet());
}
 
Example #2
Source File: InstructionCodecTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests the encoding of protocol-independent instructions.
 */
@Test
public void piInstructionEncodingTest() {
    PiActionId actionId = PiActionId.of("set_egress_port");
    PiActionParamId actionParamId = PiActionParamId.of("port");
    PiActionParam actionParam = new PiActionParam(actionParamId, ImmutableByteSequence.copyFrom(10));
    PiTableAction action = PiAction.builder().withId(actionId).withParameter(actionParam).build();
    final PiInstruction actionInstruction = Instructions.piTableAction(action);
    final ObjectNode actionInstructionJson =
            instructionCodec.encode(actionInstruction, context);
    assertThat(actionInstructionJson, matchesInstruction(actionInstruction));

    PiTableAction actionGroupId = PiActionProfileGroupId.of(10);
    final PiInstruction actionGroupIdInstruction = Instructions.piTableAction(actionGroupId);
    final ObjectNode actionGroupIdInstructionJson =
            instructionCodec.encode(actionGroupIdInstruction, context);
    assertThat(actionGroupIdInstructionJson, matchesInstruction(actionGroupIdInstruction));

    PiTableAction actionProfileMemberId = PiActionProfileMemberId.of(10);
    final PiInstruction actionProfileMemberIdInstruction = Instructions.piTableAction(actionProfileMemberId);
    final ObjectNode actionProfileMemberIdInstructionJson =
            instructionCodec.encode(actionProfileMemberIdInstruction, context);
    assertThat(actionProfileMemberIdInstructionJson, matchesInstruction(actionProfileMemberIdInstruction));
}
 
Example #3
Source File: AbstractCriterionTranslator.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public Pair<ImmutableByteSequence, Integer> lpmMatch() throws CriterionTranslatorException {
    switch (initType) {
        case EXACT:
            prefixLength = bitWidth;
            break;
        case TERNARY:
            prefixLength = getPrefixLengthFromMask(mask).orElseThrow(
                    () -> new CriterionTranslatorException(
                            "trying to use masked field as a longest-prefix match, " +
                                    "but mask is not equivalent to a prefix length"));
            break;
        case LPM:
            break;
        default:
            throw new IllegalArgumentException("Unrecognized init type " + initType.name());
    }

    return Pair.of(value, prefixLength);
}
 
Example #4
Source File: ActionCodec.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
protected PiAction decode(
        P4RuntimeOuterClass.Action message, Object ignored,
        PiPipeconf pipeconf, P4InfoBrowser browser)
        throws P4InfoBrowser.NotFoundException {
    final P4InfoBrowser.EntityBrowser<P4InfoOuterClass.Action.Param> paramInfo =
            browser.actionParams(message.getActionId());
    final String actionName = browser.actions()
            .getById(message.getActionId())
            .getPreamble().getName();
    final PiAction.Builder builder = PiAction.builder()
            .withId(PiActionId.of(actionName));
    for (P4RuntimeOuterClass.Action.Param p : message.getParamsList()) {
        final String paramName = paramInfo.getById(p.getParamId()).getName();
        final ImmutableByteSequence value = ImmutableByteSequence.copyFrom(
                p.getValue().toByteArray());
        builder.withParameter(new PiActionParam(PiActionParamId.of(paramName), value));
    }
    return builder.build();
}
 
Example #5
Source File: AbstractCriterionTranslator.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public Pair<ImmutableByteSequence, ImmutableByteSequence> ternaryMatch() {
    switch (initType) {
        case EXACT:
            mask = ImmutableByteSequence.prefixZeros(value.size(), prefixPadding());
            break;
        case TERNARY:
            break;
        case LPM:
            mask = getMaskFromPrefixLength(prefixLength, value.size());
            break;
        default:
            throw new IllegalArgumentException("Unrecognized init type " + initType.name());
    }

    return Pair.of(value, mask);
}
 
Example #6
Source File: FabricInterpreterTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Map treatment to push_internal_vlan action.
 */
@Test
public void testFilteringTreatmentPermitWithInternalVlan() throws Exception {
    TrafficTreatment treatment = DefaultTrafficTreatment.builder()
            .pushVlan()
            .setVlanId(VLAN_100)
            .build();
    PiAction mappedAction = interpreter.mapTreatment(treatment,
                                                     FabricConstants.FABRIC_INGRESS_FILTERING_INGRESS_PORT_VLAN);
    PiActionParam param = new PiActionParam(FabricConstants.VLAN_ID,
                                            ImmutableByteSequence.copyFrom(VLAN_100.toShort()));
    PiAction expectedAction = PiAction.builder()
            .withId(FabricConstants.FABRIC_INGRESS_FILTERING_PERMIT_WITH_INTERNAL_VLAN)
            .withParameter(param)
            .build();

    assertEquals(expectedAction, mappedAction);
}
 
Example #7
Source File: AbstractCriterionTranslator.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public ImmutableByteSequence exactMatch() throws CriterionTranslatorException {
    switch (initType) {
        case EXACT:
            break;
        case TERNARY:
            ImmutableByteSequence exactMask = ImmutableByteSequence.ofOnes(value.size());
            if (!mask.equals(exactMask)) {
                throw new CriterionTranslator.CriterionTranslatorException(
                        "trying to use masked field as an exact match, but mask is not exact");
            }
            break;
        case LPM:
            if (prefixLength < bitWidth) {
                throw new CriterionTranslator.CriterionTranslatorException(
                        "trying to use LPM field as an exact match, but prefix is not full");
            }
            break;
        default:
            throw new IllegalArgumentException("Unrecognized init type " + initType.name());
    }
    return value;
}
 
Example #8
Source File: AbstractCriterionTranslator.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that the given mask is equivalent to a longest-prefix match and returns the prefix length. If not
 * possible, the optional value will not be present.
 *
 * @param mask byte sequence
 * @return optional prefix length
 */
private Optional<Integer> getPrefixLengthFromMask(ImmutableByteSequence mask) {
    Integer prefixLength = 0;

    byte[] byteArray = mask.asArray();
    int byteArrayIndex = 0;
    while (byteArrayIndex < byteArray.length && byteArray[byteArrayIndex] == (byte) 0xff) {
        prefixLength += Byte.SIZE;
        byteArrayIndex++;
    }

    byte byteVal = byteArray[byteArrayIndex];
    while (byteVal != 0) {
        if ((byteVal & Integer.MIN_VALUE) != Integer.MIN_VALUE) {
            return Optional.empty();
        }
        prefixLength++;
        byteVal <<= 1;
    }

    byteArrayIndex++;
    while (byteArrayIndex < byteArray.length) {
        if (byteArray[byteArrayIndex] != 0) {
            return Optional.empty();
        }
        byteArrayIndex++;
    }

    return Optional.of(prefixLength);
}
 
Example #9
Source File: PipelineInterpreterImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
private PiPacketMetadata createPacketMetadata(long portNumber)
        throws PiInterpreterException {
    try {
        return PiPacketMetadata.builder()
                .withId(PiPacketMetadataId.of(EGRESS_PORT))
                .withValue(copyFrom(portNumber).fit(PORT_FIELD_BITWIDTH))
                .build();
    } catch (ImmutableByteSequence.ByteSequenceTrimException e) {
        throw new PiInterpreterException(format(
                "Port number %d too big, %s", portNumber, e.getMessage()));
    }
}
 
Example #10
Source File: PiCriterionTranslatorsTest.java    From onos with Apache License 2.0 5 votes vote down vote up
@Test
public void testLpmToTernaryTranslation() throws Exception {
    IpPrefix ipPrefix = IpPrefix.valueOf("10.0.0.1/23");
    int bitWidth = ipPrefix.address().toOctets().length * Byte.SIZE;

    IPCriterion criterion = (IPCriterion) Criteria.matchIPDst(ipPrefix);
    PiTernaryFieldMatch ternaryMatch =
            (PiTernaryFieldMatch) translateCriterion(criterion, fieldId, TERNARY, bitWidth);

    ImmutableByteSequence expectedMask = ImmutableByteSequence.prefixOnes(Integer.BYTES, 23);
    ImmutableByteSequence expectedValue = ImmutableByteSequence.copyFrom(ipPrefix.address().toOctets());

    assertThat(ternaryMatch.mask(), is(expectedMask));
    assertThat(ternaryMatch.value(), is(expectedValue));
}
 
Example #11
Source File: IntProgrammableImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public boolean init() {
    if (!setupBehaviour()) {
        return false;
    }

    PiActionParam transitIdParam = new PiActionParam(
            IntConstants.SWITCH_ID,
            ImmutableByteSequence.copyFrom(
                    Integer.parseInt(deviceId.toString().substring(
                            deviceId.toString().length() - 2))));
    TrafficSelector selector = DefaultTrafficSelector.builder()
            .matchPi(PiCriterion.builder().matchExact(
                    IntConstants.HDR_INT_IS_VALID, (byte) 0x01)
                     .build())
            .build();
    PiAction transitAction = PiAction.builder()
            .withId(IntConstants.EGRESS_PROCESS_INT_TRANSIT_INIT_METADATA)
            .withParameter(transitIdParam)
            .build();
    TrafficTreatment treatment = DefaultTrafficTreatment.builder()
            .piTableAction(transitAction)
            .build();

    FlowRule transitFlowRule = DefaultFlowRule.builder()
            .withSelector(selector)
            .withTreatment(treatment)
            .fromApp(appId)
            .withPriority(DEFAULT_PRIORITY)
            .makePermanent()
            .forDevice(deviceId)
            .forTable(IntConstants.EGRESS_PROCESS_INT_TRANSIT_TB_INT_INSERT)
            .build();

    flowRuleService.applyFlowRules(transitFlowRule);

    return true;
}
 
Example #12
Source File: FieldMatchCodec.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public PiFieldMatch decode(
        P4RuntimeOuterClass.FieldMatch message, P4InfoOuterClass.Preamble tablePreamble,
        PiPipeconf pipeconf, P4InfoBrowser browser)
        throws CodecException, P4InfoBrowser.NotFoundException {

    String fieldMatchName = browser.matchFields(tablePreamble.getId())
            .getById(message.getFieldId()).getName();
    PiMatchFieldId headerFieldId = PiMatchFieldId.of(fieldMatchName);

    P4RuntimeOuterClass.FieldMatch.FieldMatchTypeCase typeCase = message.getFieldMatchTypeCase();

    switch (typeCase) {
        case EXACT:
            P4RuntimeOuterClass.FieldMatch.Exact exactFieldMatch = message.getExact();
            ImmutableByteSequence exactValue = copyFrom(exactFieldMatch.getValue().asReadOnlyByteBuffer());
            return new PiExactFieldMatch(headerFieldId, exactValue);
        case TERNARY:
            P4RuntimeOuterClass.FieldMatch.Ternary ternaryFieldMatch = message.getTernary();
            ImmutableByteSequence ternaryValue = copyFrom(ternaryFieldMatch.getValue().asReadOnlyByteBuffer());
            ImmutableByteSequence ternaryMask = copyFrom(ternaryFieldMatch.getMask().asReadOnlyByteBuffer());
            return new PiTernaryFieldMatch(headerFieldId, ternaryValue, ternaryMask);
        case LPM:
            P4RuntimeOuterClass.FieldMatch.LPM lpmFieldMatch = message.getLpm();
            ImmutableByteSequence lpmValue = copyFrom(lpmFieldMatch.getValue().asReadOnlyByteBuffer());
            int lpmPrefixLen = lpmFieldMatch.getPrefixLen();
            return new PiLpmFieldMatch(headerFieldId, lpmValue, lpmPrefixLen);
        case RANGE:
            P4RuntimeOuterClass.FieldMatch.Range rangeFieldMatch = message.getRange();
            ImmutableByteSequence rangeHighValue = copyFrom(rangeFieldMatch.getHigh().asReadOnlyByteBuffer());
            ImmutableByteSequence rangeLowValue = copyFrom(rangeFieldMatch.getLow().asReadOnlyByteBuffer());
            return new PiRangeFieldMatch(headerFieldId, rangeLowValue, rangeHighValue);
        default:
            throw new CodecException(format(
                    "Decoding of field match type '%s' not implemented", typeCase.name()));
    }
}
 
Example #13
Source File: P4DataCodec.java    From onos with Apache License 2.0 5 votes vote down vote up
private static PiHeader decodeHeader(P4Header p4Header) {
    List<ImmutableByteSequence> bitStrings = p4Header.getBitstringsList().stream()
            .map(bit -> ImmutableByteSequence.copyFrom(bit.asReadOnlyByteBuffer()))
            .collect(Collectors.toList());

    return PiHeader.of(p4Header.getIsValid(), bitStrings);
}
 
Example #14
Source File: FabricFilteringPipelinerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
private Collection<FlowRule> buildExpectedFwdClassifierRule(PortNumber inPort,
                                                            MacAddress dstMac,
                                                            MacAddress dstMacMask,
                                                            short ethType,
                                                            byte fwdClass) {
    PiActionParam classParam = new PiActionParam(FabricConstants.FWD_TYPE,
                                                 ImmutableByteSequence.copyFrom(fwdClass));
    PiAction fwdClassifierAction = PiAction.builder()
            .withId(FabricConstants.FABRIC_INGRESS_FILTERING_SET_FORWARDING_TYPE)
            .withParameter(classParam)
            .build();
    TrafficTreatment treatment = DefaultTrafficTreatment.builder()
            .piTableAction(fwdClassifierAction)
            .build();

    TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder()
            .matchInPort(inPort);
    if (dstMacMask != null) {
        sbuilder.matchEthDstMasked(dstMac, dstMacMask);
    } else {
        sbuilder.matchEthDstMasked(dstMac, MacAddress.EXACT_MASK);
    }
    // Special case for MPLS UNICAST forwarding, need to build 2 rules for MPLS+IPv4 and MPLS+IPv6
    if (ethType == Ethernet.MPLS_UNICAST) {
        return buildExpectedFwdClassifierRulesMpls(fwdClassifierAction, treatment, sbuilder);
    }
    sbuilder.matchPi(PiCriterion.builder()
                             .matchExact(FabricConstants.HDR_IP_ETH_TYPE, ethType)
                             .build());
    TrafficSelector selector = sbuilder.build();
    return List.of(DefaultFlowRule.builder()
                           .withPriority(PRIORITY)
                           .withSelector(selector)
                           .withTreatment(treatment)
                           .fromApp(APP_ID)
                           .forDevice(DEVICE_ID)
                           .makePermanent()
                           .forTable(FabricConstants.FABRIC_INGRESS_FILTERING_FWD_CLASSIFIER)
                           .build());
}
 
Example #15
Source File: InterpreterImpl.java    From ngsdn-tutorial with Apache License 2.0 5 votes vote down vote up
/**
 * Builds a pipeconf-specific packet-out instance with the given payload and
 * egress port.
 *
 * @param pktData    packet payload
 * @param portNumber egress port
 * @return packet-out
 * @throws PiInterpreterException if packet-out cannot be built
 */
private PiPacketOperation buildPacketOut(ByteBuffer pktData, long portNumber)
        throws PiInterpreterException {

    // Make sure port number can fit in v1model port metadata bitwidth.
    final ImmutableByteSequence portBytes;
    try {
        portBytes = copyFrom(portNumber).fit(V1MODEL_PORT_BITWIDTH);
    } catch (ImmutableByteSequence.ByteSequenceTrimException e) {
        throw new PiInterpreterException(format(
                "Port number %d too big, %s", portNumber, e.getMessage()));
    }

    // Create metadata instance for egress port.
    // TODO EXERCISE 3: modify metadata names to match P4 program
    // ---- START SOLUTION ----
    final String outPortMetadataName = "egress_port";
    // ---- END SOLUTION ----
    final PiPacketMetadata outPortMetadata = PiPacketMetadata.builder()
            .withId(PiPacketMetadataId.of(outPortMetadataName))
            .withValue(portBytes)
            .build();

    // Build packet out.
    return PiPacketOperation.builder()
            .withType(PACKET_OUT)
            .withData(copyFrom(pktData))
            .withMetadata(outPortMetadata)
            .build();
}
 
Example #16
Source File: P4DataCodec.java    From onos with Apache License 2.0 5 votes vote down vote up
private static P4Header encodeHeader(PiHeader piHeader) {
    P4Header.Builder builder = P4Header.newBuilder();
    int i = 0;
    for (ImmutableByteSequence bitString : piHeader.bitStrings()) {
        builder.setBitstrings(i, ByteString.copyFrom(bitString.asArray()));
        i++;
    }
    return builder.setIsValid(piHeader.isValid()).build();
}
 
Example #17
Source File: InterpreterImpl.java    From onos-p4-tutorial with Apache License 2.0 5 votes vote down vote up
/**
 * Builds a pipeconf-specific packet-out instance with the given payload and
 * egress port.
 *
 * @param pktData    packet payload
 * @param portNumber egress port
 * @return packet-out
 * @throws PiInterpreterException if packet-out cannot be built
 */
private PiPacketOperation buildPacketOut(ByteBuffer pktData, long portNumber)
        throws PiInterpreterException {

    // Make sure port number can fit in v1model port metadata bitwidth.
    final ImmutableByteSequence portBytes;
    try {
        portBytes = copyFrom(portNumber).fit(V1MODEL_PORT_BITWIDTH);
    } catch (ImmutableByteSequence.ByteSequenceTrimException e) {
        throw new PiInterpreterException(format(
                "Port number %d too big, %s", portNumber, e.getMessage()));
    }

    // Create metadata instance for egress port.
    // TODO EXERCISE 1: modify metadata names to match P4 program
    // ---- START SOLUTION ----
    final String outPortMetadataName = "MODIFY ME";
    // ---- END SOLUTION ----
    final PiPacketMetadata outPortMetadata = PiPacketMetadata.builder()
            .withId(PiPacketMetadataId.of(outPortMetadataName))
            .withValue(portBytes)
            .build();

    // Build packet out.
    return PiPacketOperation.builder()
            .withType(PACKET_OUT)
            .withData(copyFrom(pktData))
            .withMetadata(outPortMetadata)
            .build();
}
 
Example #18
Source File: InterpreterImpl.java    From ngsdn-tutorial with Apache License 2.0 5 votes vote down vote up
/**
 * Builds a pipeconf-specific packet-out instance with the given payload and
 * egress port.
 *
 * @param pktData    packet payload
 * @param portNumber egress port
 * @return packet-out
 * @throws PiInterpreterException if packet-out cannot be built
 */
private PiPacketOperation buildPacketOut(ByteBuffer pktData, long portNumber)
        throws PiInterpreterException {

    // Make sure port number can fit in v1model port metadata bitwidth.
    final ImmutableByteSequence portBytes;
    try {
        portBytes = copyFrom(portNumber).fit(V1MODEL_PORT_BITWIDTH);
    } catch (ImmutableByteSequence.ByteSequenceTrimException e) {
        throw new PiInterpreterException(format(
                "Port number %d too big, %s", portNumber, e.getMessage()));
    }

    // Create metadata instance for egress port.
    // *** TODO EXERCISE 3: modify metadata names to match P4 program
    // ---- START SOLUTION ----
    final String outPortMetadataName = "<ADD HERE METADATA NAME FOR THE EGRESS PORT>";
    // ---- END SOLUTION ----
    final PiPacketMetadata outPortMetadata = PiPacketMetadata.builder()
            .withId(PiPacketMetadataId.of(outPortMetadataName))
            .withValue(portBytes)
            .build();

    // Build packet out.
    return PiPacketOperation.builder()
            .withType(PACKET_OUT)
            .withData(copyFrom(pktData))
            .withMetadata(outPortMetadata)
            .build();
}
 
Example #19
Source File: BasicInterpreterImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public InboundPacket mapInboundPacket(PiPacketOperation packetIn, DeviceId deviceId)
        throws PiInterpreterException {
    // Assuming that the packet is ethernet, which is fine since basic.p4
    // can deparse only ethernet packets.
    Ethernet ethPkt;
    try {
        ethPkt = Ethernet.deserializer().deserialize(packetIn.data().asArray(), 0,
                                                     packetIn.data().size());
    } catch (DeserializationException dex) {
        throw new PiInterpreterException(dex.getMessage());
    }

    // Returns the ingress port packet metadata.
    Optional<PiPacketMetadata> packetMetadata = packetIn.metadatas()
            .stream().filter(m -> m.id().equals(INGRESS_PORT))
            .findFirst();

    if (packetMetadata.isPresent()) {
        ImmutableByteSequence portByteSequence = packetMetadata.get().value();
        short s = portByteSequence.asReadOnlyBuffer().getShort();
        ConnectPoint receivedFrom = new ConnectPoint(deviceId, PortNumber.portNumber(s));
        ByteBuffer rawData = ByteBuffer.wrap(packetIn.data().asArray());
        return new DefaultInboundPacket(receivedFrom, ethPkt, rawData);
    } else {
        throw new PiInterpreterException(format(
                "Missing metadata '%s' in packet-in received from '%s': %s",
                INGRESS_PORT, deviceId, packetIn));
    }
}
 
Example #20
Source File: BasicInterpreterImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
private PiPacketMetadata createPacketMetadata(long portNumber) throws PiInterpreterException {
    try {
        return PiPacketMetadata.builder()
                .withId(EGRESS_PORT)
                .withValue(copyFrom(portNumber).fit(PORT_BITWIDTH))
                .build();
    } catch (ImmutableByteSequence.ByteSequenceTrimException e) {
        throw new PiInterpreterException(format(
                "Port number %d too big, %s", portNumber, e.getMessage()));
    }
}
 
Example #21
Source File: PiRangeFieldMatch.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new range field match for the given low and high value.
 *
 * @param fieldId   field identifier
 * @param lowValue  low value
 * @param highValue high value
 */
public PiRangeFieldMatch(PiMatchFieldId fieldId, ImmutableByteSequence lowValue,
                         ImmutableByteSequence highValue) {
    super(fieldId);
    this.lowValue = checkNotNull(lowValue);
    this.highValue = checkNotNull(highValue);
    checkArgument(lowValue.size() == highValue.size() && lowValue.size() > 0,
                  "Low and high values must have the same non-zero size.");
}
 
Example #22
Source File: PiLpmFieldMatch.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new LPM field match.
 *
 * @param fieldId      field identifier
 * @param value        value
 * @param prefixLength prefix length
 */
public PiLpmFieldMatch(PiMatchFieldId fieldId, ImmutableByteSequence value, int prefixLength) {
    super(fieldId);
    this.value = checkNotNull(value);
    this.prefixLength = prefixLength;
    checkArgument(value.size() > 0, "Value must have non-zero size");
    checkArgument(prefixLength >= 0, "Prefix length must be a non-negative integer");
}
 
Example #23
Source File: PiActionParamTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Checks the construction of a PiActionParam object.
 */
@Test
public void testConstruction() {
    ImmutableByteSequence value = copyFrom(0x0b010102);
    final PiActionParamId piActionParamId = PiActionParamId.of(SRC_ADDR);
    final PiActionParam piActionParam = new PiActionParam(piActionParamId, value);
    assertThat(piActionParam, is(notNullValue()));
    assertThat(piActionParam.id(), is(piActionParamId));
    assertThat(piActionParam.value(), is(value));
}
 
Example #24
Source File: PiExactFieldMatchTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Checks the construction of a PiExactFieldMatch object.
 */
@Test
public void testConstruction() {
    final ImmutableByteSequence value = copyFrom(0x0806);
    final PiMatchFieldId piMatchField = PiMatchFieldId.of(ETH_HEADER_NAME + DOT + ETH_TYPE);
    PiExactFieldMatch piExactFieldMatch = new PiExactFieldMatch(piMatchField, value);
    assertThat(piExactFieldMatch, is(notNullValue()));
    assertThat(piExactFieldMatch.value(), is(value));
    assertThat(piExactFieldMatch.type(), is(PiMatchType.EXACT));
}
 
Example #25
Source File: ImmutableByteSequenceSerializer.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public ImmutableByteSequence read(Kryo kryo, Input input, Class<ImmutableByteSequence> type) {
    int length = input.readInt();
    byte[] data = new byte[length];
    int bytesRead = input.read(data);
    if (bytesRead != length) {
        throw new IllegalStateException("Byte sequence serializer read expected " + length +
                " but got " + bytesRead);
    }
    return ImmutableByteSequence.copyFrom(data);
}
 
Example #26
Source File: PiTableEntryTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Tests creation of a DefaultFlowRule using a FlowRule constructor.
 */
@Test
public void testBuilder() {

    PiTableId piTableId = PiTableId.of("table10");
    long cookie = 0xfff0323;
    int priority = 100;
    double timeout = 1000;
    PiMatchFieldId piMatchFieldId = PiMatchFieldId.of(IPV4_HEADER_NAME + DOT + DST_ADDR);
    PiFieldMatch piFieldMatch = new PiExactFieldMatch(piMatchFieldId, ImmutableByteSequence.copyFrom(0x0a010101));
    PiAction piAction = PiAction.builder().withId(PiActionId.of(DROP)).build();
    final Map<PiMatchFieldId, PiFieldMatch> fieldMatches = Maps.newHashMap();
    fieldMatches.put(piMatchFieldId, piFieldMatch);
    final PiTableEntry piTableEntry = PiTableEntry.builder()
            .forTable(piTableId)
            .withMatchKey(PiMatchKey.builder()
                                  .addFieldMatches(fieldMatches.values())
                                  .build())
            .withAction(piAction)
            .withCookie(cookie)
            .withPriority(priority)
            .withTimeout(timeout)
            .build();

    assertThat(piTableEntry.table(), is(piTableId));
    assertThat(piTableEntry.cookie(), is(cookie));
    assertThat("Priority must be set", piTableEntry.priority().isPresent());
    assertThat("Timeout must be set", piTableEntry.timeout().isPresent());
    assertThat(piTableEntry.priority().getAsInt(), is(priority));
    assertThat(piTableEntry.timeout().get(), is(timeout));
    assertThat("Incorrect match param value",
               CollectionUtils.isEqualCollection(piTableEntry.matchKey().fieldMatches(), fieldMatches.values()));
    assertThat(piTableEntry.action(), is(piAction));
}
 
Example #27
Source File: PiTernaryFieldMatchTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Checks the construction of a PiTernaryFieldMatch object.
 */
@Test
public void testConstruction() {
    final ImmutableByteSequence value = copyFrom(0x0a01010a);
    final ImmutableByteSequence mask = copyFrom(0x00ffffff);
    final PiMatchFieldId piMatchField = PiMatchFieldId.of(IPV4_HEADER_NAME + DOT + DST_ADDR);
    PiTernaryFieldMatch piTernaryFieldMatch = new PiTernaryFieldMatch(piMatchField, value, mask);
    assertThat(piTernaryFieldMatch, is(notNullValue()));
    assertThat(piTernaryFieldMatch.value(), is(value));
    assertThat(piTernaryFieldMatch.mask(), is(mask));
    assertThat(piTernaryFieldMatch.type(), is(PiMatchType.TERNARY));
}
 
Example #28
Source File: PiRangeFieldMatchTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Checks the construction of a PiRangeFieldMatch object.
 */
@Test
public void testConstruction() {
    final ImmutableByteSequence high = copyFrom(0x50);
    final ImmutableByteSequence low = copyFrom(0x00);
    final PiMatchFieldId piMatchField = PiMatchFieldId.of(VLAN_HEADER_NAME + DOT + VID);
    PiRangeFieldMatch piRangeFieldMatch = new PiRangeFieldMatch(piMatchField, low, high);
    assertThat(piRangeFieldMatch, is(notNullValue()));
    assertThat(piRangeFieldMatch.lowValue(), is(low));
    assertThat(piRangeFieldMatch.highValue(), is(high));
    assertThat(piRangeFieldMatch.type(), is(PiMatchType.RANGE));
}
 
Example #29
Source File: PiLpmFieldMatchTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Checks the construction of a PiLpmFieldMatch object.
 */
@Test
public void testConstruction() {
    final ImmutableByteSequence value = copyFrom(0x0a01010a);
    int prefix = 24;
    final PiMatchFieldId piMatchField = PiMatchFieldId.of(IPV4_HEADER_NAME + DOT + DST_ADDR);
    PiLpmFieldMatch piLpmFieldMatch = new PiLpmFieldMatch(piMatchField, value, prefix);
    assertThat(piLpmFieldMatch, is(notNullValue()));
    assertThat(piLpmFieldMatch.value(), is(value));
    assertThat(piLpmFieldMatch.prefixLength(), is(prefix));
    assertThat(piLpmFieldMatch.type(), is(PiMatchType.LPM));
}
 
Example #30
Source File: PiTernaryFieldMatch.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new ternary field match.
 *
 * @param fieldId field identifier
 * @param value   value
 * @param mask    mask
 */
public PiTernaryFieldMatch(PiMatchFieldId fieldId, ImmutableByteSequence value,
                           ImmutableByteSequence mask) {
    super(fieldId);
    this.value = checkNotNull(value);
    this.mask = checkNotNull(mask);
    checkArgument(value.size() == mask.size() && value.size() > 0,
                  "Value and mask must have same non-zero size");
}