Esempio n. 1
0
    def get(self, app):
        if app_connector.is_app_connected(self.application, app) is False:
            error_message = "App '{}' is not installed".format(app)
            logger.error(error_message)
            self.set_status(FORBIDDEN, error_message)
            self.finish()
        else:
            topology_parser = app_connector.get_topology_parser(
                self.application, app)()

            try:
                res, parsed_topology = TopologyHandler.get_topology(
                    topology_parser)
            except Exception as e:
                logger.error("Topology fetch failed. Error: {}".format(
                    e.message))
                if DEBUG:
                    self.set_status(INTERNAL_SERVER_ERROR, e.message)
                else:
                    self.set_status(INTERNAL_SERVER_ERROR)
                self.finish()
            else:
                if res is True:
                    logger.debug("Parsed topology: {}".format(parsed_topology))

                    if parsed_topology:
                        self.set_header("Content-Type", "application/json")
                        self.write(parsed_topology)
                    else:
                        logger.error("Failed to parse topology")
                else:
                    logger.error(
                        "Failed to parse topology. Received controller topology: {}"
                        .format(parsed_topology))
Esempio n. 2
0
    def get(self, app):
        if app_connector.is_app_connected(self.application, app) is False:
            error_message = "App '{}' is not installed".format(app)
            logger.error(error_message)
            self.set_status(FORBIDDEN, error_message)
            self.finish()
        else:
            topology_parser = app_connector.get_topology_parser(self.application, app)()

            try:
                res, parsed_topology = TopologyHandler.get_topology(topology_parser)
            except Exception as e:
                logger.error("Topology fetch failed. Error: {}".format(e.message))
                if DEBUG:
                    self.set_status(INTERNAL_SERVER_ERROR, e.message)
                else:
                    self.set_status(INTERNAL_SERVER_ERROR)
                self.finish()
            else:
                if res is True:
                    logger.debug("Parsed topology: {}".format(parsed_topology))

                    if parsed_topology:
                        self.set_header("Content-Type", "application/json")
                        self.write(parsed_topology)
                    else:
                        logger.error("Failed to parse topology")
                else:
                    logger.error("Failed to parse topology. Received controller topology: {}".format(parsed_topology))
Esempio n. 3
0
 def parse_links(self):
     logger.debug("BGP compose links")
     link_list = []
     try:
         return map(lambda link: {
             'source': link['source']['source-node'],
             'target': link['destination']['dest-node'],
             'metric': link['l3-unicast-igp-topology:igp-link-attributes']['metric']
         }, self.topology['link'])
     except Exception as ex:
         logger.exception("BGP get node error3: {}".format(ex.message))
     return link_list
Esempio n. 4
0
    def parse_nodes(self):

        logger.debug("BGP build node topology")
        node_list = []
        try:
            for nodes in self.topology['node']:
                node = {}
                prefix_array = []
                node_dict = html_style(nodes['node-id'])
                if 'prefix' in nodes['l3-unicast-igp-topology:igp-node-attributes'].keys():
                    for prefix in nodes['l3-unicast-igp-topology:igp-node-attributes']['prefix']:
                        prefix_array.append(prefix['prefix'])
                if 'router-id' in nodes['l3-unicast-igp-topology:igp-node-attributes'].keys():
                    if 'name' in nodes['l3-unicast-igp-topology:igp-node-attributes'].keys():
                        node['name'] = nodes['l3-unicast-igp-topology:igp-node-attributes']['name']
                    else:
                        success, name = name_check(nodes['l3-unicast-igp-topology:igp-node-attributes']['router-id'][0])
                        if success:
                            node['name'] = name
                        else:
                            node['name'] = node_dict['router']
                    node['loopback'] = nodes['l3-unicast-igp-topology:igp-node-attributes']['router-id'][0]
                else:
                    node['name'] = node_dict['router']
                    node['loopback'] = "0.0.0.0"
                node['prefix'] = prefix_array
                node['id'] = nodes['node-id']
                node_list.append(node)
            for node in node_list:
                node_dict = html_style(node['id'])
                if node['name'] == node_dict['router'] and node['loopback'] == "0.0.0.0":
                    for owner in node_list:
                        owner_dict = html_style(owner['id'])
                        if node['name'][:len(owner_dict['router'])] == owner_dict['router'] and node['name'] != owner['name']:
                            node['name'] = owner['name']+node_dict['router'][len(owner_dict['router']):]
        except Exception as ex:
            logger.exception("BGP get node error2: {}".format(ex.message))
        logger.debug("BGP Nodelist Len: %s" %len(node_list))
        return node_list
Esempio n. 5
0
    def send_request(self, method, url, data=None, data_type="json"):
        method = method.upper()

        has_payload = method == self.POST or method == self.PUT
        is_CUD = has_payload or method == self.DELETE

        full_url = urlparse.urlunparse((controller_address['scheme'],
                                        controller_address['host'] + ':' + str(controller_address['port']),
                                        url,
                                        None, None, None))

        headers = {
            'Content-Type': HttpClient.set_content_type(data_type)
        }
        request = HTTPRequest(url=full_url,
                              method=method,
                              headers=headers,
                              auth_username=controller_auth['username'],
                              auth_password=controller_auth['password'],
                              connect_timeout=http_client_settings.get("timeouts", {}).get("connect", 3),
                              request_timeout=http_client_settings.get("timeouts", {}).get("request", 10))

        if has_payload:
            if data_type == "json":
                request.body = json.dumps(data)

        if is_CUD:
            if self.dry_run:
                logger.info("\nDRY RUN")
            logger.debug("\n\nSending {} request.\nUrl: {}\nBody: {}\n".format(method, full_url, request.body))

        if is_CUD and self.dry_run:
            response = json.dumps({
                "status": "ok",
                "msg": "dry_run"
            })
        else:
            try:
                response = HTTPClient().fetch(request)
                if not self.fail_silently and not self.is_ok(response.code):
                    raise HttpClientException(response)

                logger.debug("\n\nResponse ({}).\nUrl: {}\nBody: {}\n".format(response.code, full_url, response.body))

                return response
            except HTTPError as e:
                logger.debug("HttpClient error: {}".format(e.message))
                if not self.fail_silently:
                    raise HttpClientException(e)
                return None
        return response
Esempio n. 6
0
    def __init__(self, dry_run=False, fail_silently=False):
        self.dry_run = dry_run or http_client_settings.get("dry_run")
        self.fail_silently = fail_silently

        logger.debug("HTTP Client initialized with config:\ndry_run={}\nfail_silently={}".format(self.dry_run, self.fail_silently))