예제 #1
0
def datacenter_delete():
    datacenter_ids = request.values.get('datacenter_ids')
    if not datacenter_ids:
        logging.error('no datacenter_ids when delete datacenter')
        return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR)

    datacenter_ids_list = datacenter_ids.split(',')
    # 操作的datacenter数
    all_num = len(datacenter_ids_list)
    msg = None
    fail_num = 0
    for _id in datacenter_ids_list:
        _net_area_nums = net_area_s.NetAreaService().get_net_area_nums_in_dc(
            _id)
        if _net_area_nums > 0:
            logging.error('no allow to delete datacenter %s that has net area',
                          _id)
            fail_num += 1
            # 单台操作且已失败则直接跳出循环
            if all_num == 1:
                msg = '该机房下已分配有网络区域,不允许删除'
                break
            continue

        _ret = dc_s.DataCenterService().delete_datacenter(_id)
        if _ret <= 0:
            logging.error(
                'db delete datacenter %s fail when delete datacenter', _id)
            fail_num += 1
            continue

        _dc_info = dc_s.DataCenterService().get_datacenter_info(_id)
        if not _dc_info:
            logging.error(
                'datacenter info %s is not exist in db when delete datacenter',
                _id)
            fail_num += 1
            continue

        # 把该机房的主机名增量值清空
        incre_s.clean_dc_increment_value(_dc_info['name'])

    # 全失败
    if fail_num == all_num:
        logging.error("delete datacenter all failed")
        if msg:
            return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg=msg)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)
    # 部分成功
    if 0 < fail_num < all_num:
        logging.error("delete all %s datacenter part %s failed", all_num,
                      fail_num)
        return json_helper.format_api_resp(code=ErrorCode.SUCCESS_PART,
                                           msg="部分机房删除成功")
    return json_helper.format_api_resp(code=ErrorCode.SUCCESS)
예제 #2
0
def get_parent_areas():
    '''
        获取所有适合做父区域的数据
    :return:
    '''

    parent_list = []
    user_areas_list = current_user_all_area_ids()
    if not user_areas_list:
        return json_helper.format_api_resp(code=ErrorCode.SUCCESS,
                                           data=parent_list)

    parent_nums, parent_datas = area_s.AreaService().get_available_parents(
        user_areas_list)
    for i in parent_datas:
        # 没有子区域但有机房的区域不能作为父区域
        _dc_nums = dc_s.DataCenterService().get_datacenter_nums_in_area(
            i['id'])
        _child_nums = area_s.AreaService().get_child_areas_nums(i['id'])
        if _child_nums < 1 and _dc_nums > 0:
            continue

        _parent = {
            "parent_id": i["id"],
            "parent_name": i["displayname"],
        }
        parent_list.append(_parent)

    return json_helper.format_api_resp(code=ErrorCode.SUCCESS,
                                       data=parent_list)
예제 #3
0
def allocate_dc_2_area(datacenter_id, area_id):
    '''
        分配机房给区域
    :param datacenter_id:
    :param area_id:
    :return:
    '''
    if not datacenter_id or not area_id:
        logging.info(
            'no datacenter_id or area_id when allocate datacenter to area')
        return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR)

    update_data = {
        'area_id': area_id,
    }
    where_data = {
        'datacenter_id': datacenter_id,
    }
    ret = dc_s.DataCenterService().update_datacenter_info(
        update_data, where_data)
    if ret.get('row_num') <= 0:
        logging.error(
            "allocate datacenter to area error, update_data:%s, where_data:%s",
            str(update_data), str(where_data))
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)
    return json_helper.format_api_resp(code=ErrorCode.SUCCESS)
예제 #4
0
def datacenter_update(datacenter_id):
    name = request.values.get('name')
    province = request.values.get('province')
    address = request.values.get('address')
    description = request.values.get('description')

    if not datacenter_id or not name or not province:
        logging.error('the params is invalid when update datacenter')
        return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR)

    dc_data = dc_s.DataCenterService().get_datacenter_info(datacenter_id)
    if not dc_data:
        logging.error(
            'the datacenter %s is no exist in db when update datacenter',
            datacenter_id)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

    if dc_data['name'] != name:
        # 同类型的机房不能同名
        name_exist = dc_s.DataCenterService().check_dc_name_exist_in_same_type(
            name, dc_data['dc_type'])
        if name_exist:
            logging.error(
                'name %s in type %s is duplicated when update datacenter',
                name, dc_data['dc_type'])
            return json_helper.format_api_resp(code=ErrorCode.DUPLICATED_ERR,
                                               msg="同环境类型下机房名不能重复,请修改机房名")

    update_data = {
        'name': name,
        'displayname': name,
        'province': province,
        'address': address,
        'description': description,
        'updated_at': get_datetime_str()
    }
    where_data = {
        'id': datacenter_id,
    }
    ret = dc_s.DataCenterService().update_datacenter_info(
        update_data, where_data)
    if ret < 0:
        logging.error("update datacenter error, update_data:%s, where_data:%s",
                      str(update_data), str(where_data))
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)
    return json_helper.format_api_resp(code=ErrorCode.SUCCESS)
예제 #5
0
def dashboard_v1():
    resp = DashboardV1Resp()
    user_areas_ids = current_user_areas()
    resp.overview['area_nums'] = len(user_areas_ids)

    # 当前用户所有机房
    all_dc_num, all_dc_data = dc_s.DataCenterService().get_all_datacenters_of_areas(user_areas_ids)
    resp.overview['datacenter_nums'] = all_dc_num
    for _dc in all_dc_data:
        _all_ins = get_instances_in_dc(_dc['id'])
        _shutdown_num = 0
        _startup_num = 0
        _other_num = 0
        if _all_ins:
            for _ins in _all_ins:
                if _ins['status'] == VMStatus.STARTUP:
                    _startup_num += 1
                elif _ins['status'] == VMStatus.SHUTDOWN:
                    _shutdown_num += 1
                else:
                    _other_num += 1

        _dc_vms = {
            'dc_name': _dc['name'],
            'dc_type': _dc['dc_type'],
            'all_vms': len(_all_ins),
            'shutdown_vms': _shutdown_num,
            'startup_vms': _startup_num,
            'other_vms': _other_num
        }
        resp.dc_vms.append(_dc_vms)

        _used_data = get_cpu_mem_used_in_dc(_dc['id'])
        _dc_cpu = {
            'dc_name': _dc['name'],
            'dc_type': _dc['dc_type'],
            'used': _used_data['cpu_used'],
            'unused': _used_data['cpu_unused'],
            'used_per': _used_data['cpu_used_per'],
            'unused_per': _used_data['cpu_unused_per'],
        }
        resp.dc_cpu.append(_dc_cpu)

        _dc_mem = {
            'dc_name': _dc['name'],
            'dc_type': _dc['dc_type'],
            'used': _used_data['mem_used'],
            'unused': _used_data['mem_unused'],
            'used_per': _used_data['mem_used_per'],
            'unused_per': _used_data['mem_unused_per'],
        }
        resp.dc_mem.append(_dc_mem)

    resp.overview['hostpool_nums'] = get_hostpool_nums_in_dcs(all_dc_data)
    resp.overview['host_nums'] = get_host_nums_in_dcs(all_dc_data)

    return json_helper.format_api_resp(code=ErrorCode.SUCCESS, data=resp.to_json())
