Carmelo Cascone
Committed by Gerrit Code Review

Major refactoring of the BMv2 protocol module (onos1.6 cherry-pick)

- Created 3 separate sub-modules: API (doesn't depend on
    Thrift), CTL (depends on Thrift), THRIFT-API (to generate Thrift
    sources)
- Implemented 2 new services (for device configuration swapping and
    table entry management) needed to distribute BMv2-specific state
    among ONOS instances.
- Implemented a BMv2 controller (previously other modules where
    using separately a Thrift client and a server)
- Added a default BMv2 JSON configuration (default.json) and interpreter
    to be used for devices that connect for the first time to ONOS.
    This allows for basic services to work (i.e. LLDP link discovery,
    ARP proxy. etc.).
- Changed behavior of the flow rule translator and extension selector,
    now it allows extension to specify only some of the match parameters
    (before extension selectors were expected to describe the whole
    match key, i.e. all fields)
- Various renaming to better represent the API
- Various java doc fixes / improvements

Change-Id: Ida4b5e546b0def97c3552a6c05f7bce76fd32c28
Showing 72 changed files with 2599 additions and 414 deletions
......@@ -39,7 +39,7 @@ public class ExtensionSelectorType {
NICIRA_MATCH_NSH_CH3(4),
NICIRA_MATCH_NSH_CH4(5),
OFDPA_MATCH_VLAN_VID(16),
P4_BMV2_MATCH_KEY(128);
BMV2_MATCH_PARAMS(128);
private ExtensionSelectorType type;
......
......@@ -46,7 +46,7 @@ public final class ExtensionTreatmentType {
NICIRA_SET_NSH_CH3(36),
NICIRA_SET_NSH_CH4(37),
OFDPA_SET_VLAN_ID(64),
P4_BMV2_ACTION(128);
BMV2_ACTION(128);
private ExtensionTreatmentType type;
......
......@@ -33,6 +33,7 @@ import org.onlab.packet.VlanId;
import org.onlab.util.Bandwidth;
import org.onlab.util.ClosedOpenRange;
import org.onlab.util.Frequency;
import org.onlab.util.ImmutableByteSequence;
import org.onlab.util.KryoNamespace;
import org.onlab.util.Match;
import org.onosproject.app.ApplicationState;
......@@ -535,6 +536,7 @@ public final class KryoNamespaces {
)
.register(ClosedOpenRange.class)
.register(DiscreteResourceCodec.class)
.register(ImmutableByteSequence.class)
.build("API");
......
......@@ -41,7 +41,7 @@
<module>utilities</module>
<module>lumentum</module>
<module>bti</module>
<module>bmv2</module>
<!--<module>bmv2</module>-->
<module>corsa</module>
<module>optical</module>
</modules>
......
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2016-present 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>onos-bmv2-protocol</artifactId>
<groupId>org.onosproject</groupId>
<version>1.6.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>bundle</packaging>
<artifactId>onos-bmv2-protocol-api</artifactId>
<dependencies>
<dependency>
<groupId>org.onosproject</groupId>
<artifactId>onos-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.apache.felix.scr.annotations</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
......@@ -14,8 +14,9 @@
* limitations under the License.
*/
package org.onosproject.bmv2.api.model;
package org.onosproject.bmv2.api.context;
import com.google.common.annotations.Beta;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
......@@ -26,22 +27,23 @@ import java.util.Objects;
import static com.google.common.base.MoreObjects.toStringHelper;
/**
* BMv2 model action.
* A BMv2 action model.
*/
public final class Bmv2ModelAction {
@Beta
public final class Bmv2ActionModel {
private final String name;
private final int id;
private final LinkedHashMap<String, Bmv2ModelRuntimeData> runtimeDatas = Maps.newLinkedHashMap();
private final LinkedHashMap<String, Bmv2RuntimeDataModel> runtimeDatas = Maps.newLinkedHashMap();
/**
* Creates a new action object.
* Creates a new action model.
*
* @param name name
* @param id id
* @param runtimeDatas list of runtime data
*/
protected Bmv2ModelAction(String name, int id, List<Bmv2ModelRuntimeData> runtimeDatas) {
protected Bmv2ActionModel(String name, int id, List<Bmv2RuntimeDataModel> runtimeDatas) {
this.name = name;
this.id = id;
runtimeDatas.forEach(r -> this.runtimeDatas.put(r.name(), r));
......@@ -66,22 +68,22 @@ public final class Bmv2ModelAction {
}
/**
* Returns this action's runtime data defined by the passed name, null
* Returns this action's runtime data defined by the given name, null
* if not present.
*
* @return runtime data or null
*/
public Bmv2ModelRuntimeData runtimeData(String name) {
public Bmv2RuntimeDataModel runtimeData(String name) {
return runtimeDatas.get(name);
}
/**
* Returns an immutable list of runtime data for this action.
* The list is ordered according to the values defined in the model.
* The list is ordered according to the values defined in the configuration.
*
* @return list of runtime data.
*/
public List<Bmv2ModelRuntimeData> runtimeDatas() {
public List<Bmv2RuntimeDataModel> runtimeDatas() {
return ImmutableList.copyOf(runtimeDatas.values());
}
......@@ -98,7 +100,7 @@ public final class Bmv2ModelAction {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final Bmv2ModelAction other = (Bmv2ModelAction) obj;
final Bmv2ActionModel other = (Bmv2ActionModel) obj;
return Objects.equals(this.name, other.name)
&& Objects.equals(this.id, other.id)
&& Objects.equals(this.runtimeDatas, other.runtimeDatas);
......
/*
* Copyright 2016-present 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.bmv2.api.context;
import com.eclipsesource.json.JsonObject;
import com.google.common.annotations.Beta;
import java.util.List;
/**
* BMv2 packet processing configuration. Such a configuration is used to define the way BMv2 should process packets
* (i.e. it defines the device ingress/egress pipelines, parser, tables, actions, etc.). It must be noted that this
* class exposes only a subset of the configuration properties of a BMv2 device (only those that are needed for the
* purpose of translating ONOS structures to BMv2 structures). Such a configuration is backed by a JSON object.
* BMv2 JSON configuration files are usually generated using a P4 frontend compiler such as p4c-bmv2.
*/
@Beta
public interface Bmv2Configuration {
/**
* Return an unmodifiable view of the JSON backing this configuration.
*
* @return a JSON object.
*/
JsonObject json();
/**
* Returns the header type associated with the given numeric ID, null if there's no such an ID in the configuration.
*
* @param id integer value
* @return header type object or null
*/
Bmv2HeaderTypeModel headerType(int id);
/**
* Returns the header type associated with the given name, null if there's no such a name in the configuration.
*
* @param name string value
* @return header type object or null
*/
Bmv2HeaderTypeModel headerType(String name);
/**
* Returns the list of all the header types defined by in this configuration. Values returned are sorted in
* ascending order based on the numeric ID.
*
* @return list of header types
*/
List<Bmv2HeaderTypeModel> headerTypes();
/**
* Returns the header associated with the given numeric ID, null if there's no such an ID in the configuration.
*
* @param id integer value
* @return header object or null
*/
Bmv2HeaderModel header(int id);
/**
* Returns the header associated with the given name, null if there's no such a name in the configuration.
*
* @param name string value
* @return header object or null
*/
Bmv2HeaderModel header(String name);
/**
* Returns the list of all the header instances defined in this configuration. Values returned are sorted in
* ascending order based on the numeric ID.
*
* @return list of header types
*/
List<Bmv2HeaderModel> headers();
/**
* Returns the action associated with the given numeric ID, null if there's no such an ID in the configuration.
*
* @param id integer value
* @return action object or null
*/
Bmv2ActionModel action(int id);
/**
* Returns the action associated with the given name, null if there's no such a name in the configuration.
*
* @param name string value
* @return action object or null
*/
Bmv2ActionModel action(String name);
/**
* Returns the list of all the actions defined by in this configuration. Values returned are sorted in ascending
* order based on the numeric ID.
*
* @return list of actions
*/
List<Bmv2ActionModel> actions();
/**
* Returns the table associated with the given numeric ID, null if there's no such an ID in the configuration.
*
* @param id integer value
* @return table object or null
*/
Bmv2TableModel table(int id);
/**
* Returns the table associated with the given name, null if there's no such a name in the configuration.
*
* @param name string value
* @return table object or null
*/
Bmv2TableModel table(String name);
/**
* Returns the list of all the tables defined by in this configuration. Values returned are sorted in ascending
* order based on the numeric ID.
*
* @return list of actions
*/
List<Bmv2TableModel> tables();
}
/*
* Copyright 2016-present 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.bmv2.api.context;
import com.google.common.annotations.Beta;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* A BMv2 device context, defined by a configuration and an interpreter.
*/
@Beta
public final class Bmv2DeviceContext {
private final Bmv2Configuration configuration;
private final Bmv2Interpreter interpreter;
/**
* Creates a new BMv2 device context.
*
* @param configuration a configuration
* @param interpreter an interpreter
*/
public Bmv2DeviceContext(Bmv2Configuration configuration, Bmv2Interpreter interpreter) {
this.configuration = checkNotNull(configuration, "configuration cannot be null");
this.interpreter = checkNotNull(interpreter, "interpreter cannot be null");
}
/**
* Returns the BMv2 configuration of this context.
*
* @return a configuration
*/
public Bmv2Configuration configuration() {
return configuration;
}
/**
* Returns the BMv2 interpreter of this context.
*
* @return an interpreter
*/
public Bmv2Interpreter interpreter() {
return interpreter;
}
@Override
public int hashCode() {
return Objects.hashCode(configuration, interpreter);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final Bmv2DeviceContext other = (Bmv2DeviceContext) obj;
return Objects.equal(this.configuration, other.configuration)
&& Objects.equal(this.interpreter, other.interpreter);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("configuration", configuration)
.add("interpreter", interpreter)
.toString();
}
}
......@@ -14,21 +14,23 @@
* limitations under the License.
*/
package org.onosproject.bmv2.api.model;
package org.onosproject.bmv2.api.context;
import com.google.common.annotations.Beta;
import com.google.common.base.Objects;
import static com.google.common.base.MoreObjects.toStringHelper;
/**
* Representation of a BMv2 model's header field instance.
* A BMv2 header field model.
*/
public final class Bmv2ModelField {
@Beta
public final class Bmv2FieldModel {
private final Bmv2ModelHeader header;
private final Bmv2ModelFieldType type;
private final Bmv2HeaderModel header;
private final Bmv2FieldTypeModel type;
protected Bmv2ModelField(Bmv2ModelHeader header, Bmv2ModelFieldType type) {
protected Bmv2FieldModel(Bmv2HeaderModel header, Bmv2FieldTypeModel type) {
this.header = header;
this.type = type;
}
......@@ -38,7 +40,7 @@ public final class Bmv2ModelField {
*
* @return a header instance
*/
public Bmv2ModelHeader header() {
public Bmv2HeaderModel header() {
return header;
}
......@@ -47,7 +49,7 @@ public final class Bmv2ModelField {
*
* @return a field type value
*/
public Bmv2ModelFieldType type() {
public Bmv2FieldTypeModel type() {
return type;
}
......@@ -64,7 +66,7 @@ public final class Bmv2ModelField {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final Bmv2ModelField other = (Bmv2ModelField) obj;
final Bmv2FieldModel other = (Bmv2FieldModel) obj;
return Objects.equal(this.header, other.header)
&& Objects.equal(this.type, other.type);
}
......
......@@ -14,21 +14,23 @@
* limitations under the License.
*/
package org.onosproject.bmv2.api.model;
package org.onosproject.bmv2.api.context;
import com.google.common.annotations.Beta;
import com.google.common.base.Objects;
import static com.google.common.base.MoreObjects.toStringHelper;
/**
* BMv2 model header type field.
* A BMv2 header type field model.
*/
public final class Bmv2ModelFieldType {
@Beta
public final class Bmv2FieldTypeModel {
private final String name;
private final int bitWidth;
protected Bmv2ModelFieldType(String name, int bitWidth) {
protected Bmv2FieldTypeModel(String name, int bitWidth) {
this.name = name;
this.bitWidth = bitWidth;
}
......@@ -64,7 +66,7 @@ public final class Bmv2ModelFieldType {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final Bmv2ModelFieldType other = (Bmv2ModelFieldType) obj;
final Bmv2FieldTypeModel other = (Bmv2FieldTypeModel) obj;
return Objects.equal(this.name, other.name)
&& Objects.equal(this.bitWidth, other.bitWidth);
}
......
/*
* Copyright 2016-present 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.bmv2.api.context;
import com.google.common.annotations.Beta;
import org.onosproject.bmv2.api.runtime.Bmv2TableEntry;
import org.onosproject.net.flow.FlowRule;
/**
* Translator of ONOS flow rules to BMv2 table entries.
*/
@Beta
public interface Bmv2FlowRuleTranslator {
/**
* Returns a BMv2 table entry equivalent to the given flow rule for the given context.
* <p>
* Translation is performed according to the following logic:
* <ul>
* <li> table name: obtained from the context interpreter {@link Bmv2Interpreter#tableIdMap() table ID map}.
* <li> match key: is built using both the context interpreter {@link Bmv2Interpreter#criterionTypeMap() criterion
* map} and all {@link org.onosproject.bmv2.api.runtime.Bmv2ExtensionSelector extension selectors} (if any).
* <li> action: is built using the context interpreter
* {@link Bmv2Interpreter#mapTreatment(org.onosproject.net.flow.TrafficTreatment, Bmv2Configuration)
* treatment mapping function} or the flow rule
* {@link org.onosproject.bmv2.api.runtime.Bmv2ExtensionTreatment} extension treatment} (if any).
* <li> timeout: if the table supports timeout, use the same as the flow rule, otherwise none (i.e. permanent
* entry).
* </ul>
*
* @param rule a flow rule
* @param context a context
* @return a BMv2 table entry
* @throws Bmv2FlowRuleTranslatorException if the flow rule cannot be translated
*/
Bmv2TableEntry translate(FlowRule rule, Bmv2DeviceContext context) throws Bmv2FlowRuleTranslatorException;
}
......@@ -14,41 +14,14 @@
* limitations under the License.
*/
package org.onosproject.bmv2.api.runtime;
import org.onlab.util.KryoNamespace;
import org.onosproject.net.flow.AbstractExtension;
import org.onosproject.net.flow.criteria.ExtensionSelector;
import org.onosproject.net.flow.criteria.ExtensionSelectorType;
package org.onosproject.bmv2.api.context;
/**
* Extension selector for Bmv2 used as a wrapper for a {@link Bmv2MatchKey}.
* BMv2 flow rule translator exception.
*/
public class Bmv2ExtensionSelector extends AbstractExtension implements ExtensionSelector {
private final KryoNamespace appKryo = new KryoNamespace.Builder().build();
private Bmv2MatchKey matchKey;
public Bmv2ExtensionSelector(Bmv2MatchKey matchKey) {
this.matchKey = matchKey;
}
public Bmv2MatchKey matchKey() {
return matchKey;
}
@Override
public ExtensionSelectorType type() {
return ExtensionSelectorType.ExtensionSelectorTypes.P4_BMV2_MATCH_KEY.type();
}
@Override
public byte[] serialize() {
return appKryo.serialize(matchKey);
}
public class Bmv2FlowRuleTranslatorException extends Exception {
@Override
public void deserialize(byte[] data) {
matchKey = appKryo.deserialize(data);
public Bmv2FlowRuleTranslatorException(String msg) {
super(msg);
}
}
......
......@@ -14,31 +14,33 @@
* limitations under the License.
*/
package org.onosproject.bmv2.api.model;
package org.onosproject.bmv2.api.context;
import com.google.common.annotations.Beta;
import com.google.common.base.Objects;
import static com.google.common.base.MoreObjects.toStringHelper;
/**
* Representation of a BMv2 model header instance.
* BMv2 header instance model.
*/
public final class Bmv2ModelHeader {
@Beta
public final class Bmv2HeaderModel {
private final String name;
private final int id;
private final Bmv2ModelHeaderType type;
private final Bmv2HeaderTypeModel type;
private final boolean isMetadata;
/**
* Creates a new header instance.
* Creates a new header instance model.
*
* @param name name
* @param id id
* @param type header type
* @param metadata if is metadata
*/
protected Bmv2ModelHeader(String name, int id, Bmv2ModelHeaderType type, boolean metadata) {
protected Bmv2HeaderModel(String name, int id, Bmv2HeaderTypeModel type, boolean metadata) {
this.name = name;
this.id = id;
this.type = type;
......@@ -68,7 +70,7 @@ public final class Bmv2ModelHeader {
*
* @return a header type value
*/
public Bmv2ModelHeaderType type() {
public Bmv2HeaderTypeModel type() {
return type;
}
......@@ -94,7 +96,7 @@ public final class Bmv2ModelHeader {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final Bmv2ModelHeader other = (Bmv2ModelHeader) obj;
final Bmv2HeaderModel other = (Bmv2HeaderModel) obj;
return Objects.equal(this.name, other.name)
&& Objects.equal(this.id, other.id)
&& Objects.equal(this.type, other.type)
......
......@@ -14,8 +14,9 @@
* limitations under the License.
*/
package org.onosproject.bmv2.api.model;
package org.onosproject.bmv2.api.context;
import com.google.common.annotations.Beta;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
......@@ -26,22 +27,23 @@ import java.util.List;
import static com.google.common.base.MoreObjects.toStringHelper;
/**
* BMv2 model header type.
* BMv2 header type model.
*/
public final class Bmv2ModelHeaderType {
@Beta
public final class Bmv2HeaderTypeModel {
private final String name;
private final int id;
private final LinkedHashMap<String, Bmv2ModelFieldType> fields = Maps.newLinkedHashMap();
private final LinkedHashMap<String, Bmv2FieldTypeModel> fields = Maps.newLinkedHashMap();
/**
* Creates a new header type instance.
* Creates a new header type model.
*
* @param name name
* @param id id
* @param fieldTypes fields
*/
protected Bmv2ModelHeaderType(String name, int id, List<Bmv2ModelFieldType> fieldTypes) {
protected Bmv2HeaderTypeModel(String name, int id, List<Bmv2FieldTypeModel> fieldTypes) {
this.name = name;
this.id = id;
fieldTypes.forEach(f -> this.fields.put(f.name(), f));
......@@ -72,7 +74,7 @@ public final class Bmv2ModelHeaderType {
* @param fieldName field name
* @return field or null
*/
public Bmv2ModelFieldType field(String fieldName) {
public Bmv2FieldTypeModel field(String fieldName) {
return fields.get(fieldName);
}
......@@ -83,7 +85,7 @@ public final class Bmv2ModelHeaderType {
*
* @return list of fields
*/
public List<Bmv2ModelFieldType> fields() {
public List<Bmv2FieldTypeModel> fields() {
return ImmutableList.copyOf(fields.values());
}
......@@ -100,7 +102,7 @@ public final class Bmv2ModelHeaderType {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final Bmv2ModelHeaderType other = (Bmv2ModelHeaderType) obj;
final Bmv2HeaderTypeModel other = (Bmv2HeaderTypeModel) obj;
return Objects.equal(this.name, other.name)
&& Objects.equal(this.id, other.id)
&& Objects.equal(this.fields, other.fields);
......
/*
* Copyright 2016-present 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.bmv2.api.context;
import com.google.common.annotations.Beta;
import com.google.common.collect.ImmutableBiMap;
import org.onosproject.bmv2.api.runtime.Bmv2Action;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.flow.criteria.Criterion;
/**
* A BMv2 configuration interpreter.
*/
@Beta
public interface Bmv2Interpreter {
/**
* Returns a bi-map describing a one-to-one relationship between ONOS flow rule table IDs and BMv2 table names.
*
* @return a {@link com.google.common.collect.BiMap} where the key is a ONOS flow rule table id and
* the value is a BMv2 table names
*/
ImmutableBiMap<Integer, String> tableIdMap();
/**
* Returns a bi-map describing a one-to-one relationship between ONOS criterion types and BMv2 header field names.
* Header field names are formatted using the notation {@code header_name.field_member_name}.
*
* @return a {@link com.google.common.collect.BiMap} where the keys are ONOS criterion types and the values are
* BMv2 header field names
*/
ImmutableBiMap<Criterion.Type, String> criterionTypeMap();
/**
* Return a BMv2 action that is functionally equivalent to the given ONOS traffic treatment for the given
* configuration.
*
* @param treatment a ONOS traffic treatment
* @param configuration a BMv2 configuration
* @return a BMv2 action object
* @throws Bmv2InterpreterException if the treatment cannot be mapped to any BMv2 action
*/
Bmv2Action mapTreatment(TrafficTreatment treatment, Bmv2Configuration configuration)
throws Bmv2InterpreterException;
}
......@@ -14,18 +14,14 @@
* limitations under the License.
*/
package org.onosproject.bmv2.api.runtime;
package org.onosproject.bmv2.api.context;
/**
* General exception of the Bmv2 runtime APIs.
* A BMv2 interpreter exception.
*/
public class Bmv2RuntimeException extends Exception {
public class Bmv2InterpreterException extends Exception {
public Bmv2RuntimeException(String message, Throwable cause) {
super(message, cause);
}
public Bmv2RuntimeException(String message) {
public Bmv2InterpreterException(String message) {
super(message);
}
}
......
......@@ -14,27 +14,30 @@
* limitations under the License.
*/
package org.onosproject.bmv2.api.model;
package org.onosproject.bmv2.api.context;
import com.google.common.annotations.Beta;
import java.util.Objects;
import static com.google.common.base.MoreObjects.toStringHelper;
/**
* BMv2 model action runtime data.
* A BMv2 action runtime data model.
*/
public final class Bmv2ModelRuntimeData {
@Beta
public final class Bmv2RuntimeDataModel {
private final String name;
private final int bitWidth;
/**
* Creates a new runtime data.
* Creates a new runtime data model.
*
* @param name name
* @param bitWidth bitwidth
*/
protected Bmv2ModelRuntimeData(String name, int bitWidth) {
protected Bmv2RuntimeDataModel(String name, int bitWidth) {
this.name = name;
this.bitWidth = bitWidth;
}
......@@ -70,7 +73,7 @@ public final class Bmv2ModelRuntimeData {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final Bmv2ModelRuntimeData other = (Bmv2ModelRuntimeData) obj;
final Bmv2RuntimeDataModel other = (Bmv2RuntimeDataModel) obj;
return Objects.equals(this.name, other.name)
&& Objects.equals(this.bitWidth, other.bitWidth);
}
......
......@@ -14,28 +14,30 @@
* limitations under the License.
*/
package org.onosproject.bmv2.api.model;
package org.onosproject.bmv2.api.context;
import com.google.common.annotations.Beta;
import com.google.common.base.Objects;
import org.onosproject.bmv2.api.runtime.Bmv2MatchParam;
import static com.google.common.base.MoreObjects.toStringHelper;
/**
* Representation of a table key.
* A BMv2 table key model.
*/
public final class Bmv2ModelTableKey {
@Beta
public final class Bmv2TableKeyModel {
private final Bmv2MatchParam.Type matchType;
private final Bmv2ModelField field;
private final Bmv2FieldModel field;
/**
* Creates a new table key.
* Creates a new table key model.
*
* @param matchType match type
* @param field field instance
*/
protected Bmv2ModelTableKey(Bmv2MatchParam.Type matchType, Bmv2ModelField field) {
protected Bmv2TableKeyModel(Bmv2MatchParam.Type matchType, Bmv2FieldModel field) {
this.matchType = matchType;
this.field = field;
}
......@@ -55,7 +57,7 @@ public final class Bmv2ModelTableKey {
*
* @return a header field value
*/
public Bmv2ModelField field() {
public Bmv2FieldModel field() {
return field;
}
......@@ -72,7 +74,7 @@ public final class Bmv2ModelTableKey {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final Bmv2ModelTableKey other = (Bmv2ModelTableKey) obj;
final Bmv2TableKeyModel other = (Bmv2TableKeyModel) obj;
return Objects.equal(this.matchType, other.matchType)
&& Objects.equal(this.field, other.field);
}
......
......@@ -14,8 +14,9 @@
* limitations under the License.
*/
package org.onosproject.bmv2.api.model;
package org.onosproject.bmv2.api.context;
import com.google.common.annotations.Beta;
import com.google.common.base.Objects;
import java.util.List;
......@@ -24,9 +25,10 @@ import java.util.Set;
import static com.google.common.base.MoreObjects.toStringHelper;
/**
* BMv2 model table representation.
* A BMv2 table model.
*/
public final class Bmv2ModelTable {
@Beta
public final class Bmv2TableModel {
private final String name;
private final int id;
......@@ -35,11 +37,11 @@ public final class Bmv2ModelTable {
private final int maxSize;
private final boolean hasCounters;
private final boolean hasTimeouts;
private final List<Bmv2ModelTableKey> keys;
private final Set<Bmv2ModelAction> actions;
private final List<Bmv2TableKeyModel> keys;
private final Set<Bmv2ActionModel> actions;
/**
* Creates a new table.
* Creates a new table model.
*
* @param name name
* @param id id
......@@ -51,9 +53,9 @@ public final class Bmv2ModelTable {
* @param keys list of match keys
* @param actions list of actions
*/
protected Bmv2ModelTable(String name, int id, String matchType, String type,
protected Bmv2TableModel(String name, int id, String matchType, String type,
int maxSize, boolean withCounters, boolean supportTimeout,
List<Bmv2ModelTableKey> keys, Set<Bmv2ModelAction> actions) {
List<Bmv2TableKeyModel> keys, Set<Bmv2ActionModel> actions) {
this.name = name;
this.id = id;
this.matchType = matchType;
......@@ -134,7 +136,7 @@ public final class Bmv2ModelTable {
*
* @return a list of match keys
*/
public List<Bmv2ModelTableKey> keys() {
public List<Bmv2TableKeyModel> keys() {
return keys;
}
......@@ -143,7 +145,7 @@ public final class Bmv2ModelTable {
*
* @return a list of actions
*/
public Set<Bmv2ModelAction> actions() {
public Set<Bmv2ActionModel> actions() {
return actions;
}
......@@ -161,7 +163,7 @@ public final class Bmv2ModelTable {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final Bmv2ModelTable other = (Bmv2ModelTable) obj;
final Bmv2TableModel other = (Bmv2TableModel) obj;
return Objects.equal(this.name, other.name)
&& Objects.equal(this.id, other.id)
&& Objects.equal(this.matchType, other.matchType)
......
......@@ -15,6 +15,6 @@
*/
/**
* BMv2 configuration model classes.
* BMv2 device context API.
*/
package org.onosproject.bmv2.api.model;
\ No newline at end of file
package org.onosproject.bmv2.api.context;
\ No newline at end of file
......
......@@ -15,11 +15,6 @@
*/
/**
* Bmv2 API abstractions.
* <p>
* Bmv2 APIs are divided in two sub-packages, runtime and model.
* Runtime APIs are used to represent operations that can be performed at runtime
* on a Bmv2 device, while model APIs are used to describe the Bmv2 packet
* processing model.
* BMv2 protocol API.
*/
package org.onosproject.bmv2.api;
\ No newline at end of file
......
......@@ -28,7 +28,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
* Bmv2 action representation.
* An action of a BMv2 match-action table entry.
*/
public final class Bmv2Action {
......@@ -94,7 +94,7 @@ public final class Bmv2Action {
}
/**
* A Bmv2 action builder.
* A BMv2 action builder.
*/
public static final class Builder {
......@@ -128,9 +128,9 @@ public final class Bmv2Action {
}
/**
* Builds a Bmv2 action object.
* Builds a BMv2 action object.
*
* @return a Bmv2 action
* @return a BMv2 action
*/
public Bmv2Action build() {
checkState(name != null, "action name not set");
......
......@@ -21,6 +21,8 @@ import org.onosproject.net.DeviceId;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.google.common.base.Preconditions.checkNotNull;
......@@ -29,20 +31,25 @@ import static com.google.common.base.Preconditions.checkNotNull;
*/
public final class Bmv2Device {
public static final String N_A = "n/a";
public static final String SCHEME = "bmv2";
public static final String PROTOCOL = "bmv2-thrift";
public static final String MANUFACTURER = "p4.org";
public static final String HW_VERSION = "bmv2";
public static final String SW_VERSION = N_A;
public static final String SERIAL_NUMBER = N_A;
private final String thriftServerHost;
private final int thriftServerPort;
private final int internalDeviceId;
/**
* Creates a new Bmv2 device object.
* Creates a new BMv2 device object.
*
* @param thriftServerHost the host of the Thrift runtime server running inside the device
* @param thriftServerPort the port of the Thrift runtime server running inside the device
* @param internalDeviceId the internal device id
* @param thriftServerHost the hostname / IP address of the Thrift runtime server running on the device
* @param thriftServerPort the port of the Thrift runtime server running on the device
* @param internalDeviceId the internal device ID number
*/
public Bmv2Device(String thriftServerHost, int thriftServerPort, int internalDeviceId) {
this.thriftServerHost = checkNotNull(thriftServerHost, "host cannot be null");
......@@ -51,7 +58,17 @@ public final class Bmv2Device {
}
/**
* Returns the hostname (or IP address) of the Thrift runtime server running inside the device.
* Returns a Bmv2Device representing the given deviceId.
*
* @param deviceId a deviceId
* @return
*/
public static Bmv2Device of(DeviceId deviceId) {
return DeviceIdParser.parse(checkNotNull(deviceId, "deviceId cannot be null"));
}
/**
* Returns the hostname (or IP address) of the Thrift runtime server running on the device.
*
* @return a string value
*/
......@@ -60,7 +77,7 @@ public final class Bmv2Device {
}
/**
* Returns the port of the Thrift runtime server running inside the device.
* Returns the port of the Thrift runtime server running on the device.
*
* @return an integer value
*/
......@@ -86,7 +103,8 @@ public final class Bmv2Device {
public DeviceId asDeviceId() {
try {
// TODO: include internalDeviceId number in the deviceId URI
return DeviceId.deviceId(new URI(SCHEME, this.thriftServerHost + ":" + this.thriftServerPort, null));
return DeviceId.deviceId(new URI(SCHEME, this.thriftServerHost + ":" + this.thriftServerPort,
String.valueOf(this.internalDeviceId)));
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Unable to build deviceID for device " + this.toString(), e);
}
......@@ -113,6 +131,23 @@ public final class Bmv2Device {
@Override
public String toString() {
return thriftServerHost + ":" + thriftServerPort + "/" + internalDeviceId;
return asDeviceId().toString();
}
private static class DeviceIdParser {
private static final Pattern REGEX = Pattern.compile(SCHEME + ":(.+):(\\d+)#(\\d+)");
public static Bmv2Device parse(DeviceId deviceId) {
Matcher matcher = REGEX.matcher(deviceId.toString());
if (matcher.find()) {
String host = matcher.group(1);
int port = Integer.valueOf(matcher.group(2));
int internalDeviceId = Integer.valueOf(matcher.group(3));
return new Bmv2Device(host, port, internalDeviceId);
} else {
throw new RuntimeException("Unable to parse bmv2 device id string: " + deviceId.toString());
}
}
}
}
......
......@@ -18,14 +18,29 @@ package org.onosproject.bmv2.api.runtime;
import org.apache.commons.lang3.tuple.Pair;
import org.onlab.util.ImmutableByteSequence;
import org.onosproject.net.DeviceId;
import java.util.Collection;
import java.util.List;
/**
* RPC client to control a BMv2 device.
* An agent to control a BMv2 device.
*/
public interface Bmv2Client {
public interface Bmv2DeviceAgent {
/**
* Returns the device ID of this agent.
*
* @return a device id
*/
DeviceId deviceId();
/**
* Pings the device, returns true if the device is reachable, false otherwise.
*
* @return true if reachable, false otherwise
*/
boolean ping();
/**
* Adds a new table entry.
*
......@@ -36,16 +51,14 @@ public interface Bmv2Client {
long addTableEntry(Bmv2TableEntry entry) throws Bmv2RuntimeException;
/**
* Modifies a currently installed entry by updating its action.
* Modifies an existing table entry by updating its action.
*
* @param tableName string value of table name
* @param entryId long value of entry ID
* @param action an action value
* @throws Bmv2RuntimeException if any error occurs
*/
void modifyTableEntry(String tableName,
long entryId, Bmv2Action action)
throws Bmv2RuntimeException;
void modifyTableEntry(String tableName, long entryId, Bmv2Action action) throws Bmv2RuntimeException;
/**
* Deletes currently installed entry.
......@@ -54,8 +67,7 @@ public interface Bmv2Client {
* @param entryId long value of entry ID
* @throws Bmv2RuntimeException if any error occurs
*/
void deleteTableEntry(String tableName,
long entryId) throws Bmv2RuntimeException;
void deleteTableEntry(String tableName, long entryId) throws Bmv2RuntimeException;
/**
* Sets table default action.
......@@ -64,11 +76,10 @@ public interface Bmv2Client {
* @param action an action value
* @throws Bmv2RuntimeException if any error occurs
*/
void setTableDefaultAction(String tableName, Bmv2Action action)
throws Bmv2RuntimeException;
void setTableDefaultAction(String tableName, Bmv2Action action) throws Bmv2RuntimeException;
/**
* Returns information of the ports currently configured in the switch.
* Returns information on the ports currently configured in the switch.
*
* @return collection of port information
* @throws Bmv2RuntimeException if any error occurs
......@@ -76,7 +87,7 @@ public interface Bmv2Client {
Collection<Bmv2PortInfo> getPortsInfo() throws Bmv2RuntimeException;
/**
* Return a string representation of a table content.
* Return a string representation of the given table content.
*
* @param tableName string value of table name
* @return table string dump
......@@ -85,24 +96,6 @@ public interface Bmv2Client {
String dumpTable(String tableName) throws Bmv2RuntimeException;
/**
* Returns a list of ids for the entries installed in the given table.
*
* @param tableName string value of table name
* @return a list of entry ids
* @throws Bmv2RuntimeException if any error occurs
*/
List<Long> getInstalledEntryIds(String tableName) throws Bmv2RuntimeException;
/**
* Removes all entries installed in the given table.
*
* @param tableName string value of table name
* @return the number of entries removed
* @throws Bmv2RuntimeException if any error occurs
*/
int cleanupTable(String tableName) throws Bmv2RuntimeException;
/**
* Requests the device to transmit a given byte sequence over the given port.
*
* @param portNumber a port number
......@@ -112,14 +105,14 @@ public interface Bmv2Client {
void transmitPacket(int portNumber, ImmutableByteSequence packet) throws Bmv2RuntimeException;
/**
* Reset the state of the switch (e.g. delete all entries, etc.).
* Resets the state of the switch (e.g. delete all entries, etc.).
*
* @throws Bmv2RuntimeException if any error occurs
*/
void resetState() throws Bmv2RuntimeException;
/**
* Returns the JSON-formatted model configuration currently used to process packets.
* Returns the JSON configuration currently used to process packets.
*
* @return a JSON-formatted string value
* @throws Bmv2RuntimeException if any error occurs
......@@ -127,7 +120,7 @@ public interface Bmv2Client {
String dumpJsonConfig() throws Bmv2RuntimeException;
/**
* Returns the md5 hash of the JSON-formatted model configuration currently used to process packets.
* Returns the md5 sum of the JSON-formatted model configuration currently used to process packets.
*
* @return a string value
* @throws Bmv2RuntimeException if any error occurs
......@@ -143,4 +136,39 @@ public interface Bmv2Client {
* @throws Bmv2RuntimeException if any error occurs
*/
Pair<Long, Long> readTableEntryCounter(String tableName, long entryId) throws Bmv2RuntimeException;
/**
* Returns the counter values for a given counter and index.
*
* @param counterName a counter name
* @param index an integer value
* @return a pair of long values, where the left value is the number of bytes and the right value is the number of
* packets
* @throws Bmv2RuntimeException if any error occurs
*/
Pair<Long, Long> readCounter(String counterName, int index) throws Bmv2RuntimeException;
/**
* Returns the ID of the current BMv2 process instance (used to distinguish between different executions of the
* same BMv2 device).
*
* @return an integer value
* @throws Bmv2RuntimeException if any error occurs
*/
int getProcessInstanceId() throws Bmv2RuntimeException;
/**
* Uploads a new JSON configuration on the device.
*
* @param jsonString a string value
* @throws Bmv2RuntimeException if any error occurs
*/
void loadNewJsonConfig(String jsonString) throws Bmv2RuntimeException;
/**
* Triggers a configuration swap on the device.
*
* @throws Bmv2RuntimeException
*/
void swapJsonConfig() throws Bmv2RuntimeException;
}
......
......@@ -23,9 +23,9 @@ import org.onlab.util.ImmutableByteSequence;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Representation of a Bmv2 exact match parameter.
* Representation of a BMv2 exact match parameter.
*/
public class Bmv2ExactMatchParam implements Bmv2MatchParam {
public final class Bmv2ExactMatchParam implements Bmv2MatchParam {
private final ImmutableByteSequence value;
......
/*
* Copyright 2016-present 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.bmv2.api.runtime;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import org.onlab.util.KryoNamespace;
import org.onosproject.net.flow.AbstractExtension;
import org.onosproject.net.flow.criteria.ExtensionSelector;
import org.onosproject.net.flow.criteria.ExtensionSelectorType;
import java.util.HashMap;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Extension selector for BMv2 used as a wrapper for multiple BMv2 match parameters.
*/
public final class Bmv2ExtensionSelector extends AbstractExtension implements ExtensionSelector {
private final KryoNamespace appKryo = new KryoNamespace.Builder()
.register(HashMap.class)
.register(Bmv2MatchParam.class)
.register(Bmv2ExactMatchParam.class)
.register(Bmv2TernaryMatchParam.class)
.register(Bmv2LpmMatchParam.class)
.register(Bmv2ValidMatchParam.class)
.build();
private Map<String, Bmv2MatchParam> parameterMap;
/**
* Creates a new BMv2 extension selector for the given match parameters map, where the keys are expected to be field
* names formatted as headerName.fieldMemberName (e.g. ethernet.dstAddr).
*
* @param paramMap a map
*/
public Bmv2ExtensionSelector(Map<String, Bmv2MatchParam> paramMap) {
this.parameterMap = checkNotNull(paramMap, "param map cannot be null");
}
/**
* Returns the match parameters map of this selector.
*
* @return a match parameter map
*/
public Map<String, Bmv2MatchParam> parameterMap() {
return parameterMap;
}
@Override
public ExtensionSelectorType type() {
return ExtensionSelectorType.ExtensionSelectorTypes.BMV2_MATCH_PARAMS.type();
}
@Override
public byte[] serialize() {
return appKryo.serialize(parameterMap);
}
@Override
public void deserialize(byte[] data) {
this.parameterMap = appKryo.deserialize(data);
}
@Override
public int hashCode() {
return Objects.hashCode(parameterMap);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final Bmv2ExtensionSelector other = (Bmv2ExtensionSelector) obj;
return Objects.equal(this.parameterMap, other.parameterMap);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("parameterMap", parameterMap)
.toString();
}
}
......@@ -16,15 +16,19 @@
package org.onosproject.bmv2.api.runtime;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import org.onlab.util.KryoNamespace;
import org.onosproject.net.flow.AbstractExtension;
import org.onosproject.net.flow.instructions.ExtensionTreatment;
import org.onosproject.net.flow.instructions.ExtensionTreatmentType;
import static org.onosproject.net.flow.instructions.ExtensionTreatmentType.ExtensionTreatmentTypes.BMV2_ACTION;
/**
* Extension treatment for Bmv2 used as a wrapper for a {@link Bmv2Action}.
* Extension treatment for BMv2 used as a wrapper for a {@link Bmv2Action}.
*/
public class Bmv2ExtensionTreatment extends AbstractExtension implements ExtensionTreatment {
public final class Bmv2ExtensionTreatment extends AbstractExtension implements ExtensionTreatment {
private final KryoNamespace appKryo = new KryoNamespace.Builder().build();
private Bmv2Action action;
......@@ -39,7 +43,7 @@ public class Bmv2ExtensionTreatment extends AbstractExtension implements Extensi
@Override
public ExtensionTreatmentType type() {
return ExtensionTreatmentType.ExtensionTreatmentTypes.P4_BMV2_ACTION.type();
return BMV2_ACTION.type();
}
@Override
......@@ -51,4 +55,28 @@ public class Bmv2ExtensionTreatment extends AbstractExtension implements Extensi
public void deserialize(byte[] data) {
action = appKryo.deserialize(data);
}
@Override
public int hashCode() {
return Objects.hashCode(action);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final Bmv2ExtensionTreatment other = (Bmv2ExtensionTreatment) obj;
return Objects.equal(this.action, other.action);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("action", action)
.toString();
}
}
......
/*
* Copyright 2016-present 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.bmv2.api.runtime;
import com.google.common.base.Objects;
import org.onosproject.net.flow.FlowRule;
import java.util.Date;
/**
* A wrapper class for a ONOS flow rule installed on a BMv2 device.
*/
public class Bmv2FlowRuleWrapper {
private final FlowRule rule;
private final long entryId;
private final Date creationDate;
/**
* Creates a new flow rule wrapper.
*
* @param rule a flow rule
* @param entryId a BMv2 table entry ID
* @param creationDate the creation date of the flow rule
*/
public Bmv2FlowRuleWrapper(FlowRule rule, long entryId, Date creationDate) {
this.rule = rule;
this.entryId = entryId;
this.creationDate = new Date();
}
/**
* Returns the flow rule contained by this wrapper.
*
* @return a flow rule
*/
public FlowRule rule() {
return rule;
}
/**
* Return the seconds since when this flow rule was installed on the device.
*
* @return an integer value
*/
public long lifeInSeconds() {
return (new Date().getTime() - creationDate.getTime()) / 1000;
}
/**
* Returns the creation date of this flow rule.
*
* @return a date
*/
public Date creationDate() {
return creationDate;
}
/**
* Returns the BMv2 entry ID of this flow rule.
*
* @return a long value
*/
public long entryId() {
return entryId;
}
@Override
public int hashCode() {
return Objects.hashCode(rule, entryId, creationDate);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final Bmv2FlowRuleWrapper other = (Bmv2FlowRuleWrapper) obj;
return Objects.equal(this.rule, other.rule)
&& Objects.equal(this.entryId, other.entryId)
&& Objects.equal(this.creationDate, other.creationDate);
}
@Override
public String toString() {
return creationDate + "-" + rule.hashCode();
}
}
......@@ -24,9 +24,9 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Representation of a Bmv2 longest prefix match (LPM) parameter.
* Representation of a BMv2 longest prefix match (LPM) parameter.
*/
public class Bmv2LpmMatchParam implements Bmv2MatchParam {
public final class Bmv2LpmMatchParam implements Bmv2MatchParam {
private final ImmutableByteSequence value;
private final int prefixLength;
......
......@@ -28,7 +28,7 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Bmv2 match key representation.
* A match key of a BMv2 match-action table entry.
*/
public final class Bmv2MatchKey {
......@@ -39,13 +39,17 @@ public final class Bmv2MatchKey {
this.matchParams = matchParams;
}
/**
* Returns a new match key builder.
*
* @return a match key builder
*/
public static Builder builder() {
return new Builder();
}
/**
* Returns an immutable view of the ordered list of match parameters of this
* match key.
* Returns the list of match parameters of this match key.
*
* @return list match parameters
*/
......@@ -79,7 +83,7 @@ public final class Bmv2MatchKey {
}
/**
* Builder of a Bmv2 match key.
* Builder of a BMv2 match key.
*/
public static final class Builder {
......@@ -89,6 +93,12 @@ public final class Bmv2MatchKey {
this.matchParams = Lists.newArrayList();
}
/**
* Adds a match parameter to the match key.
*
* @param param a match parameter
* @return this
*/
public Builder add(Bmv2MatchParam param) {
this.matchParams.add(checkNotNull(param));
return this;
......
......@@ -17,7 +17,7 @@
package org.onosproject.bmv2.api.runtime;
/**
* Representation of a Bmv2 match parameter.
* Representation of a BMv2 match parameter.
*/
public interface Bmv2MatchParam {
......@@ -29,7 +29,7 @@ public interface Bmv2MatchParam {
Type type();
/**
* Bmv2 match types.
* BMv2 match types.
*/
enum Type {
/**
......
/*
* Copyright 2016-present 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.bmv2.api.runtime;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
/**
* Representation of a table entry obtained by parsing a BMv2 table dump.
*/
public final class Bmv2ParsedTableEntry {
private final long entryId;
private final Bmv2MatchKey matchKey;
private final Bmv2Action action;
/**
* Creates a new parsed table entry.
*
* @param entryId an entry ID
* @param matchKey a match key
* @param action an action
*/
public Bmv2ParsedTableEntry(long entryId, Bmv2MatchKey matchKey, Bmv2Action action) {
this.entryId = entryId;
this.matchKey = matchKey;
this.action = action;
}
/**
* Returns the entry ID.
*
* @return a long value
*/
public long entryId() {
return entryId;
}
/**
* Returns the match key.
*
* @return a match key object
*/
public Bmv2MatchKey matchKey() {
return matchKey;
}
/**
* Returns the action.
*
* @return an action object
*/
public Bmv2Action action() {
return action;
}
@Override
public int hashCode() {
return Objects.hashCode(entryId, matchKey, action);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final Bmv2ParsedTableEntry other = (Bmv2ParsedTableEntry) obj;
return Objects.equal(this.entryId, other.entryId)
&& Objects.equal(this.matchKey, other.matchKey)
&& Objects.equal(this.action, other.action);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("entryId", entryId)
.add("matchKey", matchKey)
.add("action", action)
.toString();
}
}
/*
* Copyright 2016-present 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.bmv2.api.runtime;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
/**
* Information of a port of a BMv2 device.
*/
public final class Bmv2PortInfo {
private final String ifaceName;
private final int number;
private final boolean isUp;
/**
* Creates a new port description.
*
* @param ifaceName the common name of the network interface
* @param number a port number
* @param isUp interface status
*/
public Bmv2PortInfo(String ifaceName, int number, boolean isUp) {
this.ifaceName = ifaceName;
this.number = number;
this.isUp = isUp;
}
/**
* Returns the common name the network interface used by this port.
*
* @return a string value
*/
public String ifaceName() {
return ifaceName;
}
/**
* Returns the number of this port.
*
* @return an integer value
*/
public int number() {
return number;
}
/**
* Returns true if the port is up, false otherwise.
*
* @return a boolean value
*/
public boolean isUp() {
return isUp;
}
@Override
public int hashCode() {
return Objects.hashCode(ifaceName, number, isUp);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final Bmv2PortInfo other = (Bmv2PortInfo) obj;
return Objects.equal(this.ifaceName, other.ifaceName)
&& Objects.equal(this.number, other.number)
&& Objects.equal(this.isUp, other.isUp);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("ifaceName", ifaceName)
.add("number", number)
.add("isUp", isUp)
.toString();
}
}
/*
* Copyright 2016-present 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.bmv2.api.runtime;
/**
* General exception of the BMv2 runtime APIs.
*/
public final class Bmv2RuntimeException extends Exception {
private final Code code;
private String codeString;
public Bmv2RuntimeException(String message) {
super(message);
this.code = Code.OTHER;
this.codeString = message;
}
public Bmv2RuntimeException(Throwable cause) {
super(cause);
this.code = Code.OTHER;
this.codeString = cause.toString();
}
public Bmv2RuntimeException(Code code) {
super(code.name());
this.code = code;
}
public Code getCode() {
return this.code;
}
public String explain() {
return (codeString == null) ? code.name() : code.name() + " " + codeString;
}
@Override
public String toString() {
return getClass().getSimpleName() + " " + explain();
}
public enum Code {
TABLE_FULL,
TABLE_INVALID_HANDLE,
TABLE_EXPIRED_HANDLE,
TABLE_COUNTERS_DISABLED,
TABLE_METERS_DISABLED,
TABLE_AGEING_DISABLED,
TABLE_INVALID_TABLE_NAME,
TABLE_INVALID_ACTION_NAME,
TABLE_WRONG_TABLE_TYPE,
TABLE_INVALID_MBR_HANDLE,
TABLE_MBR_STILL_USED,
TABLE_MBR_ALREADY_IN_GRP,
TABLE_MBR_NOT_IN_GRP,
TABLE_INVALID_GRP_HANDLE,
TABLE_GRP_STILL_USED,
TABLE_EMPTY_GRP,
TABLE_DUPLICATE_ENTRY,
TABLE_BAD_MATCH_KEY,
TABLE_INVALID_METER_OPERATION,
TABLE_DEFAULT_ACTION_IS_CONST,
TABLE_DEFAULT_ENTRY_IS_CONST,
TABLE_GENERAL_ERROR,
TABLE_UNKNOWN_ERROR,
DEV_MGR_ERROR_GENERAL,
DEV_MGR_UNKNOWN,
COUNTER_INVALID_NAME,
COUNTER_INVALID_INDEX,
COUNTER_ERROR_GENERAL,
COUNTER_ERROR_UNKNOWN,
SWAP_CONFIG_DISABLED,
SWAP_ONGOING,
SWAP_NO_ONGOING,
SWAP_ERROR_UKNOWN,
// TODO: add other codes based on autogenerated Thrift APIs
OTHER
}
}
......@@ -22,7 +22,7 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Bmv2 representation of a table entry.
* An entry of a match-action table in a BMv2 device.
*/
public final class Bmv2TableEntry {
......@@ -45,7 +45,7 @@ public final class Bmv2TableEntry {
}
/**
* Returns a new Bmv2 table entry builder.
* Returns a new BMv2 table entry builder.
*
* @return a new builder.
*/
......@@ -63,7 +63,7 @@ public final class Bmv2TableEntry {
}
/**
* Returns the match key.
* Returns the match key of this table entry.
*
* @return match key
*/
......@@ -72,7 +72,7 @@ public final class Bmv2TableEntry {
}
/**
* Returns the action.
* Returns the action of this table entry.
*
* @return action
*/
......@@ -81,7 +81,7 @@ public final class Bmv2TableEntry {
}
/**
* Returns true is the entry has a valid priority value set.
* Returns true is the entry has a valid priority.
*
* @return true if priority is set, false elsewhere
*/
......@@ -90,7 +90,7 @@ public final class Bmv2TableEntry {
}
/**
* Return the entry priority.
* Return the priority of this table entry.
*
* @return priority
*/
......@@ -99,7 +99,7 @@ public final class Bmv2TableEntry {
}
/**
* Returns true is the entry has a valid timeout value set.
* Returns true is this table entry has a valid timeout.
*
* @return true if timeout is set, false elsewhere
*/
......@@ -108,9 +108,9 @@ public final class Bmv2TableEntry {
}
/**
* Returns the entry timeout in fractional seconds.
* Returns the timeout (in fractional seconds) of this table entry.
*
* @return timeout
* @return a timeout vale (in fractional seconds)
*/
public final double timeout() {
return timeout;
......
/*
* Copyright 2016-present 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.bmv2.api.runtime;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import org.onosproject.net.DeviceId;
/**
* A reference to a table entry installed on a BMv2 device.
*/
public final class Bmv2TableEntryReference {
private final DeviceId deviceId;
private final String tableName;
private final Bmv2MatchKey matchKey;
/**
* Creates a new table entry reference.
*
* @param deviceId a device ID
* @param tableName a table name
* @param matchKey a match key
*/
public Bmv2TableEntryReference(DeviceId deviceId, String tableName, Bmv2MatchKey matchKey) {
this.deviceId = deviceId;
this.tableName = tableName;
this.matchKey = matchKey;
}
/**
* Returns the device ID of this table entry reference.
*
* @return a device ID
*/
public DeviceId deviceId() {
return deviceId;
}
/**
* Returns the name of the table of this table entry reference.
*
* @return a table name
*/
public String tableName() {
return tableName;
}
/**
* Returns the match key of this table entry reference.
*
* @return a match key
*/
public Bmv2MatchKey matchKey() {
return matchKey;
}
@Override
public int hashCode() {
return Objects.hashCode(deviceId, tableName, matchKey);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final Bmv2TableEntryReference other = (Bmv2TableEntryReference) obj;
return Objects.equal(this.deviceId, other.deviceId)
&& Objects.equal(this.tableName, other.tableName)
&& Objects.equal(this.matchKey, other.matchKey);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("deviceId", deviceId)
.add("tableName", tableName)
.add("matchKey", matchKey)
.toString();
}
}
......@@ -24,9 +24,9 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
* Representation of a Bmv2 ternary match parameter.
* Representation of a BMv2 ternary match parameter.
*/
public class Bmv2TernaryMatchParam implements Bmv2MatchParam {
public final class Bmv2TernaryMatchParam implements Bmv2MatchParam {
private final ImmutableByteSequence value;
private final ImmutableByteSequence mask;
......
......@@ -22,9 +22,9 @@ import com.google.common.base.MoreObjects;
import java.util.Objects;
/**
* Representation of a Bmv2 valid match parameter.
* Representation of a BMv2 valid match parameter.
*/
public class Bmv2ValidMatchParam implements Bmv2MatchParam {
public final class Bmv2ValidMatchParam implements Bmv2MatchParam {
private final boolean flag;
......
......@@ -15,6 +15,6 @@
*/
/**
* Bmv2 runtime APIs.
* BMv2 runtime API.
*/
package org.onosproject.bmv2.api.runtime;
\ No newline at end of file
......
......@@ -14,70 +14,64 @@
* limitations under the License.
*/
package org.onosproject.bmv2.api.runtime;
package org.onosproject.bmv2.api.service;
import org.onlab.util.ImmutableByteSequence;
import org.onosproject.bmv2.api.runtime.Bmv2DeviceAgent;
import org.onosproject.bmv2.api.runtime.Bmv2RuntimeException;
import org.onosproject.net.DeviceId;
/**
* A server that listens for requests from a BMv2 device.
* A controller of BMv2 devices.
*/
public interface Bmv2ControlPlaneServer {
public interface Bmv2Controller {
/**
* Default listening port.
* Default port.
*/
int DEFAULT_PORT = 40123;
/**
* Register the given hello listener, to be called each time a hello message is received from a BMv2 device.
* Return an agent to operate on the given device.
*
* @param listener a hello listener
* @param deviceId a device ID
* @return a BMv2 agent
* @throws Bmv2RuntimeException if the agent is not available
*/
void addHelloListener(HelloListener listener);
Bmv2DeviceAgent getAgent(DeviceId deviceId) throws Bmv2RuntimeException;
/**
* Unregister the given hello listener.
* Returns true if the given device is reachable from this controller, false otherwise.
*
* @param listener a hello listener
* @param deviceId a device ID
* @return a boolean value
*/
void removeHelloListener(HelloListener listener);
boolean isReacheable(DeviceId deviceId);
/**
* Register the given packet listener, to be called each time a packet-in message is received from a BMv2 device.
* Register the given device listener.
*
* @param listener a device listener
*/
void addDeviceListener(Bmv2DeviceListener listener);
/**
* Unregister the given device listener.
*
* @param listener a device listener
*/
void removeDeviceListener(Bmv2DeviceListener listener);
/**
* Register the given packet listener.
*
* @param listener a packet listener
*/
void addPacketListener(PacketListener listener);
void addPacketListener(Bmv2PacketListener listener);
/**
* Unregister the given packet listener.
*
* @param listener a packet listener
*/
void removePacketListener(PacketListener listener);
interface HelloListener {
/**
* Handles a hello message.
*
* @param device the BMv2 device that originated the message
*/
void handleHello(Bmv2Device device);
}
interface PacketListener {
/**
* Handles a packet-in message.
*
* @param device the BMv2 device that originated the message
* @param inputPort the device port where the packet was received
* @param reason a reason code
* @param tableId the table id that originated this packet-in
* @param contextId the context id where the packet-in was originated
* @param packet the packet body
*/
void handlePacketIn(Bmv2Device device, int inputPort, long reason, int tableId, int contextId,
ImmutableByteSequence packet);
}
}
\ No newline at end of file
void removePacketListener(Bmv2PacketListener listener);
}
......
/*
* Copyright 2016-present 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.bmv2.api.service;
import org.onosproject.bmv2.api.context.Bmv2DeviceContext;
import org.onosproject.bmv2.api.context.Bmv2Interpreter;
import org.onosproject.net.DeviceId;
/**
* A service for managing BMv2 device contexts.
*/
public interface Bmv2DeviceContextService {
// TODO: handle the potential configuration states (e.g. RUNNING, SWAP_REQUESTED, etc.)
/**
* Returns the context of a given device. The context returned is the last one for which a configuration swap was
* triggered, hence there's no guarantees that the device is enforcing the returned context's configuration at the
* time of the call.
*
* @param deviceId a device ID
* @return a BMv2 device context
*/
Bmv2DeviceContext getContext(DeviceId deviceId);
/**
* Triggers a configuration swap on a given device.
*
* @param deviceId a device ID
* @param context a BMv2 device context
*/
void triggerConfigurationSwap(DeviceId deviceId, Bmv2DeviceContext context);
/**
* Binds the given interpreter with the given class loader so that other ONOS instances in the cluster can properly
* load the interpreter.
*
* @param interpreterClass an interpreter class
* @param loader a class loader
*/
void registerInterpreterClassLoader(Class<? extends Bmv2Interpreter> interpreterClass, ClassLoader loader);
/**
* Notifies this service that a given device has been updated, meaning a potential context change.
* It returns true if the device configuration is the same as the last for which a swap was triggered, false
* otherwise. In the last case, the service will asynchronously trigger a swap to the last
* configuration stored by this service. If no swap has already been triggered then a default configuration will be
* applied.
*
* @param deviceId a device ID
* @return a boolean value
*/
boolean notifyDeviceChange(DeviceId deviceId);
}
/*
* Copyright 2016-present 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.bmv2.api.service;
import org.onosproject.bmv2.api.runtime.Bmv2Device;
/**
* A listener of BMv2 device events.
*/
public interface Bmv2DeviceListener {
/**
* Handles a hello message.
*
* @param device the BMv2 device that originated the message
* @param instanceId the ID of the BMv2 process instance
* @param jsonConfigMd5 the MD5 sum of the JSON configuration currently running on the device
*/
void handleHello(Bmv2Device device, int instanceId, String jsonConfigMd5);
}
/*
* Copyright 2016-present 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.bmv2.api.service;
import org.onlab.util.ImmutableByteSequence;
import org.onosproject.bmv2.api.runtime.Bmv2Device;
/**
* A listener of BMv2 packet events.
*/
public interface Bmv2PacketListener {
/**
* Handles a packet-in message.
*
* @param device the BMv2 device that originated the message
* @param inputPort the device port where the packet was received
* @param reason a reason code
* @param tableId the ID of table that originated this packet-in
* @param contextId the ID of the BMv2 context where the packet-in was originated
* @param packet the packet raw data
*/
void handlePacketIn(Bmv2Device device, int inputPort, long reason, int tableId, int contextId,
ImmutableByteSequence packet);
}
/*
* Copyright 2016-present 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.bmv2.api.service;
import org.onosproject.bmv2.api.context.Bmv2FlowRuleTranslator;
import org.onosproject.bmv2.api.runtime.Bmv2FlowRuleWrapper;
import org.onosproject.bmv2.api.runtime.Bmv2ParsedTableEntry;
import org.onosproject.bmv2.api.runtime.Bmv2TableEntryReference;
import org.onosproject.net.DeviceId;
import java.util.List;
/**
* A service for managing BMv2 table entries.
*/
public interface Bmv2TableEntryService {
/**
* Returns a flow rule translator.
*
* @return a flow rule translator
*/
Bmv2FlowRuleTranslator getFlowRuleTranslator();
/**
* Returns a list of table entries installed in the given device and table. The table entries returned are the
* result of a table dump parse.
*
* @param deviceId a device id
* @param tableName a table name
* @return a list of parsed table entries
*/
List<Bmv2ParsedTableEntry> getTableEntries(DeviceId deviceId, String tableName);
/**
* Binds the given ONOS flow rule with a BMv2 table entry reference.
*
* @param entryRef a table entry reference
* @param rule a BMv2 flow rule wrapper
*/
void bindEntryReference(Bmv2TableEntryReference entryRef, Bmv2FlowRuleWrapper rule);
/**
* Returns the ONOS flow rule associated with the given BMv2 table entry reference, or null if there's no such a
* mapping.
*
* @param entryRef a table entry reference
* @return a BMv2 flow rule wrapper
*/
Bmv2FlowRuleWrapper lookupEntryReference(Bmv2TableEntryReference entryRef);
/**
* Removes any flow rule previously bound with a given BMv2 table entry reference.
*
* @param entryRef a table entry reference
*/
void unbindEntryReference(Bmv2TableEntryReference entryRef);
}
/*
* Copyright 2016-present 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.
*/
/**
* BMv2 service API.
*/
package org.onosproject.bmv2.api.service;
\ No newline at end of file
/*
* Copyright 2016-present 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.bmv2.api.utils;
import org.onlab.util.HexString;
import org.onlab.util.ImmutableByteSequence;
import java.util.Arrays;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Collection of util methods to deal with flow rule translation.
*/
public final class Bmv2TranslatorUtils {
private Bmv2TranslatorUtils() {
// Ban constructor.
}
/**
* Returns the number of bytes necessary to contain the given bit-width.
*
* @param bitWidth an integer value
* @return an integer value
*/
public static int roundToBytes(int bitWidth) {
return (int) Math.ceil((double) bitWidth / 8);
}
/**
* Trims or expands the given byte sequence so to fit a given bit-width.
*
* @param original a byte sequence
* @param bitWidth an integer value
* @return a new byte sequence
* @throws ByteSequenceFitException if the byte sequence cannot be fitted in the given bit-width
*/
public static ImmutableByteSequence fitByteSequence(ImmutableByteSequence original, int bitWidth)
throws ByteSequenceFitException {
checkNotNull(original, "byte sequence cannot be null");
checkArgument(bitWidth > 0, "byte width must a non-zero positive integer");
int newByteWidth = roundToBytes(bitWidth);
if (original.size() == newByteWidth) {
// nothing to do
return original;
}
byte[] originalBytes = original.asArray();
if (newByteWidth > original.size()) {
// pad missing bytes with zeros
return ImmutableByteSequence.copyFrom(Arrays.copyOf(originalBytes, newByteWidth));
}
byte[] newBytes = new byte[newByteWidth];
// ImmutableByteSequence is always big-endian, hence check the array in reverse order
int diff = originalBytes.length - newByteWidth;
for (int i = originalBytes.length - 1; i > 0; i--) {
byte ob = originalBytes[i]; // original byte
byte nb; // new byte
if (i > diff) {
// no need to truncate, copy as is
nb = ob;
} else if (i == diff) {
// truncate this byte, check if we're loosing something
byte mask = (byte) ((1 >> ((bitWidth % 8) + 1)) - 1);
if ((ob & ~mask) != 0) {
throw new ByteSequenceFitException(originalBytes, bitWidth);
} else {
nb = (byte) (ob & mask);
}
} else {
// drop this byte, check if we're loosing something
if (originalBytes[i] != 0) {
throw new ByteSequenceFitException(originalBytes, bitWidth);
} else {
continue;
}
}
newBytes[i - diff] = nb;
}
return ImmutableByteSequence.copyFrom(newBytes);
}
/**
* A byte sequence fit exception.
*/
public static class ByteSequenceFitException extends Exception {
public ByteSequenceFitException(byte[] bytes, int bitWidth) {
super("cannot fit " + HexString.toHexString(bytes) + " into a " + bitWidth + " bits value");
}
}
}
......@@ -14,45 +14,7 @@
* limitations under the License.
*/
package org.onosproject.bmv2.api.runtime;
import com.google.common.base.MoreObjects;
import org.p4.bmv2.thrift.DevMgrPortInfo;
import java.util.Collections;
import java.util.Map;
/**
* Bmv2 representation of a switch port information.
* BMv2 utils.
*/
public final class Bmv2PortInfo {
private final DevMgrPortInfo portInfo;
public Bmv2PortInfo(DevMgrPortInfo portInfo) {
this.portInfo = portInfo;
}
public final String ifaceName() {
return portInfo.getIface_name();
}
public final int portNumber() {
return portInfo.getPort_num();
}
public final boolean isUp() {
return portInfo.isIs_up();
}
public final Map<String, String> getExtraProperties() {
return Collections.unmodifiableMap(portInfo.getExtra());
}
@Override
public final String toString() {
return MoreObjects.toStringHelper(this)
.addValue(portInfo)
.toString();
}
}
package org.onosproject.bmv2.api.utils;
\ No newline at end of file
......
......@@ -14,11 +14,12 @@
* limitations under the License.
*/
package org.onosproject.bmv2.api.model;
package org.onosproject.bmv2.api.context;
import com.eclipsesource.json.Json;
import com.eclipsesource.json.JsonObject;
import com.google.common.testing.EqualsTester;
import org.hamcrest.collection.IsIterableContainingInOrder;
import org.junit.Before;
import org.junit.Test;
import org.onosproject.bmv2.api.runtime.Bmv2MatchParam;
......@@ -30,13 +31,12 @@ import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.hamcrest.core.IsEqual.equalTo;
/**
* BMv2 model parser test suite.
* BMv2 JSON configuration parser test.
*/
public class Bmv2ModelTest {
public class Bmv2ConfigurationTest {
private JsonObject json;
private JsonObject json2;
......@@ -44,28 +44,28 @@ public class Bmv2ModelTest {
@Before
public void setUp() throws Exception {
json = Json.parse(new BufferedReader(new InputStreamReader(
this.getClass().getResourceAsStream("/simple_pipeline.json")))).asObject();
this.getClass().getResourceAsStream("/simple.json")))).asObject();
json2 = Json.parse(new BufferedReader(new InputStreamReader(
this.getClass().getResourceAsStream("/simple_pipeline.json")))).asObject();
this.getClass().getResourceAsStream("/simple.json")))).asObject();
}
@Test
public void testParse() throws Exception {
Bmv2Model model = Bmv2Model.parse(json);
Bmv2Model model2 = Bmv2Model.parse(json2);
Bmv2Configuration config = Bmv2DefaultConfiguration.parse(json);
Bmv2Configuration config2 = Bmv2DefaultConfiguration.parse(json2);
new EqualsTester()
.addEqualityGroup(model, model2)
.addEqualityGroup(config, config2)
.testEquals();
/* Check header types */
Bmv2ModelHeaderType stdMetaT = model.headerType("standard_metadata_t");
Bmv2ModelHeaderType ethernetT = model.headerType("ethernet_t");
Bmv2ModelHeaderType intrinsicMetaT = model.headerType("intrinsic_metadata_t");
Bmv2HeaderTypeModel stdMetaT = config.headerType("standard_metadata_t");
Bmv2HeaderTypeModel ethernetT = config.headerType("ethernet_t");
Bmv2HeaderTypeModel intrinsicMetaT = config.headerType("intrinsic_metadata_t");
Bmv2ModelHeaderType stdMetaT2 = model2.headerType("standard_metadata_t");
Bmv2ModelHeaderType ethernetT2 = model2.headerType("ethernet_t");
Bmv2ModelHeaderType intrinsicMetaT2 = model2.headerType("intrinsic_metadata_t");
Bmv2HeaderTypeModel stdMetaT2 = config2.headerType("standard_metadata_t");
Bmv2HeaderTypeModel ethernetT2 = config2.headerType("ethernet_t");
Bmv2HeaderTypeModel intrinsicMetaT2 = config2.headerType("intrinsic_metadata_t");
new EqualsTester()
.addEqualityGroup(stdMetaT, stdMetaT2)
......@@ -88,7 +88,7 @@ public class Bmv2ModelTest {
// check that fields are in order
assertThat("Incorrect order for header type fields",
stdMetaT.fields(), contains(
stdMetaT.fields(), IsIterableContainingInOrder.contains(
stdMetaT.field("ingress_port"),
stdMetaT.field("packet_length"),
stdMetaT.field("egress_spec"),
......@@ -99,13 +99,13 @@ public class Bmv2ModelTest {
stdMetaT.field("_padding")));
/* Check actions */
Bmv2ModelAction floodAction = model.action("flood");
Bmv2ModelAction dropAction = model.action("_drop");
Bmv2ModelAction fwdAction = model.action("fwd");
Bmv2ActionModel floodAction = config.action("flood");
Bmv2ActionModel dropAction = config.action("_drop");
Bmv2ActionModel fwdAction = config.action("set_egress_port");
Bmv2ModelAction floodAction2 = model2.action("flood");
Bmv2ModelAction dropAction2 = model2.action("_drop");
Bmv2ModelAction fwdAction2 = model2.action("fwd");
Bmv2ActionModel floodAction2 = config2.action("flood");
Bmv2ActionModel dropAction2 = config2.action("_drop");
Bmv2ActionModel fwdAction2 = config2.action("set_egress_port");
new EqualsTester()
.addEqualityGroup(floodAction, floodAction2)
......@@ -133,8 +133,8 @@ public class Bmv2ModelTest {
fwdAction.runtimeData("port").bitWidth(), is(equalTo(9)));
/* Check tables */
Bmv2ModelTable table0 = model.table(0);
Bmv2ModelTable table02 = model2.table(0);
Bmv2TableModel table0 = config.table(0);
Bmv2TableModel table02 = config2.table(0);
new EqualsTester()
.addEqualityGroup(table0, table02)
......
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2016-present 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>onos-bmv2-protocol</artifactId>
<groupId>org.onosproject</groupId>
<version>1.6.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>onos-bmv2-protocol-ctl</artifactId>
<packaging>bundle</packaging>
<dependencies>
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.9.3</version>
</dependency>
<dependency>
<groupId>org.onosproject</groupId>
<artifactId>onos-bmv2-protocol-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.onosproject</groupId>
<artifactId>onos-bmv2-protocol-thrift-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.apache.felix.scr.annotations</artifactId>
</dependency>
<dependency>
<groupId>org.onosproject</groupId>
<artifactId>onos-core-serializers</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.onosproject</groupId>
<artifactId>onos-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
/*
* Copyright 2016-present 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.bmv2.ctl;
import com.google.common.collect.ImmutableBiMap;
import org.onlab.util.ImmutableByteSequence;
import org.onosproject.bmv2.api.context.Bmv2Configuration;
import org.onosproject.bmv2.api.context.Bmv2Interpreter;
import org.onosproject.bmv2.api.context.Bmv2InterpreterException;
import org.onosproject.bmv2.api.runtime.Bmv2Action;
import org.onosproject.bmv2.api.utils.Bmv2TranslatorUtils;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.flow.criteria.Criterion;
import org.onosproject.net.flow.instructions.Instruction;
import static org.onosproject.net.PortNumber.CONTROLLER;
import static org.onosproject.net.flow.instructions.Instructions.OutputInstruction;
/**
* Implementation of a BMv2 interpreter for the BMv2 default.json configuration.
*/
public final class Bmv2DefaultInterpreterImpl implements Bmv2Interpreter {
public static final String TABLE0 = "table0";
public static final String SEND_TO_CPU = "send_to_cpu";
public static final String DROP = "_drop";
public static final String SET_EGRESS_PORT = "set_egress_port";
// Lazily populate field map.
private static final ImmutableBiMap<Criterion.Type, String> CRITERION_MAP = ImmutableBiMap.of(
Criterion.Type.IN_PORT, "standard_metadata.ingress_port",
Criterion.Type.ETH_DST, "ethernet.dstAddr",
Criterion.Type.ETH_SRC, "ethernet.srcAddr",
Criterion.Type.ETH_TYPE, "ethernet.etherType");
private static final ImmutableBiMap<Integer, String> TABLE_MAP = ImmutableBiMap.of(
0, TABLE0);
@Override
public ImmutableBiMap<Criterion.Type, String> criterionTypeMap() {
return CRITERION_MAP;
}
@Override
public ImmutableBiMap<Integer, String> tableIdMap() {
return TABLE_MAP;
}
@Override
public Bmv2Action mapTreatment(TrafficTreatment treatment, Bmv2Configuration configuration)
throws Bmv2InterpreterException {
if (treatment.allInstructions().size() == 0) {
// No instructions means drop for us.
return Bmv2Action.builder().withName(DROP).build();
} else if (treatment.allInstructions().size() > 1) {
// Otherwise, we understand treatments with only 1 instruction.
throw new Bmv2InterpreterException("Treatment has multiple instructions");
}
Instruction instruction = treatment.allInstructions().get(0);
switch (instruction.type()) {
case OUTPUT:
OutputInstruction outInstruction = (OutputInstruction) instruction;
if (outInstruction.port() == CONTROLLER) {
return Bmv2Action.builder().withName(SEND_TO_CPU).build();
} else {
return buildEgressAction(outInstruction, configuration);
}
case NOACTION:
return Bmv2Action.builder().withName(DROP).build();
default:
throw new Bmv2InterpreterException("Instruction type not supported: " + instruction.type().name());
}
}
/**
* Builds an egress action equivalent to the given output instruction for the given configuration.
*
* @param instruction an output instruction
* @param configuration a configuration
* @return a BMv2 action
* @throws Bmv2InterpreterException if the instruction cannot be translated to a BMv2 action
*/
private Bmv2Action buildEgressAction(OutputInstruction instruction, Bmv2Configuration configuration)
throws Bmv2InterpreterException {
Bmv2Action.Builder actionBuilder = Bmv2Action.builder();
actionBuilder.withName(SET_EGRESS_PORT);
if (instruction.port().isLogical()) {
throw new Bmv2InterpreterException("Output on logic port not supported: " + instruction);
}
// Get the byte sequence for the out port with the right length
long portNumber = instruction.port().toLong();
int bitWidth = configuration.action(SET_EGRESS_PORT).runtimeData("port").bitWidth();
try {
ImmutableByteSequence outPort = Bmv2TranslatorUtils.fitByteSequence(
ImmutableByteSequence.copyFrom(portNumber), bitWidth);
return Bmv2Action.builder().withName(SET_EGRESS_PORT).addParameter(outPort).build();
} catch (Bmv2TranslatorUtils.ByteSequenceFitException e) {
throw new Bmv2InterpreterException(e.getMessage());
}
}
}
/*
* Copyright 2016-present 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.bmv2.ctl;
import com.eclipsesource.json.Json;
import com.eclipsesource.json.JsonObject;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.google.common.collect.Maps;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
import org.onlab.util.KryoNamespace;
import org.onlab.util.SharedExecutors;
import org.onosproject.bmv2.api.context.Bmv2Configuration;
import org.onosproject.bmv2.api.context.Bmv2DefaultConfiguration;
import org.onosproject.bmv2.api.context.Bmv2DeviceContext;
import org.onosproject.bmv2.api.context.Bmv2Interpreter;
import org.onosproject.bmv2.api.runtime.Bmv2DeviceAgent;
import org.onosproject.bmv2.api.runtime.Bmv2RuntimeException;
import org.onosproject.bmv2.api.service.Bmv2Controller;
import org.onosproject.bmv2.api.service.Bmv2DeviceContextService;
import org.onosproject.net.DeviceId;
import org.onosproject.store.serializers.KryoNamespaces;
import org.onosproject.store.service.ConsistentMap;
import org.onosproject.store.service.Serializer;
import org.onosproject.store.service.StorageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import static com.google.common.base.Preconditions.checkNotNull;
@Component(immediate = true)
@Service
public class Bmv2DeviceContextServiceImpl implements Bmv2DeviceContextService {
private static final String JSON_DEFAULT_CONFIG_PATH = "/default.json";
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
private StorageService storageService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
private Bmv2Controller controller;
private final ExecutorService executorService = SharedExecutors.getPoolThreadExecutor();
private ConsistentMap<DeviceId, Bmv2DeviceContext> contexts;
private Map<DeviceId, Bmv2DeviceContext> contextsMap;
private Map<String, ClassLoader> interpreterClassLoaders;
private Bmv2DeviceContext defaultContext;
private final Logger log = LoggerFactory.getLogger(getClass());
@Activate
public void activate() {
KryoNamespace kryo = new KryoNamespace.Builder()
.register(KryoNamespaces.API)
.register(new BmvDeviceContextSerializer(), Bmv2DeviceContext.class)
.build();
this.contexts = storageService.<DeviceId, Bmv2DeviceContext>consistentMapBuilder()
.withSerializer(Serializer.using(kryo))
.withName("onos-bmv2-contexts")
.build();
contextsMap = contexts.asJavaMap();
interpreterClassLoaders = Maps.newConcurrentMap();
Bmv2Configuration defaultConfiguration = loadDefaultConfiguration();
Bmv2Interpreter defaultInterpreter = new Bmv2DefaultInterpreterImpl();
defaultContext = new Bmv2DeviceContext(defaultConfiguration, defaultInterpreter);
interpreterClassLoaders.put(defaultInterpreter.getClass().getName(), this.getClass().getClassLoader());
log.info("Started");
}
@Deactivate
public void deactivate() {
log.info("Stopped");
}
@Override
public Bmv2DeviceContext getContext(DeviceId deviceId) {
checkNotNull(deviceId, "device id cannot be null");
return contextsMap.get(deviceId);
}
@Override
public void triggerConfigurationSwap(DeviceId deviceId, Bmv2DeviceContext context) {
checkNotNull(deviceId, "device id cannot be null");
checkNotNull(context, "context cannot be null");
if (!interpreterClassLoaders.containsKey(context.interpreter().getClass().getName())) {
log.error("Unable to trigger configuration swap, missing class loader for context interpreter. " +
"Please register it with registerInterpreterClassLoader()");
} else {
executorService.execute(() -> executeConfigurationSwap(deviceId, context));
}
}
@Override
public void registerInterpreterClassLoader(Class<? extends Bmv2Interpreter> interpreterClass, ClassLoader loader) {
interpreterClassLoaders.put(interpreterClass.getName(), loader);
}
private void executeConfigurationSwap(DeviceId deviceId, Bmv2DeviceContext context) {
contexts.compute(deviceId, (key, existingValue) -> {
if (context.equals(existingValue)) {
log.info("Dropping swap request as one has already been triggered for the given context.");
return existingValue;
}
try {
Bmv2DeviceAgent agent = controller.getAgent(deviceId);
String jsonString = context.configuration().json().toString();
agent.loadNewJsonConfig(jsonString);
agent.swapJsonConfig();
return context;
} catch (Bmv2RuntimeException e) {
log.error("Unable to swap configuration on {}: {}", deviceId, e.explain());
return existingValue;
}
});
}
@Override
public boolean notifyDeviceChange(DeviceId deviceId) {
checkNotNull(deviceId, "device id cannot be null");
Bmv2DeviceContext storedContext = getContext(deviceId);
if (storedContext == null) {
log.info("No context previously stored for {}, swapping to DEFAULT_CONTEXT.", deviceId);
triggerConfigurationSwap(deviceId, defaultContext);
// Device can be accepted.
return false;
} else {
Bmv2Configuration deviceConfiguration = loadDeviceConfiguration(deviceId);
if (deviceConfiguration == null) {
log.warn("Unable to load configuration from device {}", deviceId);
return false;
}
if (storedContext.configuration().equals(deviceConfiguration)) {
return true;
} else {
log.info("Device context is different from the stored one, triggering configuration swap for {}...",
deviceId);
triggerConfigurationSwap(deviceId, storedContext);
return false;
}
}
}
/**
* Load and parse a BMv2 JSON configuration from the given device.
*
* @param deviceId a device id
* @return a BMv2 configuration
*/
private Bmv2Configuration loadDeviceConfiguration(DeviceId deviceId) {
try {
String jsonString = controller.getAgent(deviceId).dumpJsonConfig();
return Bmv2DefaultConfiguration.parse(Json.parse(jsonString).asObject());
} catch (Bmv2RuntimeException e) {
log.warn("Unable to load JSON configuration from {}: {}", deviceId, e.explain());
return null;
}
}
/**
* Loads default configuration from file.
*
* @return a BMv2 configuration
*/
protected static Bmv2DefaultConfiguration loadDefaultConfiguration() {
try {
JsonObject json = Json.parse(new BufferedReader(new InputStreamReader(
Bmv2DeviceContextServiceImpl.class.getResourceAsStream(JSON_DEFAULT_CONFIG_PATH)))).asObject();
return Bmv2DefaultConfiguration.parse(json);
} catch (IOException e) {
throw new RuntimeException("Unable to load default configuration", e);
}
}
/**
* Internal BMv2 context serializer.
*/
private class BmvDeviceContextSerializer extends com.esotericsoftware.kryo.Serializer<Bmv2DeviceContext> {
@Override
public void write(Kryo kryo, Output output, Bmv2DeviceContext context) {
kryo.writeObject(output, context.configuration().json().toString());
kryo.writeObject(output, context.interpreter().getClass().getName());
}
@Override
public Bmv2DeviceContext read(Kryo kryo, Input input, Class<Bmv2DeviceContext> type) {
String jsonStr = kryo.readObject(input, String.class);
String interpreterClassName = kryo.readObject(input, String.class);
Bmv2Configuration configuration = Bmv2DefaultConfiguration.parse(Json.parse(jsonStr).asObject());
ClassLoader loader = interpreterClassLoaders.get(interpreterClassName);
if (loader == null) {
throw new IllegalStateException("No class loader registered for interpreter: " + interpreterClassName);
}
try {
Bmv2Interpreter interpreter = (Bmv2Interpreter) loader.loadClass(interpreterClassName).newInstance();
return new Bmv2DeviceContext(configuration, interpreter);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
throw new RuntimeException("Unable to load interpreter class", e);
}
}
}
}
/*
* Copyright 2016-present 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.bmv2.ctl;
import org.apache.thrift.TException;
import org.onosproject.bmv2.api.runtime.Bmv2RuntimeException;
import org.onosproject.bmv2.thriftapi.InvalidCounterOperation;
import org.onosproject.bmv2.thriftapi.InvalidDevMgrOperation;
import org.onosproject.bmv2.thriftapi.InvalidLearnOperation;
import org.onosproject.bmv2.thriftapi.InvalidMcOperation;
import org.onosproject.bmv2.thriftapi.InvalidMeterOperation;
import org.onosproject.bmv2.thriftapi.InvalidRegisterOperation;
import org.onosproject.bmv2.thriftapi.InvalidSwapOperation;
import org.onosproject.bmv2.thriftapi.InvalidTableOperation;
import static org.onosproject.bmv2.api.runtime.Bmv2RuntimeException.Code;
/**
* Utility class to translate a Thrift exception into a Bmv2RuntimeException.
*/
final class Bmv2TExceptionParser {
private Bmv2TExceptionParser() {
// ban constructor.
}
static Bmv2RuntimeException parseTException(TException cause) {
try {
return new Bmv2RuntimeException(getCode(cause));
} catch (ParserException e) {
return new Bmv2RuntimeException(e.codeString);
}
}
private static Code getCode(TException e) throws ParserException {
if (e instanceof InvalidTableOperation) {
InvalidTableOperation t = (InvalidTableOperation) e;
switch (t.getCode()) {
case TABLE_FULL:
return Code.TABLE_FULL;
case INVALID_HANDLE:
return Code.TABLE_INVALID_HANDLE;
case EXPIRED_HANDLE:
return Code.TABLE_EXPIRED_HANDLE;
case COUNTERS_DISABLED:
return Code.TABLE_COUNTERS_DISABLED;
case METERS_DISABLED:
return Code.TABLE_METERS_DISABLED;
case AGEING_DISABLED:
return Code.TABLE_AGEING_DISABLED;
case INVALID_TABLE_NAME:
return Code.TABLE_INVALID_TABLE_NAME;
case INVALID_ACTION_NAME:
return Code.TABLE_INVALID_ACTION_NAME;
case WRONG_TABLE_TYPE:
return Code.TABLE_WRONG_TABLE_TYPE;
case INVALID_MBR_HANDLE:
return Code.TABLE_INVALID_MBR_HANDLE;
case MBR_STILL_USED:
return Code.TABLE_MBR_STILL_USED;
case MBR_ALREADY_IN_GRP:
return Code.TABLE_MBR_ALREADY_IN_GRP;
case MBR_NOT_IN_GRP:
return Code.TABLE_MBR_NOT_IN_GRP;
case INVALID_GRP_HANDLE:
return Code.TABLE_INVALID_GRP_HANDLE;
case GRP_STILL_USED:
return Code.TABLE_GRP_STILL_USED;
case EMPTY_GRP:
return Code.TABLE_EMPTY_GRP;
case DUPLICATE_ENTRY:
return Code.TABLE_DUPLICATE_ENTRY;
case BAD_MATCH_KEY:
return Code.TABLE_BAD_MATCH_KEY;
case INVALID_METER_OPERATION:
return Code.TABLE_INVALID_METER_OPERATION;
case DEFAULT_ACTION_IS_CONST:
return Code.TABLE_DEFAULT_ACTION_IS_CONST;
case DEFAULT_ENTRY_IS_CONST:
return Code.TABLE_DEFAULT_ENTRY_IS_CONST;
case ERROR:
return Code.TABLE_GENERAL_ERROR;
default:
return Code.TABLE_UNKNOWN_ERROR;
}
} else if (e instanceof InvalidCounterOperation) {
InvalidCounterOperation t = (InvalidCounterOperation) e;
switch (t.getCode()) {
case INVALID_COUNTER_NAME:
return Code.COUNTER_INVALID_NAME;
case INVALID_INDEX:
return Code.COUNTER_INVALID_INDEX;
case ERROR:
return Code.COUNTER_ERROR_GENERAL;
default:
return Code.COUNTER_ERROR_UNKNOWN;
}
} else if (e instanceof InvalidDevMgrOperation) {
InvalidDevMgrOperation t = (InvalidDevMgrOperation) e;
switch (t.getCode()) {
case ERROR:
return Code.DEV_MGR_ERROR_GENERAL;
default:
return Code.DEV_MGR_UNKNOWN;
}
} else if (e instanceof InvalidSwapOperation) {
InvalidSwapOperation t = (InvalidSwapOperation) e;
switch (t.getCode()) {
case CONFIG_SWAP_DISABLED:
return Code.SWAP_CONFIG_DISABLED;
case ONGOING_SWAP:
return Code.SWAP_ONGOING;
case NO_ONGOING_SWAP:
return Code.SWAP_NO_ONGOING;
default:
return Code.SWAP_ERROR_UKNOWN;
}
} else if (e instanceof InvalidMeterOperation) {
// TODO
throw new ParserException(e.toString());
} else if (e instanceof InvalidRegisterOperation) {
// TODO
throw new ParserException(e.toString());
} else if (e instanceof InvalidLearnOperation) {
// TODO
throw new ParserException(e.toString());
} else if (e instanceof InvalidMcOperation) {
// TODO
throw new ParserException(e.toString());
} else {
throw new ParserException(e.toString());
}
}
private static class ParserException extends Exception {
private String codeString;
public ParserException(String codeString) {
this.codeString = codeString;
}
}
}
/*
* Copyright 2016-present 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.bmv2.ctl;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
import org.onlab.util.KryoNamespace;
import org.onosproject.bmv2.api.context.Bmv2DeviceContext;
import org.onosproject.bmv2.api.context.Bmv2FlowRuleTranslator;
import org.onosproject.bmv2.api.service.Bmv2DeviceContextService;
import org.onosproject.bmv2.api.service.Bmv2Controller;
import org.onosproject.bmv2.api.runtime.Bmv2DeviceAgent;
import org.onosproject.bmv2.api.runtime.Bmv2ExactMatchParam;
import org.onosproject.bmv2.api.runtime.Bmv2FlowRuleWrapper;
import org.onosproject.bmv2.api.runtime.Bmv2LpmMatchParam;
import org.onosproject.bmv2.api.runtime.Bmv2MatchKey;
import org.onosproject.bmv2.api.runtime.Bmv2ParsedTableEntry;
import org.onosproject.bmv2.api.runtime.Bmv2RuntimeException;
import org.onosproject.bmv2.api.runtime.Bmv2TableEntryReference;
import org.onosproject.bmv2.api.service.Bmv2TableEntryService;
import org.onosproject.bmv2.api.runtime.Bmv2TernaryMatchParam;
import org.onosproject.bmv2.api.runtime.Bmv2ValidMatchParam;
import org.onosproject.net.DeviceId;
import org.onosproject.store.serializers.KryoNamespaces;
import org.onosproject.store.service.EventuallyConsistentMap;
import org.onosproject.store.service.StorageService;
import org.onosproject.store.service.WallClockTimestamp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Implementation of the Bmv2TableEntryService.
*/
@Component(immediate = true)
@Service
public class Bmv2TableEntryServiceImpl implements Bmv2TableEntryService {
private final Logger log = LoggerFactory.getLogger(this.getClass());
private final Bmv2FlowRuleTranslator translator = new Bmv2FlowRuleTranslatorImpl();
private EventuallyConsistentMap<Bmv2TableEntryReference, Bmv2FlowRuleWrapper> flowRules;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected StorageService storageService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected Bmv2Controller controller;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected Bmv2DeviceContextService contextService;
@Activate
public void activate() {
KryoNamespace kryo = new KryoNamespace.Builder()
.register(KryoNamespaces.API)
.register(Bmv2TableEntryReference.class)
.register(Bmv2MatchKey.class)
.register(Bmv2ExactMatchParam.class)
.register(Bmv2TernaryMatchParam.class)
.register(Bmv2LpmMatchParam.class)
.register(Bmv2ValidMatchParam.class)
.register(Bmv2FlowRuleWrapper.class)
.build();
flowRules = storageService.<Bmv2TableEntryReference, Bmv2FlowRuleWrapper>eventuallyConsistentMapBuilder()
.withSerializer(kryo)
.withTimestampProvider((k, v) -> new WallClockTimestamp())
.withName("onos-bmv2-flowrules")
.build();
log.info("Started");
}
@Deactivate
public void deactivate() {
log.info("Stopped");
}
@Override
public Bmv2FlowRuleTranslator getFlowRuleTranslator() {
return translator;
}
@Override
public List<Bmv2ParsedTableEntry> getTableEntries(DeviceId deviceId, String tableName) {
try {
Bmv2DeviceContext context = contextService.getContext(deviceId);
if (context == null) {
log.warn("Unable to get table entries, found null context for {}", deviceId);
return Collections.emptyList();
}
Bmv2DeviceAgent agent = controller.getAgent(deviceId);
String tableDump = agent.dumpTable(tableName);
return Bmv2TableDumpParser.parse(tableDump, context.configuration());
} catch (Bmv2RuntimeException e) {
log.warn("Unable to get table entries for {}: {}", deviceId, e.explain());
return Collections.emptyList();
}
}
@Override
public Bmv2FlowRuleWrapper lookupEntryReference(Bmv2TableEntryReference entryRef) {
checkNotNull(entryRef, "table entry reference cannot be null");
return flowRules.get(entryRef);
}
@Override
public void bindEntryReference(Bmv2TableEntryReference entryRef, Bmv2FlowRuleWrapper rule) {
checkNotNull(entryRef, "table entry reference cannot be null");
checkNotNull(rule, "bmv2 flow rule cannot be null");
flowRules.put(entryRef, rule);
}
@Override
public void unbindEntryReference(Bmv2TableEntryReference entryRef) {
checkNotNull(entryRef, "table entry reference cannot be null");
flowRules.remove(entryRef);
}
}
......@@ -218,8 +218,8 @@ public final class SafeThriftClient {
// Thrift transport layer is not thread-safe (it's a wrapper on a socket), hence we need locking.
synchronized (transport) {
LOG.debug("Invoking client method... > method={}, fromThread={}",
method.getName(), Thread.currentThread().getId());
LOG.debug("Invoking method... > fromThread={}, method={}, args={}",
Thread.currentThread().getId(), method.getName(), args);
try {
......@@ -235,15 +235,13 @@ public final class SafeThriftClient {
// If here, transport has been successfully open, hence new exceptions will be thrown.
return method.invoke(baseClient, args);
} catch (InvocationTargetException e1) {
LOG.debug("Exception while invoking client method: {} > method={}, fromThread={}",
e1, method.getName(), Thread.currentThread().getId());
LOG.debug("Exception: {}", e1.getTargetException());
throw e1.getTargetException();
}
}
}
// Target exception is neither a TTransportException nor a restartable cause.
LOG.debug("Exception while invoking client method: {} > method={}, fromThread={}",
e, method.getName(), Thread.currentThread().getId());
LOG.debug("Exception: {}", e.getTargetException());
throw e.getTargetException();
}
}
......
/*
* Copyright 2014-2016 Open Networking Laboratory
* Copyright 2016-present 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.
......
This diff is collapsed. Click to expand it.
/*
* Copyright 2016-present 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.bmv2.ctl;
import com.google.common.testing.EqualsTester;
import org.junit.Test;
import org.onlab.packet.MacAddress;
import org.onosproject.bmv2.api.context.Bmv2Configuration;
import org.onosproject.bmv2.api.context.Bmv2DeviceContext;
import org.onosproject.bmv2.api.context.Bmv2FlowRuleTranslator;
import org.onosproject.bmv2.api.context.Bmv2Interpreter;
import org.onosproject.bmv2.api.runtime.Bmv2TableEntry;
import org.onosproject.bmv2.api.runtime.Bmv2TernaryMatchParam;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.DefaultApplicationId;
import org.onosproject.net.DeviceId;
import org.onosproject.net.PortNumber;
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.TrafficSelector;
import org.onosproject.net.flow.TrafficTreatment;
import java.util.Random;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.onosproject.bmv2.ctl.Bmv2DefaultInterpreterImpl.TABLE0;
/**
* Tests for {@link Bmv2FlowRuleTranslatorImpl}.
*/
public class Bmv2FlowRuleTranslatorImplTest {
private Random random = new Random();
private Bmv2Configuration configuration = Bmv2DeviceContextServiceImpl.loadDefaultConfiguration();
private Bmv2Interpreter interpreter = new Bmv2DefaultInterpreterImpl();
private Bmv2DeviceContext context = new Bmv2DeviceContext(configuration, interpreter);
private Bmv2FlowRuleTranslator translator = new Bmv2FlowRuleTranslatorImpl();
@Test
public void testTranslate() throws Exception {
DeviceId deviceId = DeviceId.NONE;
ApplicationId appId = new DefaultApplicationId(1, "test");
int tableId = 0;
MacAddress ethDstMac = MacAddress.valueOf(random.nextLong());
MacAddress ethSrcMac = MacAddress.valueOf(random.nextLong());
short ethType = (short) (0x0000FFFF & random.nextInt());
short outPort = (short) random.nextInt(65);
short inPort = (short) random.nextInt(65);
int timeout = random.nextInt(100);
int priority = random.nextInt(100);
TrafficSelector matchInPort1 = DefaultTrafficSelector
.builder()
.matchInPort(PortNumber.portNumber(inPort))
.matchEthDst(ethDstMac)
.matchEthSrc(ethSrcMac)
.matchEthType(ethType)
.build();
TrafficTreatment outPort2 = DefaultTrafficTreatment
.builder()
.setOutput(PortNumber.portNumber(outPort))
.build();
FlowRule rule1 = DefaultFlowRule.builder()
.forDevice(deviceId)
.forTable(tableId)
.fromApp(appId)
.withSelector(matchInPort1)
.withTreatment(outPort2)
.makeTemporary(timeout)
.withPriority(priority)
.build();
FlowRule rule2 = DefaultFlowRule.builder()
.forDevice(deviceId)
.forTable(tableId)
.fromApp(appId)
.withSelector(matchInPort1)
.withTreatment(outPort2)
.makeTemporary(timeout)
.withPriority(priority)
.build();
Bmv2TableEntry entry1 = translator.translate(rule1, context);
Bmv2TableEntry entry2 = translator.translate(rule1, context);
// check equality, i.e. same rules must produce same entries
new EqualsTester()
.addEqualityGroup(rule1, rule2)
.addEqualityGroup(entry1, entry2)
.testEquals();
int numMatchParams = configuration.table(TABLE0).keys().size();
// parse values stored in entry1
Bmv2TernaryMatchParam inPortParam = (Bmv2TernaryMatchParam) entry1.matchKey().matchParams().get(0);
Bmv2TernaryMatchParam ethDstParam = (Bmv2TernaryMatchParam) entry1.matchKey().matchParams().get(1);
Bmv2TernaryMatchParam ethSrcParam = (Bmv2TernaryMatchParam) entry1.matchKey().matchParams().get(2);
Bmv2TernaryMatchParam ethTypeParam = (Bmv2TernaryMatchParam) entry1.matchKey().matchParams().get(3);
double expectedTimeout = (double) (configuration.table(TABLE0).hasTimeouts() ? rule1.timeout() : -1);
// check that the number of parameters in the entry is the same as the number of table keys
assertThat("Incorrect number of match parameters",
entry1.matchKey().matchParams().size(), is(equalTo(numMatchParams)));
// check that values stored in entry are the same used for the flow rule
assertThat("Incorrect inPort match param value",
inPortParam.value().asReadOnlyBuffer().getShort(), is(equalTo(inPort)));
assertThat("Incorrect ethDestMac match param value",
ethDstParam.value().asArray(), is(equalTo(ethDstMac.toBytes())));
assertThat("Incorrect ethSrcMac match param value",
ethSrcParam.value().asArray(), is(equalTo(ethSrcMac.toBytes())));
assertThat("Incorrect ethType match param value",
ethTypeParam.value().asReadOnlyBuffer().getShort(), is(equalTo(ethType)));
assertThat("Incorrect priority value",
entry1.priority(), is(equalTo(Integer.MAX_VALUE - rule1.priority())));
assertThat("Incorrect timeout value",
entry1.timeout(), is(equalTo(expectedTimeout)));
}
}
\ No newline at end of file
......@@ -14,35 +14,36 @@
* limitations under the License.
*/
package org.onosproject.bmv2.api.model;
package org.onosproject.bmv2.ctl;
import org.junit.Test;
import org.onosproject.bmv2.ctl.Bmv2TableDumpParser;
import org.onosproject.bmv2.api.context.Bmv2Configuration;
import org.onosproject.bmv2.api.runtime.Bmv2ParsedTableEntry;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.Matchers.equalTo;
public class Bmv2TableDumpParserTest {
@Test
public void testParse() throws Exception, Bmv2TableDumpParser.Bmv2TableDumpParserException {
String text =
"0: 0000 000000000000 000000000000 &&& 0000000000000000000000000000 => send_to_cpu -\n" +
"1: 0000 000000000000 000000000000 &&& 0000000000000000000000000000 => send_to_cpu -\n" +
"2: 0000 000000000000 000000000000 &&& 0000000000000000000000000000 => send_to_cpu -\n" +
"3: 0000 000000000000 000000000000 &&& 0000000000000000000000000000 => send_to_cpu -";
private Bmv2Configuration configuration = Bmv2DeviceContextServiceImpl.loadDefaultConfiguration();
Bmv2TableDumpParser parser = new Bmv2TableDumpParser();
List<Long> result = parser.getEntryIds(text);
@Test
public void testParse() throws Exception {
String text = readFile();
List<Bmv2ParsedTableEntry> result = Bmv2TableDumpParser.parse(text, configuration);
assertThat(result.size(), equalTo(10));
}
assertThat("invalid parsed values", result.get(0), is(equalTo(0L)));
assertThat("invalid parsed values", result.get(1), is(equalTo(1L)));
assertThat("invalid parsed values", result.get(2), is(equalTo(2L)));
assertThat("invalid parsed values", result.get(3), is(equalTo(3L)));
private String readFile()
throws IOException, URISyntaxException {
byte[] encoded = Files.readAllBytes(Paths.get(this.getClass().getResource("/tabledump.txt").toURI()));
return new String(encoded, Charset.defaultCharset());
}
}
......
0: 0000 000000000000 000000000000 0806 &&& 0000000000000000000000000000ffff => send_to_cpu -
1: 0000 000000000000 000000000000 0800 &&& 0000000000000000000000000000ffff => send_to_cpu -
2: 0000 000000000000 000000000000 88cc &&& 0000000000000000000000000000ffff => send_to_cpu -
3: 0000 000000000000 000000000000 8942 &&& 0000000000000000000000000000ffff => send_to_cpu -
4: 0001 000400000001 000400000000 0000 &&& ffffffffffffffffffffffffffff0000 => set_egress_port - 2,
5: 0002 000400000000 000400000001 0000 &&& ffffffffffffffffffffffffffff0000 => set_egress_port - 1,
51539607552: 0001 0000 => set_egress_port - 1,
51539607553: 0001 0002 => set_egress_port - 3,
51539607554: 0001 0001 => set_egress_port - 2,
51539607555: 0001 0003 => set_egress_port - 4,
\ No newline at end of file
This diff is collapsed. Click to expand it.
/*
* Copyright 2016-present 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.bmv2.ctl;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.tuple.Pair;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* String parser for the BMv2 table dump.
*/
public class Bmv2TableDumpParser {
/*
Example of BMv2 table dump:
0: 0000 000000000000 000000000000 0806 &&& 0000000000000000000000000000ffff => send_to_cpu -
For each entry, we want to match the id and all the rest.
*/
private static final String ENTRY_PATTERN_STRING = "(\\d+):(.+)";
private static final Pattern ENTRY_PATTERN = Pattern.compile(ENTRY_PATTERN_STRING);
/**
* Returns a list of entry Ids for the given table dump.
*
* @param tableDump a string value
* @return a list of long values
* @throws Bmv2TableDumpParserException if dump can't be parsed
*/
public List<Long> getEntryIds(String tableDump) throws Bmv2TableDumpParserException {
return parse(tableDump).stream().map(Pair::getKey).collect(Collectors.toList());
}
private List<Pair<Long, String>> parse(String tableDump) throws Bmv2TableDumpParserException {
checkNotNull(tableDump, "tableDump cannot be null");
List<Pair<Long, String>> results = Lists.newArrayList();
// TODO: consider caching parser results for speed.
Matcher matcher = ENTRY_PATTERN.matcher(tableDump);
while (matcher.find()) {
String entryString = matcher.group(1);
if (entryString == null) {
throw new Bmv2TableDumpParserException("Unable to parse entry for string: " + matcher.group());
}
Long entryId = -1L;
try {
entryId = Long.valueOf(entryString.trim());
} catch (NumberFormatException e) {
throw new Bmv2TableDumpParserException("Unable to parse entry id for string: " + matcher.group());
}
String allTheRest = matcher.group(2);
if (allTheRest == null) {
throw new Bmv2TableDumpParserException("Unable to parse entry for string: " + matcher.group());
}
results.add(Pair.of(entryId, allTheRest));
}
return results;
}
public class Bmv2TableDumpParserException extends Throwable {
public Bmv2TableDumpParserException(String msg) {
super(msg);
}
}
}
This diff is collapsed. Click to expand it.
......@@ -18,7 +18,7 @@
set -e
basedir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
ns="org.p4.bmv2.thrift"
ns="org.onosproject.bmv2.thriftapi"
# add java namespace at beginning of file
for f in ${basedir}/*.thrift
......
......@@ -46,7 +46,7 @@
<module>lldpcommon</module>
<module>lldp</module>
<module>netcfglinks</module>
<module>bmv2</module>
<!--<module>bmv2</module>-->
<module>isis</module>
</modules>
......
......@@ -73,6 +73,24 @@ public final class ImmutableByteSequence {
}
/**
* Creates a new immutable byte sequence with the same content and order of
* the passed byte array, from/to the given indexes (inclusive).
*
* @param original a byte array value
* @return a new immutable byte sequence
*/
public static ImmutableByteSequence copyFrom(byte[] original, int fromIdx, int toIdx) {
checkArgument(original != null && original.length > 0,
"Cannot copy from an empty or null array");
checkArgument(toIdx >= fromIdx && toIdx < original.length, "invalid indexes");
ByteBuffer buffer = ByteBuffer.allocate((toIdx - fromIdx) + 1);
for (int i = fromIdx; i <= toIdx; i++) {
buffer.put(original[i]);
}
return new ImmutableByteSequence(buffer);
}
/**
* Creates a new immutable byte sequence copying bytes from the given
* ByteBuffer {@link ByteBuffer}. If the byte buffer order is not big-endian
* bytes will be copied in reverse order.
......