Exemple #1
0
    def post(self):
        """
        Insert switch IP and the credential to db. Invoke a task to poll
        switch at the same time.

        :param ip: switch IP address
        :param credential: a dict for accessing the switch
        """
        ip_addr = None
        credential = None
        logging.debug('post switch request from curl is %s', request.data)
        json_data = json.loads(request.data)
        ip_addr = json_data['switch']['ip']
        credential = json_data['switch']['credential']

        logging.info('post switch ip_addr=%s credential=%s(%s)', ip_addr,
                     credential, type(credential))

        if not util.is_valid_ip(ip_addr):
            error_msg = "Invalid IP address format!"
            return errors.handle_invalid_usage(
                errors.UserInvalidUsage(error_msg))

        new_switch = {}
        with database.session() as session:
            switch = session.query(ModelSwitch).filter_by(ip=ip_addr).first()
            logging.info('switch for ip %s: %s', ip_addr, switch)

            if switch:
                error_msg = "IP address '%s' already exists" % ip_addr
                value = {'failedSwitch': switch.id}
                return errors.handle_duplicate_object(
                    errors.ObjectDuplicateError(error_msg), value)

            switch = ModelSwitch(ip=ip_addr)
            switch.credential = credential
            session.add(switch)
            session.flush()
            new_switch['id'] = switch.id
            new_switch['ip'] = switch.ip
            new_switch['state'] = switch.state
            link = {
                'rel': 'self',
                'href': '/'.join((self.ENDPOINT, str(switch.id)))
            }
            new_switch['link'] = link

        celery.send_task("compass.tasks.pollswitch", (ip_addr, ))
        logging.info('new switch added: %s', new_switch)
        return util.make_json_response(202, {
            "status": "accepted",
            "switch": new_switch
        })
Exemple #2
0
    def post(self):
        """
        Insert switch IP and the credential to db. Invoke a task to poll
        switch at the same time.

        :param ip: switch IP address
        :param credential: a dict for accessing the switch
        """
        ip_addr = None
        credential = None
        logging.debug('post switch request from curl is %s', request.data)
        json_data = json.loads(request.data)
        ip_addr = json_data['switch']['ip']
        credential = json_data['switch']['credential']

        logging.info('post switch ip_addr=%s credential=%s(%s)',
                     ip_addr, credential, type(credential))

        if not util.is_valid_ip(ip_addr):
            error_msg = "Invalid IP address format!"
            return errors.handle_invalid_usage(
                errors.UserInvalidUsage(error_msg)
                )

        new_switch = {}
        with database.session() as session:
            switch = session.query(ModelSwitch).filter_by(ip=ip_addr).first()
            logging.info('switch for ip %s: %s', ip_addr, switch)

            if switch:
                error_msg = "IP address '%s' already exists" % ip_addr
                value = {'failedSwitch': switch.id}
                return errors.handle_duplicate_object(
                    errors.ObjectDuplicateError(error_msg), value
                )

            switch = ModelSwitch(ip=ip_addr)
            switch.credential = credential
            session.add(switch)
            session.flush()
            new_switch['id'] = switch.id
            new_switch['ip'] = switch.ip
            new_switch['state'] = switch.state
            link = {'rel': 'self',
                    'href': '/'.join((self.ENDPOINT, str(switch.id)))}
            new_switch['link'] = link

        celery.send_task("compass.tasks.pollswitch", (ip_addr,))
        logging.info('new switch added: %s', new_switch)
        return util.make_json_response(
            202, {"status": "accepted",
                  "switch":  new_switch}
            )
