Exemplo n.º 1
0
    def discover(self, device_id):
        """
        Discovers information about a given libra worker based on device ID
        """

        if not tenant_is_user(request.headers):
            response.status = 401
            return dict(
                faultcode="Client",
                faultstring="Client not authorized to access this function")

        with db_session() as session:
            device = session.query(Device.name).\
                filter(Device.id == device_id).scalar()
            device_name = str(device)
            session.commit()
        if device_name is None:
            response.status = 404
            return dict(faultcode="Client",
                        faultstring="Device " + device_id + " not found")
        gearman = GearJobs()
        discover = gearman.get_discover(device_name)
        if discover is None:
            response.status = 500
            return dict(faultcode="Server",
                        faultstring="Could not discover device")
        return dict(id=device_id,
                    version=discover['version'],
                    release=discover['release'])
Exemplo n.º 2
0
    def discover(self, device_id):
        """
        Discovers information about a given libra worker based on device ID
        """

        if not tenant_is_user(request.headers):
            response.status = 401
            return dict(
                faultcode="Client",
                faultstring="Client not authorized to access this function"
            )

        with db_session() as session:
            device = session.query(Device.name).\
                filter(Device.id == device_id).scalar()
            device_name = str(device)
            session.commit()
        if device_name is None:
            response.status = 404
            return dict(
                faultcode="Client",
                faultstring="Device " + device_id + " not found"
            )
        gearman = GearJobs()
        discover = gearman.get_discover(device_name)
        if discover is None:
            response.status = 500
            return dict(
                faultcode="Server",
                faultstring="Could not discover device"
            )
        return dict(
            id=device_id, version=discover['version'],
            release=discover['release']
        )
Exemplo n.º 3
0
Arquivo: user.py Projeto: pcrews/libra
    def get_one(self, tenant_id=None):
        """
        Get a single Admin API user or details about self
        """
        if not tenant_is_user(request.headers):
            response.status = 401
            return dict(
                faultcode="Client",
                faultstring="Client not authorized to access this function"
            )

        with db_session() as session:
            user = session.query(AdminAuth).\
                filter(AdminAuth.tenant_id == tenant_id).first()
            if user is None:
                response.status = 404
                return dict(
                    faultcode="Client",
                    faultstatus="User not found"
                )
            ret = {
                "tenant": user.tenant_id,
                "level": user.level
            }
            session.commit()
        return ret
Exemplo n.º 4
0
 def get(self):
     if not tenant_is_user(request.headers):
         response.status = 401
         return dict(
             faultcode="Client",
             faultstring="Client not authorized to access this function")
     with db_session() as session:
         counters = session.query(Counters.name, Counters.value).all()
         return counters
Exemplo n.º 5
0
 def get(self):
     if not tenant_is_user(request.headers):
         response.status = 401
         return dict(
             faultcode="Client",
             faultstring="Client not authorized to access this function"
         )
     with db_session() as session:
         counters = session.query(Counters.name, Counters.value).all()
         return counters
Exemplo n.º 6
0
    def get_one(self, tenant_id):
        if not tenant_is_user(request.headers):
            response.status = 401
            return dict(
                faultcode="Client",
                faultstring="Client not authorized to access this function")
        ret = {}
        with db_session() as session:
            limit = session.query(TenantLimits.loadbalancers).\
                filter(TenantLimits.tenantid == tenant_id).scalar()

            ret['maxLoadBalancers'] = limit
            session.commit()
        return ret
Exemplo n.º 7
0
    def get_one(self, tenant_id):
        if not tenant_is_user(request.headers):
            response.status = 401
            return dict(
                faultcode="Client",
                faultstring="Client not authorized to access this function"
            )
        ret = {}
        with db_session() as session:
            limit = session.query(TenantLimits.loadbalancers).\
                filter(TenantLimits.tenantid == tenant_id).scalar()

            ret['maxLoadBalancers'] = limit
            session.commit()
        return ret
