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)
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)
def edit_image(): ''' 镜像信息修改 :return: ''' actual_size_mb = request.values.get('actual_size_mb') size_gb = request.values.get('size_gb') md5 = request.values.get('md5') image_id = request.values.get('image_id') if not actual_size_mb or not size_gb or not md5 or not image_id: logging.info('入参缺失') return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR, msg='入参缺失') # 入参合法性判断 actual_size = float(actual_size_mb) size_total = float(size_gb) * 1024 if actual_size > size_total: error_msg = '镜像实际大小大于镜像总大小' logging.info(error_msg) return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR, msg=error_msg) elif actual_size <= 0: error_msg = '镜像实际大小小于等于0' logging.info(error_msg) return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR, msg=error_msg) #入参合法,更新DB else: update_res = _update_image_info(actual_size_mb, size_gb, md5, image_id) return json_helper.format_api_resp(code=ErrorCode.SUCCESS, msg='镜像信息更新成功')
def lock(host_id): ''' 锁定物理机,即虚机不分配到该物理机上 :param host_id: :return: ''' # flag:'1' 锁定 flag:'0' 解除锁定 flag = request.values.get("flag") if not host_id or not flag: logging.info('no host_id or flag when lock/unlock host') return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR, msg="参数错误") host_data = host_service.HostService().get_host_info(host_id) if not (host_data and host_data['isdeleted'] == '0'): logging.info('the host %s is invalid when lock/unlock host', host_id) return json_helper.format_api_resp(code=ErrorCode.SYS_ERR) if host_data['typestatus'] == flag: logging.info('the host %s is done before when lock/unlock host', host_id) return json_helper.format_api_resp(code=ErrorCode.SUCCESS) update_data = {"typestatus": flag} where_data = {"id": host_id} ret = host_service.HostService().update_host_info(update_data, where_data) if ret != 1: return json_helper.format_api_resp(code=ErrorCode.SYS_ERR) return json_helper.format_api_resp(code=ErrorCode.SUCCESS)
def single_host_image_return(host_id): #获取当前host已有的镜像信息汇总 res1, local_image_data = local_image_return(host_id) if not res1: return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg=local_image_data) else: #获取当前host上没有的镜像信息汇总 res2, remote_image_data = image_remote_list(host_id) if not res2: return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg=local_image_data) else: #获取当前库中任务存在的镜像任务 host_info = host_s.HostService().get_host_info(host_id) host_ip = host_info['ipaddress'] image_task_list = im_sy_s.get_host_working_list(host_ip) #分别对local_image_list和remote_image_list做处理 local_image_data_ch = local_image_list_ch(host_id, local_image_data, image_task_list) remote_image_data_ch = remote_image_list_ch( remote_image_data, image_task_list) return_data = { 'local_image_data': local_image_data_ch, 'remote_image_data': remote_image_data_ch } return json_helper.format_api_resp(code=ErrorCode.SUCCESS, data=return_data)
def hostpool_add(net_area_id): name = request.values.get('name') least_host_num = request.values.get('least_host_num') hostpool_type = request.values.get('hostpool_type') # '0'一般类型,'1'特殊类型 app_code = request.values.get('app_code') if not net_area_id or not name or not least_host_num: logging.error('the params is invalid when add hostpool') return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR) # 名字不重复 ret = hostpool_s.HostPoolService().check_name_exist(net_area_id, name) if ret > 0: logging.error('hostpool name is duplicated when add hostpool') return json_helper.format_api_resp(code=ErrorCode.DUPLICATED_ERR, msg='集群名不能重复,请更换集群名') if int(hostpool_type) == 0: app_code = "公共资源池" insert_data = { 'name': name, 'displayname': name, 'isdeleted': '0', 'net_area_id': net_area_id, 'least_host_num': least_host_num, 'app_code': app_code, 'hostpool_type': hostpool_type, 'created_at': get_datetime_str() } ret = hostpool_s.HostPoolService().add_hostpool(insert_data) if ret.get('row_num') <= 0: return json_helper.format_api_resp(code=ErrorCode.SYS_ERR) return json_helper.format_api_resp(code=ErrorCode.SUCCESS)
def rate_limit(): #TODO 通用化 配置化 module_name = request.values.get('module_name') ip = request.values.get('ip') redis_cache = redis_lib.RedisForCommon.get_instance_for_common_1() if module_name == '/account/check_sign_in': #ip地址的限制 if ip: key = 'ip' ip_limiter = Limiter(redis_cache, action=module_name + key, limit=20, period=60 * 10) ip_limiter_2 = Limiter(redis_cache, action=module_name + key + '2', limit=50, period=60 * 60 * 2) ret = ip_limiter.checked_insert(ip) if not ret: return json_helper.format_api_resp( const_define.ErrorCode.RATE_LIMIT_ERR) ret = ip_limiter_2.checked_insert(ip) if not ret: return json_helper.format_api_resp( const_define.ErrorCode.RATE_LIMIT_ERR) return json_helper.format_api_resp()
def instance_add_netcard(instance_id): ''' kvm平台虚拟机添加网卡接口 :param instance_id: :return: ''' # 判断指定虚拟机是否存在 if not instance_id: return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR, msg="instance_id为空,添加网卡失败") ins_data = ins_s.InstanceService().get_instance_info(instance_id) if not ins_data: return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR, msg="无法找到待添加网卡虚拟机") # 查询指定虚拟机网卡数量,目前不能超过3块 instance_net_card = ins_s.get_net_info_of_instance(instance_id) if instance_net_card: if len(instance_net_card) >= INSTANCE_NETCARD_NUMS: return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR, msg="虚拟机网卡数量不能超过%s张" % str(INSTANCE_NETCARD_NUMS)) # 往instance_ip表添加记录 mac = randomMAC() instance_ip_data = { 'instance_id': instance_id, 'mac': mac, 'type': InstanceNicType.NORMAL_NETWORK_NIC, 'isdeleted': '0', 'created_at': get_datetime_str() } ret_add = ins_ip_s.InstanceIPService().add_instance_ip_info(instance_ip_data) if ret_add.get('row_num') <= 0: return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg="虚拟机网卡创建失败") return json_helper.format_api_resp(code=ErrorCode.SUCCESS, msg="虚拟机网卡创建成功")
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="该组没有角色权限对应关系,不能添加新用户")
def hold_ip(): ''' 保留IP :return: ''' ip_address = request.values.get('ip_address') if not ip_address: logging.info('no ip_address when hold ip') return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR) ip_info = ip_service.IPService().get_ip_info_by_ipaddress(ip_address) # 已初始化且未使用的IP才能保留 if not (ip_info and ip_info['status'] == IPStatus.UNUSED): logging.info('IP status is wrong when hold ip') return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg="只能保留已初始化且未使用的IP") update_data = { 'status': IPStatus.HOLD, 'updated_at': get_datetime_str(), } where_data = { 'ip_address': ip_address, } ret = ip_service.IPService().update_ip_info(update_data, where_data) if ret <= 0: logging.error("hold ip 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)
def instance_retry_create(request_id_list): ''' 虚拟机重新创建,通过request_id重新发送kafka消息 :return: ''' threads = [] req_ids = request_id_list #req_ids = request.values.get('request_ids') if not req_ids: return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR) req_ids_list = req_ids.split(',') for req_id in req_ids_list: ins_info = ins_s.InstanceService().get_instance_info_by_requestid(req_id) if ins_info: if ins_info['status'] != '100': continue kafka_send_thread = threading.Thread(target=instance_msg_send_to_kafka, args=(ins_info['task_id'], req_id,)) threads.append(kafka_send_thread) kafka_send_thread.start() # 判断多线程是否结束 if len(threads) == 0: return json_helper.format_api_resp(code=ErrorCode.SUCCESS, data='没有找到需要重试的虚拟机') for t in threads: t.join() return json_helper.format_api_resp(code=ErrorCode.SUCCESS)
def feedback_list(): user_id = request.values.get('user_id') params = { 'ORDER': [ ['id', 'desc'], ], 'PAGINATION': { 'page_size': request.values.get('page_size', 20), 'page_no': request.values.get('page_no', 1), }, 'WHERE_AND': { '=': { } } } if user_id: params['WHERE_AND']['=']['user_id'] = user_id else: return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR) total_nums, data = feedback_service.FeedbackService().query_data(**params) resp = FeedbackResp() resp.total = total_nums for i in data: _feedback_info = feedback_info.FeedbackInfo().init_from_db(i) resp.rows.append(_feedback_info) return json_helper.format_api_resp(code=ErrorCode.SUCCESS, data=resp.to_json())
def add_feedback(): user_id = request.values.get('user_id') problem_id = request.values.get('problem_id') problem_description = request.values.get('problem_description') network_address = request.values.get('network_address') problem_category = request.values.get('problem_category') submit_time = datetime.datetime.now() if not user_id or not problem_id or not problem_description or not network_address: logging.info('the params is invalid when add feedback') return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR) insert_data = { 'user_id': user_id, 'problem_id': problem_id, 'problem_description': problem_description, 'network_address': network_address, 'problem_category': problem_category, 'submit_time': submit_time } ret = feedback_service.FeedbackService().add_feedback_info(insert_data) if ret.get('row_num') <= 0: logging.error("add feedback 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 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())
def add_image(): name = request.values.get('name') displayname = request.values.get('displayname') system = request.values.get('system') description = request.values.get('description') version = request.values.get('version') url = request.values.get('url') md5 = request.values.get('md5') format = request.values.get('format') actual_size_mb = request.values.get('actual_size_mb') size_gb = request.values.get('size_gb') type = request.values.get('type') if not name or not system or not url or not md5 or not format or not actual_size_mb or not size_gb or not type: logging.info('入参缺失') return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR, msg='入参缺失') # url唯一 image_db = image_service.ImageService().get_image_by_url(url) is_image = image_db[1] if is_image: logging.info('image url %s is duplicated when add image', url) return json_helper.format_api_resp(code=ErrorCode.DUPLICATED_ERR, msg="镜像路径不能重复") # 系统盘唯一判断 if type == '0': image_res = image_service.ImageService().image_sys_disk_confirm( name)[1] if image_res: logging.info('image sys disk is unique can not add more') return json_helper.format_api_resp(code=ErrorCode.DUPLICATED_ERR, msg="镜像系统盘唯一无法再添加") insert_data = { 'name': name, 'displayname': displayname, 'system': system, 'version': version, 'description': description, 'md5': md5, 'format': format, 'actual_size_mb': actual_size_mb, 'size_gb': size_gb, 'isdeleted': '0', 'created_at': get_datetime_str(), 'url': url, 'type': type, } ret = image_service.ImageService().add_image_info(insert_data) if ret.get('row_num') <= 0: logging.error("add image error, insert_data:%s", str(insert_data)) error_msg = "添加新镜像 %s 失败", str(insert_data) return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg=error_msg) return json_helper.format_api_resp(code=ErrorCode.SUCCESS)
def net_area_delete(): net_area_ids = request.values.get('net_area_ids') if not net_area_ids: logging.error('no net_area_ids when delete net area') return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR) net_area_ids_list = net_area_ids.split(',') # 操作的net area数 all_num = len(net_area_ids_list) msg = None fail_num = 0 for _id in net_area_ids_list: # 有集群和网段的都不能删除 _hostpool_num = hostpool_s.HostPoolService( ).get_hostpool_nums_in_net_area(_id) if _hostpool_num > 0: logging.error('no allow to delete net area %s that has hostpool', _id) fail_num += 1 # 单台操作且已失败则直接跳出循环 if all_num == 1: msg = '该网络区域下已分配有集群,不允许删除' break continue _segment_num = segment_s.SegmentService().get_segment_nums_in_net_area( _id) if _segment_num > 0: logging.error( 'no allow to delete net area %s that has network segment', _id) fail_num += 1 # 单台操作且已失败则直接跳出循环 if all_num == 1: msg = '该网络区域下已分配有网段,不允许删除' break continue _ret = net_area_s.NetAreaService().delete_net_area(_id) if _ret <= 0: logging.error('db delete net area %s fail when delete net area', _id) fail_num += 1 continue # 全失败 if fail_num == all_num: logging.error("delete net 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 %s net area 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)
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)
def get_host_detail(host_id): ''' 获取host详情 :param host_id: :return: ''' if not host_id: logging.info('no host_id when get host detail') return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR) host_db = host_s.HostService().get_host_info(host_id) if not host_db: logging.info('host %s no exist in db when get host detail', host_id) return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg="不存在该物理机信息") host = host_info.HostInfo() host.displayname = host_db['displayname'] host.ipaddress = host_db['ipaddress'] host.manage_ip = host_db['manage_ip'] host.status = host_db['status'] host.hold_mem_gb = host_db['hold_mem_gb'] host.sn = host_db['sn'] host.ostype = host_db['ostype'] # host性能数据 host_perform_info = host_s_s.get_host_used(host_db, expire=False) if host_perform_info: host.cpu_core = host_perform_info.get('cpu_core', 'unknown') host.current_cpu_used = host_perform_info.get('current_cpu_used', 'unknown') host.mem_size = host_perform_info.get('mem_size', 'unknown') host.current_mem_used = host_perform_info.get('current_mem_used', 'unknown') host.disk_size = host_perform_info.get('disk_size', 'unknown') host.current_disk_used = host_perform_info.get('current_disk_used', 'unknown') host.collect_time = host_perform_info['collect_time'] host.start_time = host_perform_info['start_time'] host.images = host_perform_info.get('images', 'unknown') host.libvirt_status = host_perform_info.get('libvirt_status', 'unknown') host.libvirt_port = host_perform_info.get('libvirt_port', 'unknown') host_level_info = host_s.get_level_info(host_db['id']) if host_level_info: host.hostpool = host_level_info['hostpool_name'] host.net_area = host_level_info['net_area_name'] host.datacenter = host_level_info['datacenter_name'] host.instance_nums = ins_s.get_instances_nums_in_host(host_db['id']) # todo: libvirtd状态、服务端口,物理机开机时间、os版本、镜像数量、卷存储路径、序列号 return json_helper.format_api_resp(code=ErrorCode.SUCCESS, data=host.to_json())
def monitor(): ''' Balent监控 :return: ''' # ip_list: [{ip1:[m1,m2,m3,m4]},{ip2:[m1,m2,m3,m4]},{ip3:[]}] print "-"*25 print request.get_data() print "-" * 25 ip_list = json.loads(request.get_data()).get('ip_list') start_time = json.loads(request.get_data()).get('start_time') end_time = json.loads(request.get_data()).get('end_time') if not ip_list or not start_time or not end_time: logging.info('params is invalid when get monitor data') return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR, msg="参数错误") try: start_timestamp, end_timestamp = get_range_timestamp_str(start_time) except Exception: start_timestamp = change_datetime_to_timestamp(start_time) end_timestamp = change_datetime_to_timestamp(end_time) if not all((start_timestamp, end_timestamp)): return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR, msg="时间区间无效") if not ip_list: return json_helper.format_api_resp(code=ErrorCode.SUCCESS, data=[]) req_metrics = [] req_ips = [] for ip_dict in ip_list: metrics = ip_dict.values()[0] temp_metric = [] if metrics: for i in range(0, len(BALANT_ATTR)): temp_metric.append(metrics[i]) req_metrics.append(temp_metric) ip = ip_dict.keys()[0] req_ips.append(ip) if any(req_metrics): pass else: for index, ip in enumerate(req_ips): target_id = get_target_id(ip) print target_id metric_list = get_metric_id(target_id) req_metrics[index] = metric_list metric_data = get_metric_data(req_ips, req_metrics, start_timestamp, end_timestamp) return json_helper.format_api_resp(code=ErrorCode.SUCCESS, data=metric_data)
def delete_host(): ERR_RET = 0 all_host_id = request.values.get("host_id") if not all_host_id: logging.info('no host_id input when delete host') return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR, msg="参数错误") for host_id in all_host_id.split(','): host_data = host_s.HostService().get_host_info(host_id) if not host_data: ERR_RET += 1 continue if host_data['isdeleted'] == '1': ERR_RET += 1 continue instance_nums = ins_s.get_instances_nums_in_host(host_id) if instance_nums == None: ERR_RET += 1 continue elif instance_nums > 0: ERR_RET += 1 continue elif instance_nums == 0: host_ip = host_data['ipaddress'] host_s._pool_delete(host_ip) update_data = { "isdeleted": '1', "deleted_at": datetime.datetime.now() } where_data = {"id": host_id} db_ret = host_s.HostService().update_host_info( update_data, where_data) if db_ret != 1: ERR_RET += 1 continue else: logging.info('host ' + str(host_id) + ' delete successful') continue else: ERR_RET += 1 continue if ERR_RET == 0: return json_helper.format_api_resp(code=ErrorCode.SUCCESS) elif len(all_host_id.split(',')) == 1 and ERR_RET == 1: return json_helper.format_api_resp(code=ErrorCode.SYS_ERR) elif len(all_host_id.split(',')) == ERR_RET: return json_helper.format_api_resp(code=ErrorCode.SYS_ERR) else: return json_helper.format_api_resp(code=ErrorCode.SUCCESS_PART)
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="匹配网段已成功加入")
def get_ips_segment(segment_id, page): ''' 获取指定网段下所有IP地址 :return: ''' if not segment_id or not page: logging.info('no segment_id or page when get ips segment') return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR) flag, ips_data = segment_service.get_ips_page(segment_id, page) if flag == -1: logging.info('no segment: %s in db when get ips segment', segment_id) return json_helper.format_api_resp(code=ErrorCode.SYS_ERR) # 通过指定的网段输出该网段的IP个数 if flag == 1: try: ip = IP(ips_data[0]["segment"] + "/" + ips_data[0]["netmask"]) ip_len = ip.len() except: logging.info('the segment %s/%s is invalid', ips_data["segment"], ips_data["netmask"]) ip_len = 0 ips = ips_data segment_id = ips_data[0]["segment_id"] segment = ips_data[0]["segment"] netmask = ips_data[0]["netmask"] elif flag == 2: # 该网段下暂时无IP信息在db try: ip = IP(ips_data["segment"] + "/" + ips_data["netmask"]) ip_len = ip.len() except: logging.info('the segment %s/%s is invalid', ips_data["segment"], ips_data["netmask"]) ip_len = 0 ips = None segment_id = ips_data["id"] segment = ips_data["segment"] netmask = ips_data["netmask"] ip_dic = { "ips": ips, "segment_id": segment_id, "segment": segment, "netmask": netmask, "len": ip_len, "pages": ip_len / 256 } return json_helper.format_api_resp(code=ErrorCode.SUCCESS, data=ip_dic)
def net_area_level_info_get(): resp = NetArealevelInfoResp() user_all_area_ids = current_user_all_area_ids() level_datas = net_area.get_level_info() for i in level_datas: # 只获取当前用户所在区域 if user_all_area_ids and i['area_id'] not in user_all_area_ids: continue _level = net_area_level_info.NetArealevelInfo().init_from_db(i) # 如果有父区域 if i['parent_id']: _parent_data = area_s.AreaService().get_area_info(i['parent_id']) if _parent_data: _level.area = _parent_data['displayname'] _level.child_area = i['area_name'] else: # 有父区域ID但没有相应信息,则当做没有父区域 _level.area = i['area_name'] else: # 如果没有父区域,则本身作为区域,子区域为空 _level.area = i['area_name'] resp.level_info.append(_level) return json_helper.format_api_resp(code=ErrorCode.SUCCESS, data=resp.to_json())
def image_list(): params = { 'WHERE_AND': { '=': { '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 = image_service.ImageService().query_data(**params) resp = ImageListResp() resp.total = total_nums for i in data: _image_info = image_info.ImageInfo().init_from_db(i) resp.rows.append(_image_info) return json_helper.format_api_resp(code=ErrorCode.SUCCESS, data=resp.to_json())
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())
def net_area_info_init(): ''' 为前端提供一个创建网络区域的区域--子区域--机房初始列表 ''' user_all_area_ids = current_user_all_area_ids() ret_init = net_area_s.get_datacenter_area_info() if not ret_init: return [] for i in ret_init: if user_all_area_ids and i['id'] not in user_all_area_ids: del i continue if i['parent_id'] == -1: i['parent_id'] = i['id'] i['parent_area_name'] = i['area_name'] del (i['id'], i['area_name']) resp = NetAreaListResp() for i in ret_init: # 只获取当前用户所在区域 if user_all_area_ids and i['parent_id'] not in user_all_area_ids: continue resp.rows.append(i) return json_helper.format_api_resp(code=ErrorCode.SUCCESS, data=resp.to_json())
def get_image_size_gb(image_name, disk_name): '''获取image的size_gb值''' res = ansibleCmdV2.get_image_size_gb(IMAGE_EDIT_SERVER, image_name, disk_name) if res[0] == False: return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg=res[1]) return int(res[1].rstrip('G'))
def user_list(): ''' 查询用户列表,不传参时返回所有tb_user表中没有标记删除的用户信息列表 :parameter 如果传参search中包含user_id,那就筛选出这个user_id的信息 ''' search = request.values.get('search') params = { 'ORDER': [ ['id', 'desc'], ], 'PAGINATION': { 'page_size': request.values.get('page_size', 20), 'page_no': request.values.get('page_no', 1), }, 'WHERE_AND':{ '=':{ 'isdeleted': '0', } } } if search: json_search = json.loads(search) user_id = json_search.get('user_id') if user_id: params['WHERE_AND']['=']['userid'] = user_id total_nums, data = user_service.UserService().query_data(**params) resp = UserListResp() resp.total = total_nums for i in data: _user_info = user_info.UserInfo().init_from_db(i) resp.rows.append(_user_info) return json_helper.format_api_resp(code=ErrorCode.SUCCESS, data=resp.to_json())
def add_insideuser_to_group(group_id): ''' 在user_group表中将顺丰用户添加到某个组 ''' user_id = request.values.get('user_id') group_name = request.values.get('group_name') check_info = check(group_id, user_id) if check_info: return check_info params = { 'WHERE_AND': { '=': { 'userid': user_id, 'auth_type': '0', } } } user_info = user_service.UserService().query_data(**params) if not user_info or not user_info[1]: user_name = '' # logging.error("query user error, no such user_id:%s", str(user_id)) # return json_helper.format_api_resp(code=ErrorCode.NOT_EXIST_USER, msg="该用户请先登录平台,再来添加") else: user_name = user_info[1][0]['username'] user_group_data = user_g_s.get_data_by_group_name(group_name) if not user_group_data: logging.error( "group %s role id no exist in db when add insideuser to group", group_name) return json_helper.format_api_resp(code=ErrorCode.SYS_ERR) insert_user_data = { 'user_id': user_id, 'user_name': user_name, 'group_id': group_id, 'group_name': group_name, 'role_id': user_group_data['role_id'], 'status': '0', 'created_at': get_datetime_str() } ret = user_g_s.UserGroupService().add_user_group(insert_user_data) if ret == -1: return json_helper.format_api_resp(code=ErrorCode.SYS_ERR) return json_helper.format_api_resp(code=ErrorCode.SUCCESS)
def add_child_area(parent_area_id, child_area_id): if not parent_area_id or not child_area_id: logging.info('no parent_area_id or child_area_id when add child area') return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR) update_data = { 'parent_id': parent_area_id, } where_data = { 'id': child_area_id, } ret = area_s.AreaService().update_area_info(update_data, where_data) if ret.get('row_num') <= 0: logging.error("add child 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)
def rate_limit(): #TODO 通用化 配置化 module_name = request.values.get('module_name') ip = request.values.get('ip') redis_cache = redis_lib.RedisForCommon.get_instance_for_common_1() if module_name == '/account/check_sign_in': #ip地址的限制 if ip: key='ip' ip_limiter = Limiter(redis_cache, action=module_name+key, limit= 20, period = 60 * 10 ) ip_limiter_2 = Limiter(redis_cache, action=module_name+key+'2', limit= 50, period = 60 * 60 * 2) ret = ip_limiter.checked_insert(ip) if not ret: return json_helper.format_api_resp(const_define.ErrorCode.RATE_LIMIT_ERR) ret = ip_limiter_2.checked_insert(ip) if not ret: return json_helper.format_api_resp(const_define.ErrorCode.RATE_LIMIT_ERR) return json_helper.format_api_resp()
def ping(): a = config logging.debug('test var %s ', config.TEST_VAR) return json_helper.format_api_resp()