Exemplo n.º 1
0
def _check_duplicated_group_name(group_name, env=None):
    '''
        检查应用组是否重名
    :param group_name:
    :return:
    '''
    if env:
        params = {
            'WHERE_AND': {
                '=': {
                    'name': group_name,
                    'dc_type': env,
                    'isdeleted': '0',
                },
            },
        }
    else:
        params = {
            'WHERE_AND': {
                '=': {
                    'name': group_name,
                    'isdeleted': '0',
                },
            },
        }

    group_num, group_data = group_s.GroupService().query_data(**params)
    if group_num > 0:
        return True
    return False
Exemplo n.º 2
0
def users_in_group(group_id):
    '''
    :return: 返回某个group下的所有用户信息
    '''
    checkexist = group_service.GroupService().get_group_info(group_id)
    if not checkexist:
        logging.info('no such group_id')
        return json_helper.format_api_resp(code=ErrorCode.NOT_EXIST_USER)
    params = {
        'ORDER': [
            ['id', 'desc'],
        ],
        'PAGINATION': {
            'page_size': request.values.get('page_size', 20),
            'page_no': request.values.get('page_no', 1),
        }
    }
    total_nums, data = user_group_service.UserGroupService().get_alluser_group(
        group_id)
    resp = UsersGroup()
    resp.total = total_nums
    for i in data:
        _user_group_info = user_group_info.UserGroupInfo().user_group_info(i)
        resp.rows.append(_user_group_info)
    return json_helper.format_api_resp(code=ErrorCode.SUCCESS,
                                       data=resp.to_json())
Exemplo n.º 3
0
def check(group_id, user_id):
    if not user_id or not group_id:
        logging.info(
            'no user_id or group_id or rold_id when add user to a group')
        return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR)

    group_info = group_s.GroupService().get_group_info(group_id)
    if not group_info[1]:
        logging.info('no such group_id %s when add user to a group', group_id)
        return json_helper.format_api_resp(code=ErrorCode.NOT_EXIST_USER)

    user_group = user_g_s.UserGroupService().query_user_role_group(
        user_id, group_id)
    if user_group[1]:
        logging.info(
            'same user %s already in group %s when add user to a group',
            user_id, group_id)
        return json_helper.format_api_resp(code=ErrorCode.DUPLICATED_ERR,
                                           msg='用户已经存在于该组,请不要重复加入')

    params = {
        'WHERE_AND': {
            '=': {
                'group_id': group_id,
            }
        }
    }
    is_exist_role_group = access_service.AccessService().query_info(params)
    if not is_exist_role_group[1]:
        # 查询access表中是否存在这个role-group的对应关系,(不查area)没有就报错
        logging.info('not such role_group_area mapping exist')
        return json_helper.format_api_resp(code=ErrorCode.NOT_EXIST_USER,
                                           msg="该组没有角色权限对应关系,不能添加新用户")
Exemplo n.º 4
0
def v2v_esx_init_info():
    resp = V2v_esx_InitInfoResp()

    # area层级信息 - 总部
    area_ZB, area_DQ = v2v_esx_get_hostpool_info()
    resp.area_ZB = area_ZB
    resp.area_DQ = area_DQ

    # flavor信息
    flavors_nums, flavors_data = flavor_service.FlavorService(
    ).get_all_flavors()
    for i in flavors_data:
        _flavor_info = flavor_init_info.FlavorInitInfo().init_from_db(i)
        resp.flavors.append(_flavor_info)

    #网段信息
    segmentlist = init_segment()
    resp.segment = segmentlist

    # group信息
    groups_params = {
        'WHERE_AND': {
            '=': {
                'isdeleted': '0'
            }
        },
    }
    groups_nums, groups_data = group_service.GroupService().query_data(
        **groups_params)
    for i in groups_data:
        _group_info = group_info.GroupInitInfo().init_from_db_1(i)
        resp.groups.append(_group_info)

    return json_helper.format_api_resp(code=ErrorCode.SUCCESS,
                                       data=resp.to_json())
Exemplo n.º 5
0
def current_user_groups_by_userid(user_id):
    '''
        获取指定用户的所属应用组
    :return:
    '''
    groups_list = []
    user_groups_num, user_groups_data = user_g_s.UserGroupService(
    ).get_allgroup_user(user_id)
    for _user_group in user_groups_data:
        _group_num, _group_data = group_s.GroupService().get_group_info(
            _user_group['group_id'])
        if _group_num > 0:
            groups_list.append(_group_data[0])

    return groups_list
Exemplo n.º 6
0
def init_group_info(group_id):
    '''
    用户编辑组时的初始化信息
    :param group_id:
    :return:
    '''
    resp = {}
    group_tuple = group_s.GroupService().get_group_info(group_id)
    group_dict = group_tuple[1][0]
    area_list = group_area_info(group_id)
    # role_info = access_service.AccessService().get_one('group_id', group_id)
    # role_id = role_info['role_id']
    num, role_info = user_g_s.UserGroupService().get_user_role(
        group_dict['owner'], group_id)
    if num <= 0:
        role_id = None
    else:
        role_id = role_info[0]['role_id']

    used_area = []

    result_dict = {
        'vm': group_dict['vm'],
        'disk': group_dict['disk'],
        'cpu': group_dict['cpu'],
        'mem': group_dict['mem'],
        'owner': group_dict['owner'],
        'role_id': role_id,
        'name': group_dict['name'],
        'area_list': area_list,
        'p_cluster_id': group_dict['p_cluster_id']
    }
    used_area.append(result_dict)
    # used_area = group_init_info.GroupInitInfo().init_group_info(result_dict)
    resp['used_area'] = used_area

    ret_init = area.get_area_info()
    for i in ret_init:
        if i["parent_id"] == -1:
            i["parent_id"] = i["id"]
            i["parent_name"] = i["name"]
            i["name"] = None
            i["id"] = None
        all_area = []
    for i in ret_init:
        all_area = []
    resp['all_area'] = ret_init
    return json_helper.format_api_resp(code=ErrorCode.SUCCESS, data=resp)
