Ray Milkey
Committed by Gerrit Code Review

REST API to create flows

Change-Id: I5d001782249c0eab249d7aa857ae465da95b5955
Showing 22 changed files with 815 additions and 164 deletions
......@@ -35,6 +35,7 @@ import org.onosproject.net.Path;
import org.onosproject.net.Port;
import org.onosproject.net.driver.Driver;
import org.onosproject.net.flow.FlowEntry;
import org.onosproject.net.flow.FlowRule;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.flow.criteria.Criterion;
......@@ -83,6 +84,7 @@ public class CodecManager implements CodecService {
registerCodec(Intent.class, new IntentCodec());
registerCodec(ConnectivityIntent.class, new ConnectivityIntentCodec());
registerCodec(FlowEntry.class, new FlowEntryCodec());
registerCodec(FlowRule.class, new FlowRuleCodec());
registerCodec(TrafficTreatment.class, new TrafficTreatmentCodec());
registerCodec(TrafficSelector.class, new TrafficSelectorCodec());
registerCodec(Instruction.class, new InstructionCodec());
......
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.codec.impl;
import org.onlab.packet.IpAddress;
import org.onlab.packet.MacAddress;
import org.onlab.packet.MplsLabel;
import org.onlab.packet.VlanId;
import org.onosproject.net.ChannelSpacing;
import org.onosproject.net.GridType;
import org.onosproject.net.Lambda;
import org.onosproject.net.OchSignal;
import org.onosproject.net.PortNumber;
import org.onosproject.net.flow.instructions.Instruction;
import org.onosproject.net.flow.instructions.Instructions;
import org.onosproject.net.flow.instructions.L0ModificationInstruction;
import org.onosproject.net.flow.instructions.L2ModificationInstruction;
import org.onosproject.net.flow.instructions.L3ModificationInstruction;
import com.fasterxml.jackson.databind.node.ObjectNode;
import static org.onlab.util.Tools.nullIsIllegal;
/**
* Decoding portion of the instruction codec.
*/
public final class DecodeInstructionCodec {
private final ObjectNode json;
/**
* Creates a decode instruction codec object.
*
* @param json JSON object to decode
*/
public DecodeInstructionCodec(ObjectNode json) {
this.json = json;
}
/**
* Decodes a Layer 2 instruction.
*
* @return instruction object decoded from the JSON
* @throws IllegalArgumentException if the JSON is invalid
*/
private Instruction decodeL2() {
String subType = json.get(InstructionCodec.SUBTYPE).asText();
if (subType.equals(L2ModificationInstruction.L2SubType.ETH_SRC.name())) {
String mac = nullIsIllegal(json.get(InstructionCodec.MAC),
InstructionCodec.MAC + InstructionCodec.MISSING_MEMBER_MESSAGE).asText();
return Instructions.modL2Src(MacAddress.valueOf(mac));
} else if (subType.equals(L2ModificationInstruction.L2SubType.ETH_DST.name())) {
String mac = nullIsIllegal(json.get(InstructionCodec.MAC),
InstructionCodec.MAC + InstructionCodec.MISSING_MEMBER_MESSAGE).asText();
return Instructions.modL2Dst(MacAddress.valueOf(mac));
} else if (subType.equals(L2ModificationInstruction.L2SubType.VLAN_ID.name())) {
short vlanId = (short) nullIsIllegal(json.get(InstructionCodec.VLAN_ID),
InstructionCodec.VLAN_ID + InstructionCodec.MISSING_MEMBER_MESSAGE).asInt();
return Instructions.modVlanId(VlanId.vlanId(vlanId));
} else if (subType.equals(L2ModificationInstruction.L2SubType.VLAN_PCP.name())) {
byte vlanPcp = (byte) nullIsIllegal(json.get(InstructionCodec.VLAN_PCP),
InstructionCodec.VLAN_PCP + InstructionCodec.MISSING_MEMBER_MESSAGE).asInt();
return Instructions.modVlanPcp(vlanPcp);
} else if (subType.equals(L2ModificationInstruction.L2SubType.MPLS_LABEL.name())) {
int label = nullIsIllegal(json.get(InstructionCodec.MPLS_LABEL),
InstructionCodec.MPLS_LABEL + InstructionCodec.MISSING_MEMBER_MESSAGE).asInt();
return Instructions.modMplsLabel(MplsLabel.mplsLabel(label));
} else if (subType.equals(L2ModificationInstruction.L2SubType.MPLS_PUSH.name())) {
return Instructions.pushMpls();
} else if (subType.equals(L2ModificationInstruction.L2SubType.MPLS_POP.name())) {
return Instructions.popMpls();
} else if (subType.equals(L2ModificationInstruction.L2SubType.DEC_MPLS_TTL.name())) {
return Instructions.decMplsTtl();
} else if (subType.equals(L2ModificationInstruction.L2SubType.VLAN_POP.name())) {
return Instructions.popVlan();
} else if (subType.equals(L2ModificationInstruction.L2SubType.VLAN_PUSH.name())) {
return Instructions.pushVlan();
}
throw new IllegalArgumentException("L2 Instruction subtype "
+ subType + " is not supported");
}
/**
* Decodes a Layer 3 instruction.
*
* @return instruction object decoded from the JSON
* @throws IllegalArgumentException if the JSON is invalid
*/
private Instruction decodeL3() {
String subType = json.get(InstructionCodec.SUBTYPE).asText();
if (subType.equals(L3ModificationInstruction.L3SubType.IPV4_SRC.name())) {
IpAddress ip = IpAddress.valueOf(nullIsIllegal(json.get(InstructionCodec.IP),
InstructionCodec.IP + InstructionCodec.MISSING_MEMBER_MESSAGE).asText());
return Instructions.modL3Src(ip);
} else if (subType.equals(L3ModificationInstruction.L3SubType.IPV4_DST.name())) {
IpAddress ip = IpAddress.valueOf(nullIsIllegal(json.get(InstructionCodec.IP),
InstructionCodec.IP + InstructionCodec.MISSING_MEMBER_MESSAGE).asText());
return Instructions.modL3Dst(ip);
} else if (subType.equals(L3ModificationInstruction.L3SubType.IPV6_SRC.name())) {
IpAddress ip = IpAddress.valueOf(nullIsIllegal(json.get(InstructionCodec.IP),
InstructionCodec.IP + InstructionCodec.MISSING_MEMBER_MESSAGE).asText());
return Instructions.modL3IPv6Src(ip);
} else if (subType.equals(L3ModificationInstruction.L3SubType.IPV6_DST.name())) {
IpAddress ip = IpAddress.valueOf(nullIsIllegal(json.get(InstructionCodec.IP),
InstructionCodec.IP + InstructionCodec.MISSING_MEMBER_MESSAGE).asText());
return Instructions.modL3IPv6Dst(ip);
} else if (subType.equals(L3ModificationInstruction.L3SubType.IPV6_FLABEL.name())) {
int flowLabel = nullIsIllegal(json.get(InstructionCodec.FLOW_LABEL),
InstructionCodec.FLOW_LABEL + InstructionCodec.MISSING_MEMBER_MESSAGE).asInt();
return Instructions.modL3IPv6FlowLabel(flowLabel);
}
throw new IllegalArgumentException("L3 Instruction subtype "
+ subType + " is not supported");
}
/**
* Decodes a Layer 0 instruction.
*
* @return instruction object decoded from the JSON
* @throws IllegalArgumentException if the JSON is invalid
*/
private Instruction decodeL0() {
String subType = json.get(InstructionCodec.SUBTYPE).asText();
if (subType.equals(L0ModificationInstruction.L0SubType.LAMBDA.name())) {
int lambda = nullIsIllegal(json.get(InstructionCodec.LAMBDA),
InstructionCodec.LAMBDA + InstructionCodec.MISSING_MEMBER_MESSAGE).asInt();
return Instructions.modL0Lambda(Lambda.indexedLambda(lambda));
} else if (subType.equals(L0ModificationInstruction.L0SubType.OCH.name())) {
String gridTypeString = nullIsIllegal(json.get(InstructionCodec.GRID_TYPE),
InstructionCodec.GRID_TYPE + InstructionCodec.MISSING_MEMBER_MESSAGE).asText();
GridType gridType = GridType.valueOf(gridTypeString);
if (gridType == null) {
throw new IllegalArgumentException("Unknown grid type "
+ gridTypeString);
}
String channelSpacingString = nullIsIllegal(json.get(InstructionCodec.CHANNEL_SPACING),
InstructionCodec.CHANNEL_SPACING + InstructionCodec.MISSING_MEMBER_MESSAGE).asText();
ChannelSpacing channelSpacing = ChannelSpacing.valueOf(channelSpacingString);
if (channelSpacing == null) {
throw new IllegalArgumentException("Unknown channel spacing "
+ channelSpacingString);
}
int spacingMultiplier = nullIsIllegal(json.get(InstructionCodec.SPACING_MULTIPLIER),
InstructionCodec.SPACING_MULTIPLIER + InstructionCodec.MISSING_MEMBER_MESSAGE).asInt();
int slotGranularity = nullIsIllegal(json.get(InstructionCodec.SLOT_GRANULARITY),
InstructionCodec.SLOT_GRANULARITY + InstructionCodec.MISSING_MEMBER_MESSAGE).asInt();
return Instructions.modL0Lambda(new OchSignal(gridType, channelSpacing,
spacingMultiplier, slotGranularity));
}
throw new IllegalArgumentException("L0 Instruction subtype "
+ subType + " is not supported");
}
/**
* Decodes the JSON into an instruction object.
*
* @return Criterion object
* @throws IllegalArgumentException if the JSON is invalid
*/
public Instruction decode() {
String type = json.get(InstructionCodec.TYPE).asText();
if (type.equals(Instruction.Type.OUTPUT.name())) {
PortNumber portNumber =
PortNumber.portNumber(nullIsIllegal(json.get(InstructionCodec.PORT),
InstructionCodec.PORT + InstructionCodec.MISSING_MEMBER_MESSAGE).asLong());
return Instructions.createOutput(portNumber);
} else if (type.equals(Instruction.Type.DROP.name())) {
return Instructions.createDrop();
} else if (type.equals(Instruction.Type.L0MODIFICATION.name())) {
return decodeL0();
} else if (type.equals(Instruction.Type.L2MODIFICATION.name())) {
return decodeL2();
} else if (type.equals(Instruction.Type.L3MODIFICATION.name())) {
return decodeL3();
}
throw new IllegalArgumentException("Instruction type "
+ type + " is not supported");
}
}
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.codec.impl;
import org.onosproject.codec.CodecContext;
import org.onosproject.net.OchSignal;
import org.onosproject.net.flow.instructions.Instruction;
import org.onosproject.net.flow.instructions.Instructions;
import org.onosproject.net.flow.instructions.L0ModificationInstruction;
import org.onosproject.net.flow.instructions.L2ModificationInstruction;
import org.onosproject.net.flow.instructions.L3ModificationInstruction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* JSON encoding of Instructions.
*/
public final class EncodeInstructionCodec {
protected static final Logger log = LoggerFactory.getLogger(EncodeInstructionCodec.class);
private final Instruction instruction;
private final CodecContext context;
/**
* Creates an instruction object encoder.
*
* @param instruction instruction to encode
* @param context codec context for the encoding
*/
public EncodeInstructionCodec(Instruction instruction, CodecContext context) {
this.instruction = instruction;
this.context = context;
}
/**
* Encode an L0 modification instruction.
*
* @param result json node that the instruction attributes are added to
*/
private void encodeL0(ObjectNode result) {
L0ModificationInstruction instruction =
(L0ModificationInstruction) this.instruction;
result.put(InstructionCodec.SUBTYPE, instruction.subtype().name());
switch (instruction.subtype()) {
case LAMBDA:
final L0ModificationInstruction.ModLambdaInstruction modLambdaInstruction =
(L0ModificationInstruction.ModLambdaInstruction) instruction;
result.put(InstructionCodec.LAMBDA, modLambdaInstruction.lambda());
break;
case OCH:
L0ModificationInstruction.ModOchSignalInstruction ochSignalInstruction =
(L0ModificationInstruction.ModOchSignalInstruction) instruction;
OchSignal ochSignal = ochSignalInstruction.lambda();
result.put(InstructionCodec.GRID_TYPE, ochSignal.gridType().name());
result.put(InstructionCodec.CHANNEL_SPACING, ochSignal.channelSpacing().name());
result.put(InstructionCodec.SPACING_MULTIPLIER, ochSignal.spacingMultiplier());
result.put(InstructionCodec.SLOT_GRANULARITY, ochSignal.slotGranularity());
break;
default:
log.info("Cannot convert L0 subtype of {}", instruction.subtype());
}
}
/**
* Encode an L2 modification instruction.
*
* @param result json node that the instruction attributes are added to
*/
private void encodeL2(ObjectNode result) {
L2ModificationInstruction instruction =
(L2ModificationInstruction) this.instruction;
result.put(InstructionCodec.SUBTYPE, instruction.subtype().name());
switch (instruction.subtype()) {
case ETH_SRC:
case ETH_DST:
final L2ModificationInstruction.ModEtherInstruction modEtherInstruction =
(L2ModificationInstruction.ModEtherInstruction) instruction;
result.put(InstructionCodec.MAC, modEtherInstruction.mac().toString());
break;
case VLAN_ID:
final L2ModificationInstruction.ModVlanIdInstruction modVlanIdInstruction =
(L2ModificationInstruction.ModVlanIdInstruction) instruction;
result.put(InstructionCodec.VLAN_ID, modVlanIdInstruction.vlanId().toShort());
break;
case VLAN_PCP:
final L2ModificationInstruction.ModVlanPcpInstruction modVlanPcpInstruction =
(L2ModificationInstruction.ModVlanPcpInstruction) instruction;
result.put(InstructionCodec.VLAN_PCP, modVlanPcpInstruction.vlanPcp());
break;
case MPLS_LABEL:
final L2ModificationInstruction.ModMplsLabelInstruction modMplsLabelInstruction =
(L2ModificationInstruction.ModMplsLabelInstruction) instruction;
result.put(InstructionCodec.MPLS_LABEL, modMplsLabelInstruction.label());
break;
case MPLS_PUSH:
final L2ModificationInstruction.PushHeaderInstructions pushHeaderInstructions =
(L2ModificationInstruction.PushHeaderInstructions) instruction;
result.put(InstructionCodec.ETHERNET_TYPE, pushHeaderInstructions.ethernetType());
break;
default:
log.info("Cannot convert L2 subtype of {}", instruction.subtype());
break;
}
}
/**
* Encode an L3 modification instruction.
*
* @param result json node that the instruction attributes are added to
*/
private void encodeL3(ObjectNode result) {
L3ModificationInstruction instruction =
(L3ModificationInstruction) this.instruction;
result.put(InstructionCodec.SUBTYPE, instruction.subtype().name());
switch (instruction.subtype()) {
case IPV4_SRC:
case IPV4_DST:
case IPV6_SRC:
case IPV6_DST:
final L3ModificationInstruction.ModIPInstruction modIPInstruction =
(L3ModificationInstruction.ModIPInstruction) instruction;
result.put(InstructionCodec.IP, modIPInstruction.ip().toString());
break;
case IPV6_FLABEL:
final L3ModificationInstruction.ModIPv6FlowLabelInstruction
modFlowLabelInstruction =
(L3ModificationInstruction.ModIPv6FlowLabelInstruction) instruction;
result.put(InstructionCodec.FLOW_LABEL, modFlowLabelInstruction.flowLabel());
break;
default:
log.info("Cannot convert L3 subtype of {}", instruction.subtype());
break;
}
}
/**
* Encodes the given instruction into JSON.
*
* @return JSON object node representing the instruction
*/
public ObjectNode encode() {
final ObjectNode result = context.mapper().createObjectNode()
.put(InstructionCodec.TYPE, instruction.type().toString());
switch (instruction.type()) {
case OUTPUT:
final Instructions.OutputInstruction outputInstruction =
(Instructions.OutputInstruction) instruction;
result.put(InstructionCodec.PORT, outputInstruction.port().toLong());
break;
case DROP:
break;
case L0MODIFICATION:
encodeL0(result);
break;
case L2MODIFICATION:
encodeL2(result);
break;
case L3MODIFICATION:
encodeL3(result);
break;
default:
log.info("Cannot convert instruction type of {}", instruction.type());
break;
}
return result;
}
}
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.codec.impl;
import org.onosproject.codec.CodecContext;
import org.onosproject.codec.JsonCodec;
import org.onosproject.core.CoreService;
import org.onosproject.net.DeviceId;
import org.onosproject.net.flow.DefaultFlowRule;
import org.onosproject.net.flow.FlowRule;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.flow.TrafficTreatment;
import com.fasterxml.jackson.databind.node.ObjectNode;
import static org.onlab.util.Tools.nullIsIllegal;
/**
* Flow rule JSON codec.
*/
public final class FlowRuleCodec extends JsonCodec<FlowRule> {
private static final String APP_ID = "appId";
private static final String PRIORITY = "priority";
private static final String TIMEOUT = "timeout";
private static final String IS_PERMANENT = "isPermanent";
private static final String DEVICE_ID = "deviceId";
private static final String TREATMENT = "treatment";
private static final String SELECTOR = "selector";
private static final String MISSING_MEMBER_MESSAGE =
" member is required in FlowRule";
@Override
public FlowRule decode(ObjectNode json, CodecContext context) {
if (json == null || !json.isObject()) {
return null;
}
FlowRule.Builder resultBuilder = new DefaultFlowRule.Builder();
short appId = nullIsIllegal(json.get(APP_ID),
APP_ID + MISSING_MEMBER_MESSAGE).shortValue();
CoreService coreService = context.getService(CoreService.class);
resultBuilder.fromApp(coreService.getAppId(appId));
int priority = nullIsIllegal(json.get(PRIORITY),
PRIORITY + MISSING_MEMBER_MESSAGE).asInt();
resultBuilder.withPriority(priority);
boolean isPermanent = nullIsIllegal(json.get(IS_PERMANENT),
IS_PERMANENT + MISSING_MEMBER_MESSAGE).asBoolean();
if (isPermanent) {
resultBuilder.makePermanent();
} else {
resultBuilder.makeTemporary(nullIsIllegal(json.get(TIMEOUT),
TIMEOUT
+ MISSING_MEMBER_MESSAGE
+ " if the flow is temporary").asInt());
}
DeviceId deviceId = DeviceId.deviceId(nullIsIllegal(json.get(DEVICE_ID),
DEVICE_ID + MISSING_MEMBER_MESSAGE).asText());
resultBuilder.forDevice(deviceId);
ObjectNode treatmentJson = (ObjectNode) json.get(TREATMENT);
if (treatmentJson != null) {
JsonCodec<TrafficTreatment> treatmentCodec =
context.codec(TrafficTreatment.class);
resultBuilder.withTreatment(treatmentCodec.decode(treatmentJson, context));
}
ObjectNode selectorJson = (ObjectNode) json.get(SELECTOR);
if (selectorJson != null) {
JsonCodec<TrafficSelector> selectorCodec =
context.codec(TrafficSelector.class);
resultBuilder.withSelector(selectorCodec.decode(selectorJson, context));
}
return resultBuilder.build();
}
}
......@@ -17,12 +17,7 @@ package org.onosproject.codec.impl;
import org.onosproject.codec.CodecContext;
import org.onosproject.codec.JsonCodec;
import org.onosproject.net.OchSignal;
import org.onosproject.net.flow.instructions.Instruction;
import org.onosproject.net.flow.instructions.Instructions;
import org.onosproject.net.flow.instructions.L0ModificationInstruction;
import org.onosproject.net.flow.instructions.L2ModificationInstruction;
import org.onosproject.net.flow.instructions.L3ModificationInstruction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -37,159 +32,39 @@ public final class InstructionCodec extends JsonCodec<Instruction> {
protected static final Logger log = LoggerFactory.getLogger(InstructionCodec.class);
/**
* Encode an L0 modification instruction.
*
* @param result json node that the instruction attributes are added to
* @param instruction The L0 instruction
*/
private void encodeL0(ObjectNode result, L0ModificationInstruction instruction) {
result.put("subtype", instruction.subtype().name());
switch (instruction.subtype()) {
case LAMBDA:
final L0ModificationInstruction.ModLambdaInstruction modLambdaInstruction =
(L0ModificationInstruction.ModLambdaInstruction) instruction;
result.put("lambda", modLambdaInstruction.lambda());
break;
case OCH:
L0ModificationInstruction.ModOchSignalInstruction ochSignalInstruction =
(L0ModificationInstruction.ModOchSignalInstruction) instruction;
OchSignal ochSignal = ochSignalInstruction.lambda();
result.put("gridType", ochSignal.gridType().name());
result.put("channelSpacing", ochSignal.channelSpacing().name());
result.put("spacingMultiplier", ochSignal.spacingMultiplier());
result.put("slotGranularity", ochSignal.slotGranularity());
break;
default:
log.info("Cannot convert L0 subtype of {}", instruction.subtype());
}
}
/**
* Encode an L2 modification instruction.
*
* @param result json node that the instruction attributes are added to
* @param instruction The L2 instruction
* @param context context of the request
*/
private void encodeL2(ObjectNode result,
L2ModificationInstruction instruction,
CodecContext context) {
result.put("subtype", instruction.subtype().name());
switch (instruction.subtype()) {
case ETH_SRC:
case ETH_DST:
final L2ModificationInstruction.ModEtherInstruction modEtherInstruction =
(L2ModificationInstruction.ModEtherInstruction) instruction;
result.put("mac", modEtherInstruction.mac().toString());
break;
case VLAN_ID:
final L2ModificationInstruction.ModVlanIdInstruction modVlanIdInstruction =
(L2ModificationInstruction.ModVlanIdInstruction) instruction;
result.put("vlanId", modVlanIdInstruction.vlanId().toShort());
break;
case VLAN_PCP:
final L2ModificationInstruction.ModVlanPcpInstruction modVlanPcpInstruction =
(L2ModificationInstruction.ModVlanPcpInstruction) instruction;
result.put("vlanPcp", modVlanPcpInstruction.vlanPcp());
break;
case MPLS_LABEL:
final L2ModificationInstruction.ModMplsLabelInstruction modMplsLabelInstruction =
(L2ModificationInstruction.ModMplsLabelInstruction) instruction;
result.put("label", modMplsLabelInstruction.label());
break;
case MPLS_PUSH:
final L2ModificationInstruction.PushHeaderInstructions pushHeaderInstructions =
(L2ModificationInstruction.PushHeaderInstructions) instruction;
result.put("ethernetType", pushHeaderInstructions.ethernetType());
break;
default:
log.info("Cannot convert L2 subtype of {}", instruction.subtype());
break;
}
}
/**
* Encode an L3 modification instruction.
*
* @param result json node that the instruction attributes are added to
* @param instruction The L3 instruction
*/
private void encodeL3(ObjectNode result, L3ModificationInstruction instruction) {
result.put("subtype", instruction.subtype().name());
switch (instruction.subtype()) {
case IPV4_SRC:
case IPV4_DST:
case IPV6_SRC:
case IPV6_DST:
final L3ModificationInstruction.ModIPInstruction modIPInstruction =
(L3ModificationInstruction.ModIPInstruction) instruction;
result.put("ip", modIPInstruction.ip().toString());
break;
protected static final String TYPE = "type";
protected static final String SUBTYPE = "subtype";
protected static final String PORT = "port";
protected static final String MAC = "mac";
protected static final String VLAN_ID = "vlanId";
protected static final String VLAN_PCP = "vlanPcp";
protected static final String MPLS_LABEL = "label";
protected static final String IP = "ip";
protected static final String FLOW_LABEL = "flowLabel";
protected static final String LAMBDA = "lambda";
protected static final String GRID_TYPE = "gridType";
protected static final String CHANNEL_SPACING = "channelSpacing";
protected static final String SPACING_MULTIPLIER = "spacingMultiplier";
protected static final String SLOT_GRANULARITY = "slotGranularity";
protected static final String ETHERNET_TYPE = "ethernetType";
protected static final String MISSING_MEMBER_MESSAGE =
" member is required in Instruction";
case IPV6_FLABEL:
final L3ModificationInstruction.ModIPv6FlowLabelInstruction
modFlowLabelInstruction =
(L3ModificationInstruction.ModIPv6FlowLabelInstruction) instruction;
result.put("flowLabel", modFlowLabelInstruction.flowLabel());
break;
default:
log.info("Cannot convert L3 subtype of {}", instruction.subtype());
break;
}
}
@Override
public ObjectNode encode(Instruction instruction, CodecContext context) {
checkNotNull(instruction, "Instruction cannot be null");
final ObjectNode result = context.mapper().createObjectNode()
.put("type", instruction.type().toString());
switch (instruction.type()) {
case OUTPUT:
final Instructions.OutputInstruction outputInstruction =
(Instructions.OutputInstruction) instruction;
result.put("port", outputInstruction.port().toLong());
break;
case DROP:
break;
case L0MODIFICATION:
final L0ModificationInstruction l0ModificationInstruction =
(L0ModificationInstruction) instruction;
encodeL0(result, l0ModificationInstruction);
break;
case L2MODIFICATION:
final L2ModificationInstruction l2ModificationInstruction =
(L2ModificationInstruction) instruction;
encodeL2(result, l2ModificationInstruction, context);
break;
case L3MODIFICATION:
final L3ModificationInstruction l3ModificationInstruction =
(L3ModificationInstruction) instruction;
encodeL3(result, l3ModificationInstruction);
break;
return new EncodeInstructionCodec(instruction, context).encode();
}
default:
log.info("Cannot convert instruction type of {}", instruction.type());
break;
@Override
public Instruction decode(ObjectNode json, CodecContext context) {
if (json == null || !json.isObject()) {
return null;
}
return result;
return new DecodeInstructionCodec(json).decode();
}
}
......
......@@ -15,11 +15,15 @@
*/
package org.onosproject.codec.impl;
import java.util.stream.IntStream;
import org.onosproject.codec.CodecContext;
import org.onosproject.codec.JsonCodec;
import org.onosproject.net.flow.DefaultTrafficSelector;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.flow.criteria.Criterion;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
......@@ -29,12 +33,14 @@ import static com.google.common.base.Preconditions.checkNotNull;
* Traffic selector codec.
*/
public final class TrafficSelectorCodec extends JsonCodec<TrafficSelector> {
private static final String CRITERIA = "criteria";
@Override
public ObjectNode encode(TrafficSelector selector, CodecContext context) {
checkNotNull(selector, "Traffic selector cannot be null");
final ObjectNode result = context.mapper().createObjectNode();
final ArrayNode jsonCriteria = result.putArray("criteria");
final ArrayNode jsonCriteria = result.putArray(CRITERIA);
if (selector.criteria() != null) {
final JsonCodec<Criterion> criterionCodec =
......@@ -46,4 +52,20 @@ public final class TrafficSelectorCodec extends JsonCodec<TrafficSelector> {
return result;
}
@Override
public TrafficSelector decode(ObjectNode json, CodecContext context) {
final JsonCodec<Criterion> criterionCodec =
context.codec(Criterion.class);
JsonNode criteriaJson = json.get(CRITERIA);
TrafficSelector.Builder builder = DefaultTrafficSelector.builder();
if (criteriaJson != null) {
IntStream.range(0, criteriaJson.size())
.forEach(i -> builder.add(
criterionCodec.decode((ObjectNode) criteriaJson.get(i),
context)));
}
return builder.build();
}
}
......
......@@ -15,11 +15,15 @@
*/
package org.onosproject.codec.impl;
import java.util.stream.IntStream;
import org.onosproject.codec.CodecContext;
import org.onosproject.codec.JsonCodec;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.flow.instructions.Instruction;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
......@@ -29,12 +33,14 @@ import static com.google.common.base.Preconditions.checkNotNull;
* Traffic treatment codec.
*/
public final class TrafficTreatmentCodec extends JsonCodec<TrafficTreatment> {
private static final String INSTRUCTIONS = "instructions";
@Override
public ObjectNode encode(TrafficTreatment treatment, CodecContext context) {
checkNotNull(treatment, "Traffic treatment cannot be null");
final ObjectNode result = context.mapper().createObjectNode();
final ArrayNode jsonInstructions = result.putArray("instructions");
final ArrayNode jsonInstructions = result.putArray(INSTRUCTIONS);
final JsonCodec<Instruction> instructionCodec =
context.codec(Instruction.class);
......@@ -51,4 +57,20 @@ public final class TrafficTreatmentCodec extends JsonCodec<TrafficTreatment> {
return result;
}
@Override
public TrafficTreatment decode(ObjectNode json, CodecContext context) {
final JsonCodec<Instruction> instructionsCodec =
context.codec(Instruction.class);
JsonNode instructionsJson = json.get(INSTRUCTIONS);
TrafficTreatment.Builder builder = DefaultTrafficTreatment.builder();
if (instructionsJson != null) {
IntStream.range(0, instructionsJson.size())
.forEach(i -> builder.add(
instructionsCodec.decode((ObjectNode) instructionsJson.get(i),
context)));
}
return builder.build();
}
}
......
......@@ -72,8 +72,10 @@ public class CriterionCodecTest {
*/
@Test
public void checkCriterionTypes() throws Exception {
EncodeCriterionCodec encoder = new EncodeCriterionCodec(
Criteria.dummy(), context);
EnumMap<Criterion.Type, Object> formatMap =
getField(criterionCodec, "formatMap");
getField(encoder, "formatMap");
assertThat(formatMap, notNullValue());
for (Criterion.Type type : Criterion.Type.values()) {
......
......@@ -38,6 +38,8 @@ public class ImmutableCodecsTest {
assertThatClassIsImmutable(ConnectPointCodec.class);
assertThatClassIsImmutable(ConstraintCodec.class);
assertThatClassIsImmutable(CriterionCodec.class);
assertThatClassIsImmutable(EncodeCriterionCodec.class);
assertThatClassIsImmutable(DecodeCriterionCodec.class);
assertThatClassIsImmutable(DeviceCodec.class);
assertThatClassIsImmutable(EthernetCodec.class);
assertThatClassIsImmutable(FlowEntryCodec.class);
......@@ -45,6 +47,8 @@ public class ImmutableCodecsTest {
assertThatClassIsImmutable(HostLocationCodec.class);
assertThatClassIsImmutable(HostToHostIntentCodec.class);
assertThatClassIsImmutable(InstructionCodec.class);
assertThatClassIsImmutable(EncodeInstructionCodec.class);
assertThatClassIsImmutable(DecodeInstructionCodec.class);
assertThatClassIsImmutable(IntentCodec.class);
assertThatClassIsImmutable(LinkCodec.class);
assertThatClassIsImmutable(PathCodec.class);
......@@ -54,5 +58,6 @@ public class ImmutableCodecsTest {
assertThatClassIsImmutable(TopologyCodec.class);
assertThatClassIsImmutable(TrafficSelectorCodec.class);
assertThatClassIsImmutable(TrafficTreatmentCodec.class);
assertThatClassIsImmutable(FlowRuleCodec.class);
}
}
......
{
"appId":-29467,
"priority":1,
"isPermanent":"false",
"timeout":1,
"deviceId":"of:0000000000000001",
"selector":
{"criteria":
[
{"type":"IN_PORT", "port":23},
{"type":"IN_PHY_PORT", "port":44},
{"type":"METADATA", "metadata":123456},
{"type":"ETH_TYPE","ethType":2054},
{"type":"ETH_SRC","mac":"00:11:22:33:44:55"},
{"type":"ETH_DST","mac":"00:11:22:33:44:55"},
{"type":"VLAN_VID","vlanId":777},
{"type":"VLAN_PCP","priority":3},
{"type":"IP_DSCP","ipDscp":2},
{"type":"IP_ECN","ipEcn":1},
{"type":"IP_PROTO","protocol":4},
{"type":"IPV4_SRC", "ip":"1.2.0.0/32"},
{"type":"IPV4_DST", "ip":"2.2.0.0/32"},
{"type":"IPV6_SRC", "ip":"3.2.0.0/32"},
{"type":"IPV6_DST", "ip":"4.2.0.0/32"},
{"type":"TCP_SRC", "tcpPort":80},
{"type":"TCP_DST", "tcpPort":443},
{"type":"UDP_SRC", "udpPort":180},
{"type":"UDP_DST", "udpPort":1443},
{"type":"SCTP_SRC", "sctpPort":280},
{"type":"SCTP_DST", "sctpPort":2443},
{"type":"ICMPV4_TYPE", "icmpType":24},
{"type":"ICMPV4_CODE", "icmpCode":16},
{"type":"ICMPV6_TYPE", "icmpv6Type":14},
{"type":"ICMPV6_CODE", "icmpv6Code":6},
{"type":"IPV6_FLABEL", "flowLabel":8},
{"type":"IPV6_ND_TARGET", "targetAddress":"1111:2222:3333:4444:5555:6666:7777:8888"},
{"type":"IPV6_ND_SLL", "mac":"00:11:22:33:44:56"},
{"type":"IPV6_ND_TLL", "mac":"00:11:22:33:44:57"},
{"type":"MPLS_LABEL", "label":123},
{"type":"IPV6_EXTHDR", "exthdrFlags":99},
{"type":"OCH_SIGID", "lambda":122}
]
}
}
{
"appId":-29467,
"priority":1,
"isPermanent":"false",
"timeout":1,
"deviceId":"of:0000000000000001",
"treatment":
{
"instructions":
[
{"type":"OUTPUT","port":-3},
{"type":"DROP"},
{"type":"L2MODIFICATION","subtype":"ETH_SRC","mac":"12:34:56:78:90:12"},
{"type":"L2MODIFICATION","subtype":"ETH_DST","mac":"98:76:54:32:01:00"},
{"type":"L2MODIFICATION","subtype":"VLAN_ID","vlanId":22},
{"type":"L2MODIFICATION","subtype":"VLAN_PCP","vlanPcp":1},
{"type":"L2MODIFICATION","subtype":"MPLS_LABEL","label":777},
{"type":"L2MODIFICATION","subtype":"MPLS_PUSH"},
{"type":"L2MODIFICATION","subtype":"MPLS_POP"},
{"type":"L2MODIFICATION","subtype":"DEC_MPLS_TTL"},
{"type":"L2MODIFICATION","subtype":"VLAN_POP"},
{"type":"L2MODIFICATION","subtype":"VLAN_PUSH"},
{"type":"L3MODIFICATION","subtype":"IPV4_SRC", "ip":"1.2.3.4"},
{"type":"L3MODIFICATION","subtype":"IPV4_DST", "ip":"1.2.3.3"},
{"type":"L3MODIFICATION","subtype":"IPV6_SRC", "ip":"1.2.3.2"},
{"type":"L3MODIFICATION","subtype":"IPV6_DST", "ip":"1.2.3.1"},
{"type":"L3MODIFICATION","subtype":"IPV6_FLABEL", "flowLabel":8},
{"type":"L0MODIFICATION","subtype":"LAMBDA","lambda":7},
{"type":"L0MODIFICATION","subtype":"OCH","gridType":"DWDM",
"channelSpacing":"CHL_100GHZ","spacingMultiplier":4,"slotGranularity":8}
],
"deferred":[]
},
"selector": {"criteria":[{"type":"ETH_TYPE","ethType":2054}]}
}
{
"appId":-29467,
"priority":1,
"isPermanent":"false",
"timeout":1,
"deviceId":"of:0000000000000001",
"selector":
{"criteria":
[
{"type":"OCH_SIGID",
"ochSignalId":
{
"gridType":"CWDM",
"channelSpacing":"CHL_25GHZ",
"spacingMultiplier":3,
"slotGranularity":4
}
}
]
}
}
{
"appId":-29467,
"priority":1,
"isPermanent":"false",
"timeout":1,
"deviceId":"of:0000000000000001",
"treatment":
{"instructions":
[{"type":"OUTPUT","port":-3}],"deferred":[]},
"selector":
{"criteria":
[{"type":"ETH_TYPE","ethType":2054}]}
}
......@@ -123,7 +123,7 @@ public abstract class Tools {
}
/**
* Returns the specified item if that items is null; otherwise throws
* Returns the specified item if that item is not null; otherwise throws
* not found exception.
*
* @param item item to check
......@@ -140,6 +140,23 @@ public abstract class Tools {
}
/**
* Returns the specified item if that item is not null; otherwise throws
* bad argument exception.
*
* @param item item to check
* @param message not found message
* @param <T> item type
* @return item if not null
* @throws IllegalArgumentException if item is null
*/
public static <T> T nullIsIllegal(T item, String message) {
if (item == null) {
throw new IllegalArgumentException(message);
}
return item;
}
/**
* Converts a string from hex to long.
*
* @param string hex number in string form; sans 0x
......
/*
* Copyright 2014-2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.rest.exceptions;
import javax.ws.rs.core.Response;
/**
* Mapper for illegal argument exceptions to the BAD_REQUEST response code.
*/
public class IllegalArgumentExceptionMapper extends AbstractMapper<IllegalArgumentException> {
@Override
protected Response.Status responseStatus() {
return Response.Status.BAD_REQUEST;
}
}
......@@ -15,22 +15,29 @@
*/
package org.onosproject.rest.resources;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.io.InputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.onlab.util.ItemNotFoundException;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.flow.FlowEntry;
import org.onosproject.net.flow.FlowRule;
import org.onosproject.net.flow.FlowRuleService;
import org.onosproject.rest.AbstractWebResource;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* REST resource for interacting with the inventory of flows.
......@@ -113,4 +120,27 @@ public class FlowsWebResource extends AbstractWebResource {
}
return ok(root).build();
}
/**
* Creates a flow rule from a POST of a JSON string and attempts to apply it.
*
* @param stream input JSON
* @return status of the request - ACCEPTED if the JSON is correct,
* BAD_REQUEST if the JSON is invalid
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createFlow(InputStream stream) {
try {
FlowRuleService service = get(FlowRuleService.class);
ObjectNode root = (ObjectNode) mapper().readTree(stream);
FlowRule rule = codec(FlowRule.class).decode(root, this);
service.applyFlowRules(rule);
} catch (IOException ex) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
return Response.status(Response.Status.ACCEPTED).build();
}
}
......
......@@ -61,6 +61,7 @@
org.onosproject.rest.exceptions.ServerErrorMapper,
org.onosproject.rest.exceptions.BadRequestMapper,
org.onosproject.rest.exceptions.WebApplicationExceptionMapper,
org.onosproject.rest.exceptions.IllegalArgumentExceptionMapper,
org.onosproject.rest.resources.JsonBodyWriter,
org.onosproject.rest.resources.ApplicationsWebResource,
......
......@@ -15,10 +15,13 @@
*/
package org.onosproject.rest;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.MediaType;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
import org.junit.After;
......@@ -30,11 +33,13 @@ import org.onlab.packet.MacAddress;
import org.onlab.rest.BaseResource;
import org.onosproject.codec.CodecService;
import org.onosproject.codec.impl.CodecManager;
import org.onosproject.core.CoreService;
import org.onosproject.core.DefaultGroupId;
import org.onosproject.core.GroupId;
import org.onosproject.net.DefaultDevice;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.NetTestTools;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.flow.DefaultTrafficSelector;
import org.onosproject.net.flow.DefaultTrafficTreatment;
......@@ -51,12 +56,15 @@ import org.onosproject.net.flow.instructions.Instructions;
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.google.common.collect.ImmutableSet;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.anyShort;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.hamcrest.Matchers.containsString;
......@@ -72,6 +80,8 @@ import static org.junit.Assert.fail;
*/
public class FlowsResourceTest extends ResourceTest {
final FlowRuleService mockFlowService = createMock(FlowRuleService.class);
CoreService mockCoreService = createMock(CoreService.class);
final HashMap<DeviceId, Set<FlowEntry>> rules = new HashMap<>();
final DeviceService mockDeviceService = createMock(DeviceService.class);
......@@ -245,6 +255,11 @@ public class FlowsResourceTest extends ResourceTest {
expect(mockDeviceService.getDevices())
.andReturn(ImmutableSet.of(device1, device2));
// Mock Core Service
expect(mockCoreService.getAppId(anyShort()))
.andReturn(NetTestTools.APP_ID).anyTimes();
replay(mockCoreService);
// Register the services needed for the test
final CodecManager codecService = new CodecManager();
codecService.activate();
......@@ -252,7 +267,8 @@ public class FlowsResourceTest extends ResourceTest {
new TestServiceDirectory()
.add(FlowRuleService.class, mockFlowService)
.add(DeviceService.class, mockDeviceService)
.add(CodecService.class, codecService);
.add(CodecService.class, codecService)
.add(CoreService.class, mockCoreService);
BaseResource.setServiceDirectory(testDirectory);
}
......@@ -263,6 +279,7 @@ public class FlowsResourceTest extends ResourceTest {
@After
public void tearDownTest() {
verify(mockFlowService);
verify(mockCoreService);
}
/**
......@@ -542,4 +559,27 @@ public class FlowsResourceTest extends ResourceTest {
containsString("returned a response status of"));
}
}
/**
* Tests creating a flow with POST.
*/
@Test
public void testPost() {
String json = "{\"appId\":2,\"priority\":1,\"isPermanent\":true,"
+ "\"deviceId\":\"of:0000000000000001\","
+ "\"treatment\":{\"instructions\":[ {\"type\":\"OUTPUT\",\"port\":2}]},"
+ "\"selector\":{\"criteria\":[ {\"type\":\"ETH_TYPE\",\"ethType\":2054}]}}";
mockFlowService.applyFlowRules(anyObject());
expectLastCall();
replay(mockFlowService);
WebResource rs = resource();
ClientResponse response = rs.path("flows/")
.type(MediaType.APPLICATION_JSON_TYPE)
.post(ClientResponse.class, json);
assertThat(response.getStatus(), is(HttpURLConnection.HTTP_ACCEPTED));
}
}
......