SONA: Openstackswitching
- Refactored the app to expose APIs to CordVtn App
- Added clone method in OpenstackPort and OpenstackNetwork
- Added NetworkConfig to select the working mode of the app
- Added a few more APIs for getting network topology information
- Integrated with the modified DhcpService app
Change-Id: I9e266aff10a00d80074d031276864fff195d2b3f
diff --git a/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/OpenstackArpHandler.java b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/OpenstackArpHandler.java
new file mode 100644
index 0000000..f281e4a
--- /dev/null
+++ b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/OpenstackArpHandler.java
@@ -0,0 +1,106 @@
+/*
+* 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.openstackswitching;
+
+import org.onlab.packet.ARP;
+import org.onlab.packet.Ethernet;
+import org.onlab.packet.Ip4Address;
+import org.onlab.packet.MacAddress;
+import org.onosproject.net.flow.DefaultTrafficTreatment;
+import org.onosproject.net.flow.TrafficTreatment;
+import org.onosproject.net.packet.DefaultOutboundPacket;
+import org.onosproject.net.packet.InboundPacket;
+import org.onosproject.net.packet.OutboundPacket;
+import org.onosproject.net.packet.PacketService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import java.nio.ByteBuffer;
+import java.util.Map;
+
+/**
+ * Handles ARP packet from VMs.
+ */
+public class OpenstackArpHandler {
+
+ private static Logger log = LoggerFactory
+ .getLogger(OpenstackArpHandler.class);
+ private PacketService packetService;
+ private Map<String, OpenstackPort> openstackPortMap;
+
+ /**
+ * Returns OpenstackArpHandler reference.
+ *
+ * @param openstackPortMap
+ * @param packetService
+ */
+ public OpenstackArpHandler(Map<String, OpenstackPort> openstackPortMap, PacketService packetService) {
+ this.openstackPortMap = openstackPortMap;
+ this.packetService = packetService;
+ }
+
+ /**
+ * Processes ARP packets.
+ *
+ * @param pkt ARP request packet
+ */
+ public void processPacketIn(InboundPacket pkt) {
+ Ethernet ethernet = pkt.parsed();
+ ARP arp = (ARP) ethernet.getPayload();
+
+ if (arp.getOpCode() == ARP.OP_REQUEST) {
+ byte[] srcMacAddress = arp.getSenderHardwareAddress();
+ byte[] srcIPAddress = arp.getSenderProtocolAddress();
+ byte[] dstIPAddress = arp.getTargetProtocolAddress();
+
+ //Searches the Dst MAC Address based on openstackPortMap
+ MacAddress macAddress = null;
+
+ OpenstackPort openstackPort = openstackPortMap.values().stream().filter(e -> e.fixedIps().
+ containsValue(Ip4Address.valueOf(dstIPAddress))).findAny().orElse(null);
+
+ if (openstackPort != null) {
+ macAddress = openstackPort.macAddress();
+ log.debug("Found MACAddress: {}", macAddress.toString());
+ } else {
+ return;
+ }
+
+ //Creates a response packet
+ ARP arpReply = new ARP();
+ arpReply.setOpCode(ARP.OP_REPLY)
+ .setHardwareAddressLength(arp.getHardwareAddressLength())
+ .setHardwareType(arp.getHardwareType())
+ .setProtocolAddressLength(arp.getProtocolAddressLength())
+ .setProtocolType(arp.getProtocolType())
+ .setSenderHardwareAddress(macAddress.toBytes())
+ .setSenderProtocolAddress(dstIPAddress)
+ .setTargetHardwareAddress(srcMacAddress)
+ .setTargetProtocolAddress(srcIPAddress);
+
+ //Sends a response packet
+ ethernet.setDestinationMACAddress(srcMacAddress)
+ .setSourceMACAddress(macAddress)
+ .setEtherType(Ethernet.TYPE_ARP)
+ .setPayload(arpReply);
+
+ TrafficTreatment.Builder builder = DefaultTrafficTreatment.builder();
+ builder.setOutput(pkt.receivedFrom().port());
+ OutboundPacket packet = new DefaultOutboundPacket(pkt.receivedFrom().deviceId(),
+ builder.build(), ByteBuffer.wrap(ethernet.serialize()));
+ packetService.emit(packet);
+ }
+ }
+}
diff --git a/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/OpenstackSwitchingConfig.java b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/OpenstackSwitchingConfig.java
new file mode 100644
index 0000000..12a9c2c
--- /dev/null
+++ b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/OpenstackSwitchingConfig.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2014 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.openstackswitching;
+
+import org.onosproject.core.ApplicationId;
+import org.onosproject.net.config.Config;
+import org.onosproject.net.config.basics.BasicElementConfig;
+
+/**
+ * Handles configuration for OpenstackSwitching app.
+ */
+public class OpenstackSwitchingConfig extends Config<ApplicationId> {
+ public static final String DONOTPUSH = "do_not_push_flows";
+
+ /**
+ * Returns the flag whether the app pushes flows or not.
+ *
+ * @return the flag or false if not set
+ */
+ public boolean doNotPushFlows() {
+ String flag = get(DONOTPUSH, "false");
+ return Boolean.valueOf(flag);
+ }
+
+ /**
+ * Sets the flag whether the app pushes flows or not.
+ *
+ * @param flag the flag whether the app pushes flows or not
+ * @return self
+ */
+ public BasicElementConfig doNotPushFlows(boolean flag) {
+ return (BasicElementConfig) setOrClear(DONOTPUSH, flag);
+ }
+}
diff --git a/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/OpenstackSwitchingManager.java b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/OpenstackSwitchingManager.java
new file mode 100644
index 0000000..0e7ebac
--- /dev/null
+++ b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/OpenstackSwitchingManager.java
@@ -0,0 +1,562 @@
+/*
+ * 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.openstackswitching;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+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.packet.Ethernet;
+import org.onlab.packet.Ip4Address;
+import org.onlab.packet.Ip4Prefix;
+import org.onlab.packet.MacAddress;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.dhcp.DhcpService;
+import org.onosproject.net.Device;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.Port;
+import org.onosproject.net.config.ConfigFactory;
+import org.onosproject.net.config.NetworkConfigEvent;
+import org.onosproject.net.config.NetworkConfigListener;
+import org.onosproject.net.config.NetworkConfigRegistry;
+import org.onosproject.net.device.DeviceEvent;
+import org.onosproject.net.device.DeviceListener;
+import org.onosproject.net.device.DeviceService;
+import org.onosproject.net.flowobjective.FlowObjectiveService;
+import org.onosproject.net.packet.InboundPacket;
+import org.onosproject.net.packet.PacketContext;
+import org.onosproject.net.packet.PacketProcessor;
+import org.onosproject.net.packet.PacketService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import java.util.List;
+import java.util.Map;
+import java.util.Collection;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.stream.Collectors;
+
+import static org.onosproject.net.config.basics.SubjectFactories.APP_SUBJECT_FACTORY;
+
+@SuppressWarnings("ALL")
+@Service
+@Component(immediate = true)
+/**
+ * Populates forwarding rules for VMs created by Openstack.
+ */
+public class OpenstackSwitchingManager implements OpenstackSwitchingService {
+
+ private static Logger log = LoggerFactory
+ .getLogger(OpenstackSwitchingManager.class);
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected CoreService coreService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected PacketService packetService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected DeviceService deviceService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected FlowObjectiveService flowObjectiveService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected NetworkConfigRegistry cfgService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected DhcpService dhcpService;
+
+ public static final int DHCP_PORT = 67;
+
+ private ApplicationId appId;
+ private boolean doNotPushFlows;
+ private OpenstackArpHandler arpHandler;
+
+ private OpenstackSwitchingRulePopulator rulePopulator;
+ private ExecutorService deviceEventExcutorService = Executors.newFixedThreadPool(10);
+
+ private InternalPacketProcessor internalPacketProcessor = new InternalPacketProcessor();
+ private InternalDeviceListener internalDeviceListener = new InternalDeviceListener();
+ private InternalConfigListener internalConfigListener = new InternalConfigListener();
+ private final Set<ConfigFactory> factories = ImmutableSet.of(
+ new ConfigFactory<ApplicationId, OpenstackSwitchingConfig>(APP_SUBJECT_FACTORY,
+ OpenstackSwitchingConfig.class,
+ "openstackswitching") {
+ @Override
+ public OpenstackSwitchingConfig createConfig() {
+ return new OpenstackSwitchingConfig();
+ }
+ }
+ );
+ // Map <port_id, OpenstackPort>
+ private Map<String, OpenstackPort> openstackPortMap;
+ // Map <network_id, OpenstackNetwork>
+ private Map<String, OpenstackNetwork> openstackNetworkMap;
+ // Map <subnet_id, OpenstackSubner>
+ private Map<String, OpenstackSubnet> openstackSubnetMap;
+ // Map <vni, List <Entry <portName, host ip>>
+ private Map<String, List<PortInfo>> vniPortMap;
+ private Map<Ip4Address, Port> tunnelPortMap;
+
+
+ @Activate
+ protected void activate() {
+ appId = coreService
+ .registerApplication("org.onosproject.openstackswitching");
+ packetService.addProcessor(internalPacketProcessor, PacketProcessor.director(1));
+ deviceService.addListener(internalDeviceListener);
+ cfgService.addListener(internalConfigListener);
+ factories.forEach(cfgService::registerConfigFactory);
+ OpenstackSwitchingConfig cfg =
+ cfgService.getConfig(appId, OpenstackSwitchingConfig.class);
+ if (cfg != null) {
+ doNotPushFlows = cfg.doNotPushFlows();
+ }
+ openstackPortMap = Maps.newHashMap();
+ openstackNetworkMap = Maps.newHashMap();
+ openstackSubnetMap = Maps.newHashMap();
+
+ vniPortMap = Maps.newHashMap();
+ tunnelPortMap = Maps.newHashMap();
+
+ arpHandler = new OpenstackArpHandler(openstackPortMap, packetService);
+
+ log.info("Started");
+ }
+
+ @Deactivate
+ protected void deactivate() {
+ packetService.removeProcessor(internalPacketProcessor);
+ deviceService.removeListener(internalDeviceListener);
+ cfgService.removeListener(internalConfigListener);
+
+ deviceEventExcutorService.shutdown();
+
+ log.info("Stopped");
+ }
+
+ @Override
+ public void createPorts(OpenstackPort openstackPort) {
+ registerDhcpInfo(openstackPort);
+ openstackPortMap.put(openstackPort.id(), openstackPort);
+ }
+
+ @Override
+ public void deletePorts() {
+
+ }
+
+ @Override
+ public void updatePorts() {
+
+ }
+
+ @Override
+ public void createNetwork(OpenstackNetwork openstackNetwork) {
+ openstackNetworkMap.put(openstackNetwork.id(), openstackNetwork);
+ }
+
+ @Override
+ public void createSubnet(OpenstackSubnet openstackSubnet) {
+ openstackSubnetMap.put(openstackSubnet.id(), openstackSubnet);
+ log.debug("Added Subnet Info {}", openstackNetworkMap.get(openstackSubnet.id()));
+ }
+
+ @Override
+ public Collection<OpenstackPort> ports(String networkId) {
+
+ List<OpenstackPort> portList = openstackPortMap.values().stream()
+ .filter(p -> p.networkId().equals(networkId))
+ .collect(Collectors.toList());
+
+ return portList;
+ }
+
+ @Override
+ public OpenstackPort port(String portName) {
+ String uuid = portName.substring(3);
+ return (OpenstackPort) openstackPortMap.values().stream()
+ .filter(p -> p.id().startsWith(uuid))
+ .findFirst().get().clone();
+ }
+
+ @Override
+ public OpenstackNetwork network(String networkId) {
+ OpenstackNetwork on = null;
+ try {
+ on = (OpenstackNetwork) openstackNetworkMap.get(networkId).clone();
+ } catch (CloneNotSupportedException e) {
+ log.error("Cloning is not supported {}", e);
+ }
+ return on;
+ }
+
+ private void processDeviceAdded(Device device) {
+ log.debug("device {} is added", device.id());
+ rulePopulator.populateDefaultRules(device.id());
+ }
+
+ private void processPortAdded(Device device, Port port) {
+ // TODO: Simplify the data structure to store the network info
+ // TODO: Make it stateless
+ // TODO: All the logics need to be processed inside of the rulePopulator class
+ synchronized (vniPortMap) {
+ log.debug("port {} is updated", port.toString());
+
+ updatePortMaps(device, port);
+ if (!port.annotations().value("portName").equals("vxlan")) {
+ populateFlowRulesForTrafficToSameCnode(device, port);
+ populateFlowRulesForTrafficToDifferentCnode(device, port);
+ }
+ }
+ }
+
+ private void processPortRemoved(Device device, Port port) {
+ log.debug("port {} is removed", port.toString());
+ // TODO: need to update the vniPortMap
+ }
+
+ private void registerDhcpInfo(OpenstackPort openstackPort) {
+ Ip4Address ip4Address;
+ Ip4Address subnetMask;
+ Ip4Address dhcpServer;
+ Ip4Address gatewayIPAddress;
+ Ip4Address domainServer;
+ OpenstackSubnet openstackSubnet;
+
+ ip4Address = (Ip4Address) openstackPort.fixedIps().values().toArray()[0];
+
+ openstackSubnet = openstackSubnetMap.values().stream()
+ .filter(n -> n.networkId().equals(openstackPort.networkId()))
+ .findFirst().get();
+
+ subnetMask = Ip4Address.valueOf(buildSubnetMask(openstackSubnet.cidr()));
+ gatewayIPAddress = Ip4Address.valueOf(openstackSubnet.gatewayIp());
+ dhcpServer = gatewayIPAddress;
+ // TODO: supports multiple DNS servers
+ if (openstackSubnet.dnsNameservers().isEmpty()) {
+ domainServer = Ip4Address.valueOf("8.8.8.8");
+ } else {
+ domainServer = openstackSubnet.dnsNameservers().get(0);
+ }
+ List<Ip4Address> options = Lists.newArrayList();
+ options.add(subnetMask);
+ options.add(dhcpServer);
+ options.add(gatewayIPAddress);
+ options.add(domainServer);
+
+ dhcpService.setStaticMapping(openstackPort.macAddress(), ip4Address, true, options);
+ }
+
+ private byte[] buildSubnetMask(String cidr) {
+ int prefix;
+ String[] parts = cidr.split("/");
+ prefix = Integer.parseInt(parts[1]);
+ int mask = 0xffffffff << (32 - prefix);
+ byte[] bytes = new byte[]{(byte) (mask >>> 24),
+ (byte) (mask >> 16 & 0xff), (byte) (mask >> 8 & 0xff), (byte) (mask & 0xff)};
+
+ return bytes;
+ }
+
+ /**
+ * Populates the flow rules for traffic to VMs in different Cnode using
+ * Nicira extention.
+ *
+ * @param device device to put rules
+ * @param port port information of the VM
+ */
+ private void populateFlowRulesForTrafficToDifferentCnode(Device device, Port port) {
+ String portName = port.annotations().value("portName");
+ String channelId = device.annotations().value("channelId");
+ Ip4Address hostIpAddress = Ip4Address.valueOf(channelId.split(":")[0]);
+ Ip4Address fixedIp = getFixedIpAddressForPort(portName);
+ // TODO: Avoid duplicate flow rule set up for VMs in other Cnode
+ // (possibly avoided by flowrule subsystem?)
+ if (tunnelPortMap.get(hostIpAddress) == null) {
+ log.debug("There is no tunnel port information");
+ return;
+ }
+ String vni = getVniForPort(portName);
+ MacAddress vmMac = getVmMacAddressForPort(portName);
+ if (!vniPortMap.isEmpty() && vniPortMap.get(vni) != null) {
+ for (PortInfo portInfo : vniPortMap.get(vni)) {
+ if (!portInfo.portName.equals(portName) &&
+ !portInfo.hostIp.equals(hostIpAddress)) {
+ MacAddress vmMacx = getVmMacAddressForPort(portInfo.portName);
+ rulePopulator.populateForwardingRuleForOtherCnode(vni,
+ device.id(), portInfo.hostIp, portInfo.fixedIp, vmMacx,
+ tunnelPortMap.get(hostIpAddress).number(),
+ portInfo.deviceId, hostIpAddress, fixedIp, vmMac,
+ tunnelPortMap.get(portInfo.hostIp).number());
+ }
+ }
+ }
+ }
+
+ /**
+ * Populates the flow rules for traffic to VMs in the same Cnode as the sender.
+ *
+ * @param device device to put the rules
+ * @param port port info of the VM
+ */
+ private void populateFlowRulesForTrafficToSameCnode(Device device, Port port) {
+ Ip4Prefix cidr = getCidrForPort(port.annotations().value("portName"));
+ Ip4Address vmIp = getFixedIpAddressForPort(port.annotations().value("portName"));
+ if (vmIp != null) {
+ rulePopulator.populateForwardingRule(vmIp, device.id(), port, cidr);
+ }
+ }
+
+ /**
+ * Updates the port maps using the port information.
+ *
+ * @param device device info
+ * @param port port of the VM
+ */
+ private void updatePortMaps(Device device, Port port) {
+ String portName = port.annotations().value("portName");
+ String channelId = device.annotations().value("channelId");
+ Ip4Address hostIpAddress = Ip4Address.valueOf(channelId.split(":")[0]);
+ if (portName.startsWith("vxlan")) {
+ tunnelPortMap.put(hostIpAddress, port);
+ } else {
+ String vni = getVniForPort(portName);
+ Ip4Address fixedIp = getFixedIpAddressForPort(portName);
+ if (vniPortMap.get(vni) == null) {
+ vniPortMap.put(vni, Lists.newArrayList());
+ }
+ vniPortMap.get(vni).add(new PortInfo(device.id(), portName, fixedIp, hostIpAddress));
+ }
+ }
+
+ /**
+ * Returns CIDR information from the subnet map for the port.
+ *
+ * @param portName port name of the port of the VM
+ * @return CIDR of the VNI of the VM
+ */
+ private Ip4Prefix getCidrForPort(String portName) {
+ String networkId = null;
+ String uuid = portName.substring(3);
+ OpenstackPort port = openstackPortMap.values().stream()
+ .filter(p -> p.id().startsWith(uuid))
+ .findFirst().get();
+ if (port == null) {
+ log.debug("No port information for port {}", portName);
+ return null;
+ }
+
+ OpenstackSubnet subnet = openstackSubnetMap.values().stream()
+ .filter(s -> s.networkId().equals(port.networkId()))
+ .findFirst().get();
+ if (subnet == null) {
+ log.debug("No subnet information for network {}", port.networkId());
+ return null;
+ }
+
+ return Ip4Prefix.valueOf(subnet.cidr());
+ }
+
+ /**
+ * Returns the VNI of the VM of the port.
+ *
+ * @param portName VM port
+ * @return VNI
+ */
+ private String getVniForPort(String portName) {
+ String networkId = null;
+ String uuid = portName.substring(3);
+ OpenstackPort port = openstackPortMap.values().stream()
+ .filter(p -> p.id().startsWith(uuid))
+ .findFirst().get();
+ if (port == null) {
+ log.debug("No port information for port {}", portName);
+ return null;
+ }
+ OpenstackNetwork network = openstackNetworkMap.values().stream()
+ .filter(n -> n.id().equals(port.networkId()))
+ .findFirst().get();
+ if (network == null) {
+ log.debug("No VNI information for network {}", network.id());
+ return null;
+ }
+
+ return network.segmentId();
+ }
+
+ /**
+ * Returns the Fixed IP address of the VM.
+ *
+ * @param portName VM port info
+ * @return IP address of the VM
+ */
+ private Ip4Address getFixedIpAddressForPort(String portName) {
+
+ // FIXME - For now we use the information stored from neutron Rest API call.
+ // TODO - Later, the information needs to be extracted from Neutron on-demand.
+ String uuid = portName.substring(3);
+ OpenstackPort port = openstackPortMap.values().stream()
+ .filter(p -> p.id().startsWith(uuid))
+ .findFirst().get();
+
+ if (port == null) {
+ log.error("There is no port information for port name {}", portName);
+ return null;
+ }
+
+ if (port.fixedIps().isEmpty()) {
+ log.error("There is no fixed IP info in the port information");
+ return null;
+ }
+
+ return (Ip4Address) port.fixedIps().values().toArray()[0];
+ }
+
+ /**
+ * Returns the MAC address of the VM of the port.
+ *
+ * @param portName VM port
+ * @return MAC address of the VM
+ */
+ private MacAddress getVmMacAddressForPort(String portName) {
+
+ String uuid = portName.substring(3);
+ OpenstackPort port = openstackPortMap.values().stream()
+ .filter(p -> p.id().startsWith(uuid))
+ .findFirst().get();
+
+ if (port == null) {
+ log.error("There is no mac information for port name {}", portName);
+ return null;
+ }
+
+ return port.macAddress();
+ }
+
+ private class InternalPacketProcessor implements PacketProcessor {
+
+ @Override
+ public void process(PacketContext context) {
+
+ if (context.isHandled()) {
+ return;
+ }
+
+ InboundPacket pkt = context.inPacket();
+ Ethernet ethernet = pkt.parsed();
+
+ if (ethernet.getEtherType() == Ethernet.TYPE_ARP) {
+ arpHandler.processPacketIn(pkt);
+ }
+ }
+ }
+
+ private class InternalDeviceListener implements DeviceListener {
+
+ @Override
+ public void event(DeviceEvent deviceEvent) {
+ deviceEventExcutorService.execute(new InternalEventHandler(deviceEvent));
+ }
+ }
+
+ private class InternalEventHandler implements Runnable {
+
+ volatile DeviceEvent deviceEvent;
+
+ InternalEventHandler(DeviceEvent deviceEvent) {
+ this.deviceEvent = deviceEvent;
+ }
+
+ @Override
+ public void run() {
+
+ if (doNotPushFlows) {
+ return;
+ }
+
+ switch (deviceEvent.type()) {
+ case DEVICE_ADDED:
+ processDeviceAdded((Device) deviceEvent.subject());
+ break;
+ case DEVICE_UPDATED:
+ Port port = (Port) deviceEvent.subject();
+ if (port.isEnabled()) {
+ processPortAdded((Device) deviceEvent.subject(), deviceEvent.port());
+ }
+ break;
+ case DEVICE_AVAILABILITY_CHANGED:
+ Device device = (Device) deviceEvent.subject();
+ if (deviceService.isAvailable(device.id())) {
+ processDeviceAdded(device);
+ }
+ break;
+ case PORT_ADDED:
+ processPortAdded((Device) deviceEvent.subject(), deviceEvent.port());
+ break;
+ case PORT_UPDATED:
+ processPortAdded((Device) deviceEvent.subject(), deviceEvent.port());
+ break;
+ case PORT_REMOVED:
+ processPortRemoved((Device) deviceEvent.subject(), deviceEvent.port());
+ break;
+ default:
+ break;
+ }
+ }
+ }
+
+ private class InternalConfigListener implements NetworkConfigListener {
+
+ @Override
+ public void event(NetworkConfigEvent event) {
+ if (((event.type() == NetworkConfigEvent.Type.CONFIG_ADDED ||
+ event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED)) &&
+ event.configClass().equals(OpenstackSwitchingConfig.class)) {
+ OpenstackSwitchingConfig cfg = cfgService.getConfig(appId,
+ OpenstackSwitchingConfig.class);
+ if (cfg != null) {
+ doNotPushFlows = cfg.doNotPushFlows();
+ log.info("Switching mode reconfigured");
+ }
+ }
+ }
+ }
+
+ private final class PortInfo {
+ DeviceId deviceId;
+ String portName;
+ Ip4Address fixedIp;
+ Ip4Address hostIp;
+
+ private PortInfo(DeviceId deviceId, String portName, Ip4Address fixedIp,
+ Ip4Address hostIp) {
+ this.deviceId = deviceId;
+ this.portName = portName;
+ this.fixedIp = fixedIp;
+ this.hostIp = hostIp;
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/OpenstackSwitchingRulePopulator.java b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/OpenstackSwitchingRulePopulator.java
new file mode 100644
index 0000000..fa0b7e6
--- /dev/null
+++ b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/OpenstackSwitchingRulePopulator.java
@@ -0,0 +1,226 @@
+/*
+* 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.openstackswitching;
+
+import org.onlab.packet.Ethernet;
+import org.onlab.packet.IPv4;
+import org.onlab.packet.Ip4Address;
+import org.onlab.packet.Ip4Prefix;
+import org.onlab.packet.MacAddress;
+import org.onlab.packet.TpPort;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.Port;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.flow.DefaultTrafficSelector;
+import org.onosproject.net.flow.DefaultTrafficTreatment;
+import org.onosproject.net.flow.TrafficSelector;
+import org.onosproject.net.flow.TrafficTreatment;
+import org.onosproject.net.flowobjective.DefaultForwardingObjective;
+import org.onosproject.net.flowobjective.FlowObjectiveService;
+import org.onosproject.net.flowobjective.ForwardingObjective;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Populates switching flow rules.
+ */
+public class OpenstackSwitchingRulePopulator {
+
+ private static Logger log = LoggerFactory
+ .getLogger(OpenstackSwitchingRulePopulator.class);
+
+ private FlowObjectiveService flowObjectiveService;
+ private ApplicationId appId;
+
+ /**
+ * Creates OpenstackSwitchingRulPopulator.
+ *
+ * @param appId application id
+ * @param flowObjectiveService FlowObjectiveService reference
+ */
+ public OpenstackSwitchingRulePopulator(ApplicationId appId,
+ FlowObjectiveService flowObjectiveService) {
+ this.flowObjectiveService = flowObjectiveService;
+ this.appId = appId;
+ }
+
+ /**
+ * Populates flows rules for forwarding packets to and from VMs.
+ *
+ * @param ip v4 IP Address
+ * @param id device ID
+ * @param port port
+ * @param cidr v4 IP prefix
+ * @return true if it succeeds to populate rules, false otherwise.
+ */
+ public boolean populateForwardingRule(Ip4Address ip, DeviceId id, Port port, Ip4Prefix cidr) {
+
+
+ setFlowRuleForVMsInSameCnode(ip, id, port, cidr);
+
+ return true;
+ }
+
+ /**
+ * Populates the common flows rules for all VMs.
+ *
+ * - Send ARP packets to the controller
+ * - Send DHCP packets to the controller
+ *
+ * @param id Device ID to populates rules to
+ */
+ public void populateDefaultRules(DeviceId id) {
+
+ setFlowRuleForArp(id);
+
+ log.warn("Default rule has been set");
+ }
+
+ /**
+ * Populates the forwarding rules for VMs with the same VNI but in other Code.
+ *
+ * @param vni VNI for the networks
+ * @param id device ID to populates the flow rules
+ * @param hostIp host IP address of the VM
+ * @param vmIp fixed IP address for the VM
+ * @param vmMac MAC address for the VM
+ * @param tunnelPort tunnel port number for the VM
+ * @param idx device ID for OVS of the other VM
+ * @param hostIpx host IP address of the other VM
+ * @param vmIpx fixed IP address of the other VM
+ * @param vmMacx MAC address for the other VM
+ * @param tunnelPortx x tunnel port number for other VM
+ */
+ public void populateForwardingRuleForOtherCnode(String vni, DeviceId id, Ip4Address hostIp,
+ Ip4Address vmIp, MacAddress vmMac, PortNumber tunnelPort,
+ DeviceId idx, Ip4Address hostIpx,
+ Ip4Address vmIpx, MacAddress vmMacx, PortNumber tunnelPortx) {
+ setVxLanFlowRule(vni, id, hostIp, vmIp, vmMac, tunnelPort);
+ setVxLanFlowRule(vni, idx, hostIpx, vmIpx, vmMacx, tunnelPortx);
+ }
+
+ /**
+ * Populates the flow rules for DHCP packets from VMs.
+ *
+ * @param id device ID to set the rules
+ */
+ private void setFlowRuleForDhcp(DeviceId id) {
+ TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
+
+ sBuilder.matchEthType(Ethernet.TYPE_IPV4)
+ .matchIPProtocol(IPv4.PROTOCOL_UDP)
+ .matchUdpDst(TpPort.tpPort(OpenstackSwitchingManager.DHCP_PORT));
+ tBuilder.setOutput(PortNumber.CONTROLLER);
+
+ ForwardingObjective fo = DefaultForwardingObjective.builder()
+ .withSelector(sBuilder.build())
+ .withTreatment(tBuilder.build())
+ .withPriority(5000)
+ .withFlag(ForwardingObjective.Flag.VERSATILE)
+ .fromApp(appId)
+ .add();
+
+ flowObjectiveService.forward(id, fo);
+ }
+
+ /**
+ * Populates the flow rules for ARP packets from VMs.
+ *
+ * @param id device ID to put rules.
+ */
+ private void setFlowRuleForArp(DeviceId id) {
+ TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
+
+ sBuilder.matchEthType(Ethernet.TYPE_ARP);
+ tBuilder.setOutput(PortNumber.CONTROLLER);
+
+ ForwardingObjective fo = DefaultForwardingObjective.builder()
+ .withSelector(sBuilder.build())
+ .withTreatment(tBuilder.build())
+ .withPriority(5000)
+ .withFlag(ForwardingObjective.Flag.VERSATILE)
+ .fromApp(appId)
+ .add();
+
+ flowObjectiveService.forward(id, fo);
+ }
+
+ /**
+ * Sets the flow rules for traffic between VMs in the same Cnode.
+ *
+ * @param ip4Address VM IP address
+ * @param id device ID to put rules
+ * @param port VM port
+ * @param cidr subnet info of the VMs
+ */
+ private void setFlowRuleForVMsInSameCnode(Ip4Address ip4Address, DeviceId id,
+ Port port, Ip4Prefix cidr) {
+ TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
+
+ sBuilder.matchEthType(Ethernet.TYPE_IPV4)
+ .matchIPDst(ip4Address.toIpPrefix())
+ .matchIPSrc(cidr);
+ tBuilder.setOutput(port.number());
+
+ ForwardingObjective fo = DefaultForwardingObjective.builder()
+ .withSelector(sBuilder.build())
+ .withTreatment(tBuilder.build())
+ .withPriority(5000)
+ .withFlag(ForwardingObjective.Flag.VERSATILE)
+ .fromApp(appId)
+ .add();
+
+ flowObjectiveService.forward(id, fo);
+ }
+
+ /**
+ * Sets the flow rules between traffic from VMs in different Cnode.
+ *
+ * @param vni VNI
+ * @param id device ID
+ * @param hostIp host IP of the VM
+ * @param vmIp fixed IP of the VM
+ * @param vmMac MAC address of the VM
+ * @param tunnelPort tunnel port to forward traffic to
+ */
+ private void setVxLanFlowRule(String vni, DeviceId id, Ip4Address hostIp,
+ Ip4Address vmIp, MacAddress vmMac, PortNumber tunnelPort) {
+ TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
+ TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
+
+ sBuilder.matchEthType(Ethernet.TYPE_IPV4)
+ .matchIPDst(vmIp.toIpPrefix());
+ tBuilder.setTunnelId(Long.parseLong(vni))
+ //.setTunnelDst() <- for Nicira ext
+ //.setEthDst(vmMac)
+ .setOutput(tunnelPort);
+
+ ForwardingObjective fo = DefaultForwardingObjective.builder()
+ .withSelector(sBuilder.build())
+ .withTreatment(tBuilder.build())
+ .withPriority(5000)
+ .withFlag(ForwardingObjective.Flag.VERSATILE)
+ .fromApp(appId)
+ .add();
+
+ flowObjectiveService.forward(id, fo);
+ }
+}
diff --git a/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/package-info.java b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/package-info.java
new file mode 100644
index 0000000..cd50f91
--- /dev/null
+++ b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * 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.
+ */
+
+/**
+ * OpenStack switch interface.
+ */
+package org.onosproject.openstackswitching;
diff --git a/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/web/OpenstackNetworkCodec.java b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/web/OpenstackNetworkCodec.java
new file mode 100644
index 0000000..fc1509d
--- /dev/null
+++ b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/web/OpenstackNetworkCodec.java
@@ -0,0 +1,66 @@
+/*
+ * 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.openstackswitching.web;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.onosproject.codec.CodecContext;
+import org.onosproject.codec.JsonCodec;
+import org.onosproject.openstackswitching.OpenstackNetwork;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Implementation of the OpenstackNetwork Codec.
+ *
+ */
+public class OpenstackNetworkCodec extends JsonCodec<OpenstackNetwork> {
+
+ protected static final Logger log = LoggerFactory
+ .getLogger(OpenstackNetworkCodec.class);
+
+ private static final String NETWORK = "network";
+ private static final String NAME = "name";
+ private static final String TENANT_ID = "tenant_id";
+ private static final String SEGMENTATION_ID = "provider:segmentation_id";
+ private static final String NETWORK_TYPE = "provider:network_type";
+ private static final String ID = "id";
+
+ @Override
+ public OpenstackNetwork decode(ObjectNode json, CodecContext context) {
+
+ JsonNode networkInfo = json.get(NETWORK);
+
+ String name = networkInfo.path(NAME).asText();
+ String tenantId = networkInfo.path(TENANT_ID).asText();
+ String id = networkInfo.path(ID).asText();
+
+ OpenstackNetwork.Builder onb = OpenstackNetwork.builder();
+ onb.name(name)
+ .tenantId(tenantId)
+ .id(id);
+
+ if (!networkInfo.path(NETWORK_TYPE).isMissingNode()) {
+ onb.networkType(OpenstackNetwork.NetworkType.valueOf(networkInfo.path(NETWORK_TYPE).
+ asText().toUpperCase()));
+ onb.name(networkInfo.path(NETWORK_TYPE).asText());
+ onb.segmentId(networkInfo.path(SEGMENTATION_ID).asText());
+ }
+
+ return onb.build();
+ }
+
+}
diff --git a/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/web/OpenstackNetworkWebResource.java b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/web/OpenstackNetworkWebResource.java
new file mode 100644
index 0000000..f4c401f
--- /dev/null
+++ b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/web/OpenstackNetworkWebResource.java
@@ -0,0 +1,62 @@
+/*
+ * 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.openstackswitching.web;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.onosproject.openstackswitching.OpenstackNetwork;
+import org.onosproject.openstackswitching.OpenstackSwitchingService;
+import org.onosproject.rest.AbstractWebResource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.io.InputStream;
+
+@Path("networks")
+public class OpenstackNetworkWebResource extends AbstractWebResource {
+
+ protected static final Logger log = LoggerFactory
+ .getLogger(OpenstackNetworkWebResource.class);
+
+ private static final OpenstackNetworkCodec NETWORK_CODEC = new OpenstackNetworkCodec();
+
+ @POST
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response createNetwork(InputStream input) {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ ObjectNode networkNode = (ObjectNode) mapper.readTree(input);
+
+ OpenstackNetwork openstackNetwork = NETWORK_CODEC.decode(networkNode, this);
+
+ OpenstackSwitchingService switchingService = get(OpenstackSwitchingService.class);
+ switchingService.createNetwork(openstackNetwork);
+ return Response.status(Response.Status.OK).build();
+ } catch (Exception e) {
+ log.error("Creates VirtualPort failed because of exception {}",
+ e.toString());
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.toString())
+ .build();
+ }
+ }
+}
diff --git a/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/web/OpenstackPortCodec.java b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/web/OpenstackPortCodec.java
new file mode 100644
index 0000000..94a1edb
--- /dev/null
+++ b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/web/OpenstackPortCodec.java
@@ -0,0 +1,104 @@
+/*
+ * 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.openstackswitching.web;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.onlab.packet.Ip4Address;
+import org.onlab.packet.MacAddress;
+import org.onosproject.codec.CodecContext;
+import org.onosproject.codec.JsonCodec;
+import org.onosproject.openstackswitching.OpenstackPort;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.HashMap;
+
+/**
+ * Encodes and decodes the OpenstackPort.
+ */
+public class OpenstackPortCodec extends JsonCodec<OpenstackPort> {
+
+ private static Logger log = LoggerFactory
+ .getLogger(OpenstackPortCodec.class);
+
+ // JSON field names
+ private static final String PORT = "port";
+ private static final String STATUS = "status";
+ private static final String NAME = "name";
+ private static final String ADDRESS_PAIR = "allowed_address_pairs";
+ private static final String ADMIN_STATUS = "admin_status";
+ private static final String NETWORK_ID = "network_id";
+ private static final String TENANT_ID = "tenant_id";
+ private static final String DEVICE_OWNER = "device_owner";
+ private static final String MAC_ADDRESS = "mac_address";
+ private static final String FIXED_IPS = "fixed_ips";
+ private static final String SUBNET_ID = "subnet_id";
+ private static final String IP_ADDRESS = "ip_address";
+ private static final String ID = "id";
+ private static final String SECURITY_GROUPS = "security_groups";
+ private static final String DEVICE_ID = "device_id";
+
+ @Override
+ public OpenstackPort decode(ObjectNode json, CodecContext context) {
+
+ HashMap<String, Ip4Address> fixedIpMap = new HashMap<>();
+ JsonNode portInfo = json.get(PORT);
+
+ String status = portInfo.path(STATUS).asText();
+ String name = portInfo.path(NAME).asText();
+ boolean adminStateUp = portInfo.path(ADMIN_STATUS).asBoolean();
+ String networkId = portInfo.path(NETWORK_ID).asText();
+ String tenantId = portInfo.path(TENANT_ID).asText();
+ String deviceOwner = portInfo.path(DEVICE_OWNER).asText();
+ String macStr = portInfo.path(MAC_ADDRESS).asText();
+ ArrayNode fixedIpList = (ArrayNode) portInfo.path(FIXED_IPS);
+ for (JsonNode fixedIpInfo: fixedIpList) {
+ String subnetId = fixedIpInfo.path(SUBNET_ID).asText();
+ String ipAddressStr = fixedIpInfo.path(IP_ADDRESS).asText();
+ if (ipAddressStr != null) {
+ Ip4Address ipAddress = Ip4Address.valueOf(ipAddressStr);
+ fixedIpMap.put(subnetId, ipAddress);
+ }
+ }
+ String id = portInfo.path(ID).asText();
+ String securityGroups = portInfo.path(SECURITY_GROUPS).asText();
+ String deviceId = portInfo.path(DEVICE_ID).asText();
+
+ OpenstackPort.Builder openstackPortBuilder = OpenstackPort.builder();
+ openstackPortBuilder.portStatus(OpenstackPort.PortStatus.valueOf(status))
+ .name(name)
+ .adminState(adminStateUp)
+ .netwrokId(networkId)
+ .tenantId(tenantId)
+ .deviceOwner(deviceOwner)
+ .macAddress(MacAddress.valueOf(macStr))
+ .fixedIps(fixedIpMap)
+ .id(id)
+ .deviceId(deviceId);
+
+ // FIX ME
+ if (!securityGroups.isEmpty()) {
+ openstackPortBuilder.securityGroup(securityGroups);
+ }
+
+ OpenstackPort openstackPort = openstackPortBuilder.build();
+
+ return openstackPort;
+ }
+
+}
diff --git a/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/web/OpenstackPortWebResource.java b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/web/OpenstackPortWebResource.java
new file mode 100644
index 0000000..e531ba4
--- /dev/null
+++ b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/web/OpenstackPortWebResource.java
@@ -0,0 +1,106 @@
+/*
+ * 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.openstackswitching.web;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.onosproject.openstackswitching.OpenstackPort;
+import org.onosproject.openstackswitching.OpenstackSwitchingService;
+import org.onosproject.rest.AbstractWebResource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.io.InputStream;
+
+@Path("ports")
+public class OpenstackPortWebResource extends AbstractWebResource {
+
+ protected static final Logger log = LoggerFactory
+ .getLogger(OpenstackPortWebResource.class);
+
+ private static final OpenstackPortCodec PORT_CODEC = new OpenstackPortCodec();
+
+ @POST
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response createPorts(InputStream input) {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ ObjectNode portNode = (ObjectNode) mapper.readTree(input);
+
+ OpenstackPort openstackPort = PORT_CODEC.decode(portNode, this);
+
+ OpenstackSwitchingService switchingService = get(OpenstackSwitchingService.class);
+ switchingService.createPorts(openstackPort);
+ log.debug("REST API ports is called with {}", portNode.toString());
+ return Response.status(Response.Status.OK).build();
+ } catch (Exception e) {
+ log.error("Creates VirtualPort failed because of exception {}",
+ e.toString());
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.toString())
+ .build();
+ }
+ }
+
+ @DELETE
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response deletesPorts(InputStream input) {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ ObjectNode portNode = (ObjectNode) mapper.readTree(input);
+
+ OpenstackSwitchingService switchingService = get(OpenstackSwitchingService.class);
+ switchingService.deletePorts();
+ log.info("REST API ports is called with {}", portNode.toString());
+ return Response.status(Response.Status.OK).build();
+ } catch (Exception e) {
+ log.error("Delete VirtualPort failed because of exception {}",
+ e.toString());
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.toString())
+ .build();
+ }
+ }
+
+ @PUT
+ @Path("{id}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response updatePorts(InputStream input) {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ ObjectNode portNode = (ObjectNode) mapper.readTree(input);
+
+ OpenstackSwitchingService switchingService = get(OpenstackSwitchingService.class);
+ switchingService.updatePorts();
+ log.info("REST API ports is called with {}", portNode.toString());
+ return Response.status(Response.Status.OK).build();
+ } catch (Exception e) {
+ log.error("Update VirtualPort failed because of exception {}",
+ e.toString());
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.toString())
+ .build();
+ }
+ }
+}
diff --git a/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/web/OpenstackSubnetCodec.java b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/web/OpenstackSubnetCodec.java
new file mode 100644
index 0000000..e504550
--- /dev/null
+++ b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/web/OpenstackSubnetCodec.java
@@ -0,0 +1,80 @@
+/*
+ * 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.openstackswitching.web;
+
+import com.fasterxml.jackson.databind.JsonNode;
+
+
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.google.common.collect.Lists;
+import org.onlab.packet.Ip4Address;
+import org.onosproject.codec.CodecContext;
+import org.onosproject.codec.JsonCodec;
+import org.onosproject.openstackswitching.OpenstackSubnet;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+
+/**
+ * Encodes and decodes the OpenstackSubnet.
+ */
+public class OpenstackSubnetCodec extends JsonCodec<OpenstackSubnet> {
+ private static Logger log = LoggerFactory
+ .getLogger(OpenstackSubnetCodec.class);
+
+ // JSON Field names
+ private static final String SUBNET = "subnet";
+ private static final String NAME = "name";
+ private static final String ENABLE_DHCP = "enable_dhcp";
+ private static final String NETWORK_ID = "network_id";
+ private static final String TENANT_ID = "tenant_id";
+ private static final String DNS_NAMESERVERS = "dns_nameservers";
+ private static final String GATEWAY_IP = "gateway_ip";
+ private static final String CIDR = "cidr";
+ private static final String ID = "id";
+
+ @Override
+ public OpenstackSubnet decode(ObjectNode json, CodecContext context) {
+ JsonNode subnetInfo = json.get(SUBNET);
+
+ String name = subnetInfo.path(NAME).asText();
+ boolean enableDhcp = subnetInfo.path(ENABLE_DHCP).asBoolean();
+ String networkId = subnetInfo.path(NETWORK_ID).asText();
+ String tenantId = subnetInfo.path(TENANT_ID).asText();
+ ArrayNode dnsNameservsers = (ArrayNode) subnetInfo.path(DNS_NAMESERVERS);
+ List<Ip4Address> dnsList = Lists.newArrayList();
+ if (dnsNameservsers != null && !dnsNameservsers.isMissingNode()) {
+ dnsNameservsers.forEach(dns -> dnsList.add(Ip4Address.valueOf(dns.asText())));
+ }
+ String gatewayIp = subnetInfo.path(GATEWAY_IP).asText();
+ String cidr = subnetInfo.path(CIDR).asText();
+ String id = subnetInfo.path(ID).asText();
+
+ OpenstackSubnet openstackSubnet = OpenstackSubnet.builder()
+ .setName(name)
+ .setEnableDhcp(enableDhcp)
+ .setNetworkId(networkId)
+ .setTenantId(tenantId)
+ .setDnsNameservers(dnsList)
+ .setGatewayIp(gatewayIp)
+ .setCidr(cidr)
+ .setId(id)
+ .build();
+ return openstackSubnet;
+ }
+}
diff --git a/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/web/OpenstackSubnetWebResource.java b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/web/OpenstackSubnetWebResource.java
new file mode 100644
index 0000000..bc0bb8e
--- /dev/null
+++ b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/web/OpenstackSubnetWebResource.java
@@ -0,0 +1,64 @@
+/*
+ * 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.openstackswitching.web;
+
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.onosproject.openstackswitching.OpenstackSubnet;
+import org.onosproject.openstackswitching.OpenstackSwitchingService;
+import org.onosproject.rest.AbstractWebResource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.io.InputStream;
+
+@Path("subnets")
+public class OpenstackSubnetWebResource extends AbstractWebResource {
+ protected static final Logger log = LoggerFactory
+ .getLogger(OpenstackSubnetWebResource.class);
+
+ private static final OpenstackSubnetCodec SUBNET_CODEC = new OpenstackSubnetCodec();
+
+ @POST
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response createSubnet(InputStream input) {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ ObjectNode subnetNode = (ObjectNode) mapper.readTree(input);
+
+ OpenstackSubnet openstackSubnet = SUBNET_CODEC.decode(subnetNode, this);
+
+ OpenstackSwitchingService switchingService = get(OpenstackSwitchingService.class);
+ switchingService.createSubnet(openstackSubnet);
+ log.debug("REST API subnets is called with {}", subnetNode.toString());
+ return Response.status(Response.Status.OK).build();
+ } catch (Exception e) {
+ log.error("Creates VirtualSubnet failed because of exception {}",
+ e.toString());
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.toString())
+ .build();
+ }
+ }
+
+}
diff --git a/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/web/package-info.java b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/web/package-info.java
new file mode 100644
index 0000000..91e19c6
--- /dev/null
+++ b/apps/openstackswitching/app/src/main/java/org/onosproject/openstackswitching/web/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * 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.
+ */
+
+/**
+ * OpenStack switching REST API.
+ */
+package org.onosproject.openstackswitching.web;
diff --git a/apps/openstackswitching/app/src/main/webapp/WEB-INF/web.xml b/apps/openstackswitching/app/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000..4f50ef7
--- /dev/null
+++ b/apps/openstackswitching/app/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,45 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ 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.
+ -->
+<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
+ xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
+ id="ONOS" version="2.5">
+ <display-name>Openstack Switching REST API v1.0</display-name>
+
+ <servlet>
+ <servlet-name>JAX-RS Service</servlet-name>
+ <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
+ <init-param>
+ <param-name>com.sun.jersey.config.property.resourceConfigClass</param-name>
+ <param-value>com.sun.jersey.api.core.ClassNamesResourceConfig</param-value>
+ </init-param>
+ <init-param>
+ <param-name>com.sun.jersey.config.property.classnames</param-name>
+ <param-value>
+ org.onosproject.openstackswitching.web.OpenstackPortWebResource,
+ org.onosproject.openstackswitching.web.OpenstackNetworkWebResource,
+ org.onosproject.openstackswitching.web.OpenstackSubnetWebResource
+ </param-value>
+ </init-param>
+ <load-on-startup>1</load-on-startup>
+ </servlet>
+
+ <servlet-mapping>
+ <servlet-name>JAX-RS Service</servlet-name>
+ <url-pattern>/*</url-pattern>
+ </servlet-mapping>
+</web-app>