Exemplo n.º 7
0
def current_user_groups():
    '''
        获取当前用户的所属应用组
    :return:
    '''
    c_user = get_user()
    c_user_id = c_user['user_id']
    if not c_user_id:
        return None

    groups_list = []
    user_groups_num, user_groups_data = user_g_s.UserGroupService(
    ).get_allgroup_user(c_user_id)
    for _user_group in user_groups_data:
        _group_num, _group_data = group_s.GroupService().get_group_info(
            _user_group['group_id'])
        if _group_num > 0:
            groups_list.append(_group_data[0])

    return groups_list
Exemplo n.º 8
0
def delete_user_group():
    '''
    将组中的某个用户删除
    '''
    user_id = request.values.get('user_id')
    group_id = request.values.get('group_id')
    if not user_id or not group_id:
        logging.info('no user_id or group_id when delete user from a group')
        return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR)

    user_group_num, user_group_data = user_g_s.UserGroupService(
    ).query_user_role_group(user_id, group_id)
    if user_group_num < 0:
        logging.info(
            'no such user %s in group %s when delete user from a group',
            user_id, group_id)
        return json_helper.format_api_resp(code=ErrorCode.NOT_EXIST_USER)

    groups_num, groups_data = group_s.GroupService().get_group_info(group_id)
    if groups_num < 0:
        logging.error('no group %s info in db when delete user from a group',
                      group_id)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

    # 不能删除组所有者
    if groups_data[0]['owner'] == user_id:
        logging.warn(
            'not allow delete group %s owner %s when delete user from a group',
            group_id, user_id)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                           msg='不能删除组的所有者!')

    ret = user_g_s.delete_user(user_id, group_id)
    if ret <= 0:
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)
    return json_helper.format_api_resp(code=ErrorCode.SUCCESS)
Exemplo n.º 9
0
def check_group_quota(group_id, flavor_info, data_disk_gb, vm_count):
    '''
        判断应用组配额是否足够
    :param group_id:
    :param flavor_info:
    :param data_disk_gb:
    :param vm_count:
    :return:
    '''
    quota_used = group_s.get_group_quota_used(group_id)
    if not quota_used:
        logging.error('group %s has no quota used info when check group quota',
                      group_id)
        return False, '没有该应用组配额使用情况,无法创建实例'

    group_num, group_info = group_s.GroupService().get_group_info(group_id)
    if group_num < 1:
        logging.error('no group %s info when check group quota', group_id)
        return False, '该应用组信息不存在,无法创建实例,请联系系统组处理'

    all_cpu_g = group_info[0]['cpu']
    all_mem_gb_g = group_info[0]['mem']
    all_disk_gb_g = group_info[0]['disk']
    all_vm_g = group_info[0]['vm']

    used_cpu_g = quota_used['all_vcpu']
    used_mem_mb_g = quota_used['all_mem_mb']
    used_disk_gb_g = quota_used['all_disk_gb']
    used_vm_g = quota_used['instance_num']

    cpu = flavor_info['vcpu']
    mem_mb = flavor_info['memory_mb']
    root_disk_gb = flavor_info['root_disk_gb']

    if int(used_vm_g) + int(vm_count) > int(all_vm_g):
        logging.error('group %s: vm used %s + apply count %s > all num %s',
                      group_id, used_vm_g, vm_count, all_vm_g)
        return False, '应用组VM配额已不够,无法创建实例,请联系系统组处理'

    if int(used_cpu_g) + int(cpu) * int(vm_count) > int(all_cpu_g):
        logging.error(
            'group %s: cpu used %s + flavor cpu %s * num %s > all cpu %s',
            group_id, used_cpu_g, cpu, vm_count, all_cpu_g)
        return False, '应用组CPU配额已不够,无法创建实例,请联系系统组处理'

    all_mem_mb_g = int(all_mem_gb_g) * 1024
    if int(used_mem_mb_g) + int(mem_mb) * int(vm_count) > all_mem_mb_g:
        logging.error(
            'group %s: mem used %s + flavor mem %s * num %s > all mem %s',
            group_id, used_mem_mb_g, mem_mb, vm_count, all_mem_mb_g)
        return False, '应用组MEM配额已不够,无法创建实例,请联系系统组处理'

    if int(used_disk_gb_g) + (int(root_disk_gb) + int(data_disk_gb)
                              ) * int(vm_count) > int(all_disk_gb_g):
        logging.error(
            'group %s: disk used %s + (flavor disk %s + data disk %s) * num %s > all disk %s',
            group_id, used_disk_gb_g, root_disk_gb, data_disk_gb, vm_count,
            all_disk_gb_g)
        return False, '应用组DISK配额已不够,无法创建实例,请联系系统组处理'

    return True, None
