def collect_host_data(host_ip): result = connection_manager.host_is_up(CONN_TCP, host_ip) # host_status = connection_manager.host_is_up(CONN_SSH, host_ip) if result is True: status = HostStatus.RUNNING libvirtd_status = HostLibvirtdStatus.NORMAL elif result is "error(111, 'Connection refused')" or result is "timeout('timed out',)": status = HostStatus.ERROR libvirtd_status = HostLibvirtdStatus.UNUSUAL else: status = HostStatus.ERROR libvirtd_status = HostLibvirtdStatus.UNUSUAL # 更新收集时间 _update_data_h = { 'host_collect_time': get_datetime_str(), 'status': status, 'libvirtd_status': libvirtd_status } _where_data_h = { 'ipaddress': host_ip, 'isdeleted': '0' } ret_h = host_s.HostService().update_host_info(_update_data_h, _where_data_h) if ret_h != 1: logging.error('update collect time error when collect host data, update_data:%s, where_data:%s', _update_data_h, _where_data_h) print 'end colletc host ' + host_ip + ' data at ' + get_datetime_str() print '*' * 40 return 0
def create_new_user(user_ldap): new_user_data = { 'userid': user_ldap['userid'], 'username': user_ldap['name'], 'email': user_ldap['mail'], 'telephone': user_ldap['mobile'], 'fengsheng': None, 'status': UserStatus.NORMAL, 'isdeleted': '0', 'created_at': get_datetime_str() } res = user_service.UserService().add_user(new_user_data) new_user = None # 记录安全日志 field_data = { 'User_name': user_ldap['name'] or None, 'Oper_type': 'add' } if res.get('row_num') > 0: field_data.update({'Oper_result': '1 Success'}) new_user = UserInfo.get_user(user_ldap['userid']) else: field_data.update({'Oper_result': '0 Fail', 'fail_reason': 'insert new user info to db fail'}) CloudLogger.audit(AuditType.USERMGR, field_data) return new_user
def __update_host_table(host_ip, ostype, cpu_core, mem_size, disk_size, net_size, current_cpu_used, current_mem_used, current_disk_used, week_cpu_p95_used, week_mem_p95_used, current_net_rx_used, current_net_tx_used, start_time, libvirt_port, images, libvirt_status): _update_data_h = { 'host_performance_collect_time': get_datetime_str(), 'ostype': ostype, 'cpu_core': cpu_core, 'mem_size': mem_size, 'disk_size': disk_size, 'net_size': net_size, 'current_cpu_used': current_cpu_used, 'current_mem_used': current_mem_used, 'current_disk_used': current_disk_used, 'week_cpu_p95_used': week_cpu_p95_used, 'week_mem_p95_used': week_mem_p95_used, 'current_net_rx_used': current_net_rx_used, 'current_net_tx_used': current_net_tx_used, 'start_time': start_time, 'libvirt_port': libvirt_port, 'images': images, 'libvirt_status': libvirt_status } _where_data_h = {'ipaddress': host_ip, 'isdeleted': '0'} host_s.HostService().update_host_info(_update_data_h, _where_data_h) return 'done'
def __instance_ip_configure_change_db(ins_id, net_info, env): ''' 编辑instance_ip表 :param ins_id: :param net_info: :param env: :return: ''' ip_id_new = ip_s.IPService().get_ip_by_ip_address(net_info['ip_addr_new']) if not ip_id_new: msg = '无法在数据库中找到ip:%s 记录' % ip_id_new return False, msg # 查找生产、容灾环境对应的容灾、生产环境IP ret_change_status, ret_change_detail = __change_drprd_status( env, ip_id_new) if not ret_change_status: return False, ret_change_detail instance_ip_data = { 'instance_id': ins_id, 'ip_id': ip_id_new['id'], 'mac': net_info['mac_addr'], 'type': InstanceNicType.NORMAL_NETWORK_NIC, 'isdeleted': '0', 'created_at': get_datetime_str() } ret_add_ip = instance_ip_s.InstanceIPService().add_instance_ip_info( instance_ip_data) if ret_add_ip.get('row_num') <= 0: msg = "新增虚拟机网卡ip:%s信息到数据库失败" % ip_id_new['ip_address'] return False, msg return True, '数据库记录修改成功'
def send_wget(host_ip, image_url, image_server, speed_limit_parm, check_dir, endtime, sch_task_id): #判断远端wget脚本文件是否存在,如不存在,则生成并拷贝过去 print 'before wget_file_check' print sch_task_id check_wget_tag, check_wget_msg = ansibleCmdV2.wget_file_check( host_ip, sch_task_id) if not check_wget_tag: file_name = check_dir + '/deploy/wgetdir/sync_task_' + str( sch_task_id) + '.sh' check_local = os.path.exists(file_name) if not check_local: time_left = endtime - datetime.strptime(get_datetime_str(), "%Y-%m-%d %X") time_left_sec = time_left.seconds if int(time_left_sec) < 0: time_left_sec = 0 time_left_str = str(time_left_sec) create_wget_sh(sch_task_id, image_url, image_server, speed_limit_parm, time_left_str) send_wget_tag, send_wget_msg = ansibleCmdV2.send_wget_sh( host_ip, sch_task_id, check_dir) if not send_wget_tag: return False, send_wget_msg check_wget_tag, check_wget_msg = ansibleCmdV2.wget_file_check( host_ip, sch_task_id) if not check_wget_tag: return False, check_wget_msg #执行wget命令 exec_wget_tag, exec_wget_msg = ansibleCmdV2.exec_wget_com( host_ip, sch_task_id) if not exec_wget_tag: return False, exec_wget_msg else: return True, exec_wget_msg
def msg_back(task_id, job_status, src_instance_id, instance_id): ret_request_re = request_r_s.RequestRecordService( ).get_request_record_info_by_taskid_kvm(task_id) ret_to_vs = msg_to_vishnu(job_status, src_instance_id, instance_id) if ret_to_vs not in succeed_http_code: response_to_api_status = '2' else: response_to_api_status = '1' update_db_time = get_datetime_str() if job_status == VsJobStatus.SUCCEED: updata_task_status = ActionStatus.SUCCSESS else: updata_task_status = ActionStatus.FAILD _update_data = { 'task_status': updata_task_status, 'response_to_api': response_to_api_status, 'finish_time': update_db_time, 'request_status_collect_time': update_db_time, } _where_data = { 'taskid_kvm': task_id, } ret = request_r_s.RequestRecordService().update_request_status( _update_data, _where_data) if ret <= 0: logging.error('update request %s status to db failed' % task_id) return False else: logging.error('update request %s status to db successd' % task_id) return True
def __init_ip(segment_datas, ip_address): ''' IP初始化 :param segment_datas: :param ip_address: :return: ''' ip_vlan = segment_datas['vlan'] ip_netmask = segment_datas['netmask'] ip_segment_id = segment_datas['id'] ip_gateway_ip = segment_datas['gateway_ip'] ip_dns1 = segment_datas['dns1'] ip_dns2 = segment_datas['dns2'] insert_data = { 'ip_address': ip_address, 'segment_id': ip_segment_id, 'netmask': ip_netmask, 'vlan': ip_vlan, 'gateway_ip': ip_gateway_ip, 'dns1': ip_dns1, 'dns2': ip_dns2, 'status': IPStatus.UNUSED, 'created_at': get_datetime_str() } ret = ip_service.IPService().add_ip_info(insert_data) if ret == -1: return False return True
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_ip_resource(segment_datas, env, count): ''' 判断IP资源是否足够 :param segment_datas: :param env: :param count: :return: ''' # 获取可用ip ret_ip_datas, ret_ip_segment_datas = ip_s.get_available_ips( segment_datas, int(count), env) if not ret_ip_datas: return False, [], '虚拟机所在机房、网络区域下无法找到%s个可用IP' % str(count) # 标记ip为预分配 ips_list = [] for ip in ret_ip_datas: update_data = { 'status': IPStatus.USED, 'updated_at': get_datetime_str() } where_data = {'id': ip['id']} ret_mark_ip = ip_s.IPService().update_ip_info(update_data, where_data) if ret_mark_ip <= 0: continue ips_list.append(ip) if len(ips_list) < int(count): return False, [], '虚拟机网卡配置ip所需%s个可用IP修改为使用中状态部分失败' % str(count) else: return True, ret_ip_datas, ret_ip_segment_datas
def insert_log(*argv, **kwargs): res = func(*argv, **kwargs) try: userid = request.values.get('userid') tmp = json.loads(res.data) msg = tmp['msg'] except: return res if tmp["code"] == ErrorCode.SUCCESS: operation_result = "SUCCESS" msg = "" else: operation_result = "FAILED" client_ip = request.headers.get('X-Forwarded-For', '') insert_data = { "operator": userid, "operator_ip": client_ip, "operation_object": operation_object, "operation_action": operation_action, "operation_date": time_helper.get_datetime_str(), "operation_result": operation_result, "extra_data": msg } OperationService().insert_operation(insert_data) return res
def insert_log(*argv, **kwargs): user = user_service.get_user() res = func(*argv, **kwargs) try: tmp = json.loads(res.data) except: return res if tmp["code"] == ErrorCode.SUCCESS: operation_result = "SUCCESS" elif tmp["code"] == ErrorCode.SUCCESS_PART: operation_result = "SUCCESS_PART" else: operation_result = "FAILED" client_ip = request.headers.get('X-Forwarded-For', '') insert_data = { "operator": user["user_id"], "operator_ip": client_ip, "operation_object": operation_object, "operation_action": operation_action, "operation_date": time_helper.get_datetime_str(), "operation_result": operation_result, "extra_data": "" } OperationService().insert_operation(insert_data) return res
def insert_log(*argv, **kwargs): user = user_service.get_user() res = func(*argv, **kwargs) instance_data = "" try: tmp = json.loads(res.data) instance_data += (';').join( Global_define().get_value('vm_list')) except: return res if tmp["code"] == ErrorCode.SUCCESS: operation_result = "SUCCESS" elif tmp["code"] == ErrorCode.SUCCESS_PART: operation_result = "SUCCESS_PART" else: operation_result = "FAILED" try: instance_data += " ErrorMsg:" + tmp["msg"] except: pass client_ip = request.headers.get('X-Forwarded-For', '') insert_data = { "operator": user["user_id"], "operator_ip": client_ip, "operation_object": operation_object, "operation_action": operation_action, "operation_date": time_helper.get_datetime_str(), "operation_result": operation_result, "extra_data": "" + instance_data } OperationService().insert_operation(insert_data) return res
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 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 __update_config_msg_to_db(task_id, msg, job_status): update_data = { 'message': msg, 'status': job_status, 'finish_time': get_datetime_str() } where_data = {'task_id': task_id} return instance_action_s.InstanceActionsServices( ).update_instance_action_status(update_data, where_data)
def insert_log(*argv, **kwargs): user = user_service.get_user() res = func(*argv, **kwargs) datacenter_data = "" try: tmp = json.loads(res.data) if operation_action == OperationAction.ADD: # 新增机房 area_id = json.dumps(kwargs['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') datacenter_data += "name:" + name + "," + "area_id:" + area_id + "," + "dc_type:" + dc_type + "," \ + "province:" + province + "," + "address:" + address + "," \ + "description:" + description + ";" elif operation_action == OperationAction.ALTER: # 修改机房 datacenter_id = json.dumps(kwargs['datacenter_id']) name = request.values.get('name') province = request.values.get('province') address = request.values.get('address') description = request.values.get('description') datacenter_data += "name:" + name + "," + "datacenter_id:" + datacenter_id + "," \ + "province:" + province + "," + "address:" + address + "," \ + "description:" + description + ";" elif operation_action == OperationAction.DELETE: # 删除机房 datacenter_ids = request.values.get('datacenter_ids') datacenter_data += "datacenter_ids:" + datacenter_ids + ";" else: pass except: return res if tmp["code"] == ErrorCode.SUCCESS: operation_result = "SUCCESS" elif tmp["code"] == ErrorCode.SUCCESS_PART: operation_result = "SUCCESS_PART" else: operation_result = "FAILED" try: datacenter_data += " ErrorMsg:" + tmp["msg"] except: pass client_ip = request.headers.get('X-Forwarded-For', '') insert_data = { "operator": user["user_id"], "operator_ip": client_ip, "operation_object": operation_object, "operation_action": operation_action, "operation_date": time_helper.get_datetime_str(), "operation_result": operation_result, "extra_data": "" + datacenter_data } OperationService().insert_operation(insert_data) return res
def update_image_manage_msg(self, image_name, message): update_data = { 'update_time':get_datetime_str(), 'message':message, } where_data = { 'eimage_name': image_name, } ret = self.update_image_info(update_data, where_data)
def insert_log(*argv, **kwargs): user = user_service.get_user() res = func(*argv, **kwargs) ip_data = "" try: tmp = json.loads(res.data) if operation_action == OperationAction.IP_APPLY: # 申请IP env = request.values.get('env') net_area = request.values.get('net_area') 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') datacenter = request.values.get('datacenter') ip_data += "env:" + env + "," + "net_area:" + net_area + "," \ + "net_name:" + net_name + "," + "cluster_id:" + cluster_id + "," \ + "opuser:"******"," + "sys_code:" + sys_code + "," \ + "datacenter:" + datacenter + "," + "vip:" + tmp["data"]["vip"] + ";" elif request.values.get( 'ip_address'): # 初始化IP、取消初始化IP、保留IP、取消保留IP ip_address = request.values.get('ip_address') ip_data += "ip_address:" + ip_address + ";" elif request.values.get('begin_ip') and request.values.get( 'end_ip'): # 批量操作(4种) begin_ip = request.values.get('begin_ip') end_ip = request.values.get('end_ip') ip_data += "begin_ip:" + begin_ip + "," + "end_ip:" + end_ip + ";" else: pass except: return res if tmp["code"] == ErrorCode.SUCCESS: operation_result = "SUCCESS" elif tmp["code"] == ErrorCode.SUCCESS_PART: operation_result = "SUCCESS_PART" else: operation_result = "FAILED" try: ip_data += " ErrorMsg:" + tmp["msg"] except: pass client_ip = request.headers.get('X-Forwarded-For', '') insert_data = { "operator": user["user_id"], "operator_ip": client_ip, "operation_object": operation_object, "operation_action": operation_action, "operation_date": time_helper.get_datetime_str(), "operation_result": operation_result, "extra_data": "" + ip_data } OperationService().insert_operation(insert_data) return res
def update_image_manage_status(self, image_name, message, status): update_data = { 'update_time':get_datetime_str(), 'message':message, 'status':status } where_data = { 'eimage_name': image_name, } ret = self.update_image_info(update_data, where_data)
def ex_disk_snapshot(host_ip, instance_name, image_disk_list): try: conn = libvirt_get_connect(host_ip, conn_type='instance', vmname=instance_name) nowtime = get_datetime_str() conn.create_disk_snapshot(image_disk_list, nowtime) time.sleep(3) except libvirtError as err: logging.error(err) return False return True
def add_image_status_action(self, image_name, update_action, state_tag, message): insert_data = { 'status': state_tag, 'update_action': update_action, 'message': message, 'update_time': get_datetime_str(), 'eimage_name': image_name } ret = self.add_image_status_info(insert_data) if ret.get('row_num') <= 0: return False return True
def backup_instance_status(instance_id): ''' 这个函数作用是当热迁移失败时,由于前端VM页面并没有热迁移失败的状态码,所以在迁移过程中失败后,都直接将VM状态改为运行中 :return: ''' update_data = { 'status': VMStatus.STARTUP, 'updated_at': get_datetime_str() } where_data = {'id': instance_id} return ins_s.InstanceService().update_instance_info( update_data, where_data)
def change_migrate_status(self, migrate_tab_id, status): ''' 修改迁移任务状态 :param migrate_tab_id: :param status: :return: ''' update_data = { 'migrate_status': status, 'deleted_at': get_datetime_str() } where_data = {'id': migrate_tab_id} return self.instance_migrate_db.update(update_data, where_data)
def update_host_table_time(host_ip): _update_data_h = { 'host_performance_collect_time': get_datetime_str(), } _where_data_h = { 'ipaddress': host_ip, 'isdeleted': '0' } ret_h = host_s.HostService().update_host_info(_update_data_h, _where_data_h) if ret_h != 1: logging.error('update collect time error when collect host data, update_data:%s, where_data:%s', _update_data_h, _where_data_h) return 'done'
def instance_performance_data_to_other_platform(): '''获取web服务器的性能数据''' msg = '' command = "supervisorctl status | awk -F ' ' '{print $2}'" supervisorctl_data = os.popen(command).read() supervisorctl_list = supervisorctl_data.split('\n')[:-1] for i in supervisorctl_list: if i.strip() != "RUNNING": msg += 'web服务器性能数据存在非running状态; ' table_vishi = ip_lock_service.IpLockService().get_ip_lock_info( "performance_data") if table_vishi: update_data = {"istraceing": "0"} where_data = {"table_name": "performance_data"} ip_lock_service.IpLockService().update_ip_lock_info( update_data, where_data) else: insert_data = {"table_name": "performance_data", "istraceing": "0"} ip_lock_service.IpLockService().add_ip_lock_db(insert_data) ret_ip_lock = ip_lock_service.IpLockService().get_ip_lock_info( "performance_data") if ret_ip_lock["istraceing"] != "0": msg += 'web服务器性能数据设置检测初始化数据失败; ' data = { "routing_key": "INSTANCE.PERFORMANCE", "send_time": get_datetime_str(), "data": { "table_name": "performance_data" } } send_async_msg(KAFKA_TOPIC_NAME, data) nums = 0 status = False while nums < 10: table_vishi = ip_lock_service.IpLockService().get_ip_lock_info( "performance_data") if str(table_vishi["istraceing"]) == '1': status = True break else: nums += 1 time.sleep(1) if not status: msg += 'kafka消费任务异常,超时10秒; ' if msg: return json_helper.format_api_resp_msg_to_vishnu_resource( job_status=VsJobStatus.FAILED, detail=msg) return json_helper.format_api_resp_msg_to_vishnu_resource( job_status=VsJobStatus.SUCCEED, detail='web服务器正常,kafka消费正常')
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 insert_log(*argv, **kwargs): user = user_service.get_user() res = func(*argv, **kwargs) hostpool_data = "" try: tmp = json.loads(res.data) if operation_action == OperationAction.ADD: # 新增集群 net_area_id = json.dumps(kwargs['net_area_id']) least_host_num = request.values.get('least_host_num') name = request.values.get('name') hostpool_data += "name:" + name + "," + "net_area_id:" + net_area_id + "," \ + "least_host_num:" + least_host_num + ";" elif operation_action == OperationAction.ALTER: # 修改集群 name = request.values.get('name') least_host_num = request.values.get('least_host_num') hostpool_id = json.dumps(kwargs['hostpool_id']) hostpool_data += "name:" + name + "," + "hostpool_id:" + hostpool_id + "," \ + "least_host_num:" + least_host_num + ";" elif operation_action == OperationAction.DELETE: # 删除集群 hostpool_ids = request.values.get('hostpool_ids') hostpool_data += "net_area_ids:" + hostpool_ids + ";" else: pass except: return res if tmp["code"] == ErrorCode.SUCCESS: operation_result = "SUCCESS" elif tmp["code"] == ErrorCode.SUCCESS_PART: operation_result = "SUCCESS_PART" else: operation_result = "FAILED" try: hostpool_data += " ErrorMsg:" + tmp["msg"] except: pass client_ip = request.headers.get('X-Forwarded-For', '') insert_data = { "operator": user["user_id"], "operator_ip": client_ip, "operation_object": operation_object, "operation_action": operation_action, "operation_date": time_helper.get_datetime_str(), "operation_result": operation_result, "extra_data": "" + hostpool_data } OperationService().insert_operation(insert_data) return res
def verify_code_create(): # 把strs发给前端,或者在后台使用session保存 code_img, strs = create_validate_code() # session存储验证码和生成时间 session['verify_code'] = strs session['verify_code_time'] = get_datetime_str() buf = StringIO.StringIO() code_img.save(buf, 'JPEG', quality=70) buf_str = buf.getvalue() response = make_response(buf_str) response.headers['Content-Type'] = 'image/jpeg' return response
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 insert_log(*argv, **kwargs): user = user_service.get_user() res = func(*argv, **kwargs) area_data = "" try: tmp = json.loads(res.data) if operation_action == OperationAction.ADD: # 新增区域 name = request.values.get('name') manager = request.values.get('manager') parent_id = request.values.get('parent_id') area_data += "name:" + name + "," + "manager:" + manager + "," + "parent_id:" + parent_id + ";" elif operation_action == OperationAction.ALTER: # 修改区域 name = request.values.get('name') manager = request.values.get('manager') area_id = json.dumps(kwargs['area_id']) area_data += "name:" + name + "," + "manager:" + manager + "," + "area_id:" + area_id + ";" elif operation_action == OperationAction.DELETE: # 删除区域 area_ids = request.values.get('area_ids') area_data += "area_ids:" + area_ids + ";" else: pass except: return res if tmp["code"] == ErrorCode.SUCCESS: operation_result = "SUCCESS" elif tmp["code"] == ErrorCode.SUCCESS_PART: operation_result = "SUCCESS_PART" else: operation_result = "FAILED" try: area_data += " ErrorMsg:" + tmp["msg"] except: pass client_ip = request.headers.get('X-Forwarded-For', '') insert_data = { "operator": user["user_id"], "operator_ip": client_ip, "operation_object": operation_object, "operation_action": operation_action, "operation_date": time_helper.get_datetime_str(), "operation_result": operation_result, "extra_data": "" + area_data } OperationService().insert_operation(insert_data) return res