예제 #6
0
def add_segment():
    '''
        录入一个新网段
    '''
    network_segment_match = request.json.get("network_segment_match",[])
    segment_match_dic = {}
    for index, item in enumerate(network_segment_match):
        status, res = check_prdr(item)
        if not status:
            return json_helper.format_api_resp(ErrorCode.ALL_FAIL, msg=res)
        bond_dev = NetCardTypeToDevice.MSG_DICT.get(item['segment_type'])
        insert_data = {
            'net_area_id': int(item['net_area_id']),
            'segment': item['segment'],
            'segment_type': item['segment_type'],
            'host_bridge_name': 'br_' + bond_dev,
            'netmask': str(item['netmask']),
            'vlan': str(item['vlan']),
            'gateway_ip': item['gateway'],
            'dns1': item['dns1'],
            'dns2': item['dns2'],
            'status': NetworkSegmentStatus.ENABLE,
            'created_at': get_datetime_str()
        }
        ret = segment_service.SegmentService().add_segment_info(insert_data)
        if ret['row_num'] <= 0:
            return json_helper.format_api_resp(code=ErrorCode.ALL_FAIL, msg="网段入库失败")
        if len(network_segment_match) == 2:
            dc_type = datacenter_service.DataCenterService().get_dctype_by_net_area_id(item['net_area_id'])
            if dc_type == '4':
                segment_match_dic['prd_segment_id'] = network_segment.get_network_segment_id_info_by_network_segment(
                    item['net_area_id'], item['segment'],
                    item['vlan'], item['gateway'],
                    'br_' + bond_dev)
            elif dc_type == '5':
                segment_match_dic['dr_segment_id'] = network_segment.get_network_segment_id_info_by_network_segment(
                    item['net_area_id'], item['segment'],
                    item['vlan'], item['gateway'],
                    'br_' + bond_dev)
    if len(network_segment_match) == 2:
        insert_data_match = {
            'prd_segment_id': int(segment_match_dic['prd_segment_id']['id']),
            'dr_segment_id': int(segment_match_dic['dr_segment_id']['id']),
            'isdeleted': '0'
        }
        ret_match = segment_match.SegmentMatchService().add_segment_match_info(insert_data_match)
        if ret_match['row_num'] <= 0:
            return json_helper.format_api_resp(code=ErrorCode.ALL_FAIL, msg="匹配网段入库失败")

    return json_helper.format_api_resp(code=ErrorCode.SUCCESS, msg="匹配网段已成功加入")
예제 #7
0
def datacenter_add(area_id):
    name = request.values.get('name')
    address = request.values.get('address')
    description = request.values.get('description')
    dc_type = request.values.get('dc_type')
    province = request.values.get('province')

    if not area_id or not name or not dc_type or not province:
        logging.info('the params is invalid when add datacenter')
        return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR)

    # 同类型的机房不能同名
    name_exist = dc_s.DataCenterService().check_dc_name_exist_in_same_type(
        name, dc_type)
    if name_exist:
        logging.error('name %s in type %s is duplicated when add datacenter',
                      name, dc_type)
        return json_helper.format_api_resp(code=ErrorCode.DUPLICATED_ERR,
                                           msg="同环境类型下机房名不能重复,请修改机房名")

    insert_data = {
        'area_id': area_id,
        'name': name,
        'displayname': name,
        'dc_type': dc_type,
        'province': province,
        'address': address,
        'description': description,
        'isdeleted': '0',
        'created_at': get_datetime_str()
    }
    ret = dc_s.DataCenterService().add_datacenter(insert_data)
    if ret.get('row_num') <= 0:
        logging.error("add datacenter error, insert_data:%s", str(insert_data))
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)
    return json_helper.format_api_resp(code=ErrorCode.SUCCESS)
def ip_resource_display_to_other_platform_new():
    '''
        将kvm已有的网段展示给其他平台新接口,查询指定网段可用的ip数量
    :return:
    '''
    data_from_vishnu = request.data
    logging.info(data_from_vishnu)
    data_requset = json_helper.loads(data_from_vishnu)
    req_datacenter = data_requset['dataCenter']
    req_env = data_requset['env']
    req_net_area = data_requset['netArea']
    req_net_name = data_requset['netName']
    # 校验入参是否为空
    if not req_env or not req_net_area or not req_net_name or not req_datacenter:
        return json_helper.format_api_resp_msg_to_vishnu_resource(job_status=VsJobStatus.FAILED, detail='入参有空值')

    # 查询指定环境、网络区域是否有所需网段
    ret_segment = segment_service.SegmentService().get_segment_info_bysegment(req_net_name.split('/')[0])
    if not ret_segment:
        return json_helper.format_api_resp_msg_to_vishnu_resource(job_status=VsJobStatus.FAILED, detail="无法找到需要申请的网段")

    ret_net_area_info = net_area.NetAreaService().get_net_area_info(ret_segment['net_area_id'])
    if not ret_net_area_info:
        return json_helper.format_api_resp_msg_to_vishnu_resource(job_status=VsJobStatus.FAILED, detail="无法找到指定网段所属网络区域信息")

    ret_datacenter_info = datacenter_service.DataCenterService().get_datacenter_info(
        ret_net_area_info['datacenter_id'])
    if not ret_datacenter_info:
        return json_helper.format_api_resp_msg_to_vishnu_resource(job_status=VsJobStatus.FAILED, detail="无法找到指定机房信息")
    if req_env not in DataCenterTypeForVishnu.TYPE_DICT:
        return json_helper.format_api_resp_msg_to_vishnu_resource(job_status=VsJobStatus.FAILED, detail="无法找到指定机房类型信息")
    if str(DataCenterTypeForVishnu.TYPE_DICT[req_env]) != ret_datacenter_info['dc_type']:
        return json_helper.format_api_resp_msg_to_vishnu_resource(job_status=VsJobStatus.FAILED, detail="无法找到指定网络区域对应网段信息")

    # 获取可用ip
    ret_ip_available_status, ret_ip_available = ip_service.get_all_available_segment_ip(ret_segment['id'], str(
        DataCenterTypeForVishnu.TYPE_DICT[req_env]))

    if not ret_ip_available_status:
        ret_params = {
            "ip_num": 0
        }
        return json_helper.format_api_resp_msg_to_vishnu_resource(job_status=VsJobStatus.SUCCEED, detail=ret_params)
    ret_params = {
        "ip_num": len(ret_ip_available)
    }
    return json_helper.format_api_resp_msg_to_vishnu_resource(job_status=VsJobStatus.SUCCEED, detail=ret_params)