Exemplo n.º 10
0
def _check_change_group_quota(n_group_id, n_flavor, c_flavor,extend_list=None):
    '''
        检查修改新应用组后的配额是否足够
    :param n_group_id:
    :param n_flavor:
    :param c_flavor:
    :return:
    '''
    quota_used = group_s.get_group_quota_used(n_group_id)
    if not quota_used:
        logging.error('group %s has no quota used info when check change group quota', n_group_id)
        return False

    group_num, group_data = group_s.GroupService().get_group_info(n_group_id)
    if group_num < 1:
        logging.error('no group %s info when check change group quota', n_group_id)
        return False

    # 新应用组的总配额情况
    all_cpu_g = group_data[0]['cpu']
    all_mem_gb_g = group_data[0]['mem']
    all_vm_g = group_data[0]['vm']
    all_disk_g = group_data[0]['disk']
    # 新应用组的配额使用情况
    used_cpu_g = quota_used['all_vcpu']
    used_mem_mb_g = quota_used['all_mem_mb']
    used_vm_g = quota_used['instance_num']
    used_disk_g = quota_used['all_disk_gb']



    # 新配额信息
    n_cpu = n_flavor['vcpu']
    n_mem_mb = n_flavor['memory_mb']
    # 旧配额信息
    c_cpu = c_flavor['vcpu']
    c_mem_mb = c_flavor['memory_mb']

    if int(used_vm_g) + 1 > int(all_vm_g):
        logging.error('group %s: vm used %s + 1 > all num %s', n_group_id, used_vm_g, all_vm_g)
        return False, '新应用组的实例数目配额不足,无法修改应用组'

    if int(used_cpu_g) - int(c_cpu) + int(n_cpu) > int(all_cpu_g):
        logging.error('group %s: cpu used %s - old cpu %s + new cpu %s > all cpu %s',
                      n_group_id, used_cpu_g, c_cpu, n_cpu, all_cpu_g)
        return False, '新应用组的CPU配额不足,无法修改应用组'

    all_mem_mb_g = int(all_mem_gb_g) * 1024
    if int(used_mem_mb_g) - int(c_mem_mb) + int(n_mem_mb) > all_mem_mb_g:
        logging.error('group %s: mem used %s - old mem %s + new mem %s > all mem %s',
                      n_group_id, used_mem_mb_g, c_mem_mb, n_mem_mb, all_mem_mb_g)
        return False, '新应用组的内存配额不足,无法修改应用组'

    if extend_list:
        sum_extend_size = sum([int(i['mount_extend_size']) for i in extend_list])
    else:
        sum_extend_size = 0
    if int(used_disk_g) + sum_extend_size > int(all_disk_g):
        logging.error('group %s: disk used %s + extend_size %s > all disk_size %s',
                      used_disk_g, sum_extend_size, all_disk_g)
        return False, '新应用组的磁盘空间配额不足,无法修改应用组'

    return True, None
