def commitorder(self, data, tmp, user, type, id): try: x = [x.rstrip(';') for x in tmp] sql = ';'.join(x) sql = sql.strip(' ').rstrip(';') workId = util.workId() SqlOrder.objects.get_or_create(username=user, date=util.date(), work_id=workId, status=2, basename=data['basename'], sql=sql, type=type, text=data['text'], backup=data['backup'], bundle_id=id, assigned=data['assigned'], delay=data['delay']) # 记录转发消息 Usermessage.objects.create(from_user=user, time=util.date(), title='工单:' + workId + ' 提交通知', content=data['text'], to_user=data['assigned'], state='unread') submit_push_messages(workId=workId, user=user, addr_ip=addr_ip, text=data['text'], assigned=data['assigned'], id=id).start() except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500)
def put(self, request, args=None): try: print(request.data) data = json.loads(request.data['data']) uporder = request.data['uporder'] config_properties = request.data['config_properties'] newserviceData = request.data['newserviceData'] user = request.data['user'] except KeyError as e: client.captureException() CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') else: try: info = onlineinfo_db.objects.get(workid=data['workid']) info.iteration_name = data['iteration_name'] info.date = util.date() info.env_name = data['env_name'] info.project_name = data['project_name'] info.upstart_time = data['upstart_time'] info.upbak_time = data['upbak_time'] info.versionvalue = data['versionvalue'] info.state_em = data['state_em'] info.updesc = data['updesc'] info.sqlorder = str(data['sqlorder']).replace('\'', '\"') info.service = data['service'] info.config_properties = config_properties info.progress_editor = data['progress_editor'] info.owner = user info.uporder = uporder info.remark = data['remark'] info.newserviceData = newserviceData info.addservice = data['addservice'] info.assigned = data['assigned'] info.save() c_info = CloudOrder.objects.get(workid=data['workid']) c_info.date = util.date() c_info.remark = data['project_name'] + '_' + env_name_list[ data['env_name']] + '_' + iteration_list[ data['iteration_name']] c_info.assigned = data['assigned'] c_info.username = user c_info.status = 3 c_info.save() edit_push_messages(workId=data['workid'], user=user, to_user=data['assigned'], id=1, addr_ip=addr_ip, assigned=data['assigned'], text='更新').run() return Response('已提交,请等待管理员审核!') except Exception as e: client.captureException() CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return Response({'status': '500'})
def post(self, request, args=None): try: print(request.data) newserviceData = request.data['newserviceData'] data = json.loads(request.data['data']) uporder = request.data['uporder'] config_properties = request.data['config_properties'] user = request.data['user'] except KeyError as e: client.captureException() CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: workId = util.workId() onlineinfo_db.objects.get_or_create( iteration_name=data['iteration_name'], date=util.date(), workid=workId, env_name=data['env_name'], project_name=data['project_name'], upstart_time=data['upstart_time'], upbak_time=data['upbak_time'], versionvalue=data['versionvalue'], newserviceData=newserviceData, state_em=data['state_em'], updesc=data['updesc'], sqlorder=str(data['sqlorder']).replace('\'', '\"'), uporder=uporder, addservice=data['addservice'], config_properties=config_properties, progress_editor=data['progress_editor'], remark=data['remark'], owner=user, assigned=data['assigned']) CloudOrder.objects.get_or_create( date=util.date(), remark=data['project_name'] + '_' + env_name_list[data['env_name']] + '_' + iteration_list[data['iteration_name']], type=0, status=3, username=user, assigned=data['assigned'], workid=workId) submit_push_messages(workId=workId, user=user, to_user=data['assigned'], id=1, addr_ip=addr_ip, assigned=data['assigned'], text='text').run() return Response({'status': 'success', 'orderid': workId}) except Exception as e: client.captureException() return Response({'status': 'error', 'log': '后端保存失败'})
def put(self, request, args=None): try: data = json.loads(request.data['data']) user = request.data['user'] except KeyError as e: client.captureException() CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') else: try: info = addnewpcinfo_db.objects.get(workid=data['workid']) info.date = util.date() info.env_name = data['env_name'] info.project_name = data['project_name'] info.remark = data['remark'] info.owner = user info.os_soft_need = str(data['os_soft_need']).replace( '\'', '\"') info.opentime = data['opentime'] info.appname = data['appname'] info.assigned = data['assigned'] info.newpc_type = data['newpc_type'] info.servernum = data['servernum'] info.cpunum = data['cpunum'] info.mem = data['mem'] info.OsDiskType = data['OsDiskType'] info.OsDiskSize = data['OsDiskSize'] info.DataDiskSize = data['DataDiskSize'] info.domain = data['domain'] info.jdk_version = data['jdk_version'] info.jvm_properties = data['jvm_properties'] info.netbrand = data['netbrand'] info.domain_choice = data['domain_choice'] info.https_choice = data['https_choice'] info.DataDiskType = data['DataDiskType'] info.save() c_info = CloudOrder.objects.get(workid=data['workid']) c_info.date = util.date() c_info.remark = data['remark'] c_info.status = 3 c_info.assigned = data['assigned'] c_info.username = user c_info.save() edit_push_messages(workId=data['workid'], user=user, to_user=data['assigned'], id=1, addr_ip=addr_ip, assigned=data['assigned'], text='更新').run() return Response('已提交,请等待管理员审核!') except Exception as e: logging.info(e) print(e) CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return Response({'status': '500'})
def post(self, request, args=None): try: print(request.data) data = json.loads(request.data['data']) user = request.data['user'] except KeyError as e: client.captureException() CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: workId = util.workId() addnewpcinfo_db.objects.get_or_create( date=util.date(), workid=workId, env_name=data['env_name'], project_name=data['project_name'], remark=data['remark'], owner=user, os_soft_need=str(data['os_soft_need']).replace('\'', '\"'), opentime=data['opentime'], appname=data['appname'], assigned=data['assigned'], newpc_type=data['newpc_type'], servernum=data['servernum'], cpunum=data['cpunum'], mem=data['mem'], OsDiskType=data['OsDiskType'], OsDiskSize=data['OsDiskSize'], DataDiskSize=data['DataDiskSize'], domain=data['domain'], jdk_version=data['jdk_version'], jvm_properties=data['jvm_properties'], netbrand=data['netbrand'], https_choice=data['https_choice'], DataDiskType=data['DataDiskType']) CloudOrder.objects.get_or_create(date=util.date(), remark=data['remark'], type=2, status=3, username=user, assigned=data['assigned'], workid=workId) submit_push_messages(workId=workId, user=user, to_user=data['assigned'], id=1, addr_ip=addr_ip, assigned=data['assigned'], text='text').run() return Response('已提交,请等待管理员审核!')
def post(self, request, args=None): try: analysis_result = json.loads(request.data['analysis_result']) sql = json.loads(request.data['sql']) user = request.data['user'] type = request.data['type'] id = request.data['id'] dbinfo_name=request.data['basename'] # redis_conn = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=0) querykey = 'sqladvisor_' + md5(dbinfo_name + '_' + sql).hexdigest() except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: SqlAdvisor.objects.get_or_create( username=user, datcreate_time=util.date(), analysis_result=analysis_result, sql=sql, type=type, dbinfo_name=dbinfo_name, db_id=id ) return Response('已提交') except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500)
def agreed(self): ''' :argument 将执行的结果通过站内信,email,dingding 发送 :param self.from_user self.to_user self.title self.order self.addr_ip :return: none ''' Usermessage.objects.get_or_create( from_user=self.from_user, time=util.date(), title=self.title, content='该工单已审核通过!', to_user=self.to_user, state='unread' ) # content = DatabaseList.objects.filter(id=self.order.bundle_id).first() # mail = Account.objects.filter(username=self.to_user).first() # tag = globalpermissions.objects.filter(authorization='global').first() try: util.dingding( '# 【<font face=\"微软雅黑\">工单执行通知</font>】 \n # \n <br> \n **工单编号:** %s \n \n **发起人员:** <font color=\"#000080\">%s</font><br /> \n \n **审核人员:** <font color=\"#000080\">%s</font><br /> \n \n **平台地址:** http://%s \n \n **工单备注:** %s \n \n **执行状态:** <font color=\"#38C759\">已同意</font><br />' % (self.order.workid, self.order.username, self.order.assigned, self.addr_ip, self.order.remark), url=dingding_url) except Exception as e: print(e) CUSTOM_ERROR.error(f'{e.__class__.__name__}--钉钉推送失败: {e}')
def put(self, request, args: str = None): try: from_user = request.data['from_user'] to_user = request.data['to_user'] text = request.data['text'] workid = request.data['workid'] print(request.data) except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: CloudOrder.objects.filter(workid=workid).update(status=4) _tmpData = CloudOrder.objects.filter(workid=workid).values( 'workid', 'username', 'assigned').first() title = '工单:' + _tmpData['workid'] + '撤销通知' Usermessage.objects.get_or_create(from_user=from_user, time=util.date(), title=title, content=text, to_user=to_user, state='unread') cancel_push_messages(_tmpData, to_user, from_user, addr_ip, text).start() return Response('操作成功,该请求已撤销!') except Exception as e: return Response({'status': 'failed', 'log': '发生错误!!'})
def post(self, request, args=None): try: data = json.loads(request.data['data']) tmp = json.loads(request.data['sql']) user = request.data['user'] type = request.data['type'] id = request.data['id'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: x = [x.rstrip(';') for x in tmp] sql = ';'.join(x) sql = sql.strip(' ').rstrip(';') workId = util.workId() SqlOrder.objects.get_or_create( username=user, date=util.date(), work_id=workId, status=2, basename=data['basename'], sql=sql, type=type, text=data['text'], backup=data['backup'], bundle_id=id ) content = DatabaseList.objects.filter(id=id).first() if content.url: util.dingding(content='工单提交通知\n' + content.before, url=content.url) return Response('已提交,请等待管理员审核!') except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500)
def post(self, request, args=None): print("post请求") try: data = json.loads(request.data['data']) tmp = json.loads(request.data['sql']) type = request.data['type'] real_name = request.data['real_name'] id = request.data['id'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: x = [x.rstrip(';') for x in tmp] if str(x[0]).lstrip().startswith('use'): del x[0] sql = ';'.join(x) sql = sql.strip(' ').rstrip(';') workId = util.workId() env_name = Env.objects.filter(id=data['env_id'])[0].env_name service_name = Service.objects.filter( id=data['service_id'])[0].service_name res, err = SqlOrder.objects.get_or_create( username=request.user, date=util.date(), work_id=workId, status=2, basename=data['basename'], sql=sql, type=type, text=data['text'], backup=data['backup'], bundle_id=id, assigned=data['assigned'], delay=data['delay'], real_name=real_name, version=data['version'], env_name=env_name, env_id=data['env_id'], service_name=service_name, service_id=data['service_id'], ) user_res = Account.objects.filter(username=request.user)[0] if err and data['env_id'] == 1 and res.bundle_id == 18: arr = order_push_message(addr_ip, res.id, real_name, real_name) threading.Timer(0, arr.run).start() submit_push_messages(workId=workId, user=request.user, addr_ip=addr_ip, text=data['text'], assigned=data['assigned'], id=id).start() return Response('已提交,请等待管理员审核!') except Exception as e: traceback.print_exc() CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500)
def agreed(self): ''' :argument 将执行的结果通过站内信,email,dingding 发送 :param self.from_user self.to_user self.title self.order self.addr_ip :return: none ''' Usermessage.objects.get_or_create( from_user=self.from_user, time=util.date(), title=self.title, content='该工单已审核通过!', to_user=self.to_user, state='unread' ) content = DatabaseList.objects.filter(id=self.order.bundle_id).first() mail = Account.objects.filter(username=self.to_user).first() tag = globalpermissions.objects.filter(authorization='global').first() if tag is None or tag.dingding == 0: pass else: try: if content.url: if self.statue == 'normal': util.dingding('# 【<font face=\"微软雅黑\">工单执行通知</font>】 \n # \n <br> \n **工单编号:** %s \n \n **发起人员:** <font color=\"#000080\">%s</font><br /> \n \n **审核人员:** <font color=\"#000080\">%s</font><br /> \n \n **平台地址:** http://%s \n \n **工单备注:** %s \n \n **执行状态:** <font color=\"#38C759\">已执行</font><br /> \n \n **执行结果:** <font color=\"#38C759\">正常</font><br /> \n \n **业务备注:** %s \n ' % (self.order.work_id, self.order.username, self.from_user,self.addr_ip, self.order.text, content.after), url=content.url) else: util.dingding( '# 【<font face=\"微软雅黑\">工单执行通知</font>】 \n # \n <br> \n **工单编号:** %s \n \n **发起人员:** <font color=\"#000080\">%s</font><br /> \n \n **审核人员:** <font color=\"#000080\">%s</font><br /> \n \n **平台地址:** http://%s \n \n **工单备注:** %s \n \n **执行状态:** <font color=\"#38C759\">已执行</font><br /> \n \n **执行结果:** <font color=\"#38C759\">正常</font><br /> \n \n **业务备注:** %s \n ' % (self.order.work_id, self.order.username, self.from_user, self.addr_ip, self.order.text, content.after), url=content.url) except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}--钉钉推送失败: {e}') if tag is None or tag.email == 0: pass else: try: if mail.email: mess_info = { 'workid': self.order.work_id, 'to_user': self.order.username, 'addr': self.addr_ip, 'text': self.order.text, 'note': content.after} put_mess = send_email.send_email(to_addr=mail.email) put_mess.send_mail(mail_data=mess_info, type=0) except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}--邮箱推送失败: {e}')
def put(self, request, args=None): try: data = json.loads(request.data['data']) user = request.data['user'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') else: try: info = extendinfo_db.objects.get(workid=data['workid']) info.date = util.date() info.env_name = data['env_name'] info.project_name = data['project_name'] info.remark = data['remark'] info.owner = user, info.extend_type = data['extend_type'] info.ghost_choice = data['ghost_choice'] info.os_soft_need = str(data['os_soft_need']).replace( '\'', '\"') info.opentime = data['opentime'] info.servernum = data['servernum'] info.properties_change = data['properties_change'] info.appname = data['appname'] info.assigned = data['assigned'] info.save() c_info = CloudOrder.objects.get(workid=data['workid']) c_info.date = util.date() c_info.status = 3 c_info.remark = data['remark'] c_info.assigned = data['assigned'] c_info.username = user c_info.save() edit_push_messages(workId=data['workid'], user=user, to_user=data['assigned'], id=1, addr_ip=addr_ip, assigned=data['assigned'], text='更新').run() return Response('已提交,请等待管理员审核!') except Exception as e: client.captureException() CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return Response({'status': '500'})
def post(self, request, args=None): try: if args == 'star': querypermissions.objects.filter(id=request.data['id']).update( is_love=1, alias=request.data['alias']) return HttpResponse({'ok': '1'}) elif args == 'unstar': querypermissions.objects.filter(id=request.data['id']).update( is_love=0) return HttpResponse({'ok': '1'}) elif args == 'fav': my = querypermissions.objects.filter(username=request.user, is_love=1).order_by('-id') serializer_my = QueryPermissions(my, many=True) return Response({'data': serializer_my.data, 'len': len(my)}) elif args == 'his': history = querypermissions.objects.filter( username=request.user).order_by('-id')[0:20] serializer_his = QueryPermissions(history, many=True) return Response({'history': serializer_his.data}) elif args == 'optimizer': history = sql_optimize_his.objects.filter( username=request.user).order_by('-id')[0:10] serializer_his = Sql_Optimize_His(history, many=True) return Response({'history': serializer_his.data}) elif args == 'get_assigned': gr = grained.objects.filter( username=request.data['username']).first() assignes = gr.permissions['person'] return Response({'assigned': assignes}) elif args == 'put_assigned': SqlOrder.objects.filter(id=request.data['id']).update( assigned=request.data['forward_assigne']) sqlorder = SqlOrder.objects.filter( id=request.data['id']).first() title = '工单:' + sqlorder.work_id + '转发通知' # 记录转发消息 Usermessage.objects.create(from_user=sqlorder.username, time=util.date(), title=title, content=sqlorder.text, to_user=sqlorder.assigned, state='unread') # 异步发送消息: forward_push_messages(workId=sqlorder.work_id, user=sqlorder.username, addr_ip=addr_ip, text=sqlorder.text, assigned=sqlorder.assigned, id=sqlorder.bundle_id).start() return Response('put_assigned ok!') except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return Response({'error': e.args[1]})
def agreed(self): ''' :argument 将执行的结果通过站内信,email,dingding 发送 :param self.from_user self.to_user self.title self.order self.addr_ip :return: none ''' Usermessage.objects.get_or_create(from_user=self.from_user, time=util.date(), title=self.title, content='该工单已审核通过!', to_user=self.to_user, state='unread') content = DatabaseList.objects.filter(id=self.order.bundle_id).first() mail = Account.objects.filter(username=self.to_user).first() tag = globalpermissions.objects.filter(authorization='global').first() if tag is None or tag.dingding == 0: pass else: try: if content.url: util.dingding( content= '工单执行通知\n工单编号:%s\n发起人:%s\n地址:%s\n工单备注:%s\n状态:已执行\n备注:%s' % (self.order.work_id, self.order.username, self.addr_ip, self.order.text, content.after), url=content.url) except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}--钉钉推送失败: {e}') if tag is None or tag.email == 0: pass else: try: if mail.email: mess_info = { 'workid': self.order.work_id, 'to_user': self.order.username, 'addr': self.addr_ip, 'text': self.order.text, 'note': content.after } put_mess = send_email.send_email(to_addr=mail.email) put_mess.send_mail(mail_data=mess_info, type=0) except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}--邮箱推送失败: {e}')
def post(self, request, args=None): try: data = json.loads(request.data['data']) user = request.data['user'] except KeyError as e: client.captureException() CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: workId = util.workId() extendinfo_db.objects.get_or_create( date=util.date(), workid=workId, env_name=data['env_name'], project_name=data['project_name'], remark=data['remark'], owner=user, extend_type=data['extend_type'], ghost_choice=data['ghost_choice'], os_soft_need=str(data['os_soft_need']).replace('\'', '\"'), opentime=data['opentime'], servernum=data['servernum'], properties_change=data['properties_change'], appname=data['appname'], assigned=data['assigned']) CloudOrder.objects.get_or_create(date=util.date(), remark=data['remark'], type=1, status=3, username=user, assigned=data['assigned'], workid=workId) submit_push_messages(workId=workId, user=user, to_user=data['assigned'], id=1, addr_ip=addr_ip, assigned=data['assigned'], text='text').run() return Response('已提交,请等待管理员审核!')
def execute(self): self.title = f'工单:{self.order.work_id}审核通过通知' ''' 根据工单编号拿出对应sql的拆解数据 ''' SQL_LIST = DatabaseList.objects.filter(id=self.order.bundle_id).first() ''' 发送sql语句到inception中执行 ''' with call_inception.Inception( LoginDic={ 'host': SQL_LIST.ip, 'user': SQL_LIST.username, 'password': SQL_LIST.password, 'db': self.order.basename, 'port': SQL_LIST.port }) as f: res = f.Execute(sql=self.order.sql, backup=self.order.backup) ''' 修改该工单编号的state状态 ''' SqlOrder.objects.filter(id=self.id).update(status=1) ''' 遍历返回结果插入到执行记录表中 ''' for i in res: SqlRecord.objects.get_or_create( date=util.date(), state=i['stagestatus'], sql=i['sql'], area=SQL_LIST.computer_room, name=SQL_LIST.connection_name, error=i['errormessage'], base=self.order.basename, workid=self.order.work_id, person=self.order.username, reviewer=self.order.assigned, affectrow=i['affected_rows'], sequence=i['sequence'], backup_dbname=i['backup_dbname'])
def execute(self): ''' :argument 将获得的sql语句提交给inception执行并将返回结果写入SqlRecord表,最后更改该工单SqlOrder表中的status :param self.order self.id :return: none ''' detail = DatabaseList.objects.filter(id=self.order.bundle_id).first() with call_inception.Inception( LoginDic={ 'host': detail.ip, 'user': detail.username, 'password': detail.password, 'db': self.order.basename, 'port': detail.port } ) as f: res = f.Execute(sql=self.order.sql, backup=self.order.backup) SqlOrder.objects.filter(id=self.id).update(status=1) for i in res: if i['stagestatus'].find('failed') != -1: self.statue = 'bad' SqlRecord.objects.get_or_create( date=util.date(), state=i['stagestatus'], sql=i['sql'], area=detail.computer_room, name=detail.connection_name, error=i['errormessage'], base=self.order.basename, workid=self.order.work_id, person=self.order.username, reviewer=self.order.assigned, affectrow=i['affected_rows'], sequence=i['sequence'], backup_dbname=i['backup_dbname'], execute_time=i['execute_time'], SQLSHA1=i['SQLSHA1'] )
def con_close(self): Usermessage.objects.get_or_create( from_user=self.from_user, time=util.date(), title=self.title, content='该工单已审核通过!', to_user=self.to_user, state='unread' ) content = DatabaseList.objects.filter(id=self.order.bundle_id).first() mail = Account.objects.filter(username=self.to_user).first() tag = globalpermissions.objects.filter(authorization='global').first() if tag.message['ding']: try: if content.url: util.dingding( content='工单执行通知\n工单编号:%s\n发起人:%s\n审核人:%s\n地址:%s\n工单备注:%s\n状态:已执行\n备注:%s' % ( self.order.work_id, self.order.username,self.order.assigned, self.addr_ip, self.order.text, content.after), url=content.url) except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}--钉钉推送失败: {e}') if tag.message['feishu']: try: user_mail = Account.objects.filter(username=self.order.username).values('email').first() user = {'mail': user_mail.get('email')} fs_send_msg( msg='工单执行通知\n工单编号:%s\n发起人:%s\n审核人:%s\n地址:%s\n工单备注:%s\n状态:已执行\n备注:%s' % (self.order.work_id, self.order.username,self.order.assigned, self.addr_ip, self.order.text, content.after),user=user) except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}--飞书推送失败: {e}') if tag.message['mail']: try: if mail.email: mess_info = { 'workid': self.order.work_id, 'to_user': self.order.username, 'addr': self.addr_ip, 'text': self.order.text, 'note': content.after} put_mess = send_email.send_email(to_addr=mail.email) put_mess.send_mail(mail_data=mess_info, type=0) except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}--邮箱推送失败: {e}')
def post(self, request, args=None): try: data = json.loads(request.data['data']) tmp = json.loads(request.data['sql']) type = request.data['type'] real_name = request.data['real_name'] id = request.data['id'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: x = [x.rstrip(';') for x in tmp] if str(x[0]).lstrip().startswith('use'): del x[0] sql = ';'.join(x) sql = sql.strip(' ').rstrip(';') workId = util.workId() SqlOrder.objects.get_or_create( username=request.user, date=util.date(), work_id=workId, status=2, basename=data['basename'], sql=sql, type=type, text=data['text'], backup=data['backup'], bundle_id=id, assigned=data['assigned'], delay=data['delay'], real_name=real_name ) submit_push_messages( workId=workId, user=request.user, addr_ip=addr_ip, text=data['text'], assigned=data['assigned'], id=id ).start() return Response('已提交,请等待Leader审核!') except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500)
def post(self, request, args=None): try: data = json.loads(request.data['data']) tmp = json.loads(request.data['sql']) type = request.data['type'] real_name = request.data['real_name'] id = request.data['id'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: x = [x.rstrip(';') for x in tmp] if str(x[0]).lstrip().startswith('use'): del x[0] sql = ';'.join(x) sql = sql.strip(' ').rstrip(';') workId = util.workId() SqlOrder.objects.get_or_create( username=request.user, date=util.date(), work_id=workId, status=2, basename=data['basename'], sql=sql, type=type, text=data['text'], backup=data['backup'], bundle_id=id, assigned=data['assigned'], delay=data['delay'], real_name=real_name ) submit_push_messages( workId=workId, user=request.user, addr_ip=addr_ip, text=data['text'], assigned=data['assigned'], id=id ).start() return Response('已提交,请等待管理员审核!') except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500)
def post(self, request, args=None): try: data = json.loads(request.data['data']) tmp = json.loads(request.data['sql']) user = request.data['user'] source_table = request.data['source_table'] dest_table = request.data['dest_table'] archive_condition = request.data['archive_condition'] soure_dbname = request.data['source_dbname'] dest_dbname = request.data['dest_dbname'] source_id = request.data['source_id'] dest_id = request.data['dest_id'] source_id = request.data['source_id'] status = request.data['status'] type = request.data['type'] ssh_hostid = request.data['ssh_hostid'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: workId = util.workId() ArchiveLog.objects.get_or_create( source_id=source_id, db_source=soure_dbname, table_source=source_table, dest_id=dest_id, db_dest=dest_dbname, dest_table=dest_table, date=util.date(), archive_condition=archive_condition, status=status, type=type, ssh_hostid=ssh_hostid, ) submit_push_messages(workId=workId, user=user, addr_ip=addr_ip, text=data['text'], assigned=data['assigned'], id=id).start() return Response('已提交!') except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500)
def con_close(self): Usermessage.objects.get_or_create( from_user=self.from_user, time=util.date(), title=self.title, content='该工单已审核通过!', to_user=self.to_user, state='unread' ) content = DatabaseList.objects.filter(id=self.order.bundle_id).first() mail = Account.objects.filter(username=self.to_user).first() tag = globalpermissions.objects.filter(authorization='global').first() if tag.message['ding']: try: if content.url: util.dingding( content='工单执行通知\n工单编号:%s\n发起人:%s\n地址:%s\n工单备注:%s\n状态:已执行\n备注:%s' % ( self.order.work_id, self.order.username, self.addr_ip, self.order.text, content.after), url=content.url) except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}--钉钉推送失败: {e}') if tag.message['mail']: try: if mail.email: mess_info = { 'workid': self.order.work_id, 'to_user': self.order.username, 'addr': self.addr_ip, 'text': self.order.text, 'note': content.after} put_mess = send_email.send_email(to_addr=mail.email) put_mess.send_mail(mail_data=mess_info, type=0) except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}--邮箱推送失败: {e}')
def post(self, request, args=None): try: data = json.loads(request.data['data']) tmp = json.loads(request.data['sql']) user = request.data['user'] type = request.data['type'] id = request.data['id'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: x = [x.rstrip(';') for x in tmp] sql = ';'.join(x) sql = sql.strip(' ').rstrip(';') workId = util.workId() SqlOrder.objects.get_or_create(username=user, date=util.date(), work_id=workId, status=2, basename=data['basename'], sql=sql, type=type, text=data['text'], backup=data['backup'], bundle_id=id, assigned=data['assigned']) content = DatabaseList.objects.filter(id=id).first() mail = Account.objects.filter( username=data['assigned']).first() tag = globalpermissions.objects.filter( authorization='global').first() ret_info = '已提交,请等待管理员审核!' if tag is None or tag.dingding == 0: pass else: if content.url: try: util.dingding( content= '工单提交通知\n工单编号:%s\n发起人:%s\n地址:%s\n工单说明:%s\n状态:已提交\n备注:%s' % (workId, user, addr_ip, data['text'], content.before), url=content.url) except: ret_info = '工单执行成功!但是钉钉推送失败,请查看错误日志排查错误.' if tag is None or tag.email == 0: pass else: if mail.email: mess_info = { 'workid': workId, 'to_user': user, 'addr': addr_ip, 'text': data['text'], 'note': content.before } try: put_mess = send_email.send_email( to_addr=mail.email) put_mess.send_mail(mail_data=mess_info, type=2) except: ret_info = '工单执行成功!但是邮箱推送失败,请查看错误日志排查错误.' return Response(ret_info) except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500)
def execute(self): self.title = f'工单:{self.order.work_id}审核通过通知' ''' 根据工单编号拿出对应sql的拆解数据 ''' SQL_LIST = DatabaseList.objects.filter(id=self.order.bundle_id).first() ''' 发送sql语句到inception中执行 ''' with call_inception.Inception( LoginDic={ 'host': SQL_LIST.ip, 'user': SQL_LIST.username, 'password': SQL_LIST.password, 'db': self.order.basename, 'port': SQL_LIST.port }) as f: res = f.Execute(sql=self.order.sql, backup=self.order.backup) ''' 修改该工单编号的state状态 ''' SqlOrder.objects.filter(id=self.id).update(status=1) ''' 遍历返回结果插入到执行记录表中 ''' for i in res: SqlRecord.objects.get_or_create( date=util.date(), state=i['stagestatus'], sql=i['sql'], area=SQL_LIST.computer_room, name=SQL_LIST.connection_name, error=i['errormessage'], base=self.order.basename, workid=self.order.work_id, person=self.order.username, reviewer=self.order.assigned, affectrow=i['affected_rows'], sequence=i['sequence'], backup_dbname=i['backup_dbname']) if self.order.type == 0 and \ i['errlevel'] == 0 and \ i['sql'].find('use') == -1 and \ i['stagestatus'] != 'Audit completed': data = testddl.AutomaticallyDDL( sql=" ".join(i['sql'].split())) if data['mode'] == 'pass': pass elif data['mode'] == 'add': SqlDictionary.objects.get_or_create( Type=data['Type'], Null=data['Null'], Default=data['Default'], Extra=data['COMMENT'], BaseName=data['BaseName'], TableName=data['TableName'], Field=data['Field'], TableComment='', Name=SQL_LIST.connection_name) elif data['mode'] == 'del': SqlDictionary.objects.filter( BaseName=data['BaseName'], TableName=data['TableName'], Field=data['Field'], Name=SQL_LIST.connection_name).delete() elif data['mode'] == 'drop': SqlDictionary.objects.filter( BaseName=self.order.basename, TableName=data['TableName']).delete()
def put(self, request, args: str = None): if request.data['mode'] == 'put': instructions = request.data['instructions'] connection_name = request.data['connection_name'] computer_room = request.data['computer_room'] real = request.data['real_name'] export = request.data['export'] audit = request.data['audit'] un_init = util.init_conf() query_switch = ast.literal_eval(un_init['other']) query_per = 2 work_id = util.workId() if not query_switch['query']: query_per = 2 else: userinfo = Account.objects.filter(username=audit, group='admin').first() try: thread = threading.Thread( target=push_message, args=( {'to_user': request.user, 'workid': work_id}, 5, request.user, userinfo.email, work_id, '提交') ) thread.start() except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') query_order.objects.create( work_id=work_id, instructions=instructions, username=request.user, date=util.date(), query_per=query_per, connection_name=connection_name, computer_room=computer_room, export=export, audit=audit, time=util.date(), real_name=real ) if not query_switch['query']: query_order.objects.filter(work_id=work_id).update(query_per=1) ## 钉钉及email站内信推送 return Response('查询工单已提交,等待管理员审核!') elif request.data['mode'] == 'agree': work_id = request.data['work_id'] query_info = query_order.objects.filter(work_id=work_id).order_by('-id').first() query_order.objects.filter(work_id=work_id).update(query_per=1) userinfo = Account.objects.filter(username=query_info.username).first() try: thread = threading.Thread(target=push_message, args=( {'to_user': query_info.username, 'workid': query_info.work_id}, 6, query_info.username, userinfo.email, work_id, '同意')) thread.start() except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return Response('查询工单状态已更新!') elif request.data['mode'] == 'disagree': work_id = request.data['work_id'] query_order.objects.filter(work_id=work_id).update(query_per=0) query_info = query_order.objects.filter(work_id=work_id).order_by('-id').first() userinfo = Account.objects.filter(username=query_info.username).first() try: thread = threading.Thread(target=push_message, args=( {'to_user': query_info.username, 'workid': query_info.work_id}, 7, query_info.username, userinfo.email, work_id, '驳回')) thread.start() except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return Response('查询工单状态已更新!') elif request.data['mode'] == 'status': try: status = query_order.objects.filter(username=request.user).order_by('-id').first() return Response(status.query_per) except: return Response(0) elif request.data['mode'] == 'end': try: query_order.objects.filter(username=request.data['username']).order_by('-id').update(query_per=3) return Response('已结束查询!') except Exception as e: return HttpResponse(e) elif request.data['mode'] == 'info': tablelist = [] highlist = [] database = query_order.objects.filter(username=request.user).order_by('-id').first() _connection = DatabaseList.objects.filter(connection_name=database.connection_name).first() with con_database.SQLgo(ip=_connection.ip, user=_connection.username, password=_connection.password, port=_connection.port) as f: dataname = f.query_info(sql='show databases') children = [] ignore = exclued_db_list() for index, uc in sorted(enumerate(dataname), reverse=True): for cc in ignore: if uc['Database'] == cc: del dataname[index] for i in dataname: with con_database.SQLgo(ip=_connection.ip, user=_connection.username, password=_connection.password, port=_connection.port, db=i['Database']) as f: tablename = f.query_info(sql='show tables') highlist.append({'vl': i['Database'], 'meta': '库名'}) for c in tablename: key = 'Tables_in_%s' % i['Database'] highlist.append({'vl': c[key], 'meta': '表名'}) children.append({ 'title': c[key] }) tablelist.append({ 'title': i['Database'], 'children': children }) children = [] data = [{ 'title': database.connection_name, 'expand': 'true', 'children': tablelist }] return Response({'info': json.dumps(data), 'status': database.export, 'highlight': highlist})
def put(self, request, args: str=None): ''' :argument 工单确认执行,驳回,二次检测接口。 :param category 根据获得的category值执行具体的操作逻辑 :return 提交结果信息 ''' try: category = request.data['type'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') else: DJANGO_INFO.info(request.data) if category == 0: try: from_user = request.data['from_user'] to_user = request.data['to_user'] text = request.data['text'] order_id = request.data['id'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: SqlOrder.objects.filter(id=order_id).update(status=0) _tmpData = SqlOrder.objects.filter(id=order_id).values( 'work_id', 'bundle_id' ).first() title = '工单:' + _tmpData['work_id'] + '驳回通知' Usermessage.objects.get_or_create( from_user=from_user, time=util.date(), title=title, content=text, to_user=to_user, state='unread' ) rejected_push_messages(_tmpData, to_user, addr_ip, text).start() return Response('操作成功,该请求已驳回!') except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) elif category == 1: try: from_user = request.data['from_user'] to_user = request.data['to_user'] order_id = request.data['id'] audit_id = request.data['audit'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: DJANGO_INFO.info(f'{addr_ip}, {order_id}, {from_user}, {to_user}') '''audit''' if audit_id == 1: SqlOrder.objects.filter(id=order_id).filter(username=from_user).update(status=3) order_push_message(addr_ip, order_id, from_user, to_user).start() return Response('工单执行成功!请通过记录页面查看具体执行结果') else: SqlOrder.objects.filter(id=order_id).filter(assigned=from_user).update(status=3) return Response('工单审批成功!请通过记录页面查看具体审批结果') except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) elif category == 'test': try: base = request.data['base'] order_id = request.data['id'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: sql = SqlOrder.objects.filter(id=order_id).first() data = DatabaseList.objects.filter(id=sql.bundle_id).first() info = { 'host': data.ip, 'user': data.username, 'password': data.password, 'db': base, 'port': data.port } try: with call_inception.Inception(LoginDic=info) as test: res = test.Check(sql=sql.sql) return Response({'result': res, 'status': 200}) except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return Response({'status': '500'})
def put(self, request, args=None): try: type = request.data['type'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') else: if type == 0: try: from_user = request.data['from_user'] to_user = request.data['to_user'] text = request.data['text'] id = request.data['id'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: SqlOrder.objects.filter(id=id).update(status=0) _tmpData = SqlOrder.objects.filter(id=id).values( 'work_id', 'bundle_id' ).first() title = '工单:' + _tmpData['work_id'] + '驳回通知' Usermessage.objects.get_or_create( from_user=from_user, time=util.date(), title=title, content=text, to_user=to_user, state='unread' ) rejected_push_messages(_tmpData, to_user, addr_ip, text).start() return Response('操作成功,该请求已驳回!') except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) elif type == 1: try: from_user = request.data['from_user'] to_user = request.data['to_user'] id = request.data['id'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: SqlOrder.objects.filter(id=id).update(status=3) order_push_message(addr_ip, id, from_user, to_user).start() return Response('工单执行成功!请通过记录页面查看具体执行结果') except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) elif type == 'test': try: base = request.data['base'] id = request.data['id'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: sql = SqlOrder.objects.filter(id=id).first() data = DatabaseList.objects.filter(id=sql.bundle_id).first() info = { 'host': data.ip, 'user': data.username, 'password': data.password, 'db': base, 'port': data.port } try: with call_inception.Inception(LoginDic=info) as test: res = test.Check(sql=sql.sql) return Response({'result': res, 'status': 200}) except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return Response({'status': '500'})
def put(self, request, args=None): try: type = request.data['type'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') else: if type == 0: try: from_user = request.data['from_user'] to_user = request.data['to_user'] text = request.data['text'] id = request.data['id'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: SqlOrder.objects.filter(id=id).update(status=0) _tmpData = SqlOrder.objects.filter(id=id).values( 'work_id', 'bundle_id').first() title = '工单:' + _tmpData['work_id'] + '驳回通知' Usermessage.objects.get_or_create(from_user=from_user, time=util.date(), title=title, content=text, to_user=to_user, state='unread') content = DatabaseList.objects.filter( id=_tmpData['bundle_id']).first() mail = Account.objects.filter(username=to_user).first() tag = globalpermissions.objects.filter( authorization='global').first() ret_info = '操作成功,该请求已驳回!' if tag is None or tag.dingding == 0: pass else: try: if content.url: util.dingding( content= '工单驳回通知\n工单编号:%s\n发起人:%s\n地址:%s\n驳回说明:%s\n状态:驳回' % (_tmpData['work_id'], to_user, addr_ip, text), url=content.url) except: ret_info = '工单执行成功!但是钉钉推送失败,请查看错误日志排查错误.' if tag is None or tag.email == 0: pass else: try: if mail.email: mess_info = { 'workid': _tmpData['work_id'], 'to_user': to_user, 'addr': addr_ip, 'rejected': text } put_mess = send_email.send_email( to_addr=mail.email) put_mess.send_mail(mail_data=mess_info, type=1) except: ret_info = '工单执行成功!但是邮箱推送失败,请查看错误日志排查错误.' return Response(ret_info) except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) elif type == 1: try: from_user = request.data['from_user'] to_user = request.data['to_user'] id = request.data['id'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: SqlOrder.objects.filter(id=id).update(status=3) c = SqlOrder.objects.filter(id=id).first() title = f'工单:{c.work_id}审核通过通知' ''' 根据工单编号拿出对应sql的拆解数据 ''' SQL_LIST = DatabaseList.objects.filter( id=c.bundle_id).first() ''' 发送sql语句到inception中执行 ''' with call_inception.Inception( LoginDic={ 'host': SQL_LIST.ip, 'user': SQL_LIST.username, 'password': SQL_LIST.password, 'db': c.basename, 'port': SQL_LIST.port }) as f: res = f.Execute(sql=c.sql, backup=c.backup) ''' 修改该工单编号的state状态 ''' SqlOrder.objects.filter(id=id).update(status=1) ''' 遍历返回结果插入到执行记录表中 ''' for i in res: SqlRecord.objects.get_or_create( date=util.date(), state=i['stagestatus'], sql=i['sql'], area=SQL_LIST.computer_room, name=SQL_LIST.connection_name, error=i['errormessage'], base=c.basename, workid=c.work_id, person=c.username, reviewer=c.assigned, affectrow=i['affected_rows'], sequence=i['sequence'], backup_dbname=i['backup_dbname']) ''' 通知消息 ''' Usermessage.objects.get_or_create(from_user=from_user, time=util.date(), title=title, content='该工单已审核通过!', to_user=to_user, state='unread') ''' Dingding ''' content = DatabaseList.objects.filter( id=c.bundle_id).first() mail = Account.objects.filter(username=to_user).first() tag = globalpermissions.objects.filter( authorization='global').first() ret_info = '操作成功,该请求已同意!并且已在相应库执行!详细执行信息请前往执行记录页面查看!' if tag is None or tag.dingding == 0: pass else: try: if content.url: util.dingding( content= '工单执行通知\n工单编号:%s\n发起人:%s\n地址:%s\n工单备注:%s\n状态:同意\n备注:%s' % (c.work_id, c.username, addr_ip, c.text, content.after), url=content.url) except: ret_info = '工单执行成功!但是钉钉推送失败,请查看错误日志排查错误.' if tag is None or tag.email == 0: pass else: try: if mail.email: mess_info = { 'workid': c.work_id, 'to_user': c.username, 'addr': addr_ip, 'text': c.text, 'note': content.after } put_mess = send_email.send_email( to_addr=mail.email) put_mess.send_mail(mail_data=mess_info, type=0) except: ret_info = '工单执行成功!但是邮箱推送失败,请查看错误日志排查错误.' return Response(ret_info) except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) elif type == 'test': try: base = request.data['base'] id = request.data['id'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: sql = SqlOrder.objects.filter(id=id).first() data = DatabaseList.objects.filter( id=sql.bundle_id).first() info = { 'host': data.ip, 'user': data.username, 'password': data.password, 'db': base, 'port': data.port } try: with call_inception.Inception(LoginDic=info) as test: res = test.Check(sql=sql.sql) return Response({'result': res, 'status': 200}) except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return Response({'status': '500'})
def put(self, request, args: str = None): if request.data['mode'] == 'put': instructions = request.data['instructions'] connection_name = request.data['connection_name'] computer_room = request.data['computer_room'] timer = int(request.data['timer']) export = request.data['export'] audit = request.data['audit'] un_init = util.init_conf() query_switch = ast.literal_eval(un_init['other']) query_per = 2 work_id = util.workId() if not query_switch['query']: query_per = 1 userinfo = Account.objects.filter(username=audit, group='admin').first() thread = threading.Thread( target=push_message, args=({'to_user': request.user, 'workid': work_id}, 5, request.user, userinfo.email, work_id, '提交') ) thread.start() query_order.objects.create( work_id=work_id, instructions=instructions, username=request.user, timer=timer, date=util.date(), query_per=query_per, connection_name=connection_name, computer_room=computer_room, export=export, audit=audit, time=util.date() ) if not query_switch['query']: t = threading.Thread(target=query_worklf.query_callback, args=(timer, work_id)) t.start() ## 钉钉及email站内信推送 return Response('查询工单已提交,等待管理员审核!') elif request.data['mode'] == 'agree': work_id = request.data['work_id'] query_info = query_order.objects.filter(work_id=work_id).order_by('-id').first() t = threading.Thread(target=query_worklf.query_callback, args=(query_info.timer, work_id)) t.start() userinfo = Account.objects.filter(username=query_info.username).first() thread = threading.Thread(target=push_message, args=( {'to_user': query_info.username, 'workid': query_info.work_id}, 6, query_info.username, userinfo.email, work_id, '同意')) thread.start() return Response('查询工单状态已更新!') elif request.data['mode'] == 'disagree': work_id = request.data['work_id'] query_order.objects.filter(work_id=work_id).update(query_per=0) query_info = query_order.objects.filter(work_id=work_id).order_by('-id').first() userinfo = Account.objects.filter(username=query_info.username).first() thread = threading.Thread(target=push_message, args=( {'to_user': query_info.username, 'workid': query_info.work_id}, 7, query_info.username, userinfo.email, work_id, '驳回')) thread.start() return Response('查询工单状态已更新!') elif request.data['mode'] == 'status': try: status = query_order.objects.filter(username=request.user).order_by('-id').first() return Response(status.query_per) except: return Response(0) elif request.data['mode'] == 'end': try: query_order.objects.filter(username=request.user).order_by('-id').update(query_per=3) return Response('结束查询工单成功!') except Exception as e: return Response(e) elif request.data['mode'] == 'info': tablelist = [] database = query_order.objects.filter(username=request.user).order_by('-id').first() _connection = DatabaseList.objects.filter(connection_name=database.connection_name).first() with con_database.SQLgo(ip=_connection.ip, user=_connection.username, password=_connection.password, port=_connection.port) as f: dataname = f.query_info(sql='show databases') children = [] ignore = ['information_schema', 'sys', 'performance_schema', 'mysql'] for index, uc in enumerate(dataname): for cc in ignore: if uc['Database'] == cc: del dataname[index] index = index - 1 for i in dataname: with con_database.SQLgo(ip=_connection.ip, user=_connection.username, password=_connection.password, port=_connection.port, db=i['Database']) as f: tablename = f.query_info(sql='show tables') for c in tablename: key = 'Tables_in_%s' % i['Database'] children.append({ 'title': c[key] }) tablelist.append({ 'title': i['Database'], 'children': children }) children = [] data = [{ 'title': database.connection_name, 'expand': 'true', 'children': tablelist }] return Response({'info': json.dumps(data), 'status': database.export})
def put(self, request, args: str = None): if request.data['mode'] == 'put': instructions = request.data['instructions'] connection_name = request.data['connection_name'] computer_room = request.data['computer_room'] timer = int(request.data['timer']) export = request.data['export'] audit = request.data['audit'] un_init = util.init_conf() query_switch = ast.literal_eval(un_init['other']) query_per = 2 work_id = util.workId() if not query_switch['query']: query_per = 1 userinfo = Account.objects.filter(username=audit, group='admin').first() thread = threading.Thread(target=push_message, args=({ 'to_user': request.user, 'workid': work_id }, 5, request.user, userinfo.email, work_id, '提交')) thread.start() query_order.objects.create(work_id=work_id, instructions=instructions, username=request.user, timer=timer, date=util.date(), query_per=query_per, connection_name=connection_name, computer_room=computer_room, export=export, audit=audit, time=util.date()) if not query_switch['query']: t = threading.Thread(target=query_worklf.query_callback, args=(timer, work_id)) t.start() ## 钉钉及email站内信推送 return Response('查询工单已提交,等待管理员审核!') elif request.data['mode'] == 'agree': work_id = request.data['work_id'] query_info = query_order.objects.filter( work_id=work_id).order_by('-id').first() t = threading.Thread(target=query_worklf.query_callback, args=(query_info.timer, work_id)) t.start() userinfo = Account.objects.filter( username=query_info.username).first() thread = threading.Thread(target=push_message, args=({ 'to_user': query_info.username, 'workid': query_info.work_id }, 6, query_info.username, userinfo.email, work_id, '同意')) thread.start() return Response('查询工单状态已更新!') elif request.data['mode'] == 'disagree': work_id = request.data['work_id'] query_order.objects.filter(work_id=work_id).update(query_per=0) query_info = query_order.objects.filter( work_id=work_id).order_by('-id').first() userinfo = Account.objects.filter( username=query_info.username).first() thread = threading.Thread(target=push_message, args=({ 'to_user': query_info.username, 'workid': query_info.work_id }, 7, query_info.username, userinfo.email, work_id, '驳回')) thread.start() return Response('查询工单状态已更新!') elif request.data['mode'] == 'status': try: status = query_order.objects.filter( username=request.user).order_by('-id').first() return Response(status.query_per) except: return Response(0) elif request.data['mode'] == 'end': try: query_order.objects.filter( username=request.user).order_by('-id').update(query_per=3) return Response('结束查询工单成功!') except Exception as e: return Response(e) elif request.data['mode'] == 'info': tablelist = [] database = query_order.objects.filter( username=request.user).order_by('-id').first() _connection = DatabaseList.objects.filter( connection_name=database.connection_name).first() with con_database.SQLgo(ip=_connection.ip, user=_connection.username, password=_connection.password, port=_connection.port) as f: dataname = f.query_info(sql='show databases') children = [] ignore = [ 'information_schema', 'sys', 'performance_schema', 'mysql' ] for index, uc in enumerate(dataname): for cc in ignore: if uc['Database'] == cc: del dataname[index] index = index - 1 for i in dataname: with con_database.SQLgo(ip=_connection.ip, user=_connection.username, password=_connection.password, port=_connection.port, db=i['Database']) as f: tablename = f.query_info(sql='show tables') for c in tablename: key = 'Tables_in_%s' % i['Database'] children.append({'title': c[key]}) tablelist.append({ 'title': i['Database'], 'children': children }) children = [] data = [{ 'title': database.connection_name, 'expand': 'true', 'children': tablelist }] return Response({ 'info': json.dumps(data), 'status': database.export })
def put(self, request, args: str = None): ''' :argument 工单确认执行,驳回,二次检测接口。 :param category 根据获得的category值执行具体的操作逻辑 :return 提交结果信息 ''' try: category = request.data['type'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') else: if category == 0: try: from_user = request.data['from_user'] to_user = request.data['to_user'] text = request.data['text'] order_id = request.data['id'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: SqlOrder.objects.filter(id=order_id).update(status=0) _tmpData = SqlOrder.objects.filter(id=order_id).values( 'work_id', 'bundle_id' ).first() title = '工单:' + _tmpData['work_id'] + '驳回通知' Usermessage.objects.get_or_create( from_user=from_user, time=util.date(), title=title, content=text, to_user=to_user, state='unread' ) rejected_push_messages(_tmpData, to_user, addr_ip, text).start() return Response('操作成功,该请求已驳回!') except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) elif category == 1: try: from_user = request.data['from_user'] to_user = request.data['to_user'] order_id = request.data['id'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: SqlOrder.objects.filter(id=order_id).update(status=3) order_push_message(addr_ip, order_id, from_user, to_user).start() return Response('工单执行成功!请通过记录页面查看具体执行结果') except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) elif category == 2: try: perform = request.data['perform'] work_id = request.data['work_id'] username = request.data['username'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: mail = Account.objects.filter(username=perform).first() SqlOrder.objects.filter(work_id=work_id).update(assigned=perform) threading.Thread(target=push_message, args=( {'to_user': username, 'workid': work_id, 'addr': addr_ip}, 9, request.user, mail.email, work_id, '已提交执行人')).start() return Response('工单已提交执行人!') elif category == 'test': try: base = request.data['base'] order_id = request.data['id'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: sql = SqlOrder.objects.filter(id=order_id).first() if not sql.sql: return Response({'status': '工单内无sql语句!'}) data = DatabaseList.objects.filter(id=sql.bundle_id).first() info = { 'host': data.ip, 'user': data.username, 'password': data.password, 'db': base, 'port': data.port } try: with call_inception.Inception(LoginDic=info) as test: res = test.Check(sql=sql.sql) return Response({'result': res, 'status': 200}) except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return Response({'status': '请检查inception信息是否正确!'})
def put(self, request, args: str = None): ''' :argument 工单确认执行,驳回,二次检测接口。 :param category 根据获得的category值执行具体的操作逻辑 :return 提交结果信息 ''' try: category = request.data['type'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') else: if category == 0: try: from_user = request.data['from_user'] to_user = request.data['to_user'] text = request.data['text'] workid = request.data['workid'] print(request.data) except KeyError as e: print(e) CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: CloudOrder.objects.filter(workid=workid).update( status=1) _tmpData = CloudOrder.objects.filter( workid=workid).values('workid', 'username', 'assigned').first() title = '工单:' + _tmpData['workid'] + '驳回通知' Usermessage.objects.get_or_create(from_user=from_user, time=util.date(), title=title, content=text, to_user=to_user, state='unread') print('e') rejected_push_messages(_tmpData, to_user, from_user, addr_ip, text).start() return Response('操作成功,该请求已驳回!') except Exception as e: print(e) CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) elif category == 1: try: from_user = request.data['from_user'] workid = request.data['workid'] to_user = '******' except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: CloudOrder.objects.filter(workid=workid).update( status=2) order_push_message(addr_ip, workid, from_user, to_user).run() return Response('管理员已同意执行工单,请联系管理员查看具体进度') except Exception as e: print(e) CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) elif category == 6: try: from_user = request.data['from_user'] workid = request.data['workid'] to_user = '******' except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: CloudOrder.objects.filter(workid=workid).update( status=6) order_result_message(addr_ip, workid, from_user, to_user).run() return Response('管理员已执行完成工单') except Exception as e: print(e) CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500)
def put(self, request, args: str = None): if request.data['mode'] == 'put': instructions = request.data['instructions'] connection_name = request.data['connection_name'] computer_room = request.data['computer_room'] real = request.data['real_name'] export = request.data['export'] audit = request.data['audit'] un_init = util.init_conf() query_switch = ast.literal_eval(un_init['other']) query_per = 2 work_id = util.workId() if not query_switch['query']: query_per = 2 else: userinfo = Account.objects.filter(username=audit, group='admin').first() try: thread = threading.Thread(target=push_message, args=({ 'to_user': request.user, 'workid': work_id }, 5, request.user, userinfo.email, work_id, '提交')) thread.start() except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') query_order.objects.create(work_id=work_id, instructions=instructions, username=request.user, date=util.date(), query_per=query_per, connection_name=connection_name, computer_room=computer_room, export=export, audit=audit, time=util.date(), real_name=real) if not query_switch['query']: query_order.objects.filter(work_id=work_id).update(query_per=1) ## 钉钉及email站内信推送 return Response('查询工单已提交,等待管理员审核!') elif request.data['mode'] == 'agree': work_id = request.data['work_id'] query_info = query_order.objects.filter( work_id=work_id).order_by('-id').first() query_order.objects.filter(work_id=work_id).update(query_per=1) userinfo = Account.objects.filter( username=query_info.username).first() try: thread = threading.Thread(target=push_message, args=({ 'to_user': query_info.username, 'workid': query_info.work_id }, 6, query_info.username, userinfo.email, work_id, '同意')) thread.start() except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return Response('查询工单状态已更新!') elif request.data['mode'] == 'disagree': work_id = request.data['work_id'] query_order.objects.filter(work_id=work_id).update(query_per=0) query_info = query_order.objects.filter( work_id=work_id).order_by('-id').first() userinfo = Account.objects.filter( username=query_info.username).first() try: thread = threading.Thread(target=push_message, args=({ 'to_user': query_info.username, 'workid': query_info.work_id }, 7, query_info.username, userinfo.email, work_id, '驳回')) thread.start() except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return Response('查询工单状态已更新!') elif request.data['mode'] == 'status': try: status = query_order.objects.filter( username=request.user).order_by('-id').first() return Response(status.query_per) except: return Response(0) elif request.data['mode'] == 'end': try: query_order.objects.filter( username=request.data['username']).order_by('-id').update( query_per=3) return Response('已结束查询!') except Exception as e: return HttpResponse(e) elif request.data['mode'] == 'info': tablelist = [] highlist = [] database = query_order.objects.filter( username=request.user).order_by('-id').first() _connection = DatabaseList.objects.filter( connection_name=database.connection_name).first() with con_database.SQLgo(ip=_connection.ip, user=_connection.username, password=_connection.password, port=_connection.port) as f: dataname = f.query_info(sql='show databases') children = [] ignore = exclued_db_list() for index, uc in sorted(enumerate(dataname), reverse=True): for cc in ignore: if uc['Database'] == cc: del dataname[index] for i in dataname: with con_database.SQLgo(ip=_connection.ip, user=_connection.username, password=_connection.password, port=_connection.port, db=i['Database']) as f: tablename = f.query_info(sql='show tables') highlist.append({'vl': i['Database'], 'meta': '库名'}) for c in tablename: key = 'Tables_in_%s' % i['Database'] highlist.append({'vl': c[key], 'meta': '表名'}) children.append({'title': c[key]}) tablelist.append({ 'title': i['Database'], 'children': children }) children = [] data = [{ 'title': database.connection_name, 'expand': 'true', 'children': tablelist }] return Response({ 'info': json.dumps(data), 'status': database.export, 'highlight': highlist })
def put(self, request, args=None): try: type = request.data['type'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') else: if type == 0: try: from_user = request.data['from_user'] to_user = request.data['to_user'] text = request.data['text'] id = request.data['id'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: SqlOrder.objects.filter(id=id).update(status=0) _tmpData = SqlOrder.objects.filter(id=id).values( 'work_id', 'bundle_id').first() title = '工单:' + _tmpData['work_id'] + '驳回通知' Usermessage.objects.get_or_create(from_user=from_user, time=util.date(), title=title, content=text, to_user=to_user, state='unread') content = DatabaseList.objects.filter( id=_tmpData['bundle_id']).first() if content.url: util.dingding(content='工单驳回通知\n' + text, url=content.url) return Response('操作成功,该请求已驳回!') except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) elif type == 1: try: from_user = request.data['from_user'] to_user = request.data['to_user'] id = request.data['id'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: c = SqlOrder.objects.filter(id=id).first() title = f'工单:{c.work_id}审核通过通知' ''' 根据工单编号拿出对应sql的拆解数据 ''' SQL_LIST = DatabaseList.objects.filter( id=c.bundle_id).first() ''' 发送sql语句到inception中执行 ''' with call_inception.Inception( LoginDic={ 'host': SQL_LIST.ip, 'user': SQL_LIST.username, 'password': SQL_LIST.password, 'db': c.basename, 'port': SQL_LIST.port }) as f: res = f.Execute(sql=c.sql, backup=c.backup) ''' 遍历返回结果插入到执行记录表中 ''' for i in res: SqlRecord.objects.get_or_create( date=util.date(), state=i['stagestatus'], sql=i['sql'], area=SQL_LIST.computer_room, name=SQL_LIST.connection_name, error=i['errormessage'], base=c.basename, workid=c.work_id, person=c.username, reviewer=from_user, affectrow=i['affected_rows'], sequence=i['sequence'], backup_dbname=i['backup_dbname']) if c.type == 0 and \ i['errlevel'] == 0 and \ i['sql'].find('use') == -1 and \ i['stagestatus'] != 'Audit completed': data = testddl.AutomaticallyDDL( sql=" ".join(i['sql'].split())) if data['mode'] == 'edit': SqlDictionary.objects.filter( BaseName=data['BaseName'], TableName=data['TableName'], Field=data['Field']).update( Type=data['Type'], Null=data['Null'], Default=data['Default']) elif data['mode'] == 'add': SqlDictionary.objects.get_or_create( Type=data['Type'], Null=data['Null'], Default=data['Default'], Extra=data['COMMENT'], BaseName=data['BaseName'], TableName=data['TableName'], Field=data['Field'], TableComment='', Name=SQL_LIST.connection_name) elif data['mode'] == 'del': SqlDictionary.objects.filter( BaseName=data['BaseName'], TableName=data['TableName'], Field=data['Field'], Name=SQL_LIST.connection_name ).delete() ''' 修改该工单编号的state状态 ''' SqlOrder.objects.filter(id=id).update(status=1) ''' 通知消息 ''' Usermessage.objects.get_or_create(from_user=from_user, time=util.date(), title=title, content='该工单已审核通过!', to_user=to_user, state='unread') ''' Dingding ''' content = DatabaseList.objects.filter( id=c.bundle_id).first() if content.url: util.dingding(content='工单执行通知\n' + content.after, url=content.url) return Response( '操作成功,该请求已同意!并且已在相应库执行!详细执行信息请前往执行记录页面查看!') except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) elif type == 'test': try: base = request.data['base'] id = request.data['id'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: sql = SqlOrder.objects.filter(id=id).first() data = DatabaseList.objects.filter( id=sql.bundle_id).first() info = { 'host': data.ip, 'user': data.username, 'password': data.password, 'db': base } try: with call_inception.Inception(LoginDic=info) as test: res = test.Check(sql=sql.sql) return Response({'result': res, 'status': 200}) except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return Response({'status': '500'})
def put(self, request, args: str = None): ''' :argument 工单确认执行,驳回,二次检测接口。 :param category 根据获得的category值执行具体的操作逻辑 :return 提交结果信息 ''' try: category = request.data['type'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') else: if category == 0: try: from_user = request.data['from_user'] to_user = request.data['to_user'] text = request.data['text'] order_id = request.data['id'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: SqlOrder.objects.filter(id=order_id).update(status=0) _tmpData = SqlOrder.objects.filter(id=order_id).values( 'work_id', 'bundle_id').first() title = '工单:' + _tmpData['work_id'] + '驳回通知' Usermessage.objects.get_or_create(from_user=from_user, time=util.date(), title=title, content=text, to_user=to_user, state='unread') rejected_push_messages(_tmpData, to_user, addr_ip, text).start() return Response('操作成功,该请求已驳回!') except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) elif category == 1: try: from_user = request.data['from_user'] to_user = request.data['to_user'] order_id = request.data['id'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: try: SqlOrder.objects.filter(id=order_id).update(status=3) order_push_message(addr_ip, order_id, from_user, to_user).start() return Response('工单执行成功!请通过记录页面查看具体执行结果') except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) elif category == 2: try: perform = request.data['perform'] work_id = request.data['work_id'] username = request.data['username'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: mail = Account.objects.filter(username=username).first() SqlOrder.objects.filter(work_id=work_id).update( assigned=perform) threading.Thread(target=push_message, args=({ 'to_user': request.user, 'workid': work_id }, 2, request.user, mail.email, work_id, '已同意')).start() return Response('工单已提交执行人!') elif category == 'test': try: base = request.data['base'] order_id = request.data['id'] except KeyError as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return HttpResponse(status=500) else: sql = SqlOrder.objects.filter(id=order_id).first() if not sql.sql: return Response({'status': '工单内无sql语句!'}) data = DatabaseList.objects.filter( id=sql.bundle_id).first() info = { 'host': data.ip, 'user': data.username, 'password': data.password, 'db': base, 'port': data.port } try: with call_inception.Inception(LoginDic=info) as test: res = test.Check(sql=sql.sql) return Response({'result': res, 'status': 200}) except Exception as e: CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}') return Response({'status': '请检查inception信息是否正确!'})