Example #1
0
def get_storages(auth, region):
    result = {"storage_device": []}
    conn = db.getDevicesConn()
    try:
        with conn.cursor() as cursor:
            sql = "SELECT * FROM Storage where regionname=%s"
            cursor.execute(sql, (region,))
            res = cursor.fetchall()
            for r in res:
                tmp = {}
                tmp["id"] = r["id"]
                tmp["name"] = r["name"]
                tmp["description"] = r.get("description", "")
                tmp["model"] = r.get("model", "")
                tmp["vendor"] = r.get("vendor", "")
                tmp["device_type"] = r.get("device_type", "")
                tmp["capacity"] = r.get("capacity", "")
                tmp["mac_address"] = r.get("mac_address", "")
                tmp["ip_address"] = r.get("ip_address", "")
                result["storage_device"].append(tmp)
    except Exception as exc:
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps(result), 200)
Example #2
0
def get_workissue(auth, region, workissue_id):
    conn = db.getWorkIssueConn()
    try:
        with conn.cursor() as cursor:
            sql = 'SELECT id, tenant_id, user_id, title,'\
                  ' content, status, user_email,'\
                  ' user_tel, created_time, response_time, fix_time'\
                  ' FROM workissue'\
                  ' WHERE region = %s and id = %s'
            cursor.execute(sql, (region, workissue_id))
            res = cursor.fetchone()
            copy_res = copy.deepcopy(res)
            if res:
                res['created_time'] = decode_datetime(
                    copy_res['created_time'])
                res['response_time'] = decode_datetime(
                    copy_res.get('response_time', ''))
                res['fix_time'] = decode_datetime(
                    copy_res.get('response_time', ''))
                result = {'workissue': res}
                return make_response(json.dumps(result), 200)
            else:
                msg = 'The workissue %s cannot be found' % workissue_id
                return make_response(msg, 404)
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
Example #3
0
def create_workissue(auth, region):
    try:
        req_body = json.loads(frequest.data)['workissue']
    except KeyError:
        raise BadRequest(description='Invalid request body')
    except Exception as exc:
        log.error(exc)
    if not set(REQ_ITEM).issubset(set(req_body.keys())):
        msg = 'You should provide requried all params in (%s)' %\
              ','.join(REQ_ITEM)
        raise BadRequest(description=msg)
    conn = db.getWorkIssueConn()
    try:
        uuid_str = str(uuid.uuid4())
        with conn.cursor() as cursor:
            sql = 'insert into workissue('\
                ' `id`,`tenant_id`, `user_id`, `title`, `content`,'\
                ' `status`, `user_email`, `user_tel`, `region`,'\
                ' `created_time`)'\
                ' VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, Now())'
            cursor.execute(sql, (uuid_str, req_body['tenant_id'],
                                 req_body['user_id'],
                                 req_body['title'],
                                 req_body['content'],
                                 req_body['status'],
                                 req_body.get('user_email', ''),
                                 req_body.get('user_tel', ''), region))
            conn.commit()
        result = {'workissue': {'id': uuid_str}}
        return make_response(json.dumps(result), 201)
    except Exception as exc:
        log.error(exc)
        return make_response(exc, 500)
    finally:
        conn.close()
Example #4
0
def get_workissue(auth, region, workissue_id):
    conn = db.getWorkIssueConn()
    try:
        with conn.cursor() as cursor:
            sql = 'SELECT id, tenant_id, user_id, title,'\
                  ' content, status, user_email,'\
                  ' user_tel, created_time, response_time, fix_time'\
                  ' FROM workissue'\
                  ' WHERE region = %s and id = %s'
            cursor.execute(sql, (region, workissue_id))
            res = cursor.fetchone()
            copy_res = copy.deepcopy(res)
            if res:
                res['created_time'] = decode_datetime(copy_res['created_time'])
                res['response_time'] = decode_datetime(
                    copy_res.get('response_time', ''))
                res['fix_time'] = decode_datetime(
                    copy_res.get('response_time', ''))
                result = {'workissue': res}
                return make_response(json.dumps(result), 200)
            else:
                msg = 'The workissue %s cannot be found' % workissue_id
                return make_response(msg, 404)
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
Example #5
0
def get_storages(auth, region):
    result = {'storage_device': []}
    conn = db.getDevicesConn()
    try:
        with conn.cursor() as cursor:
            sql = "SELECT * FROM Storage where regionname=%s"
            cursor.execute(sql, (region, ))
            res = cursor.fetchall()
            for r in res:
                tmp = {}
                tmp['id'] = r['id']
                tmp['name'] = r['name']
                tmp['description'] = r.get('description', '')
                tmp['model'] = r.get('model', '')
                tmp['vendor'] = r.get('vendor', '')
                tmp['device_type'] = r.get('device_type', '')
                tmp['capacity'] = r.get('capacity', '')
                tmp['mac_address'] = r.get('mac_address', '')
                tmp['ip_address'] = r.get('ip_address', '')
                result['storage_device'].append(tmp)
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps(result), 200)
Example #6
0
def create_workissue(auth, region):
    try:
        req_body = json.loads(frequest.data)['workissue']
    except KeyError:
        raise BadRequest(description='Invalid request body')
    except Exception as exc:
        log.error(exc)
    if not set(REQ_ITEM).issubset(set(req_body.keys())):
        msg = 'You should provide requried all params in (%s)' %\
              ','.join(REQ_ITEM)
        raise BadRequest(description=msg)
    conn = db.getWorkIssueConn()
    try:
        uuid_str = str(uuid.uuid4())
        with conn.cursor() as cursor:
            sql = 'insert into workissue('\
                ' `id`,`tenant_id`, `user_id`, `title`, `content`,'\
                ' `status`, `user_email`, `user_tel`, `region`,'\
                ' `created_time`)'\
                ' VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, Now())'
            cursor.execute(
                sql,
                (uuid_str, req_body['tenant_id'], req_body['user_id'],
                 req_body['title'], req_body['content'], req_body['status'],
                 req_body.get('user_email', ''), req_body.get('user_tel',
                                                              ''), region))
            conn.commit()
        result = {'workissue': {'id': uuid_str}}
        return make_response(json.dumps(result), 201)
    except Exception as exc:
        log.error(exc)
        return make_response(exc, 500)
    finally:
        conn.close()
Example #7
0
def get_port_monitor(auth, region, port_id):
    floating_url = auth[2][0] + '/floatingips/' + port_id
    port_url = auth[2][0] + '/ports?device_id=' + port_id

    floating_resp = httprequest.httpclient(
            'GET', floating_url, auth[0])
    port_resp = httprequest.httpclient(
            'GET', port_url, auth[0])
    port_data = json.loads(port_resp.content)
    floating_data = json.loads(floating_resp.content)
    if not floating_data.get('floatingip', '').get('id', None):
        resp = {'code': 404, 'message': 'Port Not Found'}
        return make_response(json.dumps(resp),
                             floating_resp.status_code)

    resp = {}
    port_data = port_data['ports'][0]
    floating_data = floating_data['floatingip']
    resp['port_id'] = port_id
    resp['ip_address'] = floating_data['floating_ip_address']
    resp['status'] = floating_data['status'].lower()
    resp['mac_address'] = port_data.get('mac_address', '')
    resp['inbound_rate'] = 0
    resp['outbound_rate'] = 0
    resp['health_status'] = True

    return make_response(json.dumps({'port_monitor': resp}),
                         floating_resp.status_code)