Exemplo n.º 11
0
def configure_init(instance_id):
    '''
        修改配置时获取初始数据
    :param instance_id:
    :return:
    '''
    if not instance_id:
        logging.info('no instance id when get configure info')
        return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR, msg="参数错误")

    resp = ConfigureInitInfoResp()

    ins_data = ins_s.InstanceService().get_instance_info(instance_id)

    host_ip = ins_s.get_hostip_of_instance(instance_id)
    if not ins_data or not host_ip:
        logging.info('instance %s data is no exist in db when get configure info', instance_id)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

    resp.c_instance_name = ins_data['name']
    resp.c_app_info = ins_data['app_info']
    resp.c_owner = ins_data['owner']
    ins_status = ins_data['status']
    if ins_status != VMStatus.STARTUP and ins_status != VMStatus.SHUTDOWN:
        logging.error('instance status %s is invalid when get instance configure init info', ins_status)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg='只能在开机或关机状态下修改配置')

    if ins_data['create_source'] == '0':
        ins_images_data = ins_s.get_images_of_instance(instance_id)

        if ins_images_data:
            resp.c_system = ins_images_data[0]['system']
    else:
        ins_images_data = v2v_ins_s.V2VInstanceService().get_v2v_instance_info(instance_id)
        if ins_images_data:
            resp.c_system = ins_images_data['os_type']

    """
    ins_disks_data = ins_s.get_disks_of_instance(instance_id)
    if not ins_disks_data:
        logging.error('instance %s has no disk info when change instance configure', instance_id)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

    # 关机状态、windows系统都不能修改数据盘
    if ins_status != VMStatus.SHUTDOWN and resp.c_system == 'linux':
        for _disk in ins_disks_data:
            _disk_info = {
                'size_gb': _disk['size_gb'],
                'mount_point': _disk['mount_point']
            }
            resp.c_disk_gb_list.append(_disk_info)
    """

    ins_flavor_data = ins_s.get_flavor_of_instance(instance_id)
    if not ins_flavor_data:
        logging.error('instance %s has no flavor info when change instance configure', instance_id)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

    resp.c_flavor_id = ins_flavor_data['flavor_id']

    # flavor信息
    flavors_nums, flavors_data = fla_s.FlavorService().get_all_flavors()
    for _flavor in flavors_data:
        # 系统盘容量不能修改
        if _flavor['root_disk_gb'] == ins_flavor_data['root_disk_gb']:
            # 开机状态不能修改内存
            if ins_status == VMStatus.STARTUP:
                if _flavor['memory_mb'] == ins_flavor_data['memory_mb']:
                    _flavor_info = flavor_init_info.FlavorInitInfo().init_from_db(_flavor)
                    resp.flavors.append(_flavor_info)
            else:
                _flavor_info = flavor_init_info.FlavorInitInfo().init_from_db(_flavor)
                resp.flavors.append(_flavor_info)

    ins_group_data = ins_s.get_group_of_instance(instance_id)
    if ins_group_data:
        resp.c_group_id = ins_group_data['group_id']

    # user_group_ids_list = current_user_group_ids()
    # # 超级管理员组
    # if 1 in user_group_ids_list:
    #     is_super_group = True
    # else:
    #     is_super_group = False

    # group信息
    user_groups = current_user_groups()
    user_group_ids_list = []
    is_super_group = False
    for _groups in user_groups:
        user_group_ids_list.append(_groups['id'])
        # 超级管理员组
        if _groups['name'] == "supergroup":
            is_super_group = True

    # group信息
    groups_params = {
        'WHERE_AND': {
            '=': {
                'dc_type': ins_group_data['dc_type'],
                'isdeleted': '0'
            }
        },
    }
    groups_nums, groups_data = group_s.GroupService().query_data(**groups_params)
    for _group in groups_data:
        # 管理员组的成员可以显示所有组,而非管理员组的只显示当前用户所在应用组
        if not is_super_group and _group['id'] not in user_group_ids_list:
            continue

        _group_info = {
            'group_id': _group['id'],
            'group_name': _group['name']
        }
        resp.groups.append(_group_info)

    # 连接libvirtd查询虚拟机网卡状态信息
    _net_online = []
    _net_offline = []
    _libvirt_net_ret, _libvirt_net_info = vmManager.libvirt_get_netcard_state(host_ip, ins_data['name'])
    if _libvirt_net_ret != 0:
        _nic_status = False
    else:
        _nic_status = True
        for _p_libvirt_net_info in _libvirt_net_info:
            if _p_libvirt_net_info['state'] == NetCardStatus.UP:
                _net_online.append(_p_libvirt_net_info['mac'])
            else:
                _net_offline.append(_p_libvirt_net_info['mac'])

    # 虚拟机网卡信息返回前端
    _db_net_card_data = ins_s.get_net_info_of_instance(instance_id)
    if _db_net_card_data:
        for _p_db_net_card_data in _db_net_card_data:
            if not _nic_status:
                _p_ins_nic_status = ''
            else:
                if _p_db_net_card_data['mac'] in _net_online:
                    _p_ins_nic_status = '1'
                elif _p_db_net_card_data['mac'] in _net_offline:
                    _p_ins_nic_status = '0'
                else:
                    _p_ins_nic_status = '2'
            if not _p_db_net_card_data['segment_type']:
                _ip_type = '-1'
            else:
                _ip_type = _p_db_net_card_data['segment_type']
            _i_net_info = {
                'ip_addr': _p_db_net_card_data['ip_address'],
                'vlan': _p_db_net_card_data['vlan'],
                'mac_addr': _p_db_net_card_data['mac'],
                'nic_status': _p_ins_nic_status,
                'ip_type': _ip_type,
                'nic_type': _p_db_net_card_data['nic_type']
            }
            resp.c_net.append(_i_net_info)

    # 获取虚拟机所在网络区域下所有ip信息
    resp.c_ips = []
    ins_netarea_info = ins_s.get_netarea_of_instance(instance_id)
    ins_datacenter_info = ins_s.get_datacenter_of_instance(instance_id)
    if ins_datacenter_info and ins_datacenter_info['dc_type']:
        if ins_netarea_info and ins_netarea_info['id']:
            ip_segment_num, ip_segment_datas = ip_segment_s().get_segment_datas_in_net_area(ins_netarea_info['id'])
            if ip_segment_num > 0:
                # 获取可用ip
                ips_available = ip_service.get_all_available_ips(ip_segment_datas, ins_datacenter_info['dc_type'])
                if len(ips_available) > 0:
                    ip_list = []
                    for ip_info in ips_available:
                        ip_params = {
                            "value": ip_info['ip_address'],
                            "vlan": ip_info['vlan'],
                            "ip_type": ip_info['ip_type']
                        }
                        ip_list.append(ip_params)
                    resp.c_ips = ip_list

    return json_helper.format_api_resp(code=ErrorCode.SUCCESS, data=resp.to_json())
Exemplo n.º 12
0
def v2v_op_init_info():
    resp = V2v_0p_InitInfoResp()

    # area层级信息 - 总部
    area_data = hostpool_service.get_level_info_hostpool_cs()
    for i in area_data:
        if not _filter_least_host_num(i['hostpool_id'], i['least_host_num']):
            continue
        resp.area.append(i)

    # flavor信息
    flavors_nums, flavors_data = flavor_service.FlavorService(
    ).get_all_flavors()
    for i in flavors_data:
        _flavor_info = flavor_init_info.FlavorInitInfo().init_from_db(i)
        resp.flavors.append(_flavor_info)

    # segment信息
    resp.segment = []
    #     {"env": "SIT", "seg": "10.202.26.0"},
    #     {"env": "SIT", "seg": "10.202.34.0"},
    #     {"env": "SIT", "seg": "10.202.50.0"},
    #     {"env": "SIT", "seg": "10.202.32.0"},
    #     {"env": "SIT", "seg": "10.202.84.0"},
    #     {"env": "SIT", "seg": "10.202.86.0"},
    #     {"env": "SIT", "seg": "10.202.42.0"},
    #     {"env": "SIT", "seg": "10.202.24.0"},
    #     {"env": "SIT", "seg": "10.202.44.0"},
    #     {"env": "SIT", "seg": "10.202.91.0"},
    #     {"env": "SIT", "seg": "10.202.16.0"},
    #     {"env": "SIT", "seg": "10.202.40.0"},
    #     {"env": "SIT", "seg": "10.202.98.0"},
    #     {"env": "SIT", "seg": "10.202.54.0"},
    #     {"env": "SIT", "seg": "10.202.38.0"},
    #     {"env": "SIT", "seg": "10.202.90.0"},
    #     {"env": "SIT", "seg": "10.202.52.0"},
    #     {"env": "SIT", "seg": "10.202.36.0"},
    #     {"env": "SIT", "seg": "10.202.94.0"},
    #     {"env": "SIT", "seg": "10.202.99.0"},
    #     {"env": "DEV", "seg": "10.202.10.0"},
    #     {"env": "DEV", "seg": "10.202.11.0"},
    #     {"env": "DEV", "seg": "10.202.12.0"},
    #     {"env": "DEV", "seg": "10.202.125.0"},
    #     {"env": "DEV", "seg": "10.202.23.0"},
    #     {"env": "DEV", "seg": "10.202.13.0"},
    #     {"env": "DEV", "seg": "10.202.14.0"},
    #     {"env": "DEV", "seg": "10.202.15.0"},
    #     {"env": "DEV", "seg": "10.202.4.0"},
    #     {"env": "DEV", "seg": "10.202.5.0"},
    #     {"env": "DEV", "seg": "10.202.6.0"},
    #     {"env": "DEV", "seg": "10.202.7.0"},
    #     {"env": "DEV", "seg": "10.202.8.0"},
    #     {"env": "DEV", "seg": "10.202.9.0"}
    # ]

    # group信息
    groups_params = {
        'WHERE_AND': {
            '=': {
                'isdeleted': '0'
            }
        },
    }
    groups_nums, groups_data = group_service.GroupService().query_data(
        **groups_params)
    for i in groups_data:
        _group_info = group_info.GroupInitInfo().init_from_db_1(i)
        resp.groups.append(_group_info)

    return json_helper.format_api_resp(code=ErrorCode.SUCCESS,
                                       data=resp.to_json())