예제 #9
0
def area_list():
    '''
        request
    :return:
    '''
    resp = AreaListResp()
    user_areas_list = current_user_all_area_ids()
    if not user_areas_list:
        return json_helper.format_api_resp(code=ErrorCode.SUCCESS, data=resp.to_json())

    params = {
        'WHERE_AND': {
            'in': {
                'id': user_areas_list
            },
            '=': {
                'parent_id': -1,
                'isdeleted': '0'
            }
        },
        'ORDER': [
            ['id', 'desc'],
        ],
        'PAGINATION': {
            'page_size': request.values.get('page_size', 20),
            'page_no': request.values.get('page_no', 1),
        }
    }
    total_nums, data = area_service.AreaService().query_data(**params)

    resp.total = total_nums
    for i in data:
        _area_info = area_info.AreaInfo().init_from_db(i)
        _area_info.child_areas_nums = area_service.AreaService().get_child_areas_nums(i['id'])
        _area_info.datacenter_nums = datacenter_service.DataCenterService().get_datacenter_nums_in_area(i['id'])
        resp.rows.append(_area_info)

    return json_helper.format_api_resp(code=ErrorCode.SUCCESS, data=resp.to_json())
예제 #10
0
def get_child_areas(area_id):
    if not area_id:
        logging.info('no area_id when get child areas')
        return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR)

    child_nums, child_data = area_s.AreaService().get_child_areas(area_id)
    child_list = []
    for i in child_data:
        if i["id"] not in current_user_all_area_ids():
            continue

        _child = {
            "child_id":
            i["id"],
            "child_name":
            i["displayname"],
            "datacenter_nums":
            dc_s.DataCenterService().get_datacenter_nums_in_area(i['id']),
            "manager":
            i['manager']
        }
        child_list.append(_child)

    return json_helper.format_api_resp(code=ErrorCode.SUCCESS, data=child_list)
예제 #11
0
def area_delete():
    area_ids = request.values.get('area_ids')
    if not area_ids:
        logging.error('no area_ids when delete area')
        return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR)

    area_ids_list = area_ids.split(',')
    # 操作的area数
    all_num = len(area_ids_list)
    msg = None
    fail_num = 0
    for _id in area_ids_list:
        # 有子区域、机房、组关联的都不能删除
        _child_nums = area_s.AreaService().get_child_areas_nums(_id)
        if _child_nums > 0:
            logging.error('no allow to delete area %s that has child area',
                          _id)
            fail_num += 1
            # 单台操作且已失败则直接跳出循环
            if all_num == 1:
                msg = '该区域下有子区域,不允许删除'
                break
            continue
        else:
            _dc_nums = dc_s.DataCenterService().get_datacenter_nums_in_area(
                _id)
            if _dc_nums > 0:
                logging.error('no allow to delete area %s that has datacenter',
                              _id)
                fail_num += 1
                # 单台操作且已失败则直接跳出循环
                if all_num == 1:
                    msg = '该区域下已分配有机房,不允许删除'
                    break
                continue

        _ret = area_s.AreaService().delete_area(_id)
        if _ret <= 0:
            logging.error('db delete area %s fail when delete area', _id)
            fail_num += 1
            continue

        _ret_a = access_s.delete_access_info_by_area_id(_id)
        if _ret_a <= 0:
            logging.error('db delete area %s access info when delete area',
                          _id)
            fail_num += 1
            continue

    # 全失败
    if fail_num == all_num:
        logging.error("delete area all failed")
        if msg:
            return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg=msg)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)
    # 部分成功
    if 0 < fail_num < all_num:
        logging.error("delete all area %s part %s failed", all_num, fail_num)
        return json_helper.format_api_resp(code=ErrorCode.SUCCESS_PART,
                                           msg="部分区域删除成功")
    return json_helper.format_api_resp(code=ErrorCode.SUCCESS)
예제 #12
0
def dashboard_v1_map():
    # 当前用户所有机房
    user_areas_ids = current_user_areas()
    all_dc_num, all_dc_data = dc_s.DataCenterService().get_all_datacenters_of_areas(user_areas_ids)

    province_data = [
        {'drilldown': 'beijing', 'name': '北京', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'tianjing', 'name': '天津', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'shanghai', 'name': '上海', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'chongqing', 'name': '重庆', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'hebei', 'name': '河北', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'henan', 'name': '河南', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'yunnan', 'name': '云南', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'liaoning', 'name': '辽宁', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'heilongjiang', 'name': '黑龙江', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'hunan', 'name': '湖南', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'anhui', 'name': '安徽', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'shandong', 'name': '山东', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'xinjiang', 'name': '新疆', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'jiangsu', 'name': '江苏', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'zhejiang', 'name': '浙江', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'jiangxi', 'name': '江西', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'hubei', 'name': '湖北', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'guangxi', 'name': '广西', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'gansu', 'name': '甘肃', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'shanxi', 'name': '山西', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'neimenggu', 'name': '内蒙古', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'shanxi', 'name': '陕西', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'jilin', 'name': '吉林', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'fujian', 'name': '福建', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'guizhou', 'name': '贵州', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'guangdong', 'name': '广东', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'qinghai', 'name': '青海', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'xizang', 'name': '西藏', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'sichuan', 'name': '四川', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'ningxia', 'name': '宁夏', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'hainan', 'name': '海南', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'taiwan', 'name': '台湾', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'xianggang', 'name': '香港', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0},
        {'drilldown': 'aomen', 'name': '澳门', 'value': 0, 'dc': 0, 'host': 0, 'vm': 0}
    ]

    for _dc in all_dc_data:
        _all_ins = get_instances_in_dc(_dc['id'])
        _all_host = get_hosts_of_datacenter(_dc['id'])
        # 统计错误host数
        _error_host_nums = 0
        for _host in _all_host:
            if _host['status'] == HostStatus.ERROR:
                _error_host_nums += 1

        # 机房所在省
        _dc_province = _dc['province']
        for _province in province_data:
            # 找到对应的省
            if _province['name'] == _dc_province:
                _province['dc'] += 1
                _province['host'] += len(_all_host)
                _province['vm'] += len(_all_ins)
                _province['value'] += _error_host_nums
                break

    return json_helper.format_api_resp(code=ErrorCode.SUCCESS, data=province_data)