Exemple #3
0
    def get(self):
        """
        List details of all swithes which qualifies the query conditions.
        Filtered by:
            switchIp: switch IP address
            switchIpNetwork: switch IP network
            limit: the number of records excepted to return
        Note: switchIp and swtichIpNetwork cannot be combined to use.
        """
        qkeys = request.args.keys()
        logging.info('SwitchList query strings : %s', qkeys)
        switch_list = []

        with database.session() as session:
            switches = []
            switch_ips = request.args.getlist(self.SWITCHIP)
            switch_ip_network = request.args.get(self.SWITCHIPNETWORK,
                                                 type=str)
            limit = request.args.get(self.LIMIT, 0, type=int)

            if switch_ips and switch_ip_network:
                error_msg = 'switchIp and switchIpNetwork cannot be combined!'
                return errors.handle_invalid_usage(
                    errors.UserInvalidUsage(error_msg))

            if limit < 0:
                error_msg = "limit cannot be less than 1!"
                return errors.handle_invalid_usage(
                    errors.UserInvalidUsage(error_msg))

            if switch_ips:
                for ip_addr in switch_ips:
                    ip_addr = str(ip_addr)
                    if not util.is_valid_ip(ip_addr):
                        error_msg = 'SwitchIp format is incorrect!'
                        return errors.handle_invalid_usage(
                            errors.UserInvalidUsage(error_msg))
                    switch = session.query(ModelSwitch).filter_by(ip=ip_addr)\
                                                       .first()
                    if switch:
                        switches.append(switch)
                        logging.info('[SwitchList][get] ip %s', ip_addr)

            elif switch_ip_network:
                # query all switches which belong to the same network
                if not util.is_valid_ipnetowrk(switch_ip_network):
                    error_msg = 'SwitchIpNetwork format is incorrect!'
                    return errors.handle_invalid_usage(
                        errors.UserInvalidUsage(error_msg))

                def get_queried_ip_prefix(network, prefix):
                    """ Get Ip prefex as pattern used to query switches.
                        Switches' Ip addresses need to match this pattern.
                    """
                    count = int(prefix/8)
                    if count == 0:
                        count = 1
                    return network.rsplit('.', count)[0]+'.'

                from netaddr import IPNetwork, IPAddress

                ip_network = IPNetwork(switch_ip_network)
                ip_filter = get_queried_ip_prefix(str(ip_network.network),
                                                  ip_network.prefixlen)

                logging.info('ip_filter is %s', ip_filter)
                result_set = session.query(ModelSwitch).filter(
                    ModelSwitch.ip.startswith(ip_filter)).all()

                for switch in result_set:
                    ip_addr = str(switch.ip)
                    if IPAddress(ip_addr) in ip_network:
                        switches.append(switch)
                        logging.info('[SwitchList][get] ip %s', ip_addr)

                if limit and len(switches) > limit:
                    switches = switches[:limit]

            elif limit and not switches:
                switches = session.query(ModelSwitch).limit(limit).all()
            else:
                switches = session.query(ModelSwitch).all()

            for switch in switches:
                switch_res = {}
                switch_res['id'] = switch.id
                switch_res['state'] = switch.state
                switch_res['link'] = {
                    'rel': 'self',
                    'href': '/'.join((self.ENDPOINT, str(switch.id)))}
                switch_list.append(switch_res)
        logging.info('get switch list: %s', switch_list)

        return util.make_json_response(
            200, {"status": 'OK',
                  "switches": switch_list})
Exemple #4
0
    def get(self):
        """
        List details of all switches, optionally filtered by some conditions.
        Note: switchIp and swtichIpNetwork cannot be combined to use.

        :param switchIp: switch IP address
        :param switchIpNetwork: switch IP network
        :param limit: the number of records excepted to return
        """
        qkeys = request.args.keys()
        logging.info('SwitchList query strings : %s', qkeys)
        switch_list = []

        with database.session() as session:
            switches = []
            switch_ips = request.args.getlist(self.SWITCHIP)
            switch_ip_network = request.args.get(self.SWITCHIPNETWORK,
                                                 type=str)
            limit = request.args.get(self.LIMIT, 0, type=int)

            if switch_ips and switch_ip_network:
                error_msg = 'switchIp and switchIpNetwork cannot be combined!'
                return errors.handle_invalid_usage(
                    errors.UserInvalidUsage(error_msg))

            if limit < 0:
                error_msg = "limit cannot be less than 1!"
                return errors.handle_invalid_usage(
                    errors.UserInvalidUsage(error_msg))

            if switch_ips:
                for ip_addr in switch_ips:
                    ip_addr = str(ip_addr)
                    if not util.is_valid_ip(ip_addr):
                        error_msg = 'SwitchIp format is incorrect!'
                        return errors.handle_invalid_usage(
                            errors.UserInvalidUsage(error_msg))
                    switch = session.query(ModelSwitch).filter_by(ip=ip_addr)\
                                                       .first()
                    if switch:
                        switches.append(switch)
                        logging.info('[SwitchList][get] ip %s', ip_addr)

            elif switch_ip_network:
                # query all switches which belong to the same network
                if not util.is_valid_ipnetowrk(switch_ip_network):
                    error_msg = 'SwitchIpNetwork format is incorrect!'
                    return errors.handle_invalid_usage(
                        errors.UserInvalidUsage(error_msg))

                def get_queried_ip_prefix(network, prefix):
                    """ Get Ip prefex as pattern used to query switches.
                        Switches' Ip addresses need to match this pattern.
                    """
                    count = int(prefix / 8)
                    if count == 0:
                        count = 1
                    return network.rsplit('.', count)[0] + '.'

                from netaddr import IPNetwork, IPAddress

                ip_network = IPNetwork(switch_ip_network)
                ip_filter = get_queried_ip_prefix(str(ip_network.network),
                                                  ip_network.prefixlen)

                logging.info('ip_filter is %s', ip_filter)
                result_set = session.query(ModelSwitch).filter(
                    ModelSwitch.ip.startswith(ip_filter)).all()

                for switch in result_set:
                    ip_addr = str(switch.ip)
                    if IPAddress(ip_addr) in ip_network:
                        switches.append(switch)
                        logging.info('[SwitchList][get] ip %s', ip_addr)

                if limit and len(switches) > limit:
                    switches = switches[:limit]

            elif limit and not switches:
                switches = session.query(ModelSwitch).limit(limit).all()
            else:
                switches = session.query(ModelSwitch).all()

            for switch in switches:
                switch_res = {}
                switch_res['id'] = switch.id
                switch_res['ip'] = switch.ip
                switch_res['state'] = switch.state
                switch_res['link'] = {
                    'rel': 'self',
                    'href': '/'.join((self.ENDPOINT, str(switch.id)))
                }
                switch_list.append(switch_res)
        logging.info('get switch list: %s', switch_list)

        return util.make_json_response(200, {
            "status": 'OK',
            "switches": switch_list
        })