Exemplo n.º 13
0
def delete_group(group_id):
    '''
    删除用户组的流程:查询instance_group表,如果group在表中,就在tb_group表中将group的isdeleted改为1,
    然后在user_group表中删除所有group_id的行,在access表中删除group信息
    如果group不在instance_group表中,则直接删除group
    '''
    def _check_ins_exist_in_group(group_id):
        '''
            检查组下是否有VM
        :param group_id:
        :return:
        '''
        instances = ins_s.get_instances_in_group(group_id)
        if len(instances) > 0:
            return True
        return False

    if not group_id:
        logging.info('no group_id when delete group')
        return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR)

    group_num, group_data = group_s.GroupService().get_group_info(group_id)
    if group_num <= 0:
        logging.error('no group %s info in db when delete group', group_id)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

    # 只能超级管理员组成员和组所有者才能删除,超级管理员组ID为1
    user_group_ids = current_user_group_ids()
    if group_data[0]['owner'] != get_user(
    )['user_id'] and 1 not in user_group_ids:
        logging.error(
            'only allow super group member or group owner %s to delete group %s',
            group_data[0]['owner'], group_id)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                           msg='您没有权限删除该应用组!')

    # 该应用组下没有VM才能删除
    if _check_ins_exist_in_group(group_id):
        logging.error(
            'no allow delete group %s which has vms when delete group',
            group_id)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                           msg='该应用组分配有虚拟机,不能删除该组!')

    # 删除access中所有group_id的数据,然后插入前端提交的数据
    delete_access = access.delete_access_info(group_id)
    if delete_access < 0:
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)
    rest = ins_g_s.InstanceGroupService().query_data(
        where_field="group_id", where_field_value=group_id)
    # 如果instance_group表中没有group_id,就直接在group表中删除它
    if not rest:
        group.delete_group(group_id)

    else:
        update_data = {'isdeleted': '1', 'deleted_at': get_datetime_str()}
        where_data = {
            'id': group_id,
        }
        ret = group_s.update_group_info(update_data, where_data)
        if ret < 0:
            logging.error("update group error, update_data:%s, where_data:%s",
                          str(update_data), str(where_data))
            return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)
    # 不管group在不在Instance_group表中,都删除它下面的所有用户
    delete_users = user_g_s.delete_users_in_group(group_id)
    if delete_users < 0:
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)
    return json_helper.format_api_resp(code=ErrorCode.SUCCESS)
Exemplo n.º 14
0
def add_group():
    name = request.values.get('name')
    owner = request.values.get('owner')
    cpu = request.values.get('cpu')
    mem = request.values.get('mem')
    disk = request.values.get('disk')
    vm = request.values.get('vm')
    env = request.values.get('dc_type')
    role_id = request.values.get('role_id')
    area_str = request.values.get('area_str')
    p_cluster_id = request.values.get('p_cluster_id')

    if not name or not owner or not area_str or not str(env):
        logging.info('no name or owner or area_str or env when add group')
        return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR)

    role_exist = role_service.RoleService().query_role('id', role_id)
    if not role_exist:
        logging.info('no such role %s when add group', role_id)
        return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR)

    # 应用组名不能重复
    if _check_duplicated_group_name(name, str(env)):
        logging.error('duplicated group name %s when add group', name)
        return json_helper.format_api_resp(code=ErrorCode.DUPLICATED_ERR,
                                           msg="应用组名不能重复,请更改应用组名!")

    params_u = {
        'WHERE_AND': {
            '=': {
                'userid': owner,
                'isdeleted': '0',
            },
        },
    }
    user_num, user_data = user_s.UserService().query_data(**params_u)
    if user_num <= 0:
        username = ''
        # 用户不存在,新增
        user_data = {
            'userid': owner,
            'username': username,
            'status': '0',
            'created_at': get_datetime_str()
        }
        user_ret = user_s.UserService().add_user(user_data)

        # 记录安全日志
        field_data = {'User_name': owner or None, 'Oper_type': 'add'}
        if user_ret.get('row_num') > 0:
            field_data.update({'Oper_result': '1 Success'})
            CloudLogger.audit(AuditType.USERMGR, field_data)
        else:
            field_data.update({
                'Oper_result': '0 Fail',
                'fail_reason': 'insert new user info to db fail'
            })
            CloudLogger.audit(AuditType.USERMGR, field_data)
            return False, 'add new user info to db fail'
        # logging.error('no user %s info when add group', owner)
        # return json_helper.format_api_resp(code=ErrorCode.NOT_EXIST_USER, msg='不存在该用户,请检查用户ID')
    else:
        username = user_data[0]['username']

    insert_data = {
        'name': name,
        'displayname': name,
        'isdeleted': '0',
        'owner': owner,
        'cpu': cpu,
        'mem': mem,
        'disk': disk,
        'vm': vm,
        'dc_type': str(env),
        'p_cluster_id': p_cluster_id,
        'created_at': get_datetime_str()
    }
    ret = group_s.GroupService().add_group_info(insert_data)
    if ret.get('row_num') <= 0:
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

    group_id = ret.get('last_id')
    ret_result = access_service.add_access_list(int(group_id), int(role_id),
                                                str(area_str))
    if ret_result.get('row_num') <= 0:
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

    user_group_data = {
        'user_id': owner,
        'user_name': username,
        'group_id': group_id,
        'group_name': name,
        'role_id': role_id,
        'status': '0',
        'created_at': get_datetime_str(),
        'expire_at': get_datetime_str(),  # todo
    }
    ret_u_g = user_g_s.UserGroupService().add_user_group(user_group_data)
    if ret_u_g.get('row_num') <= 0:
        logging.error(
            'add user group info error when add group, insert_data:%s',
            user_group_data)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

    return json_helper.format_api_resp(code=ErrorCode.SUCCESS)