예제 #13
0
def standard_host(manage_ip, hostpool_id):
    '''
        物理机标准化操作
    :param manage_ip:
    :return:
    '''
    url = HOST_STANDARD_DIR + '/host_std.yaml'

    host_list = [manage_ip]

    # 获取新增host所在网络区域的vlanlist
    hostpool_info = hp_s.HostPoolService().get_hostpool_info(hostpool_id)
    net_area_id = hostpool_info['net_area_id']
    vlan_res, vlan_data = seg_s.SegmentService().get_area_segment_list(
        net_area_id)
    if not vlan_res:
        return False, vlan_data
    else:
        host_vlan_filter_dict = {}
        host_vlan_list = vlan_data
        # host_vlan_list_dupl = sorted(set(host_vlan_list), key=host_vlan_list.index)
        # 根据br_bond对网段进行分类
        for _host_vlan in host_vlan_list:
            if _host_vlan['host_bridge_name'] in host_vlan_filter_dict.keys():
                host_vlan_filter_dict[_host_vlan['host_bridge_name']].append(
                    _host_vlan['vlan'])
            else:
                host_vlan_filter_dict[_host_vlan['host_bridge_name']] = [
                    _host_vlan['vlan']
                ]
        # host_vlan_list_dupl = sorted(set(host_vlan_list), key=lambda i: i["host_bridge_name"])

    # 循环调用playbook为不同bond新建网桥,每次调用完成后需要time.sleep(5)
    br_bond_create_shell_url = HOST_STANDARD_DIR + '/host_std_br_bond_create.yaml'
    for _bond_name, _vlan_list in host_vlan_filter_dict.items():
        host_dict = {
            "srcdir": HOST_STANDARD_DIR,
            "host_vlan_list": _vlan_list,
            "br_bond": _bond_name.split('_')[1]
        }

        run_result, run_message = run_standard_host(br_bond_create_shell_url,
                                                    manage_ip, host_dict)
        if not run_result:
            logging.info('物理机%s初始化新增内网vlan执行playbook失败,原因:%s' %
                         (manage_ip, run_message))

            return False, run_message

        time.sleep(2)

        time.sleep(2)

    # 构造host网桥检测入参内容
    host_test_bridge_list = []
    for vlan_info in vlan_data:
        bridge_name = vlan_info['host_bridge_name'] + '.' + vlan_info['vlan']
        gateway_ip = vlan_info['gateway']
        vlan = vlan_info['vlan']
        host_test_bridge = {
            "bridge": bridge_name,
            "gateway": gateway_ip,
            "vlan": vlan
        }
        host_test_bridge_list.append(host_test_bridge)

    # # 循环调用playbook测试HOST上对指定网桥的访问是否正常
    # bridge_test_shell_url = HOST_STANDARD_DIR + '/host_std_test_vlan.yaml'
    # host_dict = {
    #     "test_bridge_info": host_test_bridge_list
    # }
    res, message = check_vlan_connection(manage_ip, host_test_bridge_list)
    if not res:
        return False, message

    logging.info('start to do host std playbook')
    # 获取host所在网络区域的yum源地址
    datacenter_id = da_s.DataCenterService().get_dctype_by_net_area_id(
        net_area_id)
    if str(datacenter_id) in PRD_DC_TYPE:
        yum_server_addr = PRD_YUM_SERVER
    else:
        yum_server_addr = CS_YUM_SERVER

    # #构造vlan_list字符串传递给playbook作为入参
    # vlan_list_str = " ".join(host_vlan_list)
    # vlan_str = "\'" + vlan_list_str + "\'"
    # print vlan_str
    playbook_url = HOST_STANDARD_DIR + '/host_std.yaml'
    host_dict = {
        "srcdir": HOST_STANDARD_DIR,
        "agentdir": HOST_AGENT_PACKAGE_COPY_DIR,
        "agentshelldir": HOST_AGENT_PACKAGE_INSTALL_SHELL_DIR,
        "libvirt_user_pwd": decrypt(HOST_LIBVIRT_PWD),
        "root_pwd": decrypt(ROOT_PWD),
        "yum_server_ip": yum_server_addr
    }

    run_result, run_message = run_standard_host(playbook_url, manage_ip,
                                                host_dict)

    if not run_result:
        return False, run_message

    logging.info('物理机%s初始化playbook执行成功' % manage_ip)

    # 创建池
    pool_ret = _create_storage_pool(manage_ip)
    if not pool_ret:
        logging.info('host manage ip %s create pool fail when standard host',
                     manage_ip)
        msg = "创建存储池失败"
        return False, msg

    # 创建clone池
    pool_ret = _create_clone_pool(manage_ip)
    if not pool_ret:
        logging.info(
            'host manage ip %s create clone pool fail when standard host',
            manage_ip)
        msg = "创建clone存储池失败"
        return False, msg

    # host 运行checklist
    ret_checklist, msg_checklist = host_std_checklist(manage_ip)
    if not ret_checklist:
        msg = msg_checklist
        logging.info(msg)
        return False, msg

    msg = "标准化主机成功"
    return True, msg