Example #8
0
def get_devices(auth, region, project_id, device_id):
    physical_devices = {}
    if not verify_id(device_id):
        message = 'Invalid device_id! Please check it.'
        response = {'code': 400, 'message': message}
        return make_response(json.dumps(response), 400)

    try:
        conn = get_database_conn()
        with conn.cursor() as cursor:
            sql = 'select * from ' + TABLE_NAME_PHYSICAL_DEVICES + \
                ' where id=\'' + device_id + '\''
            result_num = cursor.execute(sql)
            if result_num == 1:
                physical_devices = cursor.fetchone()
            elif result_num == 0:
                message = 'Unable to find physical device with id ' + device_id
                log.debug(message)
                response = {'code': 404, 'message': message}
                return make_response(json.dumps(response), 404)
            else:
                message = 'Unknown error.'
                log.error(message)
                response = {'code': 500, 'message': message}
                return make_response(json.dumps(response), 500)

    except Exception as e:
        log.error(e)
        response = {'code': 500, 'message': str(e)}
        return make_response(json.dumps(response), 500)
    else:
        body = {'physical_devices': physical_devices}
        return make_response(json.dumps(body), 200)
Example #9
0
def get_storages(auth, region):
    result = {'storage_device': []}
    conn = db.getDevicesConn()
    try:
        with conn.cursor() as cursor:
            sql = "SELECT * FROM Storage where regionname=%s"
            cursor.execute(sql, (region,))
            res = cursor.fetchall()
            for r in res:
                tmp = {}
                tmp['id'] = r['id']
                tmp['name'] = r['name']
                tmp['description'] = r.get('description', '')
                tmp['model'] = r.get('model', '')
                tmp['vendor'] = r.get('vendor', '')
                tmp['device_type'] = r.get('device_type', '')
                tmp['capacity'] = r.get('capacity', '')
                tmp['mac_address'] = r.get('mac_address', '')
                tmp['ip_address'] = r.get('ip_address', '')
                result['storage_device'].append(tmp)
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps(result), 200)
Example #10
0
def get_port_monitor(auth, region, port_id):
    floating_url = auth[2][0] + '/floatingips/' + port_id
    port_url = auth[2][0] + '/ports?device_id=' + port_id

    floating_resp = httprequest.httpclient('GET', floating_url, auth[0])
    port_resp = httprequest.httpclient('GET', port_url, auth[0])
    port_data = json.loads(port_resp.content)
    floating_data = json.loads(floating_resp.content)
    if not floating_data.get('floatingip', '').get('id', None):
        resp = {'code': 404, 'message': 'Port Not Found'}
        return make_response(json.dumps(resp), floating_resp.status_code)

    resp = {}
    port_data = port_data['ports'][0]
    floating_data = floating_data['floatingip']
    resp['port_id'] = port_id
    resp['ip_address'] = floating_data['floating_ip_address']
    resp['status'] = floating_data['status'].lower()
    resp['mac_address'] = port_data.get('mac_address', '')
    resp['inbound_rate'] = 0
    resp['outbound_rate'] = 0
    resp['health_status'] = True

    return make_response(json.dumps({'port_monitor': resp}),
                         floating_resp.status_code)
Example #11
0
def list_virus(auth, region, project_id):
    virus = []
    try:
        conn = get_database_conn()
        with conn.cursor() as cursor:
            sql = 'select * from ' + TABLE_NAME_VIRUS + \
                ' where tenant_id=\'' + project_id + '\''
            result_num = cursor.execute(sql)
            for result in cursor:
                if result.get('upload') == 1:
                    result['upload'] = True
                else:
                    result['upload'] = False
                if result.get('download') == 1:
                    result['download'] = True
                else:
                    result['download'] = True
                virus.append(result)
    except Exception as e:
        log.error(e)
        response = {'code': 500, 'message': str(e)}
        return make_response(json.dumps(response), 500)
    else:
        body = {'virus': virus}
        return make_response(json.dumps(body), 200)
Example #12
0
def get_server_warnings(warn_id):
    conn = getDBConn()
    warning = {}
    try:
        with conn.cursor() as cursor:
            cursor.callproc('sp_get_server_warnings_detail', (warn_id, ))
            result = cursor.fetchone()
            if not result:
                return make_response('Resource not Found', 404)
            warning['id'] = result['id']
            warning['tenant_id'] = result.get('tenant_id', '')
            warning['strategy_id'] = result.get('strategy_id', '')
            warning['name'] = result.get('name', '')
            warning['type'] = result.get('type', '')
            warning['description'] = result.get('description', '')
            warning['level'] = result.get('level', '')
            warning['server_id'] = result.get('server_id', '')
            warning['created'] = str(result.get('created', ''))
            warning['status'] = result.get('status', '')
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps({'warnings': warning}), 200)
Example #13
0
def get_devices(auth, region, project_id, device_id):
    physical_devices = {}
    if not verify_id(device_id):
        message = 'Invalid device_id! Please check it.'
        response = {'code': 400, 'message': message}
        return make_response(json.dumps(response), 400)

    try:
        conn = get_database_conn()
        with conn.cursor() as cursor:
            sql = 'select * from ' + TABLE_NAME_PHYSICAL_DEVICES + \
                ' where id=\'' + device_id + '\''
            result_num = cursor.execute(sql)
            if result_num == 1:
                physical_devices = cursor.fetchone()
            elif result_num == 0:
                message = 'Unable to find physical device with id ' + device_id
                log.debug(message)
                response = {'code': 404, 'message': message}
                return make_response(json.dumps(response), 404)
            else:
                message = 'Unknown error.'
                log.error(message)
                response = {'code': 500, 'message': message}
                return make_response(json.dumps(response), 500)

    except Exception as e:
        log.error(e)
        response = {'code': 500, 'message': str(e)}
        return make_response(json.dumps(response), 500)
    else:
        body = {'physical_devices': physical_devices}
        return make_response(json.dumps(body), 200)
Example #14
0
def get_waf(auth, region, project_id, wafs_id):
    wafs = {}
    if not verify_id(wafs_id):
        message = 'Invalid wafs id! Please check it.'
        response = {'code': 400, 'message': message}
        return make_response(json.dumps(response), 400)

    try:
        conn = get_database_conn()
        with conn.cursor() as cursor:
            sql = 'select * from ' + TABLE_NAME_WAFS + \
                ' where id=\'' + wafs_id + '\''
            result_num = cursor.execute(sql)
            if result_num == 1:
                wafs = cursor.fetchone()
            elif result_num == 0:
                message = 'Unable to find ips with id ' + wafs_id
                log.debug(message)
                response = {'code': 404, 'message': message}
                return make_response(json.dumps(response), 404)
            else:
                message = 'Unknown error.'
                log.error(message)
                response = {'code': 500, 'message': message}
                return make_response(json.dumps(response), 500)

    except Exception as e:
        log.error(e)
        response = {'code': 500, 'message': str(e)}
        return make_response(json.dumps(response), 500)
    else:
        body = {'wafs': wafs}
        return make_response(json.dumps(body), 200)
Example #15
0
def get_device_warnings_list():
    requestParam = {}
    requestParam['order_by'] = request.args.get('order_by', 'created_time')
    requestParam['desc'] = request.args.get('desc', 'false')
    requestParam['start_time'] = request.args.get('start_time', None)
    requestParam['end_time'] = request.args.get('end_time', None)
    conn = getDBConn()
    try:
        cursor = conn.cursor()
        cursor.callproc('sp_get_device_warnings',(requestParam['start_time'],requestParam['end_time'] ))
        resultSet = cursor.fetchall()
        warnings=[]
        for result in resultSet:
            warning={}
            warning['id']=result.get('id','')
            warning['strategy_id']=result.get('strategy_id','')
            warning['name']=result.get('name','')
            warning['type']=result.get('type','')
            warning['description']=result.get('description','')
            warning['level']=result.get('level','')
            warning['object_id']=result.get('object_id','')
            warning['object_type']=result.get('object_type','')
            warning['created']=str(result.get('created',''))
            warning['status']=result.get('status','')
            warnings.append(warning)
        cursor.close()
        if len(warnings)>0 :
            warnings = sorted(warnings, key=lambda k: k['created'],reverse= (requestParam['desc']=='true'))
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps({'warnings':warnings}), 200)
Example #16
0
def get_server_warnings(warn_id):
    conn = getDBConn()
    warning={}
    try:
        cursor = conn.cursor()
        cursor.callproc('sp_get_server_warnings_detail',(warn_id,))
        result = cursor.fetchone()
        print result
        if result==None:
            return make_response('Resource not Found',404)
        warning['id']=result['id']
        warning['tenant_id']=result.get('tenant_id','')
        warning['strategy_id']=result.get('strategy_id','')
        warning['name']=result.get('name','')
        warning['type']=result.get('type','')
        warning['description']=result.get('description','')
        warning['level']=result.get('level','')
        warning['server_id']=result.get('server_id','')
        warning['created']=str(result.get('created',''))
        warning['status']=result.get('status','')
        cursor.close()
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps({'warnings':warning}), 200)
Example #17
0
def list_virus(auth, region, project_id):
    virus = []
    try:
        conn = get_database_conn()
        with conn.cursor() as cursor:
            sql = 'select * from ' + TABLE_NAME_VIRUS + \
                ' where tenant_id=\'' + project_id + '\''
            result_num = cursor.execute(sql)
            for result in cursor:
                if result.get('upload') == 1:
                    result['upload'] = True
                else:
                    result['upload'] = False
                if result.get('download') == 1:
                    result['download'] = True
                else:
                    result['download'] = True
                virus.append(result)
    except Exception as e:
        log.error(e)
        response = {'code': 500, 'message': str(e)}
        return make_response(json.dumps(response), 500)
    else:
        body = {'virus': virus}
        return make_response(json.dumps(body), 200)