Exemplo n.º 8
0
 def get_all(self):
     if not tenant_is_user(request.headers):
         response.status = 401
         return dict(
             faultcode="Client",
             faultstring="Client not authorized to access this function")
     ret = {}
     with db_session() as session:
         limits = session.query(Limits.name, Limits.value).all()
         if limits is None:
             response.status = 500
             return dict(faultcode="Server",
                         faultstring="Error obtaining limits")
         for limit in limits:
             ret[limit.name] = limit.value
         session.commit()
     return ret
Exemplo n.º 9
0
 def get_all(self):
     if not tenant_is_user(request.headers):
         response.status = 401
         return dict(
             faultcode="Client",
             faultstring="Client not authorized to access this function"
         )
     ret = {}
     with db_session() as session:
         limits = session.query(Limits.name, Limits.value).all()
         if limits is None:
             response.status = 500
             return dict(
                 faultcode="Server",
                 faultstring="Error obtaining limits"
             )
         for limit in limits:
             ret[limit.name] = limit.value
         session.commit()
     return ret
Exemplo n.º 10
0
 def get(self):
     if not tenant_is_user(request.headers):
         response.status = 401
         return dict(
             faultcode="Client",
             faultstring="Client not authorized to access this function"
         )
     NULL = None  # For pep8
     with db_session() as session:
         dev_use = session.query(Device).\
             filter(Device.status == 'ONLINE').count()
         dev_free = session.query(Device).\
             filter(Device.status == 'OFFLINE').count()
         dev_error = session.query(Device).\
             filter(Device.status == 'ERROR').count()
         dev_pending = session.query(Device).\
             filter(Device.status == 'DELETED').count()
         vips_use = session.query(Vip).\
             filter(Vip.device > 0).count()
         vips_free = session.query(Vip).\
             filter(Vip.device == NULL).count()
         vips_bad = session.query(Vip).\
             filter(Vip.device == 0).count()
         status = {
             "devices": {
                 "used": dev_use,
                 "available": dev_free,
                 "error": dev_error,
                 "pendingDelete": dev_pending
             },
             "vips": {
                 "used": vips_use,
                 "available": vips_free,
                 "bad": vips_bad
             }
         }
         session.commit()
     return status
Exemplo n.º 11
0
 def get(self):
     if not tenant_is_user(request.headers):
         response.status = 401
         return dict(
             faultcode="Client",
             faultstring="Client not authorized to access this function")
     NULL = None  # For pep8
     with db_session() as session:
         dev_use = session.query(Device).\
             filter(Device.status == 'ONLINE').count()
         dev_free = session.query(Device).\
             filter(Device.status == 'OFFLINE').count()
         dev_error = session.query(Device).\
             filter(Device.status == 'ERROR').count()
         dev_pending = session.query(Device).\
             filter(Device.status == 'DELETED').count()
         vips_use = session.query(Vip).\
             filter(Vip.device > 0).count()
         vips_free = session.query(Vip).\
             filter(Vip.device == NULL).count()
         vips_bad = session.query(Vip).\
             filter(Vip.device == 0).count()
         status = {
             "devices": {
                 "used": dev_use,
                 "available": dev_free,
                 "error": dev_error,
                 "pendingDelete": dev_pending
             },
             "vips": {
                 "used": vips_use,
                 "available": vips_free,
                 "bad": vips_bad
             }
         }
         session.commit()
     return status