def ip_apply_from_other_platform():
    '''
        外部平台申请ip
    :return:
    '''
    data_from_vishnu = request.data
    logging.info(data_from_vishnu)
    data_requset = json_helper.loads(data_from_vishnu)
    req_datacenter = data_requset['datacenter']
    req_env = data_requset['env']
    req_net_area = data_requset['net_area']
    req_net_name = data_requset['net_name']
    cluster_id = data_requset['cluster_id']
    opuser = data_requset['opUser']
    sys_code = data_requset['sys_code']
    taskid_vs = data_requset['taskid']
    ip_count = data_requset['ipCount']
    prd_dr_ip_all_needed = data_requset['prdDrAllNeeded']  # '0'代表普通申请,'1'需要同时申请prd、dr环境的ip

    # 校验入参是否为空
    if not req_env or not req_net_area or not req_net_name or not req_datacenter:
        return json_helper.format_api_resp_msg(code=ErrorCode.SYS_ERR, job_status=VsJobStatus.FAILED,
                                               detail='empty input of env, net area information or net name '
                                                      'when apply ip')
    if not cluster_id or not opuser or not sys_code or not taskid_vs:
        return json_helper.format_api_resp_msg(code=ErrorCode.SYS_ERR, job_status=VsJobStatus.FAILED,
                                               detail='empty input of cluster_id, opuser, '
                                                      'task id or sys_code when apply ip')

    if not str(ip_count) or not str(prd_dr_ip_all_needed):
        return json_helper.format_api_resp_msg(code=ErrorCode.SYS_ERR, job_status=VsJobStatus.FAILED,
                                               detail='empty input of ipCount or prdDrAllNeeded when apply ip')

    # 查询指定环境、网络区域是否有所需网段
    ret_segment = segment_service.SegmentService().get_segment_info_bysegment(req_net_name.split('/')[0])
    if not ret_segment:
        return json_helper.format_api_resp_msg(code=ErrorCode.SYS_ERR, job_status=VsJobStatus.FAILED,
                                               detail="无法找到需要申请的网段")

    ret_net_area_info = net_area.NetAreaService().get_net_area_info(ret_segment['net_area_id'])
    if not ret_net_area_info:
        return json_helper.format_api_resp_msg(code=ErrorCode.SYS_ERR, job_status=VsJobStatus.FAILED,
                                               detail="无法找到指定网段所属网络区域信息")

    ret_datacenter_info = datacenter_service.DataCenterService().get_datacenter_info(ret_net_area_info['datacenter_id'])
    if not ret_datacenter_info:
        return json_helper.format_api_resp_msg(code=ErrorCode.SYS_ERR, job_status=VsJobStatus.FAILED,
                                               detail="无法找到指定机房信息")
    if req_env not in DataCenterTypeForVishnu.TYPE_DICT:
        return json_helper.format_api_resp_msg(code=ErrorCode.SYS_ERR, job_status=VsJobStatus.FAILED,
                                               detail="无法找到指定机房类型信息")
    if str(DataCenterTypeForVishnu.TYPE_DICT[req_env]) != ret_datacenter_info['dc_type']:
        return json_helper.format_api_resp_msg(code=ErrorCode.SYS_ERR, job_status=VsJobStatus.FAILED,
                                               detail="无法找到指定网络区域对应网段信息")

    # 如果是申请生产或者容灾环境ip,需判断网段对应关系表中是否有记录
    if req_env == 'PRD':
        segment_dr = segment_m.SegmentMatchService().get_segment_match_info_by_prd_segment_id(
            ret_segment['id'])
        if not segment_dr:
            return json_helper.format_api_resp_msg(code=ErrorCode.SYS_ERR, job_status=VsJobStatus.FAILED,
                                                   detail='指定机房、网络区域下无法找到生产网段对应的容灾网段ID')
        segment_dr_data = segment_s.SegmentService().get_segment_info(segment_dr['dr_segment_id'])
        if not segment_dr_data:
            return json_helper.format_api_resp_msg(code=ErrorCode.SYS_ERR, job_status=VsJobStatus.FAILED,
                                                   detail='指定机房、网络区域下无法找到生产网段对应的容灾网段详细信息')

    elif req_env == 'DR':
        segment_prd = segment_m.SegmentMatchService().get_segment_match_info_by_dr_segment_id(
            ret_segment['id'])
        if not segment_prd:
            return json_helper.format_api_resp_msg(code=ErrorCode.SYS_ERR, job_status=VsJobStatus.FAILED,
                                                   detail='指定机房、网络区域下无法找到容灾网段对应的生产网段ID')
        segment_prd_data = segment_s.SegmentService().get_segment_info(segment_prd['prd_segment_id'])
        if not segment_prd_data:
            return json_helper.format_api_resp_msg(code=ErrorCode.SYS_ERR, job_status=VsJobStatus.FAILED,
                                                   detail='指定机房、网络区域下无法找到容灾网段对应的生产网段详细信息')

    # 获取IP资源,先判断是否有人也在分配IP资源,有则等待1s,时间之后再优化
    ip_lock_unused = False
    while not ip_lock_unused:
        ret_ip_lock_status = ip_l_s.IpLockService().get_ip_lock_info('ip')
        if not ret_ip_lock_status:
            logging.error('外部接口分配vip:检查IP时无法获取资源锁状态')
            return json_helper.format_api_resp_msg(code=ErrorCode.SYS_ERR, job_status=VsJobStatus.FAILED,
                                                   detail='检查IP时无法获取资源锁状态')
        if ret_ip_lock_status['istraceing'] == IpLockStatus.USED:
            time.sleep(1)
        else:
            ip_lock_unused = True

    # 更新ip_lock表istraceing字段为1
    ret_ip_lock_used_status, ret_ip_lock_used_datas = __update_ip_lock_used()
    if not ret_ip_lock_used_status:
        logging.error(ret_ip_lock_used_datas)
        return json_helper.format_api_resp_msg(code=ErrorCode.SYS_ERR, job_status=VsJobStatus.FAILED,
                                               detail=ret_ip_lock_used_datas)
    try:
        segments_data_list = []
        segments_data_list.append(ret_segment)
        # 获取可用ip
        ret_ip_datas, ret_ip_segment_datas = ip_service.get_available_ips(segments_data_list, int(ip_count), str(
            DataCenterTypeForVishnu.TYPE_DICT[req_env]))
        if not ret_ip_datas:
            ret_ip_lock_unused_status, ret_ip_lock_unused_datas = __update_ip_lock_unused()
            if not ret_ip_lock_unused_status:
                logging.error(ret_ip_lock_unused_datas)
                return json_helper.format_api_resp_msg(code=ErrorCode.SYS_ERR, job_status=VsJobStatus.FAILED,
                                                       detail=ret_ip_lock_unused_datas)
            return json_helper.format_api_resp_msg(code=ErrorCode.SYS_ERR, job_status=VsJobStatus.FAILED,
                                                   detail='指定机房、网络区域下无法找到%s个可用IP' % str(ip_count))

        # 标记ip为预分配
        logging.info(ret_ip_datas)
        ips_list = []
        prd_ips_list = []
        dr_ips_list = []
        ip_details = {}
        for ip in ret_ip_datas:
            update_data = {
                'status': IPStatus.USED
            }
            where_data = {
                'id': ip['id']
            }
            ret_mark_ip = ip_service.IPService().update_ip_info(update_data, where_data)
            if ret_mark_ip <= 0:
                continue

            # 录入vip信息到数据库中
            insert_vip_data = {
                'ip_id': ip['id'],
                'cluster_id': cluster_id,
                'apply_user_id': opuser,
                'sys_code': sys_code,
                'isdeleted': '0',
                'created_at': get_datetime_str()
            }
            ret_vip = vip_service.VIPService().add_vip_info(insert_vip_data)
            if ret_vip.get('row_num') <= 0:
                continue

            ip_datas = {
                'ip': ip['ip_address'],
                'vlanId': ip['vlan'],
                'subnetMask': __exchange_maskint(int(ip['netmask'])),
                'gateway': ip['gateway_ip']
            }
            ips_list.append(ip_datas)

            # 生产环境需要预分配对应容灾环境ip,容灾环境需要预分配生产环境ip
            if req_env == 'PRD':
                # 拼凑虚拟机容灾ip并预分配ip
                dr_ip = segment_dr_data['segment'].split('.')[0] + '.' + segment_dr_data['segment'].split('.')[1] + \
                        '.' + ip['ip_address'].split('.')[2] + '.' + ip['ip_address'].split('.')[3]
                dr_ip_info = ip_service.IPService().get_ip_by_ip_address(dr_ip)
                # 如果容灾环境ip未初始化,默认初始化
                if not dr_ip_info:
                    if not __init_ip(segment_dr_data, dr_ip):
                        continue
                    dr_ip_info = ip_service.IPService().get_ip_by_ip_address(dr_ip)

                if prd_dr_ip_all_needed == '1':
                    update_data = {
                        'status': IPStatus.USED
                    }
                    where_data = {
                        'id': dr_ip_info['id']
                    }
                    ret_mark_ip = ip_service.IPService().update_ip_info(update_data, where_data)
                    if ret_mark_ip <= 0:
                        continue

                    # 录入vip信息到数据库中
                    insert_vip_data = {
                        'ip_id': dr_ip_info['id'],
                        'cluster_id': cluster_id,
                        'apply_user_id': opuser,
                        'sys_code': sys_code,
                        'isdeleted': '0',
                        'created_at': get_datetime_str()
                    }
                    ret_vip = vip_service.VIPService().add_vip_info(insert_vip_data)
                    if ret_vip.get('row_num') <= 0:
                        continue
                else:
                    update_data = {
                        'status': IPStatus.PRE_ALLOCATION
                    }
                    where_data = {
                        'ip_address': dr_ip
                    }
                    ret_mark_ip = ip_service.IPService().update_ip_info(update_data, where_data)
                    if ret_mark_ip <= 0:
                        continue

                # 拼装容灾ip信息
                dr_ip_datas = {
                    'ip': dr_ip_info['ip_address'],
                    'vlanId': dr_ip_info['vlan'],
                    'subnetMask': __exchange_maskint(int(dr_ip_info['netmask'])),
                    'gateway': dr_ip_info['gateway_ip']
                }
                dr_ips_list.append(dr_ip_datas)
            elif req_env == 'DR':
                # 拼凑虚拟机生产ip并预分配ip
                prd_ip = segment_prd_data['segment'].split('.')[0] + '.' + segment_prd_data['segment'].split('.')[1] + \
                         '.' + ip['ip_address'].split('.')[2] + '.' + ip['ip_address'].split('.')[3]
                prd_ip_info = ip_service.IPService().get_ip_by_ip_address(prd_ip)
                # 如果生产环境ip未初始化,默认初始化
                if not prd_ip_info:
                    if not __init_ip(segment_prd_data, prd_ip):
                        continue
                    prd_ip_info = ip_service.IPService().get_ip_by_ip_address(prd_ip)

                if prd_dr_ip_all_needed == '1':
                    update_data = {
                        'status': IPStatus.USED
                    }
                    where_data = {
                        'id': prd_ip_info['id']
                    }
                    ret_mark_ip = ip_service.IPService().update_ip_info(update_data, where_data)
                    if ret_mark_ip <= 0:
                        continue

                    # 录入vip信息到数据库中
                    insert_vip_data = {
                        'ip_id': prd_ip_info['id'],
                        'cluster_id': cluster_id,
                        'apply_user_id': opuser,
                        'sys_code': sys_code,
                        'isdeleted': '0',
                        'created_at': get_datetime_str()
                    }
                    ret_vip = vip_service.VIPService().add_vip_info(insert_vip_data)
                    if ret_vip.get('row_num') <= 0:
                        continue
                else:
                    update_data = {
                        'status': IPStatus.PRE_ALLOCATION
                    }
                    where_data = {
                        'ip_address': prd_ip
                    }
                    ret_mark_ip = ip_service.IPService().update_ip_info(update_data, where_data)
                    if ret_mark_ip <= 0:
                        continue

                # 拼装生产ip信息
                prd_ip_datas = {
                    'ip': prd_ip_info['ip_address'],
                    'vlanId': prd_ip_info['vlan'],
                    'subnetMask': __exchange_maskint(int(prd_ip_info['netmask'])),
                    'gateway': prd_ip_info['gateway_ip']
                }
                prd_ips_list.append(prd_ip_datas)
    except Exception as e:
        _msg = '外部平台申请IP:预分配ip出现异常: distribution ip exception,err:%s'%e
        logging.error(_msg)
        ret_ip_lock_unused_status, ret_ip_lock_unused_datas = __update_ip_lock_unused()
        if not ret_ip_lock_unused_status:
            logging.error(ret_ip_lock_unused_datas)
            return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg=ret_ip_lock_unused_datas)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg=_msg)

    # 更新ip_lock表istraceing字段为0
    ret_ip_lock_unused_status, ret_ip_lock_unused_datas = __update_ip_lock_unused()
    if not ret_ip_lock_unused_status:
        logging.error(ret_ip_lock_unused_datas)
        return json_helper.format_api_resp_msg(code=ErrorCode.SYS_ERR, job_status=VsJobStatus.FAILED,
                                               detail=ret_ip_lock_unused_datas)

    if len(ips_list) <= 0:
        return json_helper.format_api_resp_msg(code=ErrorCode.SYS_ERR, job_status=VsJobStatus.FAILED,
                                               detail='指定机房、网络区域下%s个可用IP修改为预分配状态全部失败' % str(ip_count))
    elif req_env == 'PRD' and (len(ips_list) + len(dr_ips_list)) < int(ip_count) * 2:
        return json_helper.format_api_resp_msg(code=ErrorCode.SUCCESS_PART, job_status=VsJobStatus.FAILED,
                                               detail='生产环境指定机房、网络区域下%s个可用IP修改为预分配状态部分失败' % str(ip_count))
    elif req_env == 'DR' and (len(ips_list) + len(prd_ips_list)) < int(ip_count) * 2:
        return json_helper.format_api_resp_msg(code=ErrorCode.SUCCESS_PART, job_status=VsJobStatus.FAILED,
                                               detail='容灾环境指定机房、网络区域下%s个可用IP修改为预分配状态部分失败' % str(ip_count))
    elif len(ips_list) < int(ip_count):
        return json_helper.format_api_resp_msg(code=ErrorCode.SUCCESS_PART, job_status=VsJobStatus.FAILED,
                                               detail='指定机房、网络区域下%s个可用IP修改为预分配状态部分失败' % str(ip_count))
    else:
        if req_env == 'PRD':
            ip_details['prd'] = ips_list
            ip_details['dr'] = dr_ips_list
        elif req_env == 'DR':
            ip_details['dr'] = ips_list
            ip_details['prd'] = prd_ips_list
        else:
            ip_details['default'] = ips_list
        return json_helper.format_api_resp_msg(code=ErrorCode.SUCCESS, job_status=VsJobStatus.SUCCEED,
                                               detail=ip_details)
