Carmelo Cascone
Committed by Thomas Vachuska

Various bmv2 changes to reflect onos-bmv2 v1.0.0 (onos1.6 cherry-pick)

Most notably:
- Updated repo URL and commit ID to official onos-bmv2 fork
- Removed ugly string-based table dump parser, now there's
	a proper API to retrieve table entries (added support in
	Bmv2DeviceAgent)
- Removed unused arguments in packet-in API

Change-Id: I5ff0948eb8fec5283a085913496c187e7b278d8d
......@@ -118,10 +118,14 @@ public class Bmv2FlowRuleProgrammable extends AbstractHandlerBehaviour implement
return;
}
// Bmv2 doesn't support proper polling for table entries, but only a string based table dump.
// The trick here is to first dump the entries currently installed in the device for a given table,
// and then query a service for the corresponding, previously applied, flow rule.
List<Bmv2ParsedTableEntry> installedEntries = tableEntryService.getTableEntries(deviceId, table.name());
List<Bmv2ParsedTableEntry> installedEntries;
try {
installedEntries = deviceAgent.getTableEntries(table.name());
} catch (Bmv2RuntimeException e) {
log.warn("Failed to get table entries of table {} of {}: {}", table.name(), deviceId, e.explain());
return;
}
installedEntries.forEach(parsedEntry -> {
Bmv2TableEntryReference entryRef = new Bmv2TableEntryReference(deviceId,
table.name(),
......@@ -309,7 +313,7 @@ public class Bmv2FlowRuleProgrammable extends AbstractHandlerBehaviour implement
private void forceRemove(Bmv2DeviceAgent agent, String tableName, Bmv2MatchKey matchKey)
throws Bmv2RuntimeException {
// Find the entryID (expensive call!)
for (Bmv2ParsedTableEntry pEntry : tableEntryService.getTableEntries(agent.deviceId(), tableName)) {
for (Bmv2ParsedTableEntry pEntry : agent.getTableEntries(tableName)) {
if (pEntry.matchKey().equals(matchKey)) {
// Remove entry and drop exceptions.
silentlyRemove(agent, tableName, pEntry.entryId());
......
......@@ -16,7 +16,7 @@
~ limitations under the License.
-->
<drivers>
<driver name="bmv2-thrift" manufacturer="p4.org" hwVersion="bmv2" swVersion="n/a">
<driver name="bmv2-thrift" manufacturer="p4.org" hwVersion="bmv2" swVersion="1.0.0">
<behaviour api="org.onosproject.net.device.DeviceDescriptionDiscovery"
impl="org.onosproject.drivers.bmv2.Bmv2DeviceDescriptionDiscovery"/>
<behaviour api="org.onosproject.net.flow.FlowRuleProgrammable"
......
......@@ -37,7 +37,7 @@ public final class Bmv2Device {
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 SW_VERSION = "1.0.0";
public static final String SERIAL_NUMBER = N_A;
private final String thriftServerHost;
......
......@@ -21,6 +21,7 @@ import org.onlab.util.ImmutableByteSequence;
import org.onosproject.net.DeviceId;
import java.util.Collection;
import java.util.List;
/**
* An agent to control a BMv2 device.
......@@ -87,13 +88,13 @@ public interface Bmv2DeviceAgent {
Collection<Bmv2PortInfo> getPortsInfo() throws Bmv2RuntimeException;
/**
* Return a string representation of the given table content.
* Returns a list of table entries installed in the given table.
*
* @param tableName string value of table name
* @return table string dump
* @param tableName a string value
* @return a list of parsed table entries
* @throws Bmv2RuntimeException if any error occurs
*/
String dumpTable(String tableName) throws Bmv2RuntimeException;
List<Bmv2ParsedTableEntry> getTableEntries(String tableName) throws Bmv2RuntimeException;
/**
* Requests the device to transmit a given byte sequence over the given port.
......
......@@ -20,24 +20,27 @@ import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
/**
* Representation of a table entry obtained by parsing a BMv2 table dump.
* Representation of a table entry installed on a BMv2 device.
*/
public final class Bmv2ParsedTableEntry {
private final long entryId;
private final Bmv2MatchKey matchKey;
private final Bmv2Action action;
private final int priority;
/**
* Creates a new parsed table entry.
*
* @param entryId an entry ID
* @param entryId a long value
* @param matchKey a match key
* @param action an action
* @param priority an integer value
*/
public Bmv2ParsedTableEntry(long entryId, Bmv2MatchKey matchKey, Bmv2Action action) {
public Bmv2ParsedTableEntry(long entryId, Bmv2MatchKey matchKey, Bmv2Action action, int priority) {
this.entryId = entryId;
this.matchKey = matchKey;
this.action = action;
this.priority = priority;
}
/**
......@@ -67,9 +70,18 @@ public final class Bmv2ParsedTableEntry {
return action;
}
/**
* Returns the priority.
*
* @return an integer value
*/
public int getPriority() {
return priority;
}
@Override
public int hashCode() {
return Objects.hashCode(entryId, matchKey, action);
return Objects.hashCode(entryId, matchKey, action, priority);
}
@Override
......@@ -83,7 +95,8 @@ public final class Bmv2ParsedTableEntry {
final Bmv2ParsedTableEntry other = (Bmv2ParsedTableEntry) obj;
return Objects.equal(this.entryId, other.entryId)
&& Objects.equal(this.matchKey, other.matchKey)
&& Objects.equal(this.action, other.action);
&& Objects.equal(this.action, other.action)
&& Objects.equal(this.priority, other.priority);
}
@Override
......
......@@ -29,11 +29,7 @@ public interface Bmv2PacketListener {
*
* @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);
void handlePacketIn(Bmv2Device device, int inputPort, ImmutableByteSequence packet);
}
......
......@@ -19,11 +19,7 @@ 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.
......@@ -38,16 +34,6 @@ public interface Bmv2TableEntryService {
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
......
......@@ -244,7 +244,7 @@ public class Bmv2ControllerImpl implements Bmv2Controller {
}
@Override
public void packetIn(int port, long reason, int tableId, int contextId, ByteBuffer packet) {
public void packet_in(int port, ByteBuffer packet) {
if (remoteDevice == null) {
log.debug("Received packet-in, but the remote device is still unknown. Need a hello first...");
return;
......@@ -256,9 +256,6 @@ public class Bmv2ControllerImpl implements Bmv2Controller {
packetListeners.forEach(
l -> executorService.execute(() -> l.handlePacketIn(remoteDevice,
port,
reason,
tableId,
contextId,
ImmutableByteSequence.copyFrom(packet))));
}
}
......
......@@ -26,11 +26,14 @@ import org.onosproject.bmv2.api.runtime.Bmv2DeviceAgent;
import org.onosproject.bmv2.api.runtime.Bmv2ExactMatchParam;
import org.onosproject.bmv2.api.runtime.Bmv2LpmMatchParam;
import org.onosproject.bmv2.api.runtime.Bmv2MatchKey;
import org.onosproject.bmv2.api.runtime.Bmv2MatchParam;
import org.onosproject.bmv2.api.runtime.Bmv2ParsedTableEntry;
import org.onosproject.bmv2.api.runtime.Bmv2PortInfo;
import org.onosproject.bmv2.api.runtime.Bmv2RuntimeException;
import org.onosproject.bmv2.api.runtime.Bmv2TableEntry;
import org.onosproject.bmv2.api.runtime.Bmv2TernaryMatchParam;
import org.onosproject.bmv2.api.runtime.Bmv2ValidMatchParam;
import org.onosproject.bmv2.thriftapi.BmActionEntry;
import org.onosproject.bmv2.thriftapi.BmAddEntryOptions;
import org.onosproject.bmv2.thriftapi.BmCounterValue;
import org.onosproject.bmv2.thriftapi.BmMatchParam;
......@@ -39,6 +42,7 @@ import org.onosproject.bmv2.thriftapi.BmMatchParamLPM;
import org.onosproject.bmv2.thriftapi.BmMatchParamTernary;
import org.onosproject.bmv2.thriftapi.BmMatchParamType;
import org.onosproject.bmv2.thriftapi.BmMatchParamValid;
import org.onosproject.bmv2.thriftapi.BmMtEntry;
import org.onosproject.bmv2.thriftapi.SimpleSwitch;
import org.onosproject.bmv2.thriftapi.Standard;
import org.onosproject.net.DeviceId;
......@@ -50,6 +54,7 @@ import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import static org.onlab.util.ImmutableByteSequence.copyFrom;
import static org.onosproject.bmv2.ctl.Bmv2TExceptionParser.parseTException;
/**
......@@ -214,19 +219,71 @@ public final class Bmv2DeviceThriftClient implements Bmv2DeviceAgent {
}
@Override
public String dumpTable(String tableName) throws Bmv2RuntimeException {
public List<Bmv2ParsedTableEntry> getTableEntries(String tableName) throws Bmv2RuntimeException {
log.debug("Retrieving table dump... > deviceId={}, tableName={}", deviceId, tableName);
log.debug("Retrieving table entries... > deviceId={}, tableName={}", deviceId, tableName);
List<BmMtEntry> bmEntries;
try {
String dump = standardClient.bm_dump_table(CONTEXT_ID, tableName);
log.debug("Table dump retrieved! > deviceId={}, tableName={}", deviceId, tableName);
return dump;
bmEntries = standardClient.bm_mt_get_entries(CONTEXT_ID, tableName);
} catch (TException e) {
log.debug("Exception while retrieving table dump: {} > deviceId={}, tableName={}",
log.debug("Exception while retrieving table entries: {} > deviceId={}, tableName={}",
e, deviceId, tableName);
throw parseTException(e);
}
List<Bmv2ParsedTableEntry> parsedEntries = Lists.newArrayList();
entryLoop:
for (BmMtEntry bmEntry : bmEntries) {
Bmv2MatchKey.Builder matchKeyBuilder = Bmv2MatchKey.builder();
for (BmMatchParam bmParam : bmEntry.getMatch_key()) {
Bmv2MatchParam param;
switch (bmParam.getType()) {
case EXACT:
param = new Bmv2ExactMatchParam(copyFrom(bmParam.getExact().getKey()));
break;
case LPM:
param = new Bmv2LpmMatchParam(copyFrom(bmParam.getLpm().getKey()),
bmParam.getLpm().getPrefix_length());
break;
case TERNARY:
param = new Bmv2TernaryMatchParam(copyFrom(bmParam.getTernary().getKey()),
copyFrom(bmParam.getTernary().getMask()));
break;
case VALID:
param = new Bmv2ValidMatchParam(bmParam.getValid().isKey());
break;
default:
log.warn("Parsing of match type {} unsupported, skipping table entry.",
bmParam.getType().name());
continue entryLoop;
}
matchKeyBuilder.add(param);
}
Bmv2Action.Builder actionBuilder = Bmv2Action.builder();
BmActionEntry bmActionEntry = bmEntry.getAction_entry();
switch (bmActionEntry.getAction_type()) {
case ACTION_DATA:
actionBuilder.withName(bmActionEntry.getAction_name());
bmActionEntry.getAction_data()
.stream()
.map(ImmutableByteSequence::copyFrom)
.forEach(actionBuilder::addParameter);
break;
default:
log.warn("Parsing of action action type {} unsupported, skipping table entry.",
bmActionEntry.getAction_type().name());
continue entryLoop;
}
parsedEntries.add(new Bmv2ParsedTableEntry(bmEntry.getEntry_handle(), matchKeyBuilder.build(),
actionBuilder.build(), bmEntry.getOptions().getPriority()));
}
return parsedEntries;
}
@Override
......@@ -236,7 +293,7 @@ public final class Bmv2DeviceThriftClient implements Bmv2DeviceAgent {
try {
simpleSwitchClient.push_packet(portNumber, ByteBuffer.wrap(packet.asArray()));
simpleSwitchClient.packet_out(portNumber, ByteBuffer.wrap(packet.asArray()));
log.debug("Packet transmission requested! > portNumber={}, packetSize={}", portNumber, packet.size());
} catch (TException e) {
log.debug("Exception while requesting packet transmission: {} > portNumber={}, packetSize={}",
......
/*
* 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.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.CacheStats;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.tuple.Pair;
import org.onlab.util.HexString;
import org.onlab.util.ImmutableByteSequence;
import org.onlab.util.SharedScheduledExecutors;
import org.onosproject.bmv2.api.context.Bmv2ActionModel;
import org.onosproject.bmv2.api.context.Bmv2Configuration;
import org.onosproject.bmv2.api.runtime.Bmv2Action;
import org.onosproject.bmv2.api.runtime.Bmv2ExactMatchParam;
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.Bmv2TernaryMatchParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.onosproject.bmv2.api.utils.Bmv2TranslatorUtils.fitByteSequence;
import static org.onosproject.bmv2.api.utils.Bmv2TranslatorUtils.ByteSequenceFitException;
/**
* BMv2 table dump parser.
*/
public final class Bmv2TableDumpParser {
// Examples of a BMv2 table dump can be found in Bmv2TableDumpParserTest
// 1: entry id, 2: match string, 3: action string
private static final String ENTRY_PATTERN_REGEX = "(\\d+): (.*) => (.*)";
// 1: match values, 2: masks
private static final String MATCH_TERNARY_PATTERN_REGEX = "([0-9a-fA-F ]+) &&& ([0-9a-fA-F ]+)";
// 1: match values, 2: masks
private static final String MATCH_LPM_PATTERN_REGEX = "([0-9a-fA-F ]+) / ([0-9a-fA-F ]+)";
// 1: match values
private static final String MATCH_EXACT_PATTERN_REGEX = "([0-9a-fA-F ]+)";
// 1: action name, 2: action params
private static final String ACTION_PATTERN_REGEX = "(.+) - ?([0-9a-fA-F ,]*)";
private static final Pattern ENTRY_PATTERN = Pattern.compile(ENTRY_PATTERN_REGEX);
private static final Pattern MATCH_TERNARY_PATTERN = Pattern.compile(MATCH_TERNARY_PATTERN_REGEX);
private static final Pattern MATCH_LPM_PATTERN = Pattern.compile(MATCH_LPM_PATTERN_REGEX);
private static final Pattern MATCH_EXACT_PATTERN = Pattern.compile(MATCH_EXACT_PATTERN_REGEX);
private static final Pattern ACTION_PATTERN = Pattern.compile(ACTION_PATTERN_REGEX);
// Cache to avoid re-parsing known lines.
// The assumption here is that entries are not updated too frequently, so that the entry id doesn't change often.
// Otherwise, we should cache only the match and action strings...
private static final LoadingCache<Pair<String, Bmv2Configuration>, Optional<Bmv2ParsedTableEntry>> ENTRY_CACHE =
CacheBuilder.newBuilder()
.expireAfterAccess(60, TimeUnit.SECONDS)
.recordStats()
.build(new CacheLoader<Pair<String, Bmv2Configuration>, Optional<Bmv2ParsedTableEntry>>() {
@Override
public Optional<Bmv2ParsedTableEntry> load(Pair<String, Bmv2Configuration> key) throws Exception {
// Very expensive call.
return Optional.ofNullable(parseLine(key.getLeft(), key.getRight()));
}
});
private static final Logger log = LoggerFactory.getLogger(Bmv2TableDumpParser.class);
private static final long STATS_LOG_FREQUENCY = 3; // minutes
static {
SharedScheduledExecutors.getSingleThreadExecutor().scheduleAtFixedRate(
() -> reportStats(), 0, STATS_LOG_FREQUENCY, TimeUnit.MINUTES);
}
private Bmv2TableDumpParser() {
// Ban constructor.
}
/**
* Parse the given BMv2 table dump.
*
* @param tableDump a string value
* @return a list of {@link Bmv2ParsedTableEntry}
*/
public static List<Bmv2ParsedTableEntry> parse(String tableDump, Bmv2Configuration configuration) {
checkNotNull(tableDump, "tableDump cannot be null");
// Parse all lines
List<Bmv2ParsedTableEntry> result = Arrays.stream(tableDump.split("\n"))
.map(line -> Pair.of(line, configuration))
.map(Bmv2TableDumpParser::loadFromCache)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
return result;
}
private static Optional<Bmv2ParsedTableEntry> loadFromCache(Pair<String, Bmv2Configuration> key) {
try {
return ENTRY_CACHE.get(key);
} catch (ExecutionException e) {
Throwable t = e.getCause();
if (t instanceof Bmv2TableDumpParserException) {
Bmv2TableDumpParserException parserException = (Bmv2TableDumpParserException) t;
log.warn("{}", parserException.getMessage());
} else {
log.error("Exception while parsing table dump line", e);
}
return Optional.empty();
}
}
private static void reportStats() {
CacheStats stats = ENTRY_CACHE.stats();
log.info("Cache stats: requestCount={}, hitRate={}, exceptionsCount={}, avgLoadPenalty={}",
stats.requestCount(), stats.hitRate(), stats.loadExceptionCount(), stats.averageLoadPenalty());
}
private static Bmv2ParsedTableEntry parseLine(String line, Bmv2Configuration configuration)
throws Bmv2TableDumpParserException {
Matcher matcher = ENTRY_PATTERN.matcher(line);
if (matcher.find()) {
long entryId = parseEntryId(matcher, 1);
String matchString = parseMatchString(matcher, 2);
String actionString = parseActionString(matcher, 3);
Bmv2MatchKey matchKey = parseMatchKey(matchString);
Bmv2Action action = parseAction(actionString, configuration);
return new Bmv2ParsedTableEntry(entryId, matchKey, action);
} else {
// Not a table entry
return null;
}
}
private static Long parseEntryId(Matcher matcher, int groupIdx) throws Bmv2TableDumpParserException {
String str = matcher.group(groupIdx);
if (str == null) {
throw new Bmv2TableDumpParserException("Unable to find entry ID: " + matcher.group());
}
long entryId;
try {
entryId = Long.valueOf(str.trim());
} catch (NumberFormatException e) {
throw new Bmv2TableDumpParserException("Unable to parse entry id for string: " + matcher.group());
}
return entryId;
}
private static String parseMatchString(Matcher matcher, int groupIdx) throws Bmv2TableDumpParserException {
String str = matcher.group(groupIdx);
if (str == null) {
throw new Bmv2TableDumpParserException("Unable to find match string: " + matcher.group());
}
return str.trim();
}
private static String parseActionString(Matcher matcher, int groupIdx) throws Bmv2TableDumpParserException {
String str = matcher.group(groupIdx);
if (str == null) {
throw new Bmv2TableDumpParserException("Unable to find action string: " + matcher.group());
}
return str.trim();
}
private static Bmv2MatchKey parseMatchKey(String str) throws Bmv2TableDumpParserException {
Bmv2MatchKey.Builder builder = Bmv2MatchKey.builder();
// Try with ternary...
Matcher matcher = MATCH_TERNARY_PATTERN.matcher(str);
if (matcher.find()) {
// Ternary Match.
List<ImmutableByteSequence> values = parseMatchValues(matcher, 1);
List<ImmutableByteSequence> masks = parseMatchMasks(matcher, 2, values);
for (int i = 0; i < values.size(); i++) {
builder.add(new Bmv2TernaryMatchParam(values.get(i), masks.get(i)));
}
return builder.build();
}
// FIXME: LPM match parsing broken if table key contains also a ternary match
// Also it assumes the lpm parameter is the last one, which is wrong.
// Try with LPM...
matcher = MATCH_LPM_PATTERN.matcher(str);
if (matcher.find()) {
// Lpm Match.
List<ImmutableByteSequence> values = parseMatchValues(matcher, 1);
int prefixLength = parseLpmPrefix(matcher, 2);
for (int i = 0; i < values.size() - 1; i++) {
builder.add(new Bmv2ExactMatchParam(values.get(i)));
}
builder.add(new Bmv2LpmMatchParam(values.get(values.size() - 1), prefixLength));
return builder.build();
}
// Try with exact...
matcher = MATCH_EXACT_PATTERN.matcher(str);
if (matcher.find()) {
// Exact match.
parseMatchValues(matcher, 1)
.stream()
.map(Bmv2ExactMatchParam::new)
.forEach(builder::add);
return builder.build();
}
throw new Bmv2TableDumpParserException("Unable to parse match string: " + str);
}
private static List<ImmutableByteSequence> parseMatchValues(Matcher matcher, int groupIdx)
throws Bmv2TableDumpParserException {
String matchString = matcher.group(groupIdx);
if (matchString == null) {
throw new Bmv2TableDumpParserException("Unable to find match params for string: " + matcher.group());
}
List<ImmutableByteSequence> result = Lists.newArrayList();
for (String paramString : matchString.split(" ")) {
byte[] bytes = HexString.fromHexString(paramString, null);
result.add(ImmutableByteSequence.copyFrom(bytes));
}
return result;
}
private static List<ImmutableByteSequence> parseMatchMasks(Matcher matcher, int groupIdx,
List<ImmutableByteSequence> matchParams)
throws Bmv2TableDumpParserException {
String maskString = matcher.group(groupIdx);
if (maskString == null) {
throw new Bmv2TableDumpParserException("Unable to find mask for string: " + matcher.group());
}
List<ImmutableByteSequence> result = Lists.newArrayList();
/*
Mask here is a hex string with no spaces, hence individual mask params can be derived according
to given matchParam sizes.
*/
byte[] maskBytes = HexString.fromHexString(maskString, null);
int startPosition = 0;
for (ImmutableByteSequence bs : matchParams) {
if (startPosition + bs.size() > maskBytes.length) {
throw new Bmv2TableDumpParserException("Invalid length for mask in string: " + matcher.group());
}
ImmutableByteSequence maskParam = ImmutableByteSequence.copyFrom(maskBytes,
startPosition,
startPosition + bs.size() - 1);
result.add(maskParam);
startPosition += bs.size();
}
return result;
}
private static int parseLpmPrefix(Matcher matcher, int groupIdx)
throws Bmv2TableDumpParserException {
String str = matcher.group(groupIdx);
if (str == null) {
throw new Bmv2TableDumpParserException("Unable to find LPM prefix for string: " + matcher.group());
}
// For some reason the dumped prefix has 16 bits more than the one programmed
try {
return Integer.valueOf(str.trim()) - 16;
} catch (NumberFormatException e) {
throw new Bmv2TableDumpParserException("Unable to parse LPM prefix from string: " + matcher.group());
}
}
private static Bmv2Action parseAction(String str, Bmv2Configuration configuration)
throws Bmv2TableDumpParserException {
Matcher matcher = ACTION_PATTERN.matcher(str);
if (matcher.find()) {
String actionName = parseActionName(matcher, 1);
Bmv2ActionModel actionModel = configuration.action(actionName);
if (actionModel == null) {
throw new Bmv2TableDumpParserException("Not such an action in configuration: " + actionName);
}
Bmv2Action.Builder builder = Bmv2Action.builder().withName(actionName);
List<ImmutableByteSequence> actionParams = parseActionParams(matcher, 2);
if (actionParams.size() != actionModel.runtimeDatas().size()) {
throw new Bmv2TableDumpParserException("Invalid number of parameters for action: " + actionName);
}
for (int i = 0; i < actionModel.runtimeDatas().size(); i++) {
try {
// fit param byte-width according to configuration.
builder.addParameter(fitByteSequence(actionParams.get(i),
actionModel.runtimeDatas().get(i).bitWidth()));
} catch (ByteSequenceFitException e) {
throw new Bmv2TableDumpParserException("Unable to parse action param: " + e.toString());
}
}
return builder.build();
}
throw new Bmv2TableDumpParserException("Unable to parse action string: " + str.trim());
}
private static String parseActionName(Matcher matcher, int groupIdx) throws Bmv2TableDumpParserException {
String actionName = matcher.group(groupIdx);
if (actionName == null) {
throw new Bmv2TableDumpParserException("Unable to find action name for string: " + matcher.group());
}
return actionName.trim();
}
private static List<ImmutableByteSequence> parseActionParams(Matcher matcher, int groupIdx)
throws Bmv2TableDumpParserException {
String paramsString = matcher.group(groupIdx);
if (paramsString == null) {
throw new Bmv2TableDumpParserException("Unable to find action params for string: " + matcher.group());
}
if (paramsString.length() == 0) {
return Collections.emptyList();
}
return Arrays.stream(paramsString.split(","))
.map(String::trim)
.map(s -> HexString.fromHexString(s, null))
.map(ImmutableByteSequence::copyFrom)
.collect(Collectors.toList());
}
public static class Bmv2TableDumpParserException extends Exception {
public Bmv2TableDumpParserException(String msg) {
super(msg);
}
}
}
\ No newline at end of file
......@@ -23,22 +23,17 @@ 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.bmv2.api.service.Bmv2Controller;
import org.onosproject.bmv2.api.service.Bmv2DeviceContextService;
import org.onosproject.bmv2.api.service.Bmv2TableEntryService;
import org.onosproject.store.serializers.KryoNamespaces;
import org.onosproject.store.service.EventuallyConsistentMap;
import org.onosproject.store.service.StorageService;
......@@ -46,9 +41,6 @@ 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;
/**
......@@ -107,23 +99,6 @@ public class Bmv2TableEntryServiceImpl implements Bmv2TableEntryService {
}
@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);
......
/*
* 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.junit.Test;
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.Matchers.equalTo;
public class Bmv2TableDumpParserTest {
private Bmv2Configuration configuration = Bmv2DeviceContextServiceImpl.loadDefaultConfiguration();
@Test
public void testParse() throws Exception {
String text = readFile();
List<Bmv2ParsedTableEntry> result = Bmv2TableDumpParser.parse(text, configuration);
assertThat(result.size(), equalTo(10));
}
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
......@@ -33,11 +33,11 @@
<properties>
<!-- BMv2 Commit ID and Thrift version -->
<bmv2.commit>e55f9cdaee5e3d729f839e7ec6c322dd66c1a1a0</bmv2.commit>
<bmv2.commit>024aa03e3b52f8d32c26774511e8e5b1dc11ec65</bmv2.commit>
<bmv2.thrift.version>0.9.3</bmv2.thrift.version>
<!-- Do not change below -->
<bmv2.baseurl>
https://raw.githubusercontent.com/ccascone/behavioral-model/${bmv2.commit}
https://raw.githubusercontent.com/opennetworkinglab/behavioral-model/${bmv2.commit}
</bmv2.baseurl>
<bmv2.thrift.srcdir>${project.basedir}/src/main/thrift</bmv2.thrift.srcdir>
<thrift.path>${project.build.directory}/thrift-compiler/</thrift.path>
......
......@@ -179,8 +179,7 @@ public class Bmv2PacketProvider extends AbstractProvider implements PacketProvid
private class InternalPacketListener implements Bmv2PacketListener {
@Override
public void handlePacketIn(Bmv2Device device, int inputPort, long reason, int tableId, int contextId,
ImmutableByteSequence packet) {
public void handlePacketIn(Bmv2Device device, int inputPort, ImmutableByteSequence packet) {
Ethernet ethPkt = new Ethernet();
ethPkt.deserialize(packet.asArray(), 0, packet.size());
......