Exemplo n.º 15
0
def update_group(group_id):
    '''
        修改应用组信息
    :param group_id:
    :return:
    '''
    name_n = request.values.get('name')
    owner_n = request.values.get('owner')
    cpu_n = request.values.get('cpu')
    mem_n = request.values.get('mem')
    disk_n = request.values.get('disk')
    vm_n = request.values.get('vm')
    area_str_n = request.values.get('area_str')
    role_id_c = request.values.get('role_id')
    p_cluster_id = request.values.get('p_cluster_id')

    if not cpu_n or not mem_n or not disk_n or not vm_n or not area_str_n or not role_id_c:
        logging.info('param is invalid when update group')
        return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR)

    group_num_c, group_data_c = group_s.GroupService().get_group_info(group_id)
    if group_num_c <= 0:
        logging.error('no group %s info when update group', group_id)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

    update_data = {
        'cpu': cpu_n,
        'mem': mem_n,
        'disk': disk_n,
        'vm': vm_n,
        'updated_at': get_datetime_str()
    }

    # 只能超级管理员组成员和组所有者才能修改组名和所有者,超级管理员组ID为1
    user_group_ids = current_user_group_ids()
    if group_data_c[0]['owner'] != get_user(
    )['user_id'] and 1 not in user_group_ids:
        if name_n or owner_n:
            logging.error(
                'only allow super group member or group owner %s to update group %s name or owner',
                group_data_c[0]['owner'], group_id)
            return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                               msg='您没有权限修改该应用组的组名和所有者!')

    if name_n:
        if group_data_c[0]['name'] != name_n and _check_duplicated_group_name(
                name_n):
            logging.error('duplicated group name %s when update group', name_n)
            return json_helper.format_api_resp(code=ErrorCode.DUPLICATED_ERR,
                                               msg="应用组名不能重复,请更改应用组名!")

        update_data['name'] = name_n
    if owner_n:
        # 新所有者一定要在该应用组里
        group_user_num, group_user_data = user_g_s.UserGroupService(
        ).get_alluser_group(group_id)
        in_group_flag = False
        for _group in group_user_data:
            if _group['user_id'] == owner_n:
                in_group_flag = True
                break

        if not in_group_flag:
            logging.error(
                'new owner %s must exist in group %s when update group',
                owner_n, group_id)
            return json_helper.format_api_resp(code=ErrorCode.SYS_ERR,
                                               msg='应用组新所有者必须属于该组,请先添加入组!')

        update_data['owner'] = owner_n

    if p_cluster_id:
        update_data['p_cluster_id'] = p_cluster_id

    where_data = {
        'id': group_id,
    }
    ret = group_s.update_group_info(update_data, where_data)
    if ret < 0:
        logging.error("update group error, update_data:%s, where_data:%s",
                      str(update_data), str(where_data))
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

    # 删除access中所有group_id的数据,然后插入前端提交的数据
    delete_access = access.delete_access_info(group_id)
    if delete_access < 0:
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

    ret_result = access_service.add_access_list(int(group_id), int(role_id_c),
                                                str(area_str_n))
    if ret_result < 0:
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)
    return json_helper.format_api_resp(code=ErrorCode.SUCCESS)