Exemplo n.º 12
0
    def get(
            self, device_id=None, status=None, name=None, ip=None, vip=None
    ):
        """
        Gets either a list of all devices or a single device details.

        :param device_id: id of device (unless getall)
        Url:
            GET /devices
            List all configured devices
        Url:
            GET /devices/{device_id}
            List details of a particular device
        Returns: dict
        """

        # Work around routing issue in Pecan, doesn't work as a separate class
        # due to this get accepting more than one parameter
        if status == 'discover':
            return self.discover(device_id)

        if not tenant_is_user(request.headers):
            response.status = 401
            return dict(
                faultcode="Client",
                faultstring="Client not authorized to access this function"
            )

        with db_session() as session:
            # if we don't have an id then we want a list of all devices
            if not device_id:
                #  return all devices
                device = {'devices': []}

                devices = session.query(
                    Device.id, Device.az, Device.updated, Device.created,
                    Device.status, Device.name, Device.type,
                    Device.floatingIpAddr.label('ip'), Vip.id.label('vipid'),
                    Vip.ip.label('vip')).outerjoin(Device.vip)

                if vip is not None:
                    # Search devices by vip, should only return one
                    vip_num = int(ipaddress.IPv4Address(unicode(vip)))
                    devices = devices.filter(Vip.ip == vip_num)

                if status is not None:
                    # Search devices by status
                    status = status.upper()
                    if status not in ['OFFLINE', 'ONLINE', 'ERROR']:
                        # Invalid status specified
                        response.status = 400
                        return dict(
                            faultcode="Client",
                            faultstring="Invalid status: " + status
                        )
                    devices = devices.filter(Device.status == status)
                if name is not None:
                    # Search devices by name, should only return one
                    devices = devices.filter(Device.name == name)
                if ip is not None:
                    # Search devices by IP, should only return one
                    devices = devices.filter(Device.floatingIpAddr == ip)

                devices.all()

                for item in devices:
                    dev = item._asdict()
                    if dev['vip']:
                        dev['vip'] = [{
                            "id": dev['vipid'],
                            "address": str(ipaddress.IPv4Address(dev['vip']))
                        }]
                    else:
                        dev['vip'] = []
                    del(dev['vipid'])
                    device['devices'].append(dev)
            else:
                #  return device detail
                device = session.query(
                    Device.id, Device.az, Device.updated, Device.created,
                    Device.status, Device.floatingIpAddr.label('ip'),
                    Device.name, Device.type, Vip.id.label('vipid'),
                    Vip.ip.label('vip')
                ).outerjoin(Device.vip).filter(Device.id == device_id).first()

                if not device:
                    response.status = 404
                    session.rollback()
                    return dict(
                        faultcode="Client",
                        faultstring="device id " + device_id + "not found"
                    )

                device = device._asdict()
                if device['vip']:
                    device['vip'] = [{
                        "id": device['vipid'],
                        "address": str(ipaddress.IPv4Address(device['vip']))
                    }]
                else:
                    device['vip'] = []
                del(device['vipid'])

                device['loadBalancers'] = []

                if device['status'] != "OFFLINE":
                    lbids = session.query(
                        loadbalancers_devices.c.loadbalancer).\
                        filter(
                            loadbalancers_devices.c.device == device['id']).\
                        all()

                    lblist = [i[0] for i in lbids]
                    lbs = session.query(
                        LoadBalancer.id, LoadBalancer.tenantid).\
                        filter(LoadBalancer.id.in_(lblist)).all()

                    if lbs:
                        for item in lbs:
                            lb = item._asdict()
                            device['loadBalancers'].append(lb)

            session.commit()
            response.status = 200
            return device
