tom | 1655562 | 2014-09-29 08:49:27 -0700 | [diff] [blame^] | 1 | package org.onlab.onos.ccc; |
| 2 | |
| 3 | import com.fasterxml.jackson.core.JsonEncoding; |
| 4 | import com.fasterxml.jackson.core.JsonFactory; |
| 5 | import com.fasterxml.jackson.databind.JsonNode; |
| 6 | import com.fasterxml.jackson.databind.ObjectMapper; |
| 7 | import com.fasterxml.jackson.databind.node.ArrayNode; |
| 8 | import com.fasterxml.jackson.databind.node.ObjectNode; |
| 9 | import org.onlab.onos.cluster.DefaultControllerNode; |
| 10 | import org.onlab.onos.cluster.NodeId; |
| 11 | import org.onlab.packet.IpPrefix; |
| 12 | |
| 13 | import java.io.File; |
| 14 | import java.io.IOException; |
| 15 | import java.util.HashSet; |
| 16 | import java.util.Iterator; |
| 17 | import java.util.Set; |
| 18 | |
| 19 | /** |
| 20 | * Allows for reading and writing cluster definition as a JSON file. |
| 21 | */ |
| 22 | public class ClusterDefinitionStore { |
| 23 | |
| 24 | private final File file; |
| 25 | |
| 26 | /** |
| 27 | * Creates a reader/writer of the cluster definition file. |
| 28 | * |
| 29 | * @param filePath location of the definition file |
| 30 | */ |
| 31 | public ClusterDefinitionStore(String filePath) { |
| 32 | file = new File(filePath); |
| 33 | } |
| 34 | |
| 35 | /** |
| 36 | * Returns set of the controller nodes, including self. |
| 37 | * |
| 38 | * @return set of controller nodes |
| 39 | */ |
| 40 | public Set<DefaultControllerNode> read() throws IOException { |
| 41 | Set<DefaultControllerNode> nodes = new HashSet<>(); |
| 42 | ObjectMapper mapper = new ObjectMapper(); |
| 43 | ObjectNode clusterNodeDef = (ObjectNode) mapper.readTree(file); |
| 44 | Iterator<JsonNode> it = ((ArrayNode) clusterNodeDef.get("nodes")).elements(); |
| 45 | while (it.hasNext()) { |
| 46 | ObjectNode nodeDef = (ObjectNode) it.next(); |
| 47 | nodes.add(new DefaultControllerNode(new NodeId(nodeDef.get("id").asText()), |
| 48 | IpPrefix.valueOf(nodeDef.get("ip").asText()), |
| 49 | nodeDef.get("tcpPort").asInt(9876))); |
| 50 | } |
| 51 | return nodes; |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * Writes the given set of the controller nodes. |
| 56 | * |
| 57 | * @param nodes set of controller nodes |
| 58 | */ |
| 59 | public void write(Set<DefaultControllerNode> nodes) throws IOException { |
| 60 | ObjectMapper mapper = new ObjectMapper(); |
| 61 | ObjectNode clusterNodeDef = mapper.createObjectNode(); |
| 62 | ArrayNode nodeDefs = mapper.createArrayNode(); |
| 63 | clusterNodeDef.set("nodes", nodeDefs); |
| 64 | for (DefaultControllerNode node : nodes) { |
| 65 | ObjectNode nodeDef = mapper.createObjectNode(); |
| 66 | nodeDef.put("id", node.id().toString()) |
| 67 | .put("ip", node.ip().toString()) |
| 68 | .put("tcpPort", node.tcpPort()); |
| 69 | nodeDefs.add(nodeDef); |
| 70 | } |
| 71 | mapper.writeTree(new JsonFactory().createGenerator(file, JsonEncoding.UTF8), |
| 72 | clusterNodeDef); |
| 73 | } |
| 74 | |
| 75 | } |