Exemplo n.º 16
0
def instance_init_info():

    def _filter_least_host_num(hostpool_id, least_host_num):
        '''
            过滤掉不满足最少host数的集群
        :param hostpool_id:
        :param least_host_num:
        :return:
        '''
        # 获取主机列表
        all_hosts_nums, all_hosts_data = host_s.HostService().get_hosts_of_hostpool(hostpool_id)
        if all_hosts_nums < least_host_num or all_hosts_nums < 1:
            logging.info('filter hostpool %s that has no least host nums %s when get create init info',
                         hostpool_id, least_host_num)
            return False
        return True

    def _filter_no_segment_info(hostpool_id):
        '''
            过滤掉没有网段信息的集群
        :param hostpool_id:
        :return:
        '''
        segments_list = hostpool_service.get_segment_info(hostpool_id)
        if not segments_list:
            logging.error('filter hostpool %s that has no segment info when get create init info', hostpool_id)
            return False
        return True

    resp = InstanceInitInfoResp()
    user_all_area_ids = current_user_all_area_ids()

    # area层级信息 - 总部
    area_zb_data = hostpool_service.get_level_info_hostpool_zb()
    for i in area_zb_data:
        # 不显示不满足最少host数的集群
        if not _filter_least_host_num(i['hostpool_id'], i['least_host_num']):
            continue

        # 不显示没有网段信息的集群
        if not _filter_no_segment_info(i['hostpool_id']):
            continue

        # 只显示当前用户所属的区域
        if user_all_area_ids and i['area_id'] not in user_all_area_ids:
            continue
        resp.area_ZB.append(i)

    # area层级信息 - 地区
    area_dq_data = hostpool_service.get_level_info_hostpool_dq()
    for i in area_dq_data:
        # 不显示不满足最少host数的集群
        if not _filter_least_host_num(i['hostpool_id'], i['least_host_num']):
            continue

        # 不显示没有网段信息的集群
        if not _filter_no_segment_info(i['hostpool_id']):
            continue

        # 只显示当前用户所属的区域
        if user_all_area_ids and i['area_id'] not in user_all_area_ids:
            continue

        _area_dq_info = area_dq_init_info.AreaDQInitInfo().init_from_db(i)
        # 表示有父区域
        if i['parent_id']:
            _parent_info = area_service.AreaService().get_area_info(i['parent_id'])
            if _parent_info:
                _area_dq_info.area_name = _parent_info['displayname']
                _area_dq_info.child_area_name = i['area_name']
            else:
                # 有父区域ID但没有相应信息,则当做没有父区域
                _area_dq_info.area_name = i['area_name']
        else:
            _area_dq_info.area_name = i['area_name']
        resp.area_DQ.append(_area_dq_info)

    # flavor信息
    flavors_nums, flavors_data = flavor_service.FlavorService().get_all_flavors()
    for i in flavors_data:
        _flavor_info = flavor_init_info.FlavorInitInfo().init_from_db(i)
        resp.flavors.append(_flavor_info)

    # image信息 - windows
    images_windows_nums, images_windows_data = image_service.ImageService().get_all_images('windows')
    for i in images_windows_data:
        _image_windows_info = image_init_info.ImageInitInfo().init_from_db(i)
        resp.images_windows.append(_image_windows_info)

    # image信息 - linux
    images_linux_nums, images_linux_data = image_service.ImageService().get_all_images('linux')
    for i in images_linux_data:
        _image_linux_info = image_init_info.ImageInitInfo().init_from_db(i)
        resp.images_linux.append(_image_linux_info)

    # group信息
    user_groups = current_user_groups()
    user_group_ids_list = []
    is_super_group = False
    for _groups in user_groups:
        user_group_ids_list.append(_groups['id'])
        # 超级管理员组
        if _groups['name'] == "supergroup":
            is_super_group = True

    groups_params = {
        'WHERE_AND': {
            '=': {
                'isdeleted': '0'
            }
        },
    }
    groups_nums, groups_data = group_service.GroupService().query_data(**groups_params)
    for i in groups_data:
        # 管理员组的成员可以显示所有组,而非管理员组的只显示当前用户所在应用组
        if not is_super_group and i['id'] not in user_group_ids_list:
            continue

        _group_info = group_info.GroupInitInfo().init_from_db_1(i)
        resp.groups.append(_group_info)

    return json_helper.format_api_resp(code=ErrorCode.SUCCESS, data=resp.to_json())
Exemplo n.º 17
0
def _user_group_check(env, sys_code, sys_opr_name, sys_opr_id, cluster_id):
    # 检查应用系统管理员用户是否存在,不存在则新增
    user = user_s.UserService().get_user_info_by_user_id(sys_opr_id)
    if not user:
        # 用户不存在,新增,并将用户锁定,待后续开放用户运维在解锁
        user_data = {
            'userid': sys_opr_id,
            'username': sys_opr_name,
            'status': '1',
            'created_at': get_datetime_str()
        }
        user_ret = user_s.UserService().add_user(user_data)

        # 记录安全日志
        field_data = {'User_name': sys_opr_name or None, 'Oper_type': 'add'}
        if user_ret.get('row_num') > 0:
            field_data.update({'Oper_result': '1 Success'})
            CloudLogger.audit(AuditType.USERMGR, field_data)
        else:
            field_data.update({
                'Oper_result': '0 Fail',
                'fail_reason': 'insert new user info to db fail'
            })
            CloudLogger.audit(AuditType.USERMGR, field_data)
            return False, 'add new user info to db fail'

    # 检查应用组是否存在,不存在新建
    group = group_s.get_group_info_by_name_and_env(sys_code, env)
    if not group:
        group_data = {
            'name': sys_code,
            'displayname': sys_code,
            'isdeleted': '0',
            'dc_type': env,
            'owner': sys_opr_id,
            'cpu': 20000,
            'mem': 40000,
            'disk': 1000000,
            'vm': 5000,
            'p_cluster_id': cluster_id,
            'created_at': get_datetime_str()
        }
        group_ret = group_s.GroupService().add_group_info(group_data)
        if group_ret.get('row_num') <= 0:
            return False, 'add group info to db fail'

        group_id = group_ret.get('last_id')
        role_id = 2
        area_zb_ret = area_s.AreaService().get_area_zb_info()
        if not area_zb_ret:
            return False, 'get zongbu area id fail'
        area_zb_id = area_zb_ret['id']
        ret_result = access_service.add_access_list(int(group_id),
                                                    int(role_id),
                                                    str(area_zb_id))
        if ret_result.get('row_num') <= 0:
            return False, 'add access info to db fail'

        user_group_data = {
            'user_id': sys_opr_id,
            'user_name': sys_opr_name,
            'group_id': group_id,
            'group_name': sys_code,
            'role_id': role_id,
            'status': '0',
            'created_at': get_datetime_str(),
            'expire_at': get_datetime_str(),  # todo
        }
        ret_u_g = user_g_s.UserGroupService().add_user_group(user_group_data)
        if ret_u_g.get('row_num') <= 0:
            logging.error(
                'add user group info error when add group, insert_data:%s',
                user_group_data)
            return False, 'add user group info to db fail'
    else:
        # 获取应用组对应用户信息
        role_id = 2
        opr_is_exist = False
        group_id = group['id']
        ret_num, ret_query_g_u = user_g_s.UserGroupService().get_alluser_group(
            group_id)
        for one_ret_query_g_u in ret_query_g_u:
            if one_ret_query_g_u['user_id'] == sys_opr_id:
                opr_is_exist = True
        if not opr_is_exist:
            # 将用户加入应用组中
            user_group_data = {
                'user_id': sys_opr_id,
                'user_name': sys_opr_name,
                'group_id': group_id,
                'group_name': sys_code,
                'role_id': role_id,
                'status': '0',
                'created_at': get_datetime_str(),
                'expire_at': get_datetime_str(),  # todo
            }
            ret_u_g = user_g_s.UserGroupService().add_user_group(
                user_group_data)
            if ret_u_g.get('row_num') <= 0:
                logging.error(
                    'add user group info error when add group, insert_data:%s',
                    user_group_data)
                return False, 'add user group info to db fail'

            # 修改应用组owner
            update_data = {'owner': sys_opr_id}
            where_data = {
                'id': group_id,
            }
            ret_change_owner = group_s.update_group_info(
                update_data, where_data)
            if ret_change_owner < 0:
                logging.error(
                    "update group error, update_data:%s, where_data:%s",
                    str(update_data), str(where_data))
                return False, 'update group owner to db fail'

    return True, group_id