Example #18
0
def get_waf(auth, region, project_id, wafs_id):
    wafs = {}
    if not verify_id(wafs_id):
        message = 'Invalid wafs id! Please check it.'
        response = {'code': 400, 'message': message}
        return make_response(json.dumps(response), 400)

    try:
        conn = get_database_conn()
        with conn.cursor() as cursor:
            sql = 'select * from ' + TABLE_NAME_WAFS + \
                ' where id=\'' + wafs_id + '\''
            result_num = cursor.execute(sql)
            if result_num == 1:
                wafs = cursor.fetchone()
            elif result_num == 0:
                message = 'Unable to find ips with id ' + wafs_id
                log.debug(message)
                response = {'code': 404, 'message': message}
                return make_response(json.dumps(response), 404)
            else:
                message = 'Unknown error.'
                log.error(message)
                response = {'code': 500, 'message': message}
                return make_response(json.dumps(response), 500)

    except Exception as e:
        log.error(e)
        response = {'code': 500, 'message': str(e)}
        return make_response(json.dumps(response), 500)
    else:
        body = {'wafs': wafs}
        return make_response(json.dumps(body), 200)
Example #19
0
def get_host_monitor(host_id):
    conn = getDBConn()
    try:
        with conn.cursor() as cursor:
            cursor.callproc('sp_get_host_monitor', (host_id, ))
            resultSet = cursor.fetchall()
            host_monitor = {}
            if len(resultSet) > 0:
                host_monitor['host_id'] = host_id
                host_monitor['cpu_usage'] = '-9999'
                host_monitor['mem_usage'] = '-9999'
                host_monitor['power_status'] = 'active'
                host_monitor['running_time'] = '-9999'
                host_monitor['health_status'] = 'false'
                host_monitor['nics'] = []
                host_monitor['disks'] = []
                for result in resultSet:
                    name = result.get('name', '').lower()
                    output = result.get('output', '').lower()
                    if output == '':
                        continue
                    if name == 'uptime':
                        if output.find('uptime=') >= 0:
                            host_monitor['running_time'] =\
                                output.split('=', 1)[1]
                    elif name == 'cpu usage':
                        if output.find('cpuusage=') >= 0:
                            host_monitor['cpu_usage'] =\
                                output.split('=', 1)[1][:-1]
                    elif name == 'memory usage':
                        if output.find('memoryusage=') >= 0:
                            host_monitor['mem_usage'] =\
                                output.split('=', 1)[1][:-1]
                    elif name == 'health_status':
                        host_monitor['health_status'] = output.lower()
                    elif name.startswith('eth'):
                        if output.find('name=') >= 0:
                            host_monitor['nics'].append(
                                getNicsInfo(output))
                    elif name.startswith('disk'):
                        if output.find('name=') >= 0:
                            host_monitor['disks'].append(
                                getDisksInfo(output))
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(
        json.dumps({'host_monitor': host_monitor}), 200)
Example #20
0
def get_hosts(auth, region):
    result = {'hosts': []}
    conn = db.getDevicesConn()
    host_sql = 'SELECT t1.id, t1.os_name,t1.hostname,'\
               ' t1.description, t1.ip_address, t1.hypervisor,'\
               ' t1.model, t1.vendor, t1.cpu_count, t1.cpu_model,'\
               ' t1.cpu_frequence, t1.cpu_socket, t1.cpu_core,'\
               ' t1.memory_size '\
               ' FROM Host t1'\
               ' WHERE t1.regionname=%s'

    tmp_disk_sql = 'SELECT t1.name,'\
                   ' t1.capacity'\
                   ' FROM Disk t1 WHERE t1.host_id = %s'

    tmp_nic_sql = 'SELECT t1.name,'\
                  ' t1.description,'\
                  ' t1.status,'\
                  ' t1.mac_address'\
                  ' FROM Port t1 WHERE t1.host_id = %s'
    try:
        with conn.cursor() as cursor:
            cursor.execute(host_sql, (region, ))
            res = cursor.fetchall()
            for r in res:
                nics = []
                disks = []
                with conn.cursor() as nic_cursor:
                    nic_cursor.execute(tmp_nic_sql, (r['id'], ))
                    nic_res = nic_cursor.fetchall()
                    for nic in nic_res:
                        nics.append(nic)
                    r['nics'] = nics

                with conn.cursor() as disk_cursor:
                    disk_cursor.execute(tmp_disk_sql, (r['id'], ))
                    disk_res = disk_cursor.fetchall()
                    for disk in disk_res:
                        disks.append(disk)
                    r['disks'] = disks
                result['hosts'].append(r)
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps(result), 200)
Example #21
0
def get_host_monitor(host_id):
    conn = getDBConn()
    try:
        with conn.cursor() as cursor:
            cursor.callproc('sp_get_host_monitor', (host_id, ))
            resultSet = cursor.fetchall()
            host_monitor = {}
            if len(resultSet) > 0:
                host_monitor['host_id'] = host_id
                host_monitor['cpu_usage'] = '-9999'
                host_monitor['mem_usage'] = '-9999'
                host_monitor['power_status'] = 'active'
                host_monitor['running_time'] = '-9999'
                host_monitor['health_status'] = 'false'
                host_monitor['nics'] = []
                host_monitor['disks'] = []
                for result in resultSet:
                    name = result.get('name', '').lower()
                    output = result.get('output', '').lower()
                    if output == '':
                        continue
                    if name == 'uptime':
                        if output.find('uptime=') >= 0:
                            host_monitor['running_time'] =\
                                output.split('=', 1)[1]
                    elif name == 'cpu usage':
                        if output.find('cpuusage=') >= 0:
                            host_monitor['cpu_usage'] =\
                                output.split('=', 1)[1][:-1]
                    elif name == 'memory usage':
                        if output.find('memoryusage=') >= 0:
                            host_monitor['mem_usage'] =\
                                output.split('=', 1)[1][:-1]
                    elif name == 'health_status':
                        host_monitor['health_status'] = output.lower()
                    elif name.startswith('eth'):
                        if output.find('name=') >= 0:
                            host_monitor['nics'].append(getNicsInfo(output))
                    elif name.startswith('disk'):
                        if output.find('name=') >= 0:
                            host_monitor['disks'].append(getDisksInfo(output))
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps({'host_monitor': host_monitor}), 200)
Example #22
0
def get_hosts(auth, region):
    result = {'hosts': []}
    conn = db.getDevicesConn()
    host_sql = 'SELECT t1.id, t1.os_name,t1.hostname,'\
               ' t1.description, t1.ip_address, t1.hypervisor,'\
               ' t1.model, t1.vendor, t1.cpu_count, t1.cpu_model,'\
               ' t1.cpu_frequence, t1.cpu_socket, t1.cpu_core,'\
               ' t1.memory_size '\
               ' FROM Host t1'\
               ' WHERE t1.regionname=%s'

    tmp_disk_sql = 'SELECT t1.name,'\
                   ' t1.capacity'\
                   ' FROM Disk t1 WHERE t1.host_id = %s'

    tmp_nic_sql = 'SELECT t1.name,'\
                  ' t1.description,'\
                  ' t1.status,'\
                  ' t1.mac_address'\
                  ' FROM Port t1 WHERE t1.host_id = %s'
    try:
        with conn.cursor() as cursor:
            cursor.execute(host_sql, (region,))
            res = cursor.fetchall()
            for r in res:
                nics = []
                disks = []
                with conn.cursor() as nic_cursor:
                    nic_cursor.execute(tmp_nic_sql, (r['id'],))
                    nic_res = nic_cursor.fetchall()
                    for nic in nic_res:
                        nics.append(nic)
                    r['nics'] = nics

                with conn.cursor() as disk_cursor:
                    disk_cursor.execute(tmp_disk_sql, (r['id'],))
                    disk_res = disk_cursor.fetchall()
                    for disk in disk_res:
                        disks.append(disk)
                    r['disks'] = disks
                result['hosts'].append(r)
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps(result), 200)
Example #23
0
def list_wafs(auth, region, project_id):
    wafs = []
    try:
        conn = get_database_conn()
        with conn.cursor() as cursor:
            sql = 'select * from ' + TABLE_NAME_WAFS + \
                ' where tenant_id=\'' + project_id + '\''
            result_num = cursor.execute(sql)
            for result in cursor:
                wafs.append(result)
    except Exception as e:
        log.error(e)
        response = {'code': 500, 'message': str(e)}
        return make_response(json.dumps(response), 500)
    else:
        body = {'wafs': wafs}
        return make_response(json.dumps(body), 200)