예제 #15
0
def net_area_add():
    datacenter_id = request.values.get('datacenter_id')
    name = request.values.get('name')
    imagecache01 = request.values.get('imagecache01')
    imagecache02 = request.values.get('imagecache02')

    if not name or not datacenter_id or not imagecache01 or not imagecache02:
        logging.info('no area_name or datacenter_id when add net_area')
        return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR)

    dc_data = dc_s.DataCenterService().get_datacenter_info(datacenter_id)
    if not dc_data:
        logging.error('datacenter %s no exist in db when add net_area',
                      datacenter_id)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

    # 同一环境下机房下的网络区域不能重名
    name_exist = net_area_s.check_name_exist_in_same_dc_type(
        name, dc_data['dc_type'])
    if name_exist:
        logging.error('name %s in dc_type %s is duplicated when add net_area',
                      name, dc_data['dc_type'])
        return json_helper.format_api_resp(code=ErrorCode.DUPLICATED_ERR,
                                           msg='同环境机房下的网络区域名不能重复,请修改网络区域名')

    # 两台imagecache不能重复
    if imagecache01 == imagecache02:
        logging.info('imagecache address duplicated')
        return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR,
                                           msg="镜像缓存服务器地址重复")

    insert_data = {
        'datacenter_id': datacenter_id,
        'name': name,
        'displayname': name,
        'created_at': get_datetime_str(),
    }
    ret = net_area_s.NetAreaService().add_net_area(insert_data)
    if ret == -1:
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

    net_area_id = ret.get('last_id')
    insert_imagecache01 = {
        "net_area_id": net_area_id,
        "imagecache_ip": imagecache01,
        "create_at": get_datetime_str()
    }
    ret = imca_s.ImageCacheService().add_imagecache_info(insert_imagecache01)
    if ret.get('row_num') <= 0:
        logging.error("add imagecache01 error, insert_data:%s",
                      str(insert_data))
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                           msg="新增cache01地址失败")

    insert_imagecache02 = {
        "net_area_id": net_area_id,
        "imagecache_ip": imagecache02,
        "create_at": get_datetime_str()
    }
    ret = imca_s.ImageCacheService().add_imagecache_info(insert_imagecache02)
    if ret.get('row_num') <= 0:
        logging.error("add imagecache02 error, insert_data:%s",
                      str(insert_data))
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                           msg="新增cache02地址失败")

    return json_helper.format_api_resp(code=ErrorCode.SUCCESS, msg="新增网络区域成功")
