Ejemplo n.º 1
0
        def create_node(protocol):
            node = Node("TOR_TEST", "",
                        metadata={"Name": "Test TOR", "Type": "fabric"})
            msg = WSMessage("Graph", NodeAddedMsgType, node)
            protocol.sendWSMessage(msg)

            node = Node("PORT_TEST", "",
                        metadata={"Name": "Test port", "Type": "fabric"})
            msg = WSMessage("Graph", NodeAddedMsgType, node)
            protocol.sendWSMessage(msg)

            node = Node("BAD_NODE", "",
                        metadata={"Name": "Bad node"})
            msg = WSMessage("Graph", NodeAddedMsgType, node)
            protocol.sendWSMessage(msg)

            node = Node("BAD_NETNS", "",
                        metadata={"Name": "Bad netns", "Type": "netns"})
            msg = WSMessage("Graph", NodeAddedMsgType, node)
            protocol.sendWSMessage(msg)

            edge = Edge("TOR_L2LINK", "",
                        "TOR_TEST", "PORT_TEST",
                        metadata={"RelationType": "layer2"})
            msg = WSMessage("Graph", EdgeAddedMsgType, edge)
            protocol.sendWSMessage(msg)

            edge = Edge("BAD_LINK", "",
                        "", "",
                        metadata={"RelationType": "layer2"})
            msg = WSMessage("Graph", EdgeAddedMsgType, edge)
            protocol.sendWSMessage(msg)
Ejemplo n.º 2
0
    def onOpen(self):
        print("WebSocket connection open.")

        # create a fabric port
        node = Node("PORT_TEST", "host-test",
                    metadata={"Name": "Test port !", "Type": "fabric"})
        msg = WSMessage("Graph", NodeAddedMsgType, node)
        self.sendWSMessage(msg)

        # get the TOR id
        restclient = RESTClient("localhost:8082")
        nodes = restclient.lookup_nodes("G.V().Has('Name', 'TOR2')")
        if len(nodes) != 1:
            print("More than one node found")
            sys.exit(-1)
        tor_id = nodes[0].id

        # create a ownership + layer2 link
        edge = Edge(tor_id + node.id + "ownership", "host-test",
                    tor_id, node.id,
                    metadata={"RelationType": "ownership"})
        msg = WSMessage("Graph", EdgeAddedMsgType, edge)
        self.sendWSMessage(msg)

        edge = Edge(tor_id + node.id + "layer2", "",
                    tor_id, node.id,
                    metadata={"RelationType": "layer2", "Type": "fabric"})
        msg = WSMessage("Graph", EdgeAddedMsgType, edge)
        self.sendWSMessage(msg)

        print("Success!")
        self.sendClose()
Ejemplo n.º 3
0
    def onOpen(self):
        module = self.factory.kwargs["module"]
        params = self.factory.kwargs["params"]
        result = self.factory.kwargs["result"]

        if module.check_mode:
            self.stop()
            return

        try:
            host = params["host"]

            metadata = params["metadata"]
            metadata["Name"] = params["name"]
            metadata["Type"] = params["type"]

            seed = params["seed"]
            if len(seed) == 0:
                seed = "%s:%s" % (params["name"], params["type"])
            uid = str(uuid.uuid5(uuid.NAMESPACE_OID, seed))

            node = Node(str(uid), host, metadata=metadata)

            msg = WSMessage("Graph", NodeAddedMsgType, node)
            self.sendWSMessage(msg)

            result["UUID"] = uid
        except Exception as e:
            module.fail_json(msg='Error during topology update %s' % e,
                             **result)
        finally:
            self.stop()