Example #24
0
def list_wafs(auth, region, project_id):
    wafs = []
    try:
        conn = get_database_conn()
        with conn.cursor() as cursor:
            sql = 'select * from ' + TABLE_NAME_WAFS + \
                ' where tenant_id=\'' + project_id + '\''
            result_num = cursor.execute(sql)
            for result in cursor:
                wafs.append(result)
    except Exception as e:
        log.error(e)
        response = {'code': 500, 'message': str(e)}
        return make_response(json.dumps(response), 500)
    else:
        body = {'wafs': wafs}
        return make_response(json.dumps(body), 200)
Example #25
0
def get_warn_strategies_list(auth, region):
    conn = getDBConn()
    try:
        with conn.cursor() as cursor:
            cursor.callproc('sp_get_warn_strategies', (region, ))
            warn_strategys = []
            warn_id_dict = {}
            resultSet = cursor.fetchall()
            for result in resultSet:
                warn_strategy = {}
                warn_strategy['id'] = result.get('id', '')
                warn_strategy['tenant_id'] = result.get('tenant_id', '')
                warn_strategy['name'] = result.get('name', '')
                warn_strategy['type'] = result.get('type', '')
                warn_strategy['level'] = result.get('warn_level', '')
                warn_strategy['relationship'] = result.get('relationship', '')
                warn_strategy['rules'] = []
                warn_strategy['servers'] = []
                warn_id_dict[result['id']] = warn_strategy
                warn_strategys.append(warn_strategy)

            cursor.nextset()
            resultSet = cursor.fetchall()
            for result in resultSet:
                rule = {}
                rule['field'] = result.get('field', '')
                rule['comparison'] = result.get('comparison', '')
                rule['threshold'] = result.get('threshold', '')
                if result['strategy_id'] not in warn_id_dict.keys():
                    continue
                warn_id_dict[result['strategy_id']]['rules'].append(rule)

            cursor.nextset()
            resultSet = cursor.fetchall()
            for result in resultSet:
                if result['strategy_id'] not in warn_id_dict.keys():
                    continue
                warn_id_dict[result['strategy_id']]['servers'].append(
                    result['server_id'])
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps({'warn_strategies': warn_strategys}), 200)
Example #26
0
def get_warn_strategies_list(auth, region):
    conn = getDBConn()
    try:
        with conn.cursor() as cursor:
            cursor.callproc('sp_get_warn_strategies', (region, ))
            warn_strategys = []
            warn_id_dict = {}
            resultSet = cursor.fetchall()
            for result in resultSet:
                warn_strategy = {}
                warn_strategy['id'] = result.get('id', '')
                warn_strategy['tenant_id'] = result.get('tenant_id', '')
                warn_strategy['name'] = result.get('name', '')
                warn_strategy['type'] = result.get('type', '')
                warn_strategy['level'] = result.get('warn_level', '')
                warn_strategy['relationship'] = result.get('relationship', '')
                warn_strategy['rules'] = []
                warn_strategy['servers'] = []
                warn_id_dict[result['id']] = warn_strategy
                warn_strategys.append(warn_strategy)

            cursor.nextset()
            resultSet = cursor.fetchall()
            for result in resultSet:
                rule = {}
                rule['field'] = result.get('field', '')
                rule['comparison'] = result.get('comparison', '')
                rule['threshold'] = result.get('threshold', '')
                if result['strategy_id'] not in warn_id_dict.keys():
                    continue
                warn_id_dict[result['strategy_id']]['rules'].append(rule)

            cursor.nextset()
            resultSet = cursor.fetchall()
            for result in resultSet:
                if result['strategy_id'] not in warn_id_dict.keys():
                    continue
                warn_id_dict[result['strategy_id']]['servers'].append(
                    result['server_id'])
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps({'warn_strategies': warn_strategys}), 200)
Example #27
0
def get_hosts(auth, region):
    result = {"hosts": []}
    conn = db.getDevicesConn()
    host_sql = (
        "SELECT t1.id, t1.os_name,t1.hostname,"
        " t1.description, t1.ip_address, t1.hypervisor,"
        " t1.model, t1.vendor, t1.cpu_count, t1.cpu_model,"
        " t1.cpu_frequence, t1.cpu_socket, t1.cpu_core,"
        " t1.memory_size "
        " FROM Host t1"
        " WHERE t1.regionname=%s"
    )

    tmp_disk_sql = "SELECT t1.name," " t1.capacity" " FROM Disk t1 WHERE t1.host_id = %s"

    tmp_nic_sql = (
        "SELECT t1.name," " t1.description," " t1.status," " t1.mac_address" " FROM Port t1 WHERE t1.host_id = %s"
    )
    try:
        with conn.cursor() as cursor:
            cursor.execute(host_sql, (region,))
            res = cursor.fetchall()
            for r in res:
                nics = []
                disks = []
                with conn.cursor() as nic_cursor:
                    nic_cursor.execute(tmp_nic_sql, (r["id"],))
                    nic_res = nic_cursor.fetchall()
                    for nic in nic_res:
                        nics.append(nic)
                    r["nics"] = nics

                with conn.cursor() as disk_cursor:
                    disk_cursor.execute(tmp_disk_sql, (r["id"],))
                    disk_res = disk_cursor.fetchall()
                    for disk in disk_res:
                        disks.append(disk)
                    r["disks"] = disks
                result["hosts"].append(r)
    except Exception as exc:
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps(result), 200)
Example #28
0
def get_networks(auth, region):
    result = {'network_device': []}
    conn = db.getDevicesConn()
    try:
        with conn.cursor() as cursor:
            sql = 'SELECT id, name, description, model,'\
                  ' vendor, device_type, port_num,'\
                  ' total_ram FROM Network'\
                  ' WHERE regionname = %s'
            cursor.execute(sql, (region, ))
            res = cursor.fetchall()
            for r in res:
                result['network_device'].append(r)
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps(result), 200)
Example #29
0
def list_ips(auth, region, project_id):
    ips = []
    try:
        conn = get_database_conn()
        with conn.cursor() as cursor:
            sql = 'select * from ' + TABLE_NAME_IPS + \
                ' where tenant_id=\'' + project_id + '\''
            result_num = cursor.execute(sql)
            for result in cursor:
                protected_object = result['protected_object']
                result['protected_object'] = protected_object.split(',')
                ips.append(result)
    except Exception as e:
        log.error(e)
        response = {'code': 500, 'message': str(e)}
        return make_response(json.dumps(response), 500)
    else:
        body = {'ips': ips}
        return make_response(json.dumps(body), 200)