Exemplo n.º 13
0
    def get(
        self, lb_id=None, status=None, tenant=None, name=None, ip=None,
        vip=None
    ):
        """
        Gets either a list of all loadbalancers or a details for a single
        loadbalancer.

        :param lb_id: id of the loadbalancer (unless getall)
        Url:
            GET /loadbalancers
            List all loadbalancers
        Url:
            GET /loadbalancers/{lb_id}
            List details of a particular device
        Returns: dict
        """

        if not tenant_is_user(request.headers):
            response.status = 401
            return dict(
                faultcode="Client",
                faultstring="Client not authorized to access this function"
            )

        with db_session() as session:
            # if there is no lb_id then we want a list of loadbalancers
            if not lb_id:
                loadbalancers = {'loadBalancers': []}

                lbs = session.query(
                    LoadBalancer.id, LoadBalancer.name, LoadBalancer.status,
                    LoadBalancer.tenantid, Vip.id.label('vipid'),
                    Vip.ip.label('vip'),
                    Device.floatingIpAddr.label('ip'),
                    LoadBalancer.protocol, LoadBalancer.algorithm,
                    LoadBalancer.port, LoadBalancer.created,
                    LoadBalancer.updated
                ).join(LoadBalancer.devices).join(Device.vip)

                if status is not None:
                    if status not in ('ACTIVE', 'BUILD', 'DEGRADED', 'ERROR'):
                        response.status = 400
                        return dict(
                            faultcode="Client",
                            faultstring="Invalid status: " + status
                        )
                    lbs = lbs.filter(LoadBalancer.status == status)

                if tenant is not None:
                    lbs = lbs.filter(LoadBalancer.tenantid == tenant)

                if name is not None:
                    lbs = lbs.filter(LoadBalancer.name == name)

                if ip is not None:
                    lbs = lbs.filter(Device.floatingIpAddr == ip)

                if vip is not None:
                    vip_num = int(ipaddress.IPv4Address(unicode(vip)))
                    lbs = lbs.filter(Vip.ip == vip_num)

                lbs.all()

                for item in lbs:
                    lb = item._asdict()
                    if lb['vip']:
                        lb['vip'] = [{
                            "id": lb['vipid'],
                            "address": str(ipaddress.IPv4Address(lb['vip']))
                        }]
                        del(lb['vip'])
                        del(lb['vipid'])
                    else:
                        lb['vip'] = [None]
                        del(lb['vipid'])
                    loadbalancers['loadBalancers'].append(lb)

            else:
                lbs = session.query(
                    LoadBalancer.name, LoadBalancer.id, LoadBalancer.protocol,
                    LoadBalancer.port, LoadBalancer.algorithm,
                    LoadBalancer.status, LoadBalancer.created,
                    LoadBalancer.updated, LoadBalancer.errmsg,
                    Device.id.label('device'),
                    Vip.id.label('vipid'), Vip.ip.label('vip')
                ).join(LoadBalancer.devices).\
                    outerjoin(Device.vip).\
                    filter(LoadBalancer.id == lb_id).\
                    first()

                if not lbs:
                    response.status = 404
                    return dict(
                        faultcode="Client",
                        faultstring="Loadbalancer " + lb_id + " not found"
                    )
                loadbalancers = lbs._asdict()
                nodes = session.query(
                    Node.id, Node.address, Node.port, Node.status,
                    Node.enabled, Node.weight
                ).filter(Node.lbid == lb_id).all()
                loadbalancers['nodes'] = []

                for item in nodes:
                    node = item._asdict()
                    if node['enabled'] == 1:
                        node['condition'] = 'ENABLED'
                    else:
                        node['condition'] = 'DISABLED'
                    del node['enabled']
                    node['port'] = str(node['port'])
                    node['id'] = str(node['id'])
                    if node['weight'] == 1:
                        del node['weight']
                    loadbalancers['nodes'].append(node)

                if loadbalancers['vip']:
                    loadbalancers['vip'] = [{
                        "id": loadbalancers['vipid'],
                        "address": str(
                            ipaddress.IPv4Address(loadbalancers['vip'])
                        )
                    }]
                    del(loadbalancers['vip'])
                    del(loadbalancers['vipid'])
                else:
                    loadbalancers['vip'] = [None]
                    del(loadbalancers['vipid'])
                if not loadbalancers['errmsg']:
                    loadbalancers['statusDescription'] = None
                else:
                    loadbalancers['statusDescription'] =\
                        loadbalancers['errmsg']
                del(loadbalancers['errmsg'])

                monitor = session.query(
                    HealthMonitor.type, HealthMonitor.delay,
                    HealthMonitor.timeout, HealthMonitor.attempts,
                    HealthMonitor.path
                ).join(LoadBalancer.monitors).\
                    filter(LoadBalancer.id == lb_id).first()

                if monitor is None:
                    monitor_data = {}
                else:
                    monitor_data = {
                        'type': monitor.type,
                        'delay': monitor.delay,
                        'timeout': monitor.timeout,
                        'attemptsBeforeDeactivation': monitor.attempts
                    }
                if monitor.path:
                    monitor_data['path'] = monitor.path

                loadbalancers['monitor'] = monitor_data

                session.commit()

            return loadbalancers