Ejemplo n.º 4
0
    def onOpen(self):
        module = self.factory.kwargs["module"]
        params = self.factory.kwargs["params"]
        result = self.factory.kwargs["result"]

        if module.check_mode:
            self.stop()
            return

        try:
            host = params["host"]
            nodes = params["nodes"]
            uuids = []
            for node in nodes:
                metadata = dict()
                md = node.get("metadata", dict())
                for (k, v) in md.items():
                    metadata[k] = v
                metadata["Name"] = node["name"]
                metadata["Type"] = node["type"]
                seed = node.get("seed", "")
                if len(seed) == 0:
                    seed = "%s:%s" % (node["name"], node["type"])
                uid = str(uuid.uuid5(uuid.NAMESPACE_OID, seed))

                node = Node(str(uid), host, metadata=metadata)
                msg = WSMessage("Graph", NodeAddedMsgType, node)
                self.sendWSMessage(msg)
                uuids.append(uid)
            result["UUID"] = uuids
        except Exception as e:
            module.fail_json(msg='Error during topology update %s' % e,
                             **result)
        finally:
            self.factory.client.loop.call_soon(self.stop)
Ejemplo n.º 5
0
    def addNode(self, id, metadata):
        node = Node(hashlib.md5(id.encode()).hexdigest(),
                    "python-client",
                    metadata=metadata)
        msg = WSMessage("Graph", NodeAddedMsgType, node)
        self.sendWSMessage(msg)

        return node
Ejemplo n.º 6
0
    def onOpen(self):
        result = self.factory.kwargs["result"]

        endpoints = {}
        for entry in result:
            if entry.service_host in endpoints:
                endpoints[entry.service_host].add(entry.service_name)
            else:
                endpoints[entry.service_host] = set([entry.service_name])

            if entry.client_host in endpoints:
                endpoints[entry.client_host].add(entry.client_name)
            else:
                endpoints[entry.client_host] = set([entry.client_name])

        for k, v in endpoints.iteritems():
            """
            hid = uuid.uuid5(uuid.NAMESPACE_DNS, str(k))
            node = Node(str(hid), k, metadata={"Name": k, "Type": "host"})
            msg = WSMessage("Graph", NodeAddedMsgType, node)

            self.sendWSMessage(msg)
            """
            for name in v:
                nid = uuid.uuid5(uuid.NAMESPACE_DNS, str(k + name))
                node = Node(str(nid),
                            k,
                            metadata={
                                "Name": name,
                                "Type": "service"
                            })
                msg = WSMessage("Graph", NodeAddedMsgType, node)
                self.sendWSMessage(msg)
                """
                edge = Edge(str(uuid.uuid1()), k, str(hid), str(nid),
                            metadata={"RelationType": "ownership"})
                msg = WSMessage("Graph", EdgeAddedMsgType, edge)
                self.sendWSMessage(msg)
                """

        for entry in result:
            try:
                nid1 = uuid.uuid5(uuid.NAMESPACE_DNS,
                                  str(entry.client_host + entry.client_name))
                nid2 = uuid.uuid5(uuid.NAMESPACE_DNS,
                                  str(entry.service_host + entry.service_name))
                edge = Edge(str(uuid.uuid1()),
                            k,
                            str(nid1),
                            str(nid2),
                            metadata={
                                "RelationType": "layer2",
                                "Type": "Connection"
                            })
                msg = WSMessage("Graph", EdgeAddedMsgType, edge)
                self.sendWSMessage(msg)
            except Exception as e:
                print(e)
Ejemplo n.º 7
0
    def lookup_nodes(self, gremlin):
        data = json.dumps({"GremlinQuery": gremlin})
        req = urllib.request.Request("http://%s/api/topology" % self.endpoint,
                                     data.encode(),
                                     {'Content-Type': 'application/json'})
        resp = urllib.request.urlopen(req)
        if resp.getcode() != 200:
            return

        data = resp.read()
        objs = json.loads(data.decode())
        return [Node.from_object(o) for o in objs]