Example #30
0
def list_ips(auth, region, project_id):
    ips = []
    try:
        conn = get_database_conn()
        with conn.cursor() as cursor:
            sql = 'select * from ' + TABLE_NAME_IPS + \
                ' where tenant_id=\'' + project_id + '\''
            result_num = cursor.execute(sql)
            for result in cursor:
                protected_object = result['protected_object']
                result['protected_object'] = protected_object.split(',')
                ips.append(result)
    except Exception as e:
        log.error(e)
        response = {'code': 500, 'message': str(e)}
        return make_response(json.dumps(response), 500)
    else:
        body = {'ips': ips}
        return make_response(json.dumps(body), 200)
Example #31
0
def get_networks(auth, region):
    result = {'network_device': []}
    conn = db.getDevicesConn()
    try:
        with conn.cursor() as cursor:
            sql = 'SELECT id, name, description, model,'\
                  ' vendor, device_type, port_num,'\
                  ' total_ram FROM Network'\
                  ' WHERE regionname = %s'
            cursor.execute(sql, (region,))
            res = cursor.fetchall()
            for r in res:
                result['network_device'].append(r)
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps(result), 200)
Example #32
0
def get_server_warnings_list(auth, region):
    requestParam = {}
    requestParam['order_by'] = request.args.get('order_by', 'created_time')
    requestParam['desc'] = request.args.get('desc', 'false')
    requestParam['start_time'] = request.args.get('start_time', None)
    requestParam['end_time'] = request.args.get('end_time', None)
    requestParam['user_id'] = request.args.get('user_id', None)
    requestParam['tenant_id'] = request.args.get('tenant_id', None)
    if not requestParam['tenant_id']:
        return make_response('tenant_id is null', 400)
    conn = getDBConn()
    try:
        with conn.cursor() as cursor:
            cursor.callproc(
                'sp_get_server_warnings',
                (region, requestParam['user_id'], requestParam['tenant_id'],
                 requestParam['start_time'], requestParam['end_time']))
            resultSet = cursor.fetchall()
            warnings = []
            for result in resultSet:
                warning = {}
                warning['id'] = result.get('id', '')
                warning['tenant_id'] = result.get('tenant_id', '')
                warning['strategy_id'] = result.get('strategy_id', '')
                warning['name'] = result.get('name', '')
                warning['type'] = result.get('type', '')
                warning['description'] = result.get('description', '')
                warning['level'] = result.get('level', '')
                warning['server_id'] = result.get('server_id', '')
                warning['created'] = str(result.get('created', ''))
                warning['status'] = result.get('status', '')
                warnings.append(warning)
            if len(warnings) > 0:
                warnings = sorted(warnings,
                                  key=lambda k: k['created'],
                                  reverse=(requestParam['desc'] == 'true'))
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps({'warnings': warnings}), 200)
Example #33
0
def get_virus(auth, region, project_id, virus_id):
    virus = {}
    if not verify_id(virus_id):
        message = 'Invalid virus id! Please check it.'
        response = {'code': 400, 'message': message}
        return make_response(json.dumps(response), 400)

    try:
        conn = get_database_conn()
        with conn.cursor() as cursor:
            sql = 'select * from ' + TABLE_NAME_VIRUS + \
                ' where id=\'' + virus_id + '\''
            result_num = cursor.execute(sql)
            if result_num == 1:
                virus = cursor.fetchone()
                if virus.get('upload') == 1:
                    virus['upload'] = True
                else:
                    virus['upload'] = False
                if virus.get('download') == 1:
                    virus['download'] = True
                else:
                    virus['download'] = True
            elif result_num == 0:
                message = 'Unable to find virus with id ' + virus_id
                log.debug(message)
                response = {'code': 404, 'message': message}
                return make_response(json.dumps(response), 404)
            else:
                message = 'Unknown error.'
                log.error(message)
                response = {'code': 500, 'message': message}
                return make_response(json.dumps(response), 500)

    except Exception as e:
        log.error(e)
        response = {'code': 500, 'message': str(e)}
        return make_response(json.dumps(response), 500)
    else:
        body = {'virus': virus}
        return make_response(json.dumps(body), 200)
Example #34
0
def get_virus(auth, region, project_id, virus_id):
    virus = {}
    if not verify_id(virus_id):
        message = 'Invalid virus id! Please check it.'
        response = {'code': 400, 'message': message}
        return make_response(json.dumps(response), 400)

    try:
        conn = get_database_conn()
        with conn.cursor() as cursor:
            sql = 'select * from ' + TABLE_NAME_VIRUS + \
                ' where id=\'' + virus_id + '\''
            result_num = cursor.execute(sql)
            if result_num == 1:
                virus = cursor.fetchone()
                if virus.get('upload') == 1:
                    virus['upload'] = True
                else:
                    virus['upload'] = False
                if virus.get('download') == 1:
                    virus['download'] = True
                else:
                    virus['download'] = True
            elif result_num == 0:
                message = 'Unable to find virus with id ' + virus_id
                log.debug(message)
                response = {'code': 404, 'message': message}
                return make_response(json.dumps(response), 404)
            else:
                message = 'Unknown error.'
                log.error(message)
                response = {'code': 500, 'message': message}
                return make_response(json.dumps(response), 500)

    except Exception as e:
        log.error(e)
        response = {'code': 500, 'message': str(e)}
        return make_response(json.dumps(response), 500)
    else:
        body = {'virus': virus}
        return make_response(json.dumps(body), 200)
Example #35
0
def get_logs(auth, region):
    operation_logs = []
    try:
        conn = get_database_conn()
        with conn.cursor() as cursor:
            sql = 'select * from %s where region=\'%s\'' % (DB_TABLE_NAME_LOGS, region)
            result_num = cursor.execute(sql)
            for result in cursor:
                create_time = result.pop('created_time')
                operate_time = result.pop('operate_time')
                result['created_time'] = str(create_time.isoformat())
                result['operate_time'] = str(operate_time.isoformat())
                operation_logs.append(result)
    except Exception as e:
        message = 'Failed to get logs : %r' % e
        log.error(message)
        response = {'code': 500, 'message': message}
        return make_response(json.dumps(response), 500)
    else:
        body = {'operation_logs': operation_logs}
        return make_response(json.dumps(body), 200)
Example #36
0
def get_logs(auth, region):
    operation_logs = []
    try:
        conn = get_database_conn()
        with conn.cursor() as cursor:
            sql = 'select * from %s where region=\'%s\'' % (DB_TABLE_NAME_LOGS,
                                                            region)
            result_num = cursor.execute(sql)
            for result in cursor:
                create_time = result.pop('created_time')
                operate_time = result.pop('operate_time')
                result['created_time'] = str(create_time.isoformat())
                result['operate_time'] = str(operate_time.isoformat())
                operation_logs.append(result)
    except Exception as e:
        message = 'Failed to get logs : %r' % e
        log.error(message)
        response = {'code': 500, 'message': message}
        return make_response(json.dumps(response), 500)
    else:
        body = {'operation_logs': operation_logs}
        return make_response(json.dumps(body), 200)