예제 #16
0
def net_area_update(net_area_id):
    name = request.values.get('name')
    imagecache01 = request.values.get('imagecache01')
    imagecache02 = request.values.get('imagecache02')
    if not net_area_id or not name or not imagecache01 or not imagecache02:
        logging.error('the params is invalid when update net area')
        return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR)

    net_area_data = net_area_s.NetAreaService().get_net_area_info(net_area_id)
    if not net_area_data:
        logging.error('net area %s is no exist in db when update net area',
                      net_area_id)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

    if net_area_data['name'] != name:
        dc_data = dc_s.DataCenterService().get_datacenter_info(
            net_area_data['datacenter_id'])
        if not dc_data:
            logging.error(
                'datacenter %s is no exist in db when update net area',
                net_area_data['datacenter_id'])
            return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

        # 同一环境下机房下的网络区域不能重名
        name_exist = net_area_s.check_name_exist_in_same_dc_type(
            name, dc_data['dc_type'])
        if name_exist:
            logging.error(
                'name %s in dc_type %s is duplicated when update net area',
                name, dc_data['dc_type'])
            return json_helper.format_api_resp(code=ErrorCode.DUPLICATED_ERR,
                                               msg='同环境机房下的网络区域名不能重复,请修改网络区域名')

    # 两台imagecache不能重复
    if imagecache01 == imagecache02:
        logging.info('imagecache address duplicated')
        return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR,
                                           msg="镜像缓存服务器地址重复")

    update_data = {
        'name': name,
        'displayname': name,
        'updated_at': get_datetime_str()
    }
    where_data = {
        'id': net_area_id,
    }
    ret = net_area_s.NetAreaService().update_net_area_info(
        update_data, where_data)
    if ret < 0:
        logging.error("update net area error, update_data:%s, where_data:%s",
                      str(update_data), str(where_data))
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

    imagecache_data = imca_s.ImageCacheService(
    ).get_imagecache_info_by_net_area_id(net_area_id)
    imagecache01_data = imagecache_data[0]
    imagecache02_data = imagecache_data[1]
    exist_cache_ids = [imagecache01_data['id'], imagecache02_data['id']]
    # update imagecache01
    where_data = {"id": exist_cache_ids[0]}
    update_data = {"imagecache_ip": imagecache01}
    ret = imca_s.ImageCacheService().update_imagecache_info(
        update_data, where_data)
    # update imagecache02
    where_data = {"id": exist_cache_ids[1]}
    update_data = {"imagecache_ip": imagecache02}
    ret = imca_s.ImageCacheService().update_imagecache_info(
        update_data, where_data)
    return json_helper.format_api_resp(code=ErrorCode.SUCCESS)