Exemplo n.º 14
0
    def get(self):
        if not tenant_is_user(request.headers):
            response.status = 401
            return dict(
                faultcode="Client",
                faultstring="Client not authorized to access this function"
            )

        ret = {
            'mysql': [],
            'gearman': []
        }
        config = ConfigParser.SafeConfigParser()
        config.read(cfg.CONF['config_file'])

        # Connect to all MySQL servers and test
        for section in conf.database:
            db_conf = config._sections[section]
            conn_string = '''mysql+mysqlconnector://%s:%s@%s:%s/%s''' % (
                db_conf['username'],
                db_conf['password'],
                db_conf['host'],
                db_conf['port'],
                db_conf['schema']
            )

            if 'ssl_key' in db_conf:
                ssl_args = {'ssl': {
                    'cert': db_conf['ssl_cert'],
                    'key': db_conf['ssl_key'],
                    'ca': db_conf['ssl_ca']
                }}

                engine = create_engine(
                    conn_string, isolation_level="READ COMMITTED",
                    pool_size=1, connect_args=ssl_args, pool_recycle=3600
                )
            else:
                engine = create_engine(
                    conn_string, isolation_level="READ COMMITTED",
                    pool_size=1, pool_recycle=3600
                )
            session = sessionmaker(bind=engine)()
            try:
                session.execute("SELECT 1")
                session.close()
                ret['mysql'].append(
                    {"ip": db_conf['host'], "status": 'ONLINE'}
                )
            except:
                ret['mysql'].append(
                    {"ip": db_conf['host'], "status": 'OFFLINE'}
                )

        # Socket connect to all gearman servers, TODO: a better gearman test
        for server in conf.gearman.server:
            ghost, gport = server.split(':')
            try:
                sock = socket.socket()
                sock.settimeout(5)
                sock.connect((ghost, int(gport)))
                sock.close()
                ret['gearman'].append({"ip": ghost, "status": 'ONLINE'})
            except socket.error:
                ret['gearman'].append({"ip": ghost, "status": 'OFFLINE'})
                try:
                    sock.close()
                except:
                    pass

        return ret
Exemplo n.º 15
0
    def get(self):
        if not tenant_is_user(request.headers):
            response.status = 401
            return dict(
                faultcode="Client",
                faultstring="Client not authorized to access this function")

        ret = {'mysql': [], 'gearman': []}
        config = ConfigParser.SafeConfigParser()
        config.read(cfg.CONF['config_file'])

        # Connect to all MySQL servers and test
        for section in conf.database:
            db_conf = config._sections[section]
            conn_string = '''mysql+mysqlconnector://%s:%s@%s:%s/%s''' % (
                db_conf['username'], db_conf['password'], db_conf['host'],
                db_conf['port'], db_conf['schema'])

            if 'ssl_key' in db_conf:
                ssl_args = {
                    'ssl': {
                        'cert': db_conf['ssl_cert'],
                        'key': db_conf['ssl_key'],
                        'ca': db_conf['ssl_ca']
                    }
                }

                engine = create_engine(conn_string,
                                       isolation_level="READ COMMITTED",
                                       pool_size=1,
                                       connect_args=ssl_args,
                                       pool_recycle=3600)
            else:
                engine = create_engine(conn_string,
                                       isolation_level="READ COMMITTED",
                                       pool_size=1,
                                       pool_recycle=3600)
            session = sessionmaker(bind=engine)()
            try:
                session.execute("SELECT 1")
                session.close()
                ret['mysql'].append({
                    "ip": db_conf['host'],
                    "status": 'ONLINE'
                })
            except:
                ret['mysql'].append({
                    "ip": db_conf['host'],
                    "status": 'OFFLINE'
                })

        # Socket connect to all gearman servers, TODO: a better gearman test
        for server in conf.gearman.server:
            ghost, gport = server.split(':')
            try:
                sock = socket.socket()
                sock.settimeout(5)
                sock.connect((ghost, int(gport)))
                sock.close()
                ret['gearman'].append({"ip": ghost, "status": 'ONLINE'})
            except socket.error:
                ret['gearman'].append({"ip": ghost, "status": 'OFFLINE'})
                try:
                    sock.close()
                except:
                    pass

        return ret