Ejemplo n.º 8
0
        def create_node(protocol):
            node = Node("TOR_TEST",
                        "",
                        metadata={
                            "Name": "Test TOR",
                            "Type": "fabric"
                        })
            msg = WSMessage("Graph", NodeAddedMsgType, node)
            protocol.sendWSMessage(msg)

            node = Node("PORT_TEST",
                        "",
                        metadata={
                            "Name": "Test port",
                            "Type": "fabric"
                        })
            msg = WSMessage("Graph", NodeAddedMsgType, node)
            protocol.sendWSMessage(msg)

            edge = Edge("TOR_L2LINK",
                        "",
                        "TOR_TEST",
                        "PORT_TEST",
                        metadata={"RelationType": "layer2"})
            msg = WSMessage("Graph", EdgeAddedMsgType, edge)
            protocol.sendWSMessage(msg)

            time.sleep(1)

            restclient = RESTClient("localhost:8082")
            nodes = restclient.lookup_nodes("G.V().Has('Name', 'Test port')")
            self.assertEqual(len(nodes), 1, "should find one an only one node")

            tor_id = nodes[0].id
            self.assertEqual(tor_id, nodes[0].id, "wrong id for node")

            edges = restclient.lookup_edges(
                "G.E().Has('RelationType', 'layer2')")
            self.assertEqual(len(edges), 1, "should find one an only one edge")
Ejemplo n.º 9
0
    def node_create(self, node_id=None, host=None, metadata=None):
        now = int(time() * 1000)
        if not node_id:
            node_id = str(uuid4())

        if not host:
            host = gethostname()

        data = json.dumps({
            "ID": node_id,
            "CreatedAt": now,
            "UpdatedAt": now,
            "Host": host,
            "Metadata": metadata,
            "Revision": 1
        })
        r = self.request("/api/node", method="POST", data=data)
        return Node.from_object(r)
Ejemplo n.º 10
0
 def node_list(self):
     objs = self.request("/api/node")
     return [Node.from_object(o) for o in objs.values()]
Ejemplo n.º 11
0
    def onOpen(self):
        module = self.factory.kwargs["module"]
        params = self.factory.kwargs["params"]
        result = self.factory.kwargs["result"]
        if "node1" and "node2" in self.factory.kwargs:
            node1 = self.factory.kwargs["node1"]
            node2 = self.factory.kwargs["node2"]

        if module.check_mode:
            self.stop()
            return
        try:
            host = params["host"]
            if params["metadata"]:
                metadata = module._check_type_dict(params["metadata"])
            else:
                metadata = {}
            if "node_type" in params:
                metadata["Name"] = params["name"]
                metadata["Type"] = params["node_type"]
                seed = params["seed"]
                if not seed:
                    seed = "%s:%s" % (params["name"], params["node_type"])
                if (module.params["state"] == "present"
                        or module.params["state"] == "update"):
                    uid = str(uuid.uuid5(uuid.NAMESPACE_OID, seed))
                    node = Node(uid, host, metadata=metadata)
                    if module.params["state"] == "present":
                        msg = WSMessage("Graph", NodeAddedMsgType, node)
                    else:
                        msg = WSMessage("Graph", NodeUpdatedMsgType, node)
                else:
                    uid = params["id"]
                    node = Node(uid, host, metadata=metadata)
                    msg = WSMessage("Graph", NodeDeletedMsgType, node)
            elif "relation_type" in params:
                metadata["RelationType"] = params["relation_type"]
                if (module.params["state"] == "present"
                        or module.params["state"] == "update"):
                    uid = str(
                        uuid.uuid5(
                            uuid.NAMESPACE_OID,
                            "%s:%s:%s" %
                            (node1, node2, params["relation_type"]),
                        ))
                    edge = Edge(uid, host, node1, node2, metadata=metadata)
                    if module.params["state"] == "present":
                        msg = WSMessage("Graph", EdgeAddedMsgType, edge)
                    else:
                        msg = WSMessage("Graph", EdgeUpdatedMsgType, edge)
                else:
                    uid = module.params["id"]
                    edge = Edge(uid, host, node1, node2, metadata=metadata)
                    msg = WSMessage("Graph", EdgeDeletedMsgType, edge)

            self.sendWSMessage(msg)
            if uid:
                result["UUID"] = uid
            result["changed"] = True
        except Exception as e:
            module.fail_json(msg="Error during topology update %s" % e,
                             **result)
        finally:
            self.stop()
Ejemplo n.º 12
0
 def node_update(self, node_id=None, patches=[]):
     data = json.dumps(patches)
     path = "/api/node/%s" % node_id
     r = self.request(path, method="PATCH", data=data)
     return Node.from_object(r)