Refactoring datastore package
Preparation to make datastore replacable
- Extract datastore interfaces
- Add multi Read/Write/Remove
- Add a method to walk over RCTable
- Refactor serialize/deserialize RCObject
- Localize dependency to JRAMCloud
- Separate RAMCloud specific code into ramcloud package
- Remove dependency to RAMCloud exception classes
- Remove RC prefix from non RAMCloud specific code
- Cosmetics and update sample/test code
- reflect Naoki's comment
- more cosmetic fixes
- reordered OPERATION enums
- removed no longer used code
- follow pmd, etc. where easily possible
Change-Id: I6f9153d705600447acf48a64f713c654c9f26713
diff --git a/src/main/java/net/onrc/onos/datastore/topology/KVDevice.java b/src/main/java/net/onrc/onos/datastore/topology/KVDevice.java
new file mode 100644
index 0000000..105f6f7
--- /dev/null
+++ b/src/main/java/net/onrc/onos/datastore/topology/KVDevice.java
@@ -0,0 +1,202 @@
+package net.onrc.onos.datastore.topology;
+
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
+import net.onrc.onos.datastore.DataStoreClient;
+import net.onrc.onos.datastore.IKVTable.IKVEntry;
+import net.onrc.onos.datastore.topology.KVLink.STATUS;
+import net.onrc.onos.datastore.utils.ByteArrayComparator;
+import net.onrc.onos.datastore.utils.ByteArrayUtil;
+import net.onrc.onos.datastore.utils.KVObject;
+import net.onrc.onos.ofcontroller.networkgraph.DeviceEvent;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.esotericsoftware.kryo.Kryo;
+
+/**
+ * Device object.
+ *
+ * TODO switch to ProtoBuf, etc.
+ */
+public class KVDevice extends KVObject {
+ private static final Logger log = LoggerFactory.getLogger(KVDevice.class);
+
+ private static final ThreadLocal<Kryo> deviceKryo = new ThreadLocal<Kryo>() {
+ @Override
+ protected Kryo initialValue() {
+ Kryo kryo = new Kryo();
+ kryo.setRegistrationRequired(true);
+ kryo.setReferences(false);
+ kryo.register(byte[].class);
+ kryo.register(byte[][].class);
+ kryo.register(HashMap.class);
+ // TODO check if we should explicitly specify EnumSerializer
+ kryo.register(STATUS.class);
+ return kryo;
+ }
+ };
+
+ public static final String GLOBAL_DEVICE_TABLE_NAME = "G:Device";
+
+ // FIXME these should be Enum or some number, not String
+ private static final String PROP_MAC = "mac";
+ private static final String PROP_PORT_IDS = "port-ids";
+
+ private final byte[] mac;
+ private TreeSet<byte[]> portIds;
+ private transient boolean isPortIdsModified;
+
+ // Assuming mac is unique cluster-wide
+ public static byte[] getDeviceID(final byte[] mac) {
+ return DeviceEvent.getDeviceID(mac).array();
+ }
+
+ public static byte[] getMacFromKey(final byte[] key) {
+ ByteBuffer keyBuf = ByteBuffer.wrap(key);
+ if (keyBuf.getChar() != 'D') {
+ throw new IllegalArgumentException("Invalid Device key");
+ }
+ byte[] mac = new byte[keyBuf.remaining()];
+ keyBuf.get(mac);
+ return mac;
+ }
+
+ public KVDevice(final byte[] mac) {
+ super(DataStoreClient.getClient().getTable(GLOBAL_DEVICE_TABLE_NAME), getDeviceID(mac));
+
+ this.mac = mac;
+ this.portIds = new TreeSet<>(ByteArrayComparator.BYTEARRAY_COMPARATOR);
+ this.isPortIdsModified = true;
+ }
+
+ /**
+ * Get an instance from Key.
+ *
+ * @note You need to call `read()` to get the DB content.
+ * @param key
+ * @return
+ */
+ public static KVDevice createFromKey(final byte[] key) {
+ return new KVDevice(getMacFromKey(key));
+ }
+
+ public static Iterable<KVDevice> getAllDevices() {
+ return new DeviceEnumerator();
+ }
+
+ public static class DeviceEnumerator implements Iterable<KVDevice> {
+
+ @Override
+ public Iterator<KVDevice> iterator() {
+ return new DeviceIterator();
+ }
+ }
+
+ public static class DeviceIterator extends AbstractObjectIterator<KVDevice> {
+
+ public DeviceIterator() {
+ super(DataStoreClient.getClient().getTable(GLOBAL_DEVICE_TABLE_NAME));
+ }
+
+ @Override
+ public KVDevice next() {
+ IKVEntry o = enumerator.next();
+ KVDevice e = KVDevice.createFromKey(o.getKey());
+ e.deserialize(o.getValue(), o.getVersion());
+ return e;
+ }
+ }
+
+ public byte[] getMac() {
+ // TODO may need to clone() to be sure this object will be immutable.
+ return mac;
+ }
+
+ public byte[] getId() {
+ return getKey();
+ }
+
+ public void addPortId(final byte[] portId) {
+ // TODO: Should we copy portId, or reference is OK.
+ isPortIdsModified |= portIds.add(portId);
+ }
+
+ public void removePortId(final byte[] portId) {
+ isPortIdsModified |= portIds.remove(portId);
+ }
+
+ public void emptyPortIds() {
+ portIds.clear();
+ this.isPortIdsModified = true;
+ }
+
+ public void addAllToPortIds(final Collection<byte[]> portIds) {
+ // TODO: Should we copy portId, or reference is OK.
+ isPortIdsModified |= this.portIds.addAll(portIds);
+ }
+
+ /**
+ *
+ * @return Unmodifiable Set view of all the PortIds;
+ */
+ public Set<byte[]> getAllPortIds() {
+ return Collections.unmodifiableSet(portIds);
+ }
+
+ @Override
+ public byte[] serialize() {
+ Map<Object, Object> map = getPropertyMap();
+
+ map.put(PROP_MAC, mac);
+ if (isPortIdsModified) {
+ byte[][] portIdArray = new byte[portIds.size()][];
+ map.put(PROP_PORT_IDS, portIds.toArray(portIdArray));
+ isPortIdsModified = false;
+ }
+
+ return serializePropertyMap(deviceKryo.get(), map);
+ }
+
+ @Override
+ protected boolean deserialize(final byte[] bytes) {
+ boolean success = deserializePropertyMap(deviceKryo.get(), bytes);
+ if (!success) {
+ log.error("Deserializing Link: " + this + " failed.");
+ return false;
+ }
+ Map<Object, Object> map = this.getPropertyMap();
+
+ if (this.portIds == null) {
+ this.portIds = new TreeSet<>(
+ ByteArrayComparator.BYTEARRAY_COMPARATOR);
+ }
+ byte[][] portIdArray = (byte[][]) map.get(PROP_PORT_IDS);
+ if (portIdArray != null) {
+ this.portIds.clear();
+ this.portIds.addAll(Arrays.asList(portIdArray));
+ isPortIdsModified = false;
+ } else {
+ // trigger write on next serialize
+ isPortIdsModified = true;
+ }
+
+ return success;
+ }
+
+ @Override
+ public String toString() {
+ // TODO output all properties?
+ return "[" + this.getClass().getSimpleName()
+ + " " + ByteArrayUtil.toHexStringBuffer(mac, ":") + "]";
+ }
+}
diff --git a/src/main/java/net/onrc/onos/datastore/topology/KVLink.java b/src/main/java/net/onrc/onos/datastore/topology/KVLink.java
new file mode 100644
index 0000000..c9273ae
--- /dev/null
+++ b/src/main/java/net/onrc/onos/datastore/topology/KVLink.java
@@ -0,0 +1,217 @@
+package net.onrc.onos.datastore.topology;
+
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import net.onrc.onos.datastore.DataStoreClient;
+import net.onrc.onos.datastore.IKVTable.IKVEntry;
+import net.onrc.onos.datastore.RCProtos.LinkProperty;
+import net.onrc.onos.datastore.utils.KVObject;
+import net.onrc.onos.ofcontroller.networkgraph.LinkEvent;
+import net.onrc.onos.ofcontroller.networkgraph.PortEvent;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.esotericsoftware.kryo.Kryo;
+import com.google.protobuf.ByteString;
+import com.google.protobuf.InvalidProtocolBufferException;
+
+/**
+ * Link object in data store.
+ */
+public class KVLink extends KVObject {
+ private static final Logger log = LoggerFactory.getLogger(KVLink.class);
+
+ private static final ThreadLocal<Kryo> linkKryo = new ThreadLocal<Kryo>() {
+ @Override
+ protected Kryo initialValue() {
+ Kryo kryo = new Kryo();
+ kryo.setRegistrationRequired(true);
+ kryo.setReferences(false);
+ kryo.register(byte[].class);
+ kryo.register(byte[][].class);
+ kryo.register(HashMap.class);
+ // TODO check if we should explicitly specify EnumSerializer
+ kryo.register(STATUS.class);
+ return kryo;
+ }
+ };
+
+ public static class SwitchPort {
+ public final Long dpid;
+ public final Long number;
+
+ public SwitchPort(final Long dpid, final Long number) {
+ this.dpid = dpid;
+ this.number = number;
+ }
+
+ public byte[] getPortID() {
+ return KVPort.getPortID(dpid, number);
+ }
+
+ public byte[] getSwitchID() {
+ return KVSwitch.getSwitchID(dpid);
+ }
+
+ @Override
+ public String toString() {
+ return "(" + Long.toHexString(dpid) + "@" + number + ")";
+ }
+
+ }
+
+ public static final String GLOBAL_LINK_TABLE_NAME = "G:Link";
+
+ // must not re-order enum members, ordinal will be sent over wire
+ public enum STATUS {
+ INACTIVE, ACTIVE;
+ }
+
+ private final SwitchPort src;
+ private final SwitchPort dst;
+ private STATUS status;
+
+ public static byte[] getLinkID(final Long src_dpid, final Long src_port_no,
+ final Long dst_dpid, final Long dst_port_no) {
+ return LinkEvent.getLinkID(src_dpid, src_port_no, dst_dpid,
+ dst_port_no).array();
+ }
+
+ public static long[] getLinkTupleFromKey(final byte[] key) {
+ return getLinkTupleFromKey(ByteBuffer.wrap(key));
+ }
+
+ public static long[] getLinkTupleFromKey(final ByteBuffer keyBuf) {
+ long[] tuple = new long[4];
+ if (keyBuf.getChar() != 'L') {
+ throw new IllegalArgumentException("Invalid Link key");
+ }
+ long[] src_port_pair = KVPort.getPortPairFromKey(keyBuf.slice());
+ keyBuf.position(2 + PortEvent.PORTID_BYTES);
+ long[] dst_port_pair = KVPort.getPortPairFromKey(keyBuf.slice());
+
+ tuple[0] = src_port_pair[0];
+ tuple[1] = src_port_pair[1];
+ tuple[2] = dst_port_pair[0];
+ tuple[3] = dst_port_pair[1];
+
+ return tuple;
+ }
+
+ public KVLink(final Long src_dpid, final Long src_port_no,
+ final Long dst_dpid, final Long dst_port_no) {
+ super(DataStoreClient.getClient().getTable(GLOBAL_LINK_TABLE_NAME), getLinkID(src_dpid,
+ src_port_no, dst_dpid, dst_port_no));
+
+ src = new SwitchPort(src_dpid, src_port_no);
+ dst = new SwitchPort(dst_dpid, dst_port_no);
+ status = STATUS.INACTIVE;
+ }
+
+ /**
+ * Get an instance from Key.
+ *
+ * @note You need to call `read()` to get the DB content.
+ * @param key
+ * @return KVLink instance
+ */
+ public static KVLink createFromKey(final byte[] key) {
+ long[] linkTuple = getLinkTupleFromKey(key);
+ return new KVLink(linkTuple[0], linkTuple[1], linkTuple[2],
+ linkTuple[3]);
+ }
+
+ public static Iterable<KVLink> getAllLinks() {
+ return new LinkEnumerator();
+ }
+
+ public static class LinkEnumerator implements Iterable<KVLink> {
+
+ @Override
+ public Iterator<KVLink> iterator() {
+ return new LinkIterator();
+ }
+ }
+
+ public static class LinkIterator extends AbstractObjectIterator<KVLink> {
+
+ public LinkIterator() {
+ super(DataStoreClient.getClient().getTable(GLOBAL_LINK_TABLE_NAME));
+ }
+
+ @Override
+ public KVLink next() {
+ IKVEntry o = enumerator.next();
+ KVLink e = KVLink.createFromKey(o.getKey());
+ e.deserialize(o.getValue(), o.getVersion());
+ return e;
+ }
+ }
+
+ public STATUS getStatus() {
+ return status;
+ }
+
+ public void setStatus(final STATUS status) {
+ this.status = status;
+ }
+
+ public SwitchPort getSrc() {
+ return src;
+ }
+
+ public SwitchPort getDst() {
+ return dst;
+ }
+
+ public byte[] getId() {
+ return getKey();
+ }
+
+ @Override
+ public byte[] serialize() {
+ Map<Object, Object> map = getPropertyMap();
+
+ LinkProperty.Builder link = LinkProperty.newBuilder();
+ link.setSrcSwId(ByteString.copyFrom(src.getSwitchID()));
+ link.setSrcPortId(ByteString.copyFrom(src.getPortID()));
+ link.setDstSwId(ByteString.copyFrom(dst.getSwitchID()));
+ link.setDstPortId(ByteString.copyFrom(dst.getPortID()));
+ link.setStatus(status.ordinal());
+
+ if (!map.isEmpty()) {
+ byte[] propMaps = serializePropertyMap(linkKryo.get(), map);
+ link.setValue(ByteString.copyFrom(propMaps));
+ }
+
+ return link.build().toByteArray();
+ }
+
+ @Override
+ protected boolean deserialize(final byte[] bytes) {
+ try {
+ boolean success = true;
+
+ LinkProperty link = LinkProperty.parseFrom(bytes);
+ byte[] props = link.getValue().toByteArray();
+ success &= deserializePropertyMap(linkKryo.get(), props);
+ this.status = STATUS.values()[link.getStatus()];
+
+ return success;
+ } catch (InvalidProtocolBufferException e) {
+ log.error("Deserializing Link: " + this + " failed.", e);
+ return false;
+ }
+ }
+
+ @Override
+ public String toString() {
+ // TODO output all properties?
+ return "[" + this.getClass().getSimpleName()
+ + " " + src + "->" + dst + " STATUS:" + status + "]";
+ }
+}
diff --git a/src/main/java/net/onrc/onos/datastore/topology/KVPort.java b/src/main/java/net/onrc/onos/datastore/topology/KVPort.java
new file mode 100644
index 0000000..3b66864
--- /dev/null
+++ b/src/main/java/net/onrc/onos/datastore/topology/KVPort.java
@@ -0,0 +1,205 @@
+package net.onrc.onos.datastore.topology;
+
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import net.onrc.onos.datastore.DataStoreClient;
+import net.onrc.onos.datastore.IKVTable.IKVEntry;
+import net.onrc.onos.datastore.RCProtos.PortProperty;
+import net.onrc.onos.datastore.utils.ByteArrayUtil;
+import net.onrc.onos.datastore.utils.KVObject;
+import net.onrc.onos.ofcontroller.networkgraph.PortEvent;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.esotericsoftware.kryo.Kryo;
+import com.google.protobuf.ByteString;
+import com.google.protobuf.InvalidProtocolBufferException;
+
+/**
+ * Port object in data store.
+ *
+ * Note: This class will not maintain invariants.
+ * e.g., It will NOT automatically remove Links or Devices on Port,
+ * when deleting a Port.
+ */
+public class KVPort extends KVObject {
+ private static final Logger log = LoggerFactory.getLogger(KVPort.class);
+
+ private static final ThreadLocal<Kryo> portKryo = new ThreadLocal<Kryo>() {
+ @Override
+ protected Kryo initialValue() {
+ Kryo kryo = new Kryo();
+ kryo.setRegistrationRequired(true);
+ kryo.setReferences(false);
+ kryo.register(byte[].class);
+ kryo.register(byte[][].class);
+ kryo.register(HashMap.class);
+ // TODO check if we should explicitly specify EnumSerializer
+ kryo.register(STATUS.class);
+ return kryo;
+ }
+ };
+
+ public static final String GLOBAL_PORT_TABLE_NAME = "G:Port";
+
+ // must not re-order enum members, ordinal will be sent over wire
+ public enum STATUS {
+ INACTIVE, ACTIVE;
+ }
+
+ private final Long dpid;
+ private final Long number;
+
+ private STATUS status;
+
+ public static byte[] getPortID(final Long dpid, final Long number) {
+ return PortEvent.getPortID(dpid, number).array();
+ }
+
+ public static long[] getPortPairFromKey(final byte[] key) {
+ return getPortPairFromKey(ByteBuffer.wrap(key));
+ }
+
+ public static long[] getPortPairFromKey(final ByteBuffer keyBuf) {
+ long[] pair = new long[2];
+ if (keyBuf.getChar() != 'S') {
+ throw new IllegalArgumentException("Invalid Port key:" + keyBuf
+ + " "
+ + ByteArrayUtil.toHexStringBuffer(keyBuf.array(), ":"));
+ }
+ pair[0] = keyBuf.getLong();
+ if (keyBuf.getChar() != 'P') {
+ throw new IllegalArgumentException("Invalid Port key:" + keyBuf
+ + " "
+ + ByteArrayUtil.toHexStringBuffer(keyBuf.array(), ":"));
+ }
+ pair[1] = keyBuf.getLong();
+ return pair;
+
+ }
+
+ public static long getDpidFromKey(final byte[] key) {
+ return getPortPairFromKey(key)[0];
+ }
+
+ public static long getNumberFromKey(final byte[] key) {
+ return getPortPairFromKey(key)[1];
+ }
+
+ // FIXME specify DPID,number here, or Should caller specify the key it self?
+ // In other words, should layer above have the control of the ID?
+ public KVPort(final Long dpid, final Long number) {
+ super(DataStoreClient.getClient().getTable(GLOBAL_PORT_TABLE_NAME), getPortID(dpid, number));
+
+ // TODO Auto-generated constructor stub
+
+ this.dpid = dpid;
+ this.number = number;
+ this.status = STATUS.INACTIVE;
+ }
+
+ /**
+ * Get an instance from Key.
+ *
+ * @note You need to call `read()` to get the DB content.
+ * @param key
+ * @return KVPort instance
+ */
+ public static KVPort createFromKey(final byte[] key) {
+ long[] pair = getPortPairFromKey(key);
+ return new KVPort(pair[0], pair[1]);
+ }
+
+ public static Iterable<KVPort> getAllPorts() {
+ return new PortEnumerator();
+ }
+
+ public static class PortEnumerator implements Iterable<KVPort> {
+
+ @Override
+ public Iterator<KVPort> iterator() {
+ return new PortIterator();
+ }
+ }
+
+ public static class PortIterator extends AbstractObjectIterator<KVPort> {
+
+ public PortIterator() {
+ super(DataStoreClient.getClient().getTable(GLOBAL_PORT_TABLE_NAME));
+ }
+
+ @Override
+ public KVPort next() {
+ IKVEntry o = enumerator.next();
+ KVPort e = KVPort.createFromKey(o.getKey());
+ e.deserialize(o.getValue(), o.getVersion());
+ return e;
+ }
+ }
+
+ public STATUS getStatus() {
+ return status;
+ }
+
+ public void setStatus(final STATUS status) {
+ this.status = status;
+ }
+
+ public Long getDpid() {
+ return dpid;
+ }
+
+ public Long getNumber() {
+ return number;
+ }
+
+ public byte[] getId() {
+ return getKey();
+ }
+
+ @Override
+ public byte[] serialize() {
+ Map<Object, Object> map = getPropertyMap();
+
+ PortProperty.Builder port = PortProperty.newBuilder();
+ port.setDpid(dpid);
+ port.setNumber(number);
+ port.setStatus(status.ordinal());
+
+ if (!map.isEmpty()) {
+ byte[] propMaps = serializePropertyMap(portKryo.get(), map);
+ port.setValue(ByteString.copyFrom(propMaps));
+ }
+
+ return port.build().toByteArray();
+ }
+
+ @Override
+ protected boolean deserialize(final byte[] bytes) {
+ try {
+ boolean success = true;
+
+ PortProperty port = PortProperty.parseFrom(bytes);
+ byte[] props = port.getValue().toByteArray();
+ success &= deserializePropertyMap(portKryo.get(), props);
+ this.status = STATUS.values()[port.getStatus()];
+
+ return success;
+ } catch (InvalidProtocolBufferException e) {
+ log.error("Deserializing Port: " + this + " failed.", e);
+ return false;
+ }
+ }
+
+ @Override
+ public String toString() {
+ // TODO output all properties?
+ return "[" + this.getClass().getSimpleName()
+ + " 0x" + Long.toHexString(dpid) + "@" + number
+ + " STATUS:" + status + "]";
+ }
+}
diff --git a/src/main/java/net/onrc/onos/datastore/topology/KVSwitch.java b/src/main/java/net/onrc/onos/datastore/topology/KVSwitch.java
new file mode 100644
index 0000000..e915160
--- /dev/null
+++ b/src/main/java/net/onrc/onos/datastore/topology/KVSwitch.java
@@ -0,0 +1,174 @@
+package net.onrc.onos.datastore.topology;
+
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import net.onrc.onos.datastore.DataStoreClient;
+import net.onrc.onos.datastore.IKVTable.IKVEntry;
+import net.onrc.onos.datastore.RCProtos.SwitchProperty;
+import net.onrc.onos.datastore.utils.KVObject;
+import net.onrc.onos.ofcontroller.networkgraph.SwitchEvent;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.esotericsoftware.kryo.Kryo;
+import com.google.protobuf.ByteString;
+import com.google.protobuf.InvalidProtocolBufferException;
+
+/**
+ * Switch object in data store.
+ *
+ * Note: This class will not maintain invariants.
+ * e.g., It will NOT automatically remove Ports on Switch,
+ * when deleting a Switch.
+ */
+public class KVSwitch extends KVObject {
+ private static final Logger log = LoggerFactory.getLogger(KVSwitch.class);
+
+ private static final ThreadLocal<Kryo> switchKryo = new ThreadLocal<Kryo>() {
+ @Override
+ protected Kryo initialValue() {
+ Kryo kryo = new Kryo();
+ kryo.setRegistrationRequired(true);
+ kryo.setReferences(false);
+ kryo.register(byte[].class);
+ kryo.register(byte[][].class);
+ kryo.register(HashMap.class);
+ // TODO check if we should explicitly specify EnumSerializer
+ kryo.register(STATUS.class);
+ return kryo;
+ }
+ };
+
+ public static final String GLOBAL_SWITCH_TABLE_NAME = "G:Switch";
+
+ // must not re-order enum members, ordinal will be sent over wire
+ public enum STATUS {
+ INACTIVE, ACTIVE;
+ }
+
+ private final Long dpid;
+ private STATUS status;
+
+ public static byte[] getSwitchID(final Long dpid) {
+ return SwitchEvent.getSwitchID(dpid).array();
+ }
+
+ public static long getDpidFromKey(final byte[] key) {
+ return getDpidFromKey(ByteBuffer.wrap(key));
+ }
+
+ public static long getDpidFromKey(final ByteBuffer keyBuf) {
+ if (keyBuf.getChar() != 'S') {
+ throw new IllegalArgumentException("Invalid Switch key");
+ }
+ return keyBuf.getLong();
+ }
+
+ // FIXME specify DPID here, or Should caller specify the key it self?
+ // In other words, should layer above have the control of the ID?
+ public KVSwitch(final Long dpid) {
+ super(DataStoreClient.getClient().getTable(GLOBAL_SWITCH_TABLE_NAME), getSwitchID(dpid));
+
+ this.dpid = dpid;
+ this.status = STATUS.INACTIVE;
+ }
+
+ /**
+ * Get an instance from Key.
+ *
+ * @note You need to call `read()` to get the DB content.
+ * @param key
+ * @return KVSwitch instance
+ */
+ public static KVSwitch createFromKey(final byte[] key) {
+ return new KVSwitch(getDpidFromKey(key));
+ }
+
+ public static Iterable<KVSwitch> getAllSwitches() {
+ return new SwitchEnumerator();
+ }
+
+ public static class SwitchEnumerator implements Iterable<KVSwitch> {
+
+ @Override
+ public Iterator<KVSwitch> iterator() {
+ return new SwitchIterator();
+ }
+ }
+
+ public static class SwitchIterator extends AbstractObjectIterator<KVSwitch> {
+
+ public SwitchIterator() {
+ super(DataStoreClient.getClient().getTable(GLOBAL_SWITCH_TABLE_NAME));
+ }
+
+ @Override
+ public KVSwitch next() {
+ IKVEntry o = enumerator.next();
+ KVSwitch e = KVSwitch.createFromKey(o.getKey());
+ e.deserialize(o.getValue(), o.getVersion());
+ return e;
+ }
+ }
+
+ public STATUS getStatus() {
+ return status;
+ }
+
+ public void setStatus(final STATUS status) {
+ this.status = status;
+ }
+
+ public Long getDpid() {
+ return dpid;
+ }
+
+ public byte[] getId() {
+ return getKey();
+ }
+
+ @Override
+ public byte[] serialize() {
+ Map<Object, Object> map = getPropertyMap();
+
+ SwitchProperty.Builder sw = SwitchProperty.newBuilder();
+ sw.setDpid(dpid);
+ sw.setStatus(status.ordinal());
+
+ if (!map.isEmpty()) {
+ byte[] propMaps = serializePropertyMap(switchKryo.get(), map);
+ sw.setValue(ByteString.copyFrom(propMaps));
+ }
+
+ return sw.build().toByteArray();
+ }
+
+ @Override
+ protected boolean deserialize(final byte[] bytes) {
+ try {
+ boolean success = true;
+
+ SwitchProperty sw = SwitchProperty.parseFrom(bytes);
+ byte[] props = sw.getValue().toByteArray();
+ success &= deserializePropertyMap(switchKryo.get(), props);
+ this.status = STATUS.values()[sw.getStatus()];
+
+ return success;
+ } catch (InvalidProtocolBufferException e) {
+ log.error("Deserializing Switch: " + this + " failed.", e);
+ return false;
+ }
+ }
+
+ @Override
+ public String toString() {
+ // TODO output all properties?
+ return "[" + this.getClass().getSimpleName()
+ + " 0x" + Long.toHexString(dpid) + " STATUS:" + status + "]";
+ }
+
+}
diff --git a/src/main/java/net/onrc/onos/datastore/topology/RCDevice.java b/src/main/java/net/onrc/onos/datastore/topology/RCDevice.java
deleted file mode 100644
index bb8a1f2..0000000
--- a/src/main/java/net/onrc/onos/datastore/topology/RCDevice.java
+++ /dev/null
@@ -1,221 +0,0 @@
-package net.onrc.onos.datastore.topology;
-
-import java.nio.ByteBuffer;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.esotericsoftware.kryo.Kryo;
-
-import edu.stanford.ramcloud.JRamCloud;
-import net.onrc.onos.datastore.RCObject;
-import net.onrc.onos.datastore.RCTable;
-import net.onrc.onos.datastore.topology.RCLink.STATUS;
-import net.onrc.onos.datastore.utils.ByteArrayComparator;
-import net.onrc.onos.datastore.utils.ByteArrayUtil;
-import net.onrc.onos.ofcontroller.networkgraph.DeviceEvent;
-
-public class RCDevice extends RCObject {
- @SuppressWarnings("unused")
- private static final Logger log = LoggerFactory.getLogger(RCDevice.class);
-
- private static final ThreadLocal<Kryo> deviceKryo = new ThreadLocal<Kryo>() {
- @Override
- protected Kryo initialValue() {
- Kryo kryo = new Kryo();
- kryo.setRegistrationRequired(true);
- kryo.setReferences(false);
- kryo.register(byte[].class);
- kryo.register(byte[][].class);
- kryo.register(HashMap.class);
- // TODO check if we should explicitly specify EnumSerializer
- kryo.register(STATUS.class);
- return kryo;
- }
- };
-
- public static final String GLOBAL_DEVICE_TABLE_NAME = "G:Device";
-
- // FIXME these should be Enum or some number, not String
- private static final String PROP_MAC = "mac";
- private static final String PROP_PORT_IDS = "port-ids";
-
- private final byte[] mac;
- private TreeSet<byte[]> portIds;
- transient private boolean isPortIdsModified;
-
- // Assuming mac is unique cluster-wide
- public static byte[] getDeviceID(final byte[] mac) {
- return DeviceEvent.getDeviceID(mac).array();
- }
-
- public static StringBuilder keysToSB(Collection<byte[]> keys) {
- StringBuilder sb = new StringBuilder();
- sb.append("[");
- boolean hasWritten = false;
- for (byte[] key : keys) {
- if (hasWritten) {
- sb.append(", ");
- }
- sb.append(keyToString(key));
- hasWritten = true;
- }
- sb.append("]");
- return sb;
- }
-
- public static String keyToString(byte[] key) {
- // For debug log
- byte[] mac = getMacFromKey(key);
- return "D" + ByteArrayUtil.toHexStringBuffer(mac, ":");
- }
-
- public static byte[] getMacFromKey(byte[] key) {
- ByteBuffer keyBuf = ByteBuffer.wrap(key);
- if (keyBuf.getChar() != 'D') {
- throw new IllegalArgumentException("Invalid Device key");
- }
- byte[] mac = new byte[keyBuf.remaining()];
- keyBuf.get(mac);
- return mac;
- }
-
- public RCDevice(byte[] mac) {
- super(RCTable.getTable(GLOBAL_DEVICE_TABLE_NAME), getDeviceID(mac));
-
- this.mac = mac;
- this.portIds = new TreeSet<>(ByteArrayComparator.BYTEARRAY_COMPARATOR);
- this.isPortIdsModified = true;
- }
-
- /**
- * Get an instance from Key.
- *
- * @note You need to call `read()` to get the DB content.
- * @param key
- * @return
- */
- public static <D extends RCObject> D createFromKey(byte[] key) {
- @SuppressWarnings("unchecked")
- D d = (D) new RCDevice(getMacFromKey(key));
- return d;
- }
-
- public static Iterable<RCDevice> getAllDevices() {
- return new DeviceEnumerator();
- }
-
- public static class DeviceEnumerator implements Iterable<RCDevice> {
-
- @Override
- public Iterator<RCDevice> iterator() {
- return new DeviceIterator();
- }
- }
-
- public static class DeviceIterator extends ObjectIterator<RCDevice> {
-
- public DeviceIterator() {
- super(RCTable.getTable(GLOBAL_DEVICE_TABLE_NAME));
- }
-
- @Override
- public RCDevice next() {
- JRamCloud.Object o = enumerator.next();
- RCDevice e = RCDevice.createFromKey(o.key);
- e.setValueAndDeserialize(o.value, o.version);
- return e;
- }
- }
-
- public byte[] getMac() {
- // TODO may need to clone() to be sure this object will be immutable.
- return mac;
- }
-
- public byte[] getId() {
- return getKey();
- }
-
- public void addPortId(byte[] portId) {
- // TODO: Should we copy portId, or reference is OK.
- isPortIdsModified |= portIds.add(portId);
- }
-
- public void removePortId(byte[] portId) {
- isPortIdsModified |= portIds.remove(portId);
- }
-
- public void emptyPortIds() {
- portIds.clear();
- this.isPortIdsModified = true;
- }
-
- public void addAllToPortIds(Collection<byte[]> portIds) {
- // TODO: Should we copy portId, or reference is OK.
- isPortIdsModified |= this.portIds.addAll(portIds);
- }
-
- /**
- *
- * @return Unmodifiable Set view of all the PortIds;
- */
- public Set<byte[]> getAllPortIds() {
- return Collections.unmodifiableSet(portIds);
- }
-
- @Override
- public void serializeAndSetValue() {
- Map<Object, Object> map = getObjectMap();
-
- map.put(PROP_MAC, mac);
- if (isPortIdsModified) {
- byte[] portIdArray[] = new byte[portIds.size()][];
- map.put(PROP_PORT_IDS, portIds.toArray(portIdArray));
- isPortIdsModified = false;
- }
-
- serializeAndSetValue(deviceKryo.get(), map);
- }
-
- @Override
- public Map<Object, Object> deserializeObjectFromValue() {
- Map<Object, Object> map = deserializeObjectFromValue(deviceKryo.get());
-
- if (this.portIds == null) {
- this.portIds = new TreeSet<>(
- ByteArrayComparator.BYTEARRAY_COMPARATOR);
- }
- byte[] portIdArray[] = (byte[][]) map.get(PROP_PORT_IDS);
- if (portIdArray != null) {
- this.portIds.clear();
- this.portIds.addAll(Arrays.asList(portIdArray));
- isPortIdsModified = false;
- } else {
- // trigger write on next serialize
- isPortIdsModified = true;
- }
-
- return map;
- }
-
- @Override
- public String toString() {
- // TODO OUTPUT ALL?
- return "[RCDevice " + ByteArrayUtil.toHexStringBuffer(mac, ":") + "]";
- }
-
- public static void main(String[] args) {
- // TODO Auto-generated method stub
-
- }
-
-}
diff --git a/src/main/java/net/onrc/onos/datastore/topology/RCLink.java b/src/main/java/net/onrc/onos/datastore/topology/RCLink.java
deleted file mode 100644
index e3edff0..0000000
--- a/src/main/java/net/onrc/onos/datastore/topology/RCLink.java
+++ /dev/null
@@ -1,247 +0,0 @@
-package net.onrc.onos.datastore.topology;
-
-import java.nio.ByteBuffer;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.openflow.util.HexString;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.esotericsoftware.kryo.Kryo;
-import com.google.protobuf.ByteString;
-import com.google.protobuf.InvalidProtocolBufferException;
-
-import edu.stanford.ramcloud.JRamCloud;
-import net.onrc.onos.datastore.RCProtos.LinkProperty;
-import net.onrc.onos.datastore.RCObject;
-import net.onrc.onos.datastore.RCTable;
-import net.onrc.onos.ofcontroller.networkgraph.LinkEvent;
-import net.onrc.onos.ofcontroller.networkgraph.PortEvent;
-
-public class RCLink extends RCObject {
- private static final Logger log = LoggerFactory.getLogger(RCLink.class);
-
- private static final ThreadLocal<Kryo> linkKryo = new ThreadLocal<Kryo>() {
- @Override
- protected Kryo initialValue() {
- Kryo kryo = new Kryo();
- kryo.setRegistrationRequired(true);
- kryo.setReferences(false);
- kryo.register(byte[].class);
- kryo.register(byte[][].class);
- kryo.register(HashMap.class);
- // TODO check if we should explicitly specify EnumSerializer
- kryo.register(STATUS.class);
- return kryo;
- }
- };
-
- public static class SwitchPort {
- public final Long dpid;
- public final Long number;
-
- public SwitchPort(Long dpid, Long number) {
- this.dpid = dpid;
- this.number = number;
- }
-
- public byte[] getPortID() {
- return RCPort.getPortID(dpid, number);
- }
-
- public byte[] getSwitchID() {
- return RCSwitch.getSwitchID(dpid);
- }
-
- @Override
- public String toString() {
- return "(" + Long.toHexString(dpid) + "@" + number + ")";
- }
-
- }
-
- public static final String GLOBAL_LINK_TABLE_NAME = "G:Link";
-
- // must not re-order enum members, ordinal will be sent over wire
- public enum STATUS {
- INACTIVE, ACTIVE;
- }
-
- private final SwitchPort src;
- private final SwitchPort dst;
- private STATUS status;
-
- public static byte[] getLinkID(Long src_dpid, Long src_port_no,
- Long dst_dpid, Long dst_port_no) {
- return LinkEvent.getLinkID(src_dpid, src_port_no, dst_dpid,
- dst_port_no).array();
- }
-
- public static StringBuilder keysToSB(Collection<byte[]> keys) {
- StringBuilder sb = new StringBuilder();
- sb.append("[");
- boolean hasWritten = false;
- for (byte[] key : keys) {
- if (hasWritten) {
- sb.append(", ");
- }
- sb.append(keyToString(key));
- hasWritten = true;
- }
- sb.append("]");
- return sb;
- }
-
- public static String keyToString(byte[] key) {
- // For debug log
- long[] tuple = getLinkTupleFromKey(key);
- return "L" + "S" + HexString.toHexString(tuple[0]) + "P" + tuple[1]
- + "S" + HexString.toHexString(tuple[2]) + "P" + tuple[3];
- }
-
- public static long[] getLinkTupleFromKey(byte[] key) {
- return getLinkTupleFromKey(ByteBuffer.wrap(key));
- }
-
- public static long[] getLinkTupleFromKey(ByteBuffer keyBuf) {
- long tuple[] = new long[4];
- if (keyBuf.getChar() != 'L') {
- throw new IllegalArgumentException("Invalid Link key");
- }
- long src_port_pair[] = RCPort.getPortPairFromKey(keyBuf.slice());
- keyBuf.position(2 + PortEvent.PORTID_BYTES);
- long dst_port_pair[] = RCPort.getPortPairFromKey(keyBuf.slice());
-
- tuple[0] = src_port_pair[0];
- tuple[1] = src_port_pair[1];
- tuple[2] = dst_port_pair[0];
- tuple[3] = dst_port_pair[1];
-
- return tuple;
- }
-
- public RCLink(Long src_dpid, Long src_port_no, Long dst_dpid,
- Long dst_port_no) {
- super(RCTable.getTable(GLOBAL_LINK_TABLE_NAME), getLinkID(src_dpid,
- src_port_no, dst_dpid, dst_port_no));
-
- src = new SwitchPort(src_dpid, src_port_no);
- dst = new SwitchPort(dst_dpid, dst_port_no);
- status = STATUS.INACTIVE;
- }
-
- /**
- * Get an instance from Key.
- *
- * @note You need to call `read()` to get the DB content.
- * @param key
- * @return RCLink instance
- */
- public static <L extends RCObject> L createFromKey(byte[] key) {
- long linkTuple[] = getLinkTupleFromKey(key);
- @SuppressWarnings("unchecked")
- L l = (L) new RCLink(linkTuple[0], linkTuple[1], linkTuple[2],
- linkTuple[3]);
- return l;
- }
-
- public static Iterable<RCLink> getAllLinks() {
- return new LinkEnumerator();
- }
-
- public static class LinkEnumerator implements Iterable<RCLink> {
-
- @Override
- public Iterator<RCLink> iterator() {
- return new LinkIterator();
- }
- }
-
- public static class LinkIterator extends ObjectIterator<RCLink> {
-
- public LinkIterator() {
- super(RCTable.getTable(GLOBAL_LINK_TABLE_NAME));
- }
-
- @Override
- public RCLink next() {
- JRamCloud.Object o = enumerator.next();
- RCLink e = RCLink.createFromKey(o.key);
- e.setValueAndDeserialize(o.value, o.version);
- return e;
- }
- }
-
- public STATUS getStatus() {
- return status;
- }
-
- public void setStatus(STATUS status) {
- this.status = status;
- }
-
- public SwitchPort getSrc() {
- return src;
- }
-
- public SwitchPort getDst() {
- return dst;
- }
-
- public byte[] getId() {
- return getKey();
- }
-
- @Override
- public void serializeAndSetValue() {
- Map<Object, Object> map = getObjectMap();
-
- LinkProperty.Builder link = LinkProperty.newBuilder();
- link.setSrcSwId(ByteString.copyFrom(src.getSwitchID()));
- link.setSrcPortId(ByteString.copyFrom(src.getPortID()));
- link.setDstSwId(ByteString.copyFrom(dst.getSwitchID()));
- link.setDstPortId(ByteString.copyFrom(dst.getPortID()));
- link.setStatus(status.ordinal());
-
- if (!map.isEmpty()) {
- serializeAndSetValue(linkKryo.get(), map);
- link.setValue(ByteString.copyFrom(this.getSerializedValue()));
- }
-
- this.value = link.build().toByteArray();
- }
-
- @Override
- public Map<Object, Object> deserializeObjectFromValue() {
- LinkProperty link = null;
- Map<Object, Object> map = null;
- try {
- link = LinkProperty.parseFrom(this.value);
- this.value = link.getValue().toByteArray();
- if (this.value.length >= 1) {
- map = deserializeObjectFromValue(linkKryo.get());
- } else {
- map = new HashMap<>();
- }
- this.status = STATUS.values()[link.getStatus()];
- return map;
- } catch (InvalidProtocolBufferException e) {
- log.error("{" + toString() + "}: Read Link: ", e);
- return null;
- }
- }
-
- @Override
- public String toString() {
- return "[RCLink " + src + "->" + dst + " STATUS:" + status + "]";
- }
-
- public static void main(String[] args) {
- // TODO Auto-generated method stub
-
- }
-
-}
diff --git a/src/main/java/net/onrc/onos/datastore/topology/RCPort.java b/src/main/java/net/onrc/onos/datastore/topology/RCPort.java
deleted file mode 100644
index 0b88b60..0000000
--- a/src/main/java/net/onrc/onos/datastore/topology/RCPort.java
+++ /dev/null
@@ -1,231 +0,0 @@
-package net.onrc.onos.datastore.topology;
-
-import java.nio.ByteBuffer;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import org.openflow.util.HexString;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.esotericsoftware.kryo.Kryo;
-import com.google.protobuf.ByteString;
-import com.google.protobuf.InvalidProtocolBufferException;
-
-import edu.stanford.ramcloud.JRamCloud;
-import net.onrc.onos.datastore.RCProtos.PortProperty;
-import net.onrc.onos.datastore.RCObject;
-import net.onrc.onos.datastore.RCTable;
-import net.onrc.onos.datastore.utils.ByteArrayUtil;
-import net.onrc.onos.ofcontroller.networkgraph.PortEvent;
-
-public class RCPort extends RCObject {
- private static final Logger log = LoggerFactory.getLogger(RCPort.class);
-
- private static final ThreadLocal<Kryo> portKryo = new ThreadLocal<Kryo>() {
- @Override
- protected Kryo initialValue() {
- Kryo kryo = new Kryo();
- kryo.setRegistrationRequired(true);
- kryo.setReferences(false);
- kryo.register(byte[].class);
- kryo.register(byte[][].class);
- kryo.register(HashMap.class);
- // TODO check if we should explicitly specify EnumSerializer
- kryo.register(STATUS.class);
- return kryo;
- }
- };
-
- public static final String GLOBAL_PORT_TABLE_NAME = "G:Port";
-
- // must not re-order enum members, ordinal will be sent over wire
- public enum STATUS {
- INACTIVE, ACTIVE;
- }
-
- private final Long dpid;
- private final Long number;
-
- private STATUS status;
-
- public static byte[] getPortID(Long dpid, Long number) {
- return PortEvent.getPortID(dpid, number).array();
- }
-
- public static StringBuilder keysToSB(Collection<byte[]> keys) {
- StringBuilder sb = new StringBuilder();
- sb.append("[");
- boolean hasWritten = false;
- for (byte[] key : keys) {
- if (hasWritten) {
- sb.append(", ");
- }
- sb.append(keyToString(key));
- hasWritten = true;
- }
- sb.append("]");
- return sb;
- }
-
- public static String keyToString(byte[] key) {
- // For debug log
- long[] pair = getPortPairFromKey(key);
- return "S" + HexString.toHexString(pair[0]) + "P" + pair[1];
- }
-
- public static long[] getPortPairFromKey(byte[] key) {
- return getPortPairFromKey(ByteBuffer.wrap(key));
-
- }
-
- public static long[] getPortPairFromKey(ByteBuffer keyBuf) {
- long[] pair = new long[2];
- if (keyBuf.getChar() != 'S') {
- throw new IllegalArgumentException("Invalid Port key:" + keyBuf
- + " "
- + ByteArrayUtil.toHexStringBuffer(keyBuf.array(), ":"));
- }
- pair[0] = keyBuf.getLong();
- if (keyBuf.getChar() != 'P') {
- throw new IllegalArgumentException("Invalid Port key:" + keyBuf
- + " "
- + ByteArrayUtil.toHexStringBuffer(keyBuf.array(), ":"));
- }
- pair[1] = keyBuf.getLong();
- return pair;
-
- }
-
- public static long getDpidFromKey(byte[] key) {
- return getPortPairFromKey(key)[0];
- }
-
- public static long getNumberFromKey(byte[] key) {
- return getPortPairFromKey(key)[1];
- }
-
- // FIXME specify DPID,number here, or Should caller specify the key it self?
- // In other words, should layer above have the control of the ID?
- public RCPort(Long dpid, Long number) {
- super(RCTable.getTable(GLOBAL_PORT_TABLE_NAME), getPortID(dpid, number));
-
- // TODO Auto-generated constructor stub
-
- this.dpid = dpid;
- this.number = number;
- this.status = STATUS.INACTIVE;
- }
-
- /**
- * Get an instance from Key.
- *
- * @note You need to call `read()` to get the DB content.
- * @param key
- * @return RCPort instance
- */
- public static <P extends RCObject> P createFromKey(byte[] key) {
- long[] pair = getPortPairFromKey(key);
- @SuppressWarnings("unchecked")
- P p = (P) new RCPort(pair[0], pair[1]);
- return p;
- }
-
- public static Iterable<RCPort> getAllPorts() {
- return new PortEnumerator();
- }
-
- public static class PortEnumerator implements Iterable<RCPort> {
-
- @Override
- public Iterator<RCPort> iterator() {
- return new PortIterator();
- }
- }
-
- public static class PortIterator extends ObjectIterator<RCPort> {
-
- public PortIterator() {
- super(RCTable.getTable(GLOBAL_PORT_TABLE_NAME));
- }
-
- @Override
- public RCPort next() {
- JRamCloud.Object o = enumerator.next();
- RCPort e = RCPort.createFromKey(o.key);
- e.setValueAndDeserialize(o.value, o.version);
- return e;
- }
- }
-
- public STATUS getStatus() {
- return status;
- }
-
- public void setStatus(STATUS status) {
- this.status = status;
- }
-
- public Long getDpid() {
- return dpid;
- }
-
- public Long getNumber() {
- return number;
- }
-
- public byte[] getId() {
- return getKey();
- }
-
- @Override
- public void serializeAndSetValue() {
- Map<Object, Object> map = getObjectMap();
-
- PortProperty.Builder port = PortProperty.newBuilder();
- port.setDpid(dpid);
- port.setNumber(number);
- port.setStatus(status.ordinal());
-
- if (!map.isEmpty()) {
- serializeAndSetValue(portKryo.get(), map);
- port.setValue(ByteString.copyFrom(this.getSerializedValue()));
- }
-
- this.value = port.build().toByteArray();
- }
-
- @Override
- public Map<Object, Object> deserializeObjectFromValue() {
- PortProperty port = null;
- Map<Object, Object> map = null;
- try {
- port = PortProperty.parseFrom(this.value);
- this.value = port.getValue().toByteArray();
- if (this.value.length >= 1) {
- map = deserializeObjectFromValue(portKryo.get());
- } else {
- map = new HashMap<>();
- }
- this.status = STATUS.values()[port.getStatus()];
- return map;
- } catch (InvalidProtocolBufferException e) {
- log.error("{" + toString() + "}: Read Port: ", e);
- return null;
- }
- }
-
- @Override
- public String toString() {
- // TODO OUTPUT ALL?
- return "[RCPort 0x" + Long.toHexString(dpid) + "@" + number
- + " STATUS:" + status + "]";
- }
-
- public static void main(String[] args) {
- // TODO Auto-generated method stub
-
- }
-
-}
diff --git a/src/main/java/net/onrc/onos/datastore/topology/RCSwitch.java b/src/main/java/net/onrc/onos/datastore/topology/RCSwitch.java
deleted file mode 100644
index 19b9801..0000000
--- a/src/main/java/net/onrc/onos/datastore/topology/RCSwitch.java
+++ /dev/null
@@ -1,482 +0,0 @@
-package net.onrc.onos.datastore.topology;
-
-import java.nio.ByteBuffer;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.HashMap;
-import net.onrc.onos.datastore.RCObject;
-import net.onrc.onos.datastore.RCTable;
-import net.onrc.onos.ofcontroller.networkgraph.SwitchEvent;
-
-import org.openflow.util.HexString;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.esotericsoftware.kryo.Kryo;
-import com.google.protobuf.ByteString;
-import com.google.protobuf.InvalidProtocolBufferException;
-
-import edu.stanford.ramcloud.JRamCloud;
-import edu.stanford.ramcloud.JRamCloud.ObjectDoesntExistException;
-import edu.stanford.ramcloud.JRamCloud.ObjectExistsException;
-import edu.stanford.ramcloud.JRamCloud.WrongVersionException;
-import net.onrc.onos.datastore.RCProtos.SwitchProperty;
-
-/**
- * Switch Object in RC.
- *
- * @note This class will not maintain invariants. e.g. It will NOT automatically
- * remove Ports on Switch, when deleting a Switch.
- *
- */
-public class RCSwitch extends RCObject {
- private static final Logger log = LoggerFactory.getLogger(RCSwitch.class);
-
- private static final ThreadLocal<Kryo> switchKryo = new ThreadLocal<Kryo>() {
- @Override
- protected Kryo initialValue() {
- Kryo kryo = new Kryo();
- kryo.setRegistrationRequired(true);
- kryo.setReferences(false);
- kryo.register(byte[].class);
- kryo.register(byte[][].class);
- kryo.register(HashMap.class);
- // TODO check if we should explicitly specify EnumSerializer
- kryo.register(STATUS.class);
- return kryo;
- }
- };
-
- public static final String GLOBAL_SWITCH_TABLE_NAME = "G:Switch";
-
- // must not re-order enum members, ordinal will be sent over wire
- public enum STATUS {
- INACTIVE, ACTIVE;
- }
-
- private final Long dpid;
- private STATUS status;
-
- public static byte[] getSwitchID(Long dpid) {
- return SwitchEvent.getSwitchID(dpid).array();
- }
-
- public static StringBuilder keysToSB(Collection<byte[]> keys) {
- StringBuilder sb = new StringBuilder();
- sb.append("[");
- boolean hasWritten = false;
- for (byte[] key : keys) {
- if (hasWritten) {
- sb.append(", ");
- }
- sb.append(keyToString(key));
- hasWritten = true;
- }
- sb.append("]");
- return sb;
- }
-
- public static String keyToString(byte[] key) {
- // For debug log
- return "S" + HexString.toHexString(getDpidFromKey(key));
- }
-
- public static long getDpidFromKey(byte[] key) {
- return getDpidFromKey(ByteBuffer.wrap(key));
- }
-
- public static long getDpidFromKey(ByteBuffer keyBuf) {
- if (keyBuf.getChar() != 'S') {
- throw new IllegalArgumentException("Invalid Switch key");
- }
- return keyBuf.getLong();
- }
-
- // FIXME specify DPID here, or Should caller specify the key it self?
- // In other words, should layer above have the control of the ID?
- public RCSwitch(Long dpid) {
- super(RCTable.getTable(GLOBAL_SWITCH_TABLE_NAME), getSwitchID(dpid));
-
- this.dpid = dpid;
- this.status = STATUS.INACTIVE;
- }
-
- /**
- * Get an instance from Key.
- *
- * @note You need to call `read()` to get the DB content.
- * @param key
- * @return RCSwitch instance
- */
- public static <SW extends RCObject> SW createFromKey(byte[] key) {
- @SuppressWarnings("unchecked")
- SW sw = (SW) new RCSwitch(getDpidFromKey(key));
- return sw;
- }
-
- public static Iterable<RCSwitch> getAllSwitches() {
- return new SwitchEnumerator();
- }
-
- public static class SwitchEnumerator implements Iterable<RCSwitch> {
-
- @Override
- public Iterator<RCSwitch> iterator() {
- return new SwitchIterator();
- }
- }
-
- public static class SwitchIterator extends ObjectIterator<RCSwitch> {
-
- public SwitchIterator() {
- super(RCTable.getTable(GLOBAL_SWITCH_TABLE_NAME));
- }
-
- @Override
- public RCSwitch next() {
- JRamCloud.Object o = enumerator.next();
- RCSwitch e = RCSwitch.createFromKey(o.key);
- e.setValueAndDeserialize(o.value, o.version);
- return e;
- }
- }
-
- public STATUS getStatus() {
- return status;
- }
-
- public void setStatus(STATUS status) {
- this.status = status;
- }
-
- public Long getDpid() {
- return dpid;
- }
-
- public byte[] getId() {
- return getKey();
- }
-
- @Override
- public void serializeAndSetValue() {
- Map<Object, Object> map = getObjectMap();
-
- SwitchProperty.Builder sw = SwitchProperty.newBuilder();
- sw.setDpid(dpid);
- sw.setStatus(status.ordinal());
-
- if (!map.isEmpty()) {
- serializeAndSetValue(switchKryo.get(), map);
- sw.setValue(ByteString.copyFrom(this.getSerializedValue()));
- }
-
- this.value = sw.build().toByteArray();
- }
-
- @Override
- public Map<Object, Object> deserializeObjectFromValue() {
- SwitchProperty sw = null;
- Map<Object, Object> map = null;
- try {
- sw = SwitchProperty.parseFrom(this.value);
- this.value = sw.getValue().toByteArray();
- if (this.value.length >= 1) {
- map = deserializeObjectFromValue(switchKryo.get());
- } else {
- map = new HashMap<>();
- }
- this.status = STATUS.values()[sw.getStatus()];
- return map;
- } catch (InvalidProtocolBufferException e) {
- log.error("{" + toString() + "}: Read Switch: ", e);
- return null;
- }
- }
-
- @Override
- public String toString() {
- // TODO OUTPUT ALL?
- return "[RCSwitch 0x" + Long.toHexString(dpid) + " STATUS:" + status
- + "]";
- }
-
- public static void main(String argv[]) {
- // create active switch 0x1 with 2 ports
- RCSwitch sw = new RCSwitch(0x1L);
- sw.setStatus(STATUS.ACTIVE);
-
- try {
- sw.create();
- } catch (ObjectExistsException e) {
- log.debug("Create Switch Failed", e);
- e.printStackTrace();
- }
-
- // read switch 0x1
- RCSwitch swRead = new RCSwitch(0x1L);
- try {
- swRead.read();
- } catch (ObjectDoesntExistException e) {
- log.debug("Reading Switch Failed", e);
- }
- assert (swRead.getStatus() == STATUS.ACTIVE);
-
- // update 0x1
- swRead.setStatus(STATUS.INACTIVE);
- try {
- swRead.update();
- } catch (ObjectDoesntExistException | WrongVersionException e) {
- log.debug("Updating Switch Failed", e);
- }
-
- // read 0x1 again and delete
- RCSwitch swRead2 = new RCSwitch(0x1L);
- try {
- swRead2.read();
- } catch (ObjectDoesntExistException e) {
- log.debug("Reading Switch Again Failed", e);
- }
- assert (swRead2.getStatus() == STATUS.INACTIVE);
- try {
- swRead2.delete();
- } catch (ObjectDoesntExistException | WrongVersionException e) {
- log.debug("Deleting Switch Failed", e);
- }
-
- RCSwitch swRead3 = new RCSwitch(0x1L);
- try {
- swRead3.read();
- } catch (ObjectDoesntExistException e) {
- log.debug("Switch not found as expected");
- }
-
- topology_setup();
- topology_walk();
- topology_delete();
- }
-
- @Deprecated
- private static void topology_setup() {
- log.debug("topology_setup start.");
-
- // d1 - s1p1 - s1 - s1p2 - s2p1 - s2 - s2p2
-
- RCSwitch sw1 = new RCSwitch(0x1L);
- sw1.setStatus(STATUS.ACTIVE);
- try {
- sw1.create();
- log.debug("Create {}", sw1);
- } catch (ObjectExistsException e) {
- log.error("Switch creation failed", e);
- }
-
- RCPort sw1p1 = new RCPort(0x1L, 1L);
- sw1p1.setStatus(RCPort.STATUS.ACTIVE);
- RCPort sw1p2 = new RCPort(0x1L, 2L);
- sw1p2.setStatus(RCPort.STATUS.ACTIVE);
- try {
- sw1p1.create();
- log.debug("Create {}", sw1p1);
- sw1p2.create();
- log.debug("Create {}", sw1p2);
- } catch (ObjectExistsException e) {
- log.error("Port creation failed", e);
- }
-
- try {
- sw1.update();
- log.debug("Update {}", sw1);
- } catch (ObjectDoesntExistException | WrongVersionException e) {
- log.error("Switch update failed", e);
- }
-
- RCDevice d1 = new RCDevice(new byte[] { 0, 1, 2, 3, 4, 5, 6 });
- d1.addPortId(sw1p1.getId());
-
- try {
- d1.create();
- log.debug("Create {}", d1);
- try {
- sw1p1.update();
- } catch (ObjectDoesntExistException | WrongVersionException e) {
- log.error("Link update failed", e);
- }
- log.debug("Create {}", sw1p1);
- } catch (ObjectExistsException e) {
- log.error("Device creation failed", e);
- }
-
- RCSwitch sw2 = new RCSwitch(0x2L);
- sw2.setStatus(STATUS.ACTIVE);
- RCPort sw2p1 = new RCPort(0x2L, 1L);
- sw2p1.setStatus(RCPort.STATUS.ACTIVE);
- RCPort sw2p2 = new RCPort(0x2L, 2L);
- sw2p2.setStatus(RCPort.STATUS.ACTIVE);
-
- RCDevice d2 = new RCDevice(new byte[] { 6, 5, 4, 3, 2, 1, 0 });
- d2.addPortId(sw2p2.getId());
-
- // XXX Collection created by Arrays.asList needs to be stored, so that
- // which operation failed
- Collection<WriteOp> groupOp = Arrays.asList(
- RCObject.WriteOp.Create(sw2), RCObject.WriteOp.Create(sw2p1),
- RCObject.WriteOp.Create(sw2p2), RCObject.WriteOp.Create(d2));
- boolean failed = RCObject.multiWrite(groupOp);
- if (failed) {
- log.error("Some of Switch/Port/Device creation failed");
- for ( WriteOp op : groupOp ) {
- log.debug("{} - Result:{}", op.getObject(), op.getStatus() );
- }
- } else {
- log.debug("Create {} Version:{}", sw2, sw2.getVersion());
- log.debug("Create {} Version:{}", sw2p1, sw2p1.getVersion());
- log.debug("Create {} Version:{}", sw2p2, sw2p2.getVersion());
- log.debug("Create {} Version:{}", d2, d2.getVersion());
- }
-
- RCLink l1 = new RCLink(0x1L, 2L, 0x2L, 1L);
- l1.setStatus(RCLink.STATUS.ACTIVE);
-
- try {
- l1.create();
- log.debug("Create {}", l1);
- try {
- sw1p2.update();
- log.debug("Update {}", sw1p2);
- sw2p1.update();
- log.debug("Update {}", sw2p1);
- } catch (ObjectDoesntExistException | WrongVersionException e) {
- log.error("Port update failed", e);
- }
- } catch (ObjectExistsException e) {
- log.error("Link creation failed", e);
- }
-
- log.debug("topology_setup end.");
- }
-
- @Deprecated
- private static void topology_walk() {
- log.debug("topology_walk start.");
-
- Iterable<RCSwitch> swIt = RCSwitch.getAllSwitches();
- log.debug("Enumerating Switches start");
- for (RCSwitch sw : swIt) {
- log.debug("{}", sw);
- }
- log.debug("Enumerating Switches end");
-
- RCSwitch sw1 = new RCSwitch(0x1L);
- try {
- sw1.read();
- log.debug("{}", sw1);
- } catch (ObjectDoesntExistException e) {
- log.error("Reading switch failed", e);
- }
-
- assert (sw1.getDpid() == 0x1L);
- assert (sw1.getStatus() == STATUS.ACTIVE);
- for (RCPort port : RCPort.getAllPorts()) {
- if (port.getDpid() != 0x1L) {
- continue;
- }
- log.debug("{}", port);
-
- for (RCDevice device : RCDevice.getAllDevices()) {
- if (!device.getAllPortIds().contains(port.getId())) {
- continue;
- }
- log.debug("{} - PortIDs:{}", device,
- RCPort.keysToSB(device.getAllPortIds()));
- }
-
- for (RCLink link : RCLink.getAllLinks()) {
- if (!Arrays.equals(link.getSrc().getPortID(), port.getId())) {
- continue;
- }
- log.debug("Link {}", link);
- }
- }
-
- RCSwitch sw2 = new RCSwitch(0x2L);
- try {
- sw2.read();
- log.debug("{}", sw2);
- } catch (ObjectDoesntExistException e) {
- log.error("Reading switch failed", e);
- }
-
- assert (sw2.getDpid() == 0x2L);
- assert (sw2.getStatus() == STATUS.ACTIVE);
- for (RCPort port : RCPort.getAllPorts()) {
- if (port.getDpid() != 0x2L) {
- continue;
- }
- log.debug("{}", port);
-
- for (RCDevice device : RCDevice.getAllDevices()) {
- if (!device.getAllPortIds().contains(port.getId())) {
- continue;
- }
- log.debug("{} - PortIDs:{}", device,
- RCPort.keysToSB(device.getAllPortIds()));
- }
-
- for (RCLink link : RCLink.getAllLinks()) {
- if (!Arrays.equals(link.getSrc().getPortID(), port.getId())) {
- continue;
- }
- log.debug("Link {}", link);
- }
-
- }
-
- log.debug("topology_walk end.");
- }
-
- @Deprecated
- private static void topology_delete() {
- log.debug("topology_delete start.");
-
- for (RCSwitch sw : RCSwitch.getAllSwitches()) {
- try {
- sw.read();
- sw.delete();
- } catch (ObjectDoesntExistException | WrongVersionException e) {
- log.debug("Delete Switch Failed", e);
- }
- }
-
- for (RCPort p : RCPort.getAllPorts()) {
- try {
- p.read();
- p.delete();
- } catch (ObjectDoesntExistException | WrongVersionException e) {
- log.debug("Delete Port Failed", e);
- }
- }
-
- for (RCDevice d : RCDevice.getAllDevices()) {
- try {
- d.read();
- d.delete();
- } catch (ObjectDoesntExistException | WrongVersionException e) {
- log.debug("Delete Device Failed", e);
- }
- }
-
- for (RCLink l : RCLink.getAllLinks()) {
- try {
- l.read();
- l.delete();
- } catch (ObjectDoesntExistException | WrongVersionException e) {
- log.debug("Delete Link Failed", e);
- }
- }
-
- log.debug("topology_delete end.");
- }
-
-}