예제 #17
0
def ip_instance_info():
    '''
        获取IP分配给VM的详细信息
    :return:
    '''
    ip_address = request.values.get('ip_address')
    if not ip_address:
        logging.info('no ip_address when get ip info')
        return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR)

    ip_info = ip_s.IPService().get_ip_info_by_ipaddress(ip_address)
    if not ip_info:
        logging.error('IP %s info no exist in db when get ip info', ip_address)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

    # 检查ip是否为应用vip
    vip_info = vip_s.VIPService().get_vip_by_id(ip_info['id'])
    if not vip_info:
        if ip_info['status'] != IPStatus.USED:
            logging.info('IP %s status %s is not used when get ip info',
                         ip_address, ip_info['status'])
            return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                               msg="IP状态不对,不能查看IP详细信息")

        ip_instance_data = ip_s.get_instance_info_by_ip(ip_address)
        if ip_instance_data:
            instance_name = ip_instance_data.get('instance_name', None)
            datacenter_name = ip_instance_data.get('datacenter_name', None)
            net_area_name = ip_instance_data.get('net_area_name', None)
        else:
            instance_name = None
            datacenter_name = None
            net_area_name = None

        ip_data = {
            'ip_address': ip_address,
            'datacenter': datacenter_name,
            'net_area': net_area_name,
            'instance_name': instance_name,
            'gateway': ip_info['gateway_ip'],
            'netmask': ip_info['netmask'],
            'vlan': ip_info['vlan'],
            'service_id': '',
            'is_vip': '0'
        }
    else:
        segment_info = segment_s.SegmentService().get_segment_info(
            ip_info['segment_id'])
        if not segment_info:
            _msg = '无法获取IP:%s的网段信息' % ip_address
            return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                               msg=_msg)

        net_area_info = net_area.NetAreaService().get_net_area_info(
            segment_info['net_area_id'])
        if not net_area_info:
            net_area_name = ''
        net_area_name = net_area_info['name']
        datacenter_info = datacenter_service.DataCenterService(
        ).get_datacenter_info(net_area_info['datacenter_id'])
        if not datacenter_info:
            datacenter_name = ''
        datacenter_name = datacenter_info['name']

        ip_data = {
            'ip_address': ip_address,
            'datacenter': datacenter_name,
            'net_area': net_area_name,
            'instance_name': '',
            'gateway': ip_info['gateway_ip'],
            'netmask': ip_info['netmask'],
            'vlan': ip_info['vlan'],
            'sys_code': vip_info['sys_code'],
            'is_vip': '1'
        }

    return json_helper.format_api_resp(code=ErrorCode.SUCCESS, data=ip_data)
예제 #18
0
def ip_apply():
    '''
        IP申请
    :return:
    '''
    req_env = request.values.get('env')
    req_net_area = request.values.get('net_area')
    req_net_name = request.values.get('segment')
    cluster_id = request.values.get('cluster_id')
    opuser = request.values.get('opUser')
    sys_code = request.values.get('sys_code')

    # 校验入参是否为空
    if not req_env or not req_net_area or not req_net_name:
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                           msg="环境、网络区域、网段名输入为空")
    if not cluster_id or not opuser or not sys_code:
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                           msg="物理集群、操作用户、系统编码为空输入为空")

    # 查询指定环境、网络区域是否有所需网段
    ret_segment = segment_service.SegmentService().get_segment_info_bysegment(
        req_net_name)
    if not ret_segment:
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                           msg="无法找到需要申请的网段")

    ret_net_area_info = net_area.NetAreaService().get_net_area_info(
        ret_segment['net_area_id'])
    if not ret_net_area_info:
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                           msg="无法找到指定网络区域信息")
    ret_datacenter_info = datacenter_service.DataCenterService(
    ).get_datacenter_info(ret_net_area_info['datacenter_id'])
    if not ret_datacenter_info:
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                           msg="无法找到指定机房信息")
    if req_env not in DataCenterTypeForVishnu.TYPE_DICT:
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                           msg="无法找到指定机房类型信息")
    if str(DataCenterTypeForVishnu.TYPE_DICT[req_env]
           ) != ret_datacenter_info['dc_type']:
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                           msg="无法找到指定网络区域对应网段信息")

    # 获取IP资源,先判断是否有人也在分配IP资源,有则等待1s,时间之后再优化
    ip_lock_unused = False
    while not ip_lock_unused:
        ret_ip_lock_status = ip_l_s.IpLockService().get_ip_lock_info('ip')
        if not ret_ip_lock_status:
            logging.error('kvm平台分配vip:检查IP时无法获取资源锁状态')
            return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                               msg='检查IP时无法获取资源锁状态')
        if ret_ip_lock_status['istraceing'] == IpLockStatus.USED:
            time.sleep(1)
        else:
            ip_lock_unused = True

    # 更新ip_lock表istraceing字段为1
    ret_ip_lock_used_status, ret_ip_lock_used_datas = __update_ip_lock_used()
    if not ret_ip_lock_used_status:
        logging.error(ret_ip_lock_used_datas)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                           msg=ret_ip_lock_used_datas)
    # 获取可用ip
    try:
        ret_ip_available_status, ret_ip_available = ip_service.get_available_segment_ip(
            ret_segment['id'], str(DataCenterTypeForVishnu.TYPE_DICT[req_env]))
    except Exception as e:
        _msg = 'IP申请ip_apply:获取指定网段可用ip出现异常 : get segment available ip exception when ip apply,err:%s' % e
        logging.error(_msg)
        ret_ip_lock_unused_status, ret_ip_lock_unused_datas = __update_ip_lock_unused(
        )
        if not ret_ip_lock_unused_status:
            logging.error(ret_ip_lock_unused_datas)
            return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                               msg=ret_ip_lock_unused_datas)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg=_msg)

    if not ret_ip_available_status:
        ret_ip_lock_unused_status, ret_ip_lock_unused_datas = __update_ip_lock_unused(
        )
        if not ret_ip_lock_unused_status:
            logging.error(ret_ip_lock_unused_datas)
            return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                               msg=ret_ip_lock_unused_datas)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                           msg="指定网段没有可用ip")

    # 标记ip已使用
    update_data = {'status': IPStatus.USED}
    where_data = {'id': ret_ip_available['id']}
    ret_mark_ip = ip_service.IPService().update_ip_info(
        update_data, where_data)
    if ret_mark_ip <= 0:
        ret_ip_lock_unused_status, ret_ip_lock_unused_datas = __update_ip_lock_unused(
        )
        if not ret_ip_lock_unused_status:
            logging.error(ret_ip_lock_unused_datas)
            return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                               msg=ret_ip_lock_unused_datas)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                           msg="标记ip为已使用状态失败,请重新申请")

    # 更新ip_lock表istraceing字段为0
    ret_ip_lock_unused_status, ret_ip_lock_unused_datas = __update_ip_lock_unused(
    )
    if not ret_ip_lock_unused_status:
        logging.error(ret_ip_lock_unused_datas)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                           msg=ret_ip_lock_unused_datas)

    # 录入vip信息到数据库中
    insert_vip_data = {
        'ip_id': ret_ip_available['id'],
        'cluster_id': cluster_id,
        'apply_user_id': opuser,
        'sys_code': sys_code,
        'isdeleted': '0',
        'created_at': get_datetime_str()
    }
    ret_vip = vip_service.VIPService().add_vip_info(insert_vip_data)
    if ret_vip.get('row_num') <= 0:
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                           msg="录入ip信息失败,请联系系统管理员")

    ip_msg = {"vip": ret_ip_available['ip_address']}

    return json_helper.format_api_resp(code=ErrorCode.SUCCESS, data=ip_msg)