Exemplo n.º 16
0
    def get(self, device_id=None, status=None, name=None, ip=None, vip=None):
        """
        Gets either a list of all devices or a single device details.

        :param device_id: id of device (unless getall)
        Url:
            GET /devices
            List all configured devices
        Url:
            GET /devices/{device_id}
            List details of a particular device
        Returns: dict
        """

        # Work around routing issue in Pecan, doesn't work as a separate class
        # due to this get accepting more than one parameter
        if status == 'discover':
            return self.discover(device_id)

        if not tenant_is_user(request.headers):
            response.status = 401
            return dict(
                faultcode="Client",
                faultstring="Client not authorized to access this function")

        with db_session() as session:
            # if we don't have an id then we want a list of all devices
            if not device_id:
                #  return all devices
                device = {'devices': []}

                devices = session.query(
                    Device.id, Device.az, Device.updated, Device.created,
                    Device.status, Device.name, Device.type,
                    Device.floatingIpAddr.label('ip'), Vip.id.label('vipid'),
                    Vip.ip.label('vip')).outerjoin(Device.vip)

                if vip is not None:
                    # Search devices by vip, should only return one
                    vip_num = int(ipaddress.IPv4Address(unicode(vip)))
                    devices = devices.filter(Vip.ip == vip_num)

                if status is not None:
                    # Search devices by status
                    status = status.upper()
                    if status not in ['OFFLINE', 'ONLINE', 'ERROR']:
                        # Invalid status specified
                        response.status = 400
                        return dict(faultcode="Client",
                                    faultstring="Invalid status: " + status)
                    devices = devices.filter(Device.status == status)
                if name is not None:
                    # Search devices by name, should only return one
                    devices = devices.filter(Device.name == name)
                if ip is not None:
                    # Search devices by IP, should only return one
                    devices = devices.filter(Device.floatingIpAddr == ip)

                devices.all()

                for item in devices:
                    dev = item._asdict()
                    if dev['vip']:
                        dev['vip'] = [{
                            "id":
                            dev['vipid'],
                            "address":
                            str(ipaddress.IPv4Address(dev['vip']))
                        }]
                    else:
                        dev['vip'] = []
                    del (dev['vipid'])
                    device['devices'].append(dev)
            else:
                #  return device detail
                device = session.query(
                    Device.id, Device.az, Device.updated, Device.created,
                    Device.status, Device.floatingIpAddr.label('ip'),
                    Device.name, Device.type, Vip.id.label('vipid'),
                    Vip.ip.label('vip')).outerjoin(
                        Device.vip).filter(Device.id == device_id).first()

                if not device:
                    response.status = 404
                    session.rollback()
                    return dict(faultcode="Client",
                                faultstring="device id " + device_id +
                                "not found")

                device = device._asdict()
                if device['vip']:
                    device['vip'] = [{
                        "id":
                        device['vipid'],
                        "address":
                        str(ipaddress.IPv4Address(device['vip']))
                    }]
                else:
                    device['vip'] = []
                del (device['vipid'])

                device['loadBalancers'] = []

                if device['status'] != "OFFLINE":
                    lbids = session.query(
                        loadbalancers_devices.c.loadbalancer).\
                        filter(
                            loadbalancers_devices.c.device == device['id']).\
                        all()

                    lblist = [i[0] for i in lbids]
                    lbs = session.query(
                        LoadBalancer.id, LoadBalancer.tenantid).\
                        filter(LoadBalancer.id.in_(lblist)).all()

                    if lbs:
                        for item in lbs:
                            lb = item._asdict()
                            device['loadBalancers'].append(lb)

            session.commit()
            response.status = 200
            return device