Example #37
0
def get_server_monitor(server_id):
    conn = getDBConn() 
    try:
        cursor = conn.cursor()
        cursor.callproc('sp_get_server_monitor', (server_id,))
        resultSet = cursor.fetchall()
        server_monitor={}
        if len(resultSet) > 0 :
            server_monitor['server_id']=server_id
            server_monitor['cpu_usage']=''
            server_monitor['mem_usage']=''
            server_monitor['status']='active'
            server_monitor['running_time']=''
            server_monitor['health_status']=''
            server_monitor['nics']=[]
            server_monitor['disks']=[]
            for result in resultSet:
                name = result.get('name','').lower()
                output = result.get('output','').lower()
                if name == 'uptime':
                    server_monitor['running_time']=output.split('=',1)[1]
                elif name == 'cpu usage':
                    server_monitor['cpu_usage']=output.split('=',1)[1][:-1]
                elif name == 'memory usage':
                    server_monitor['mem_usage']=output.split('=',1)[1][:-1]
                elif name == 'health_status':
                    server_monitor['health_status']=output
                elif name.startswith('eth'):
                    server_monitor['nics'].append(getNicsInfo(output))
                elif name.startswith('disk'):
                    server_monitor['disks'].append(getDisksInfo(output))
        cursor.close()
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps({'server_monitor':server_monitor}), 200)
Example #38
0
def get_warn_strategies(strategy_id):
    conn = getDBConn()
    try:
        with conn.cursor() as cursor:
            cursor = conn.cursor()
            cursor.callproc('sp_get_warn_strategy_detail', (strategy_id, ))
            warn_strategy = {}
            result = cursor.fetchone()
            if not result:
                return make_response('Resource not Found', 404)
            warn_strategy['id'] = result.get('id', '')
            warn_strategy['tenant_id'] = result.get('tenant_id', '')
            warn_strategy['name'] = result.get('name', '')
            warn_strategy['type'] = result.get('type')
            warn_strategy['level'] = result.get('warn_level')
            warn_strategy['relationship'] = result.get('relationship', '')
            warn_strategy['rules'] = []
            cursor.nextset()
            resultSet = cursor.fetchall()
            for result in resultSet:
                rule = {}
                rule['field'] = result.get('field', '')
                rule['comparison'] = result.get('comparison', '')
                rule['threshold'] = result.get('threshold', '')
                warn_strategy['rules'].append(rule)

            warn_strategy['servers'] = []
            cursor.nextset()
            resultSet = cursor.fetchall()
            for result in resultSet:
                warn_strategy['servers'].append(result.get('server_id', ''))
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps({'warn_strategy': warn_strategy}), 200)
Example #39
0
def get_warn_strategies(strategy_id):
    conn = getDBConn()
    try:
        cursor = conn.cursor()
        cursor.callproc('sp_get_warn_strategy_detail', (strategy_id,))
        warn_strategy={}
        result = cursor.fetchone()
        if result==None:
            return make_response('Resource not Found',404)
        warn_strategy['id']=result.get('id','');
        warn_strategy['tenant_id']=result.get('tenant_id','');
        warn_strategy['name']=result.get('name','');
        warn_strategy['type']=result.get('type');
        warn_strategy['level']=result.get('warn_level');
        warn_strategy['relationship']=result.get('relationship','');
        warn_strategy['rules']=[];
        cursor.nextset()
        resultSet = cursor.fetchall()
        for result in resultSet:
            rule={}
            rule['field']=result.get('field','')
            rule['comparison']=result.get('comparison','')
            rule['threshold']=result.get('threshold','')
            warn_strategy['rules'].append(rule)

        warn_strategy['servers']=[];
        cursor.nextset()
        resultSet = cursor.fetchall()
        for result in resultSet:
            warn_strategy['servers'].append(result.get('server_id',''))
        cursor.close()
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps({'warn_strategy':warn_strategy}), 200)
Example #40
0
def get_ips(auth, region, project_id, ips_id):
    ips = {}
    if not verify_id(ips_id):
        message = 'Invalid ips id! Please check it.'
        response = {'code': 400, 'message': message}
        return make_response(json.dumps(response), 400)

    try:
        conn = get_database_conn()
        with conn.cursor() as cursor:
            sql = 'select * from ' + TABLE_NAME_IPS + \
                ' where id=\'' + ips_id + '\''
            result_num = cursor.execute(sql)
            if result_num == 1:
                protected_object = result['protected_object']
                result['protected_object'] = protected_object.split(',')
                ips.append(result)
                ips = cursor.fetchone()
            elif result_num == 0:
                message = 'Unable to find ips with id ' + ips_id
                log.debug(message)
                response = {'code': 404, 'message': message}
                return make_response(json.dumps(response), 404)
            else:
                message = 'Unknown error.'
                log.error(message)
                response = {'code': 500, 'message': message}
                return make_response(json.dumps(response), 500)

    except Exception as e:
        log.error(e)
        response = {'code': 500, 'message': str(e)}
        return make_response(json.dumps(response), 500)
    else:
        body = {'ips': ips}
        return make_response(json.dumps(body), 200)
Example #41
0
def get_device_warnings(warn_id):
    conn = getDBConn()
    try:
        with conn.cursor() as cursor:
            cursor.callproc('sp_get_device_warnings_detail', (warn_id, ))
            result = cursor.fetchone()
            warning = {}
            if not result:
                return make_response('Resource not Found', 404)
            warning['id'] = result['id']
            warning['strategy_id'] = result.get('strategy_id', '')
            warning['name'] = result.get('name', '')
            warning['type'] = result.get('type', '')
            warning['description'] = result.get('description', '')
            warning['level'] = result.get('level', '')
            warning['object_id'] = result.get('object_id', '')
            warning['object_type'] = result.get('object_type', '')
            warning['created'] = str(result.get('created', ''))
            warning['status'] = result.get('status', '')
    except Exception as exc:
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps({'warnings': warning}), 200)
Example #42
0
def get_ips(auth, region, project_id, ips_id):
    ips = {}
    if not verify_id(ips_id):
        message = 'Invalid ips id! Please check it.'
        response = {'code': 400, 'message': message}
        return make_response(json.dumps(response), 400)

    try:
        conn = get_database_conn()
        with conn.cursor() as cursor:
            sql = 'select * from ' + TABLE_NAME_IPS + \
                ' where id=\'' + ips_id + '\''
            result_num = cursor.execute(sql)
            if result_num == 1:
                protected_object = result['protected_object']
                result['protected_object'] = protected_object.split(',')
                ips.append(result)
                ips = cursor.fetchone()
            elif result_num == 0:
                message = 'Unable to find ips with id ' + ips_id
                log.debug(message)
                response = {'code': 404, 'message': message}
                return make_response(json.dumps(response), 404)
            else:
                message = 'Unknown error.'
                log.error(message)
                response = {'code': 500, 'message': message}
                return make_response(json.dumps(response), 500)

    except Exception as e:
        log.error(e)
        response = {'code': 500, 'message': str(e)}
        return make_response(json.dumps(response), 500)
    else:
        body = {'ips': ips}
        return make_response(json.dumps(body), 200)
Example #43
0
def get_logs(auth, region):
    body = {'operation_logs':[]}
    return make_response(json.dumps(body), 200)