def kvm_common_info():
    def _filter_least_host_num(hostpool_id, least_host_num):
        '''
            过滤掉不满足最少host数的集群
        :param hostpool_id:
        :param least_host_num:
        :return:
        '''
        # 获取主机列表
        all_hosts_nums, all_hosts_data = host_s.HostService(
        ).get_hosts_of_hostpool(hostpool_id)
        if all_hosts_nums < least_host_num or all_hosts_nums < 1:
            logging.info(
                'filter hostpool %s that has no least host nums %s when get create init info',
                hostpool_id, least_host_num)
            return False
        return True

    def _filter_no_segment_info(hostpool_id):
        '''
            过滤掉没有网段信息的集群
        :param hostpool_id:
        :return:
        '''
        segments_list = hostpool_service.get_segment_info(hostpool_id)
        if not segments_list:
            logging.error(
                'filter hostpool %s that has no segment info when get create init info',
                hostpool_id)
            return False
        return True

    data_from_api = request.data
    data_requset = json_helper.loads(data_from_api)
    user_id = data_requset['userId']

    resp = KvmInfoResp()
    user_all_area_ids = user_s.user_all_area_ids_by_userid(user_id)

    # area层级信息 - 总部
    area_zb_data = hostpool_service.get_level_info_hostpool_zb()
    for i in area_zb_data:
        # 不显示不满足最少host数的集群
        if not _filter_least_host_num(i['hostpool_id'], i['least_host_num']):
            continue

        # 不显示没有负载均衡网络的区域
        if "LoadBalance" not in i['net_area_name']:
            continue

        # 不显示没有网段信息的集群
        if not _filter_no_segment_info(i['hostpool_id']):
            continue

        # 只显示当前用户所属的区域
        if user_all_area_ids and i['area_id'] not in user_all_area_ids:
            continue
        resp.area_ZB.append(i)

    # area层级信息 - 地区
    area_dq_data = hostpool_service.get_level_info_hostpool_dq()
    for i in area_dq_data:
        # 不显示不满足最少host数的集群
        if not _filter_least_host_num(i['hostpool_id'], i['least_host_num']):
            continue

        # 不显示没有负载均衡网络的区域
        if "LoadBalance" not in i['net_area_name']:
            continue

        # 不显示没有网段信息的集群
        if not _filter_no_segment_info(i['hostpool_id']):
            continue

        # 只显示当前用户所属的区域
        if user_all_area_ids and i['area_id'] not in user_all_area_ids:
            continue

        _area_dq_info = area_dq_init_info.AreaDQInitInfo().init_from_db(i)
        # 表示有父区域
        if i['parent_id']:
            _parent_info = area_service.AreaService().get_area_info(
                i['parent_id'])
            if _parent_info:
                _area_dq_info.area_name = _parent_info['displayname']
                _area_dq_info.child_area_name = i['area_name']
            else:
                # 有父区域ID但没有相应信息,则当做没有父区域
                _area_dq_info.area_name = i['area_name']
        else:
            _area_dq_info.area_name = i['area_name']
        resp.area_DQ.append(_area_dq_info)

    # group信息
    user_groups = user_s.current_user_groups_by_userid(user_id)
    user_group_ids_list = []
    is_middleware_admin_group = False
    for _groups in user_groups:
        user_group_ids_list.append(_groups['id'])
        # 中间件管理员组,这里后期要注意,如果中间件管理员组id不为2,则识别不出用户是否是中间件管理员组
        if _groups['id'] == 2:
            is_middleware_admin_group = True

    groups_params = {
        'WHERE_AND': {
            '=': {
                'isdeleted': '0'
            }
        },
    }
    groups_nums, groups_data = group_service.GroupService().query_data(
        **groups_params)
    for i in groups_data:
        # 中间件管理员组可以显示所有组,而非管理员组的只显示当前用户所在应用组
        if not is_middleware_admin_group and i['id'] not in user_group_ids_list:
            continue

        _group_info = group_info.GroupInitInfo().init_from_db_1(i)
        resp.groups.append(_group_info)

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