Example #44
0
def get_storage_monitor(storage_id):
    def getIOValue(output):
        total = 0
        nodes = result.get('output','').lower().split(',')
        for node in nodes:
            total+=int(node.split('=',1)[1])
        return total
    def getTPValue(output):
        total = 0
        nodes = result.get('output','').lower().replace(' ','').split(',')
        for node in nodes:
            total+=int(node.split('=',1)[1][:-2])
        return total
    def getPowerStatus(output):
        if output.find('power=ok') <0:
            return 'down'
        else:   
            return 'active'
    conn = getDBConn()
    try:
        cursor = conn.cursor()
        cursor.callproc('sp_get_storage_device_monitor', (storage_id,))
        resultSet = cursor.fetchall()
        storage_monitor={}
        if len(resultSet) > 0 :
            storage_monitor['storage_id']=storage_id
            storage_monitor['read_iops']=''
            storage_monitor['write_iops']=''
            storage_monitor['read_throughput']=''
            storage_monitor['write_throughput']=''
            storage_monitor['health_status']=''
            storage_monitor['power_status']=''
            storage_monitor['free_space']=''
            read_iops=0
            write_iops=0
            read_throughput=0
            write_throughput=0
            for result in resultSet:
                name = result.get('name','').lower()
                output = result.get('output','').lower()
                if output=='':
                    continue
                if name=='readiops':
                    read_iops += getIOValue(output)
                elif name=='writeiops':
                    write_iops += getIOValue(output)
                elif name=='readthroughput':
                    read_throughput += getTPValue(output)
                elif name=='writethroughput':
                    write_throughput += getTPValue(output)
                elif name=='freespace':
                    storage_monitor['free_space'] = output.split('=',1)[1].split(' ',1)[0]
                elif name=='health_status':
                    storage_monitor['health_status'] = output
                elif name=='environment':
                    storage_monitor['power_status'] = getPowerStatus(output)
            storage_monitor['read_iops']=str(read_iops)
            storage_monitor['write_iops']=str(write_iops)
            storage_monitor['read_throughput']=str(read_throughput)
            storage_monitor['write_throughput']=str(write_throughput)
        cursor.close()
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps({'storage_monitor':storage_monitor}), 200)
Example #45
0
def get_network_device_monitor(network_device_id):
    def getMB(unit):
        if unit == 'g':
            return 1024.0
        elif unit == 'k':
            return 1 / 1024.0
        else:
            return 1

    def getBanwidth(output):
        pattern = re.compile('avg\.in=(\d+\.?\d*)([k|m|g]?)b/s'
                             ',avg\.out=(\d+\.?\d*)([k|m|g]?)b/s')
        res = pattern.search(output).groups()
        if (len(res) == 4):
            return {
                'in_rate': res[0],
                'in_rate_unit': res[1],
                'out_rate': res[2],
                'out_rate_unit': res[3]
            }
        else:
            return None

    def getPowerStatus(output):
        if output.find('power=ok') < 0:
            return 'down'
        else:
            return 'active'

    conn = getDBConn()
    try:
        with conn.cursor() as cursor:
            cursor.callproc('sp_get_network_device_monitor',
                            (network_device_id, ))
            resultSet = cursor.fetchall()
            network_monitor = {}
            if len(resultSet) > 0:
                network_monitor['network_device_id'] = network_device_id
                network_monitor['cpu_usage'] = 0
                network_monitor['ram_usage'] = 0
                network_monitor['power_status'] = ''
                network_monitor['inbound_rate'] = ''
                network_monitor['outbound_rate'] = ''
                network_monitor['health_status'] = ''
                inbound_rate = 0.0
                outbound_rate = 0.0
                cpu_usage = 0.0
                cpu_count = 0.0
                mem_usage = 0.0
                mem_count = 0.0
                is_multi_cpu = False
                is_multi_mem = False
                for result in resultSet:
                    name = result.get('name', '').lower()
                    output = result.get('output', '').lower()
                    if output == '':
                        continue
                    if name == 'loadavg':
                        if output.find('chassis') >= 0:
                            is_multi_cpu = True
                            cpu_list = output.split(',')
                            for cpu in cpu_list:
                                cpu_usage += int(cpu.split('=', 1)[1][:-1])
                                cpu_count += 1
                        elif output.find('loadavg=') >= 0:
                            network_monitor['cpu_usage'] =\
                                output.replace(' ', '').split('=', 1)[1][:-1]
                    elif name == 'memutil':
                        if output.find('chassis') >= 0:
                            is_multi_mem = True
                            chassis_list = output.split(' chassis')
                            for chassis in chassis_list:
                                mem_list = chassis.split('=', 1)[1].split(',')
                                for mem in mem_list:
                                    if mem == '':
                                        continue
                                    mem_usage += int(mem[:-1])
                                    mem_count += 1
                        elif output.find('memutil=') >= 0:
                            network_monitor['ram_usage'] =\
                                output.split('=', 1)[1][:-1]
                    elif name.endswith('bandwidth usage'):
                        output = output.replace(' ', '')
                        if output.find('avg.in=') >= 0:
                            inout_rate = getBanwidth(output)
                            if inout_rate is not None:
                                if inout_rate['in_rate_unit'] != '':
                                    inbound_rate +=\
                                        float(inout_rate['in_rate']) * getMB(
                                            inout_rate['in_rate_unit'])
                                if inout_rate['out_rate_unit'] != '':
                                    outbound_rate +=\
                                        float(inout_rate['out_rate']) * getMB(
                                            inout_rate['out_rate_unit'])
                    elif name == 'health_status':
                        network_monitor['health_status'] = output
                    elif name == 'environment':
                        network_monitor['power_status'] =\
                            getPowerStatus(output)
                if is_multi_cpu:
                    network_monitor['cpu_usage'] = str(
                        int(round(cpu_usage / cpu_count)))
                if is_multi_mem:
                    network_monitor['ram_usage'] = str(
                        int(round(mem_usage / mem_count)))
                network_monitor['inbound_rate'] = str(round(inbound_rate, 2))
                network_monitor['outbound_rate'] = str(round(outbound_rate, 2))
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps({'network_monitor': network_monitor}), 200)
Example #46
0
def get_network_device_monitor(network_device_id):
    def getMB(unit):
        if unit=='g':
            return 1024.0
        elif unit =='k':
            return 1/1024.0
        else:
            return 1
    def getBanwidth(output):
        pattern = re.compile('avg\. in = (\d+\.?\d*) ([k|m|g]?)b/s, avg\. out = (\d+\.?\d*) ([k|m|g]?)b/s')
        res = pattern.search(output).groups()
        if(len(res)==4):
            return {'in_rate':res[0],'in_rate_unit':res[1],'out_rate':res[2],'out_rate_unit':res[3]} 
        else:
            return None
    def getPowerStatus(output):
        if output.find('power=ok') < 0:
            return 'down'
        else:   
            return 'active'
    conn = getDBConn()
    try:
        cursor = conn.cursor()
        cursor.callproc('sp_get_network_device_monitor', (network_device_id,))
        resultSet = cursor.fetchall()
        network_monitor={}
        if len(resultSet) > 0 :
            network_monitor['network_device_id']=network_device_id
            network_monitor['cpu_usage']=''
            network_monitor['ram_usage']=''
            network_monitor['power_status']=''
            network_monitor['inbound_rate']=''
            network_monitor['outbound_rate']=''
            network_monitor['health_status']=''
            inbound_rate = 0.0
            outbound_rate = 0.0
            cpu_usage = 0.0
            cpu_count=0.0
            mem_usage = 0.0
            mem_count=0.0
            is_multi_cpu = False;
            is_multi_mem = False;
            for result in resultSet:
                name = result.get('name','').lower()
                output = result.get('output','').lower()
                if output=='':
                    continue
                if name == 'loadavg':
                    if output.find('chassis') >= 0:
                        is_multi_cpu = True
                        cpu_list = output.split(',')
                        for cpu in cpu_list:
                            cpu_usage += int(cpu.split('=',1)[1][:-1])
                            cpu_count += 1
                    else:    
                        network_monitor['cpu_usage']=output.replace(' ','').split('=',1)[1][:-1]
                elif name == 'memutil':
                    if output.find('chassis') >= 0:
                        is_multi_mem = True
                        chassis_list = output.split(' chassis')
                        for chassis in chassis_list:
                            mem_list = chassis.split('=',1)[1].split(',')
                            for mem in mem_list:
                                if mem == '':
                                    continue
                                mem_usage += int(mem[:-1])
                                mem_count += 1
                    else:
                        network_monitor['ram_usage']=output.split('=',1)[1][:-1]
                elif name.endswith('bandwidth usage'):
                    inout_rate = getBanwidth(output)
                    if inout_rate != None:
                        if inout_rate['in_rate_unit']!='':
                            inbound_rate += float(inout_rate['in_rate'])*getMB(inout_rate['in_rate_unit'])
                        if inout_rate['out_rate_unit']!='':
                            outbound_rate += float(inout_rate['out_rate'])*getMB(inout_rate['out_rate_unit'])
                elif name == 'health_status':
                    network_monitor['health_status']=output
                elif name == 'environment':
                    network_monitor['power_status']=getPowerStatus(output)
            if is_multi_cpu:
                network_monitor['cpu_usage'] = str(int(round(cpu_usage/cpu_count)))
            if is_multi_mem:
                network_monitor['ram_usage'] = str(int(round(mem_usage/mem_count)))
            network_monitor['inbound_rate'] = str(round(inbound_rate,2))
            network_monitor['outbound_rate'] = str(round(outbound_rate,2))
        cursor.close()
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps({'network_monitor':network_monitor}), 200)
Example #47
0
def get_server_monitor(auth, region, server_id):
    conn = getDBConn()
    try:
        with conn.cursor() as cursor:
            cursor.callproc('sp_get_server_monitor', (server_id, ))
            resultSet = cursor.fetchall()
            server_monitor = {}
            if len(resultSet) > 0:
                server_monitor['server_id'] = server_id
                server_monitor['cpu_usage'] = '-9999'
                server_monitor['mem_usage'] = '-9999'
                server_monitor['status'] = ''
                server_monitor['running_time'] = '-9999'
                server_monitor['health_status'] = 'false'
                server_monitor['nics'] = []
                server_monitor['disks'] = []
                try:
                    kwargs = {'headers': {'X-Openstack-Region': region}}
                    resp = httprequest.httpclient(
                        'GET', auth[1][0] + '/servers/%s' % server_id,
                        auth[0], kwargs=kwargs)
                    if resp.status_code == 200:
                        result = resp.json()
                        vm_server = result.get('server')
                        if vm_server != None:
                            vm_status = vm_server.get('status', '').lower()
                            if vm_status == 'active':
                                server_monitor['status'] = 'active'
                            elif vm_status == '':
                                server_monitor['status'] = ''
                            else:
                                server_monitor['status'] = 'down'
                except Exception as exc_inside:
                    log.error(exc_inside)
                for result in resultSet:
                    name = result.get('name', '').lower()
                    output = result.get('output', '').lower()
                    if output == '':
                        continue
                    if name == 'uptime':
                        if output.find('uptime=') >= 0:
                            server_monitor['running_time'] =\
                                output.split('=', 1)[1]
                    elif name == 'cpu usage':
                        if output.find('cpuusage=') >= 0:
                            server_monitor['cpu_usage'] =\
                                output.split('=', 1)[1][:-1]
                    elif name == 'memory usage':
                        if output.find('memoryusage=') >= 0:
                            server_monitor['mem_usage'] =\
                                output.split('=', 1)[1][:-1]
                    elif name == 'health_status':
                        server_monitor['health_status'] = output
                    elif name.startswith('eth'):
                        if output.find('name=') >= 0:
                            server_monitor['nics'].append(
                                getNicsInfo(output))
                    elif name.startswith('disk'):
                        if output.find('name=') >= 0:
                            server_monitor['disks'].append(
                                getDisksInfo(output))
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(
        json.dumps({'server_monitor': server_monitor}), 200)
Example #48
0
def get_storage_monitor(storage_id):
    def getIOValue(output):
        total = 0
        nodes = result.get('output', '').lower().split(',')
        for node in nodes:
            total += int(node.split('=', 1)[1])
        return total

    def getTPValue(output):
        total = 0
        nodes = result.get('output', '').lower().replace(' ', '').split(',')
        for node in nodes:
            total += int(node.split('=', 1)[1][:-2])
        return total

    def getPowerStatus(output):
        if output.find('power=ok') < 0:
            return 'down'
        else:
            return 'active'

    conn = getDBConn()
    try:
        with conn.cursor() as cursor:
            cursor.callproc('sp_get_storage_device_monitor', (storage_id, ))
            resultSet = cursor.fetchall()
            storage_monitor = {}
            if len(resultSet) > 0:
                storage_monitor['storage_id'] = storage_id
                storage_monitor['read_iops'] = ''
                storage_monitor['write_iops'] = ''
                storage_monitor['read_throughput'] = ''
                storage_monitor['write_throughput'] = ''
                storage_monitor['health_status'] = ''
                storage_monitor['power_status'] = ''
                storage_monitor['free_space'] = ''
                read_iops = -9999
                write_iops = -9999
                read_throughput = -9999
                write_throughput = -9999
                for result in resultSet:
                    name = result.get('name', '').lower()
                    output = result.get('output', '').lower()
                    if output == '':
                        continue
                    if name == 'readiops':
                        if output.find('readiops=') >= 0:
                            read_iops = 0
                            read_iops += getIOValue(output)
                    elif name == 'writeiops':
                        if output.find('writeiops=') >= 0:
                            write_iops = 0
                            write_iops += getIOValue(output)
                    elif name == 'readthroughput':
                        if output.find('readthroughput=') >= 0:
                            read_throughput = 0
                            read_throughput += getTPValue(output)
                    elif name == 'writethroughput':
                        if output.find('writethroughput=') >= 0:
                            write_throughput = 0
                            write_throughput += getTPValue(output)
                    elif name == 'freespace':
                        if output.find('freespace=') >= 0:
                            storage_monitor['free_space'] = str(
                                int(output.split('=', 1)[1].split(' ', 1)[0]) /
                                1024)
                    elif name == 'health_status':
                        storage_monitor['health_status'] = output
                    elif name == 'environment':
                        storage_monitor['power_status'] =\
                            getPowerStatus(output)
                storage_monitor['read_iops'] = str(read_iops)
                storage_monitor['write_iops'] = str(write_iops)
                storage_monitor['read_throughput'] = str(read_throughput)
                storage_monitor['write_throughput'] = str(write_throughput)
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps({'storage_monitor': storage_monitor}), 200)
Example #49
0
def get_server_monitor(auth, region, server_id):
    conn = getDBConn()
    try:
        with conn.cursor() as cursor:
            cursor.callproc('sp_get_server_monitor', (server_id, ))
            resultSet = cursor.fetchall()
            server_monitor = {}
            if len(resultSet) > 0:
                server_monitor['server_id'] = server_id
                server_monitor['cpu_usage'] = '-9999'
                server_monitor['mem_usage'] = '-9999'
                server_monitor['status'] = ''
                server_monitor['running_time'] = '-9999'
                server_monitor['health_status'] = 'false'
                server_monitor['nics'] = []
                server_monitor['disks'] = []
                try:
                    kwargs = {'headers': {'X-Openstack-Region': region}}
                    resp = httprequest.httpclient('GET',
                                                  auth[1][0] +
                                                  '/servers/%s' % server_id,
                                                  auth[0],
                                                  kwargs=kwargs)
                    if resp.status_code == 200:
                        result = resp.json()
                        vm_server = result.get('server')
                        if vm_server != None:
                            vm_status = vm_server.get('status', '').lower()
                            if vm_status == 'active':
                                server_monitor['status'] = 'active'
                            elif vm_status == '':
                                server_monitor['status'] = ''
                            else:
                                server_monitor['status'] = 'down'
                except Exception as exc_inside:
                    log.error(exc_inside)
                for result in resultSet:
                    name = result.get('name', '').lower()
                    output = result.get('output', '').lower()
                    if output == '':
                        continue
                    if name == 'uptime':
                        if output.find('uptime=') >= 0:
                            server_monitor['running_time'] =\
                                output.split('=', 1)[1]
                    elif name == 'cpu usage':
                        if output.find('cpuusage=') >= 0:
                            server_monitor['cpu_usage'] =\
                                output.split('=', 1)[1][:-1]
                    elif name == 'memory usage':
                        if output.find('memoryusage=') >= 0:
                            server_monitor['mem_usage'] =\
                                output.split('=', 1)[1][:-1]
                    elif name == 'health_status':
                        server_monitor['health_status'] = output
                    elif name.startswith('eth'):
                        if output.find('name=') >= 0:
                            server_monitor['nics'].append(getNicsInfo(output))
                    elif name.startswith('disk'):
                        if output.find('name=') >= 0:
                            server_monitor['disks'].append(
                                getDisksInfo(output))
    except Exception as exc:
        log.error(exc)
        return make_response(json.dumps(exc.message), 500)
    finally:
        conn.close()
    return make_response(json.dumps({'server_monitor': server_monitor}), 200)