def black_list(del_id=None): produce.Async_log(g.user, request.url) db = db_op.haproxy_blacklist VAL = [] try: val = db.query.with_entities( db.id, db.addtime, db.ip, db.rule, db.expire).filter(db.stats == '0').order_by( desc(db.id)).limit(1000).all() if val: tables = ['触发日期', '异常IP', 'IP归属地', '触发规则', '自动解封日期', ' 操作'] if del_id: db.query.filter(db.id == str(del_id)).update({db.stats: '2'}) db_op.DB.session.commit() val = db.query.with_entities( db.id, db.addtime, db.ip, db.rule, db.expire).filter(db.stats == '0').order_by( desc(db.addtime)).limit(1000).all() for va in val: va = list(va) va.insert(3, ip_area.Search(str(va[2]))) VAL.append(va) return render_template('black_list.html', Main_Infos=g.main_infos, tables=tables, values=VAL) else: flash('获取数据错误!') return render_template('Message_static.html', Main_Infos=g.main_infos) except Exception as e: flash(e) return render_template('Message_static.html', Main_Infos=g.main_infos)
def deployment_delete(): try: produce.Async_log(g.user, request.url) # Delete deployment dm_name = "weatherv3" values = db_k8s.query.with_entities( db_k8s.project, db_k8s.image, db_k8s.container_port, db_k8s.replicas, db_k8s.re_requests, db_k8s.re_limits).filter(db_k8s.deployment == dm_name).order_by( desc(db_k8s.id)).limit(1).all() if values: project, image, container_port, replicas, re_requests, re_limits = values[ 0] k8s = k8s_resource.k8s_object(dm_name, image, container_port, replicas, re_requests, re_limits) if k8s.delete_deployment(): v = db_k8s(project=project, image=image, container_port=container_port, replicas=replicas, re_requests=re_requests, re_limits=re_limits, action='delete', update_date=time.strftime('%Y-%m-%d', time.localtime()), update_time=time.strftime('%H:%M:%S', time.localtime())) db_op.DB.session.add(v) db_op.DB.session.commit() except Exception as e: logging.error(e) finally: return render_template('Message.html')
def login(): form = MyForm.MyForm_login() form.name.label = '用户名:' form.password.label = '密码:' user = request.cookies.get('user') if user: Incr = Redis.incr('%s_Incr' % user) else: Incr = 0 if form.submit.data: if form.name.data and form.password.data: user = form.name.data pw = form.password.data Key_Incr = '%s_Incr' % user Key_Lock = '%s_lock' % user try: if Incr >= 30: raise flash('该帐号异常登陆,已被锁定3分钟!') if Incr >= 5: if form.code.data: if str(form.code.data) != str(session['verify_code']): raise flash('输入验证码错误!') else: raise flash('请输入验证码,看不清点击验证码刷新!') va_p = db_op.idc_users.query.filter( and_(db_op.idc_users.name == user, db_op.idc_users.passwd == Md5.Md5_make(pw))).first() produce.Async_log(user, request.url) if va_p: URL = url_for('index.index') if pw == app.config.get('INIT_OP_PASSWORD'): URL = url_for('pw.pw') flash('请修改初始密码!') timestamp = None if form.remember_me.data: timestamp = check.timestamp(7) ID = produce.Produce(length=24, chars=string.hexdigits) app_resp = make_response(redirect(URL)) app_resp.set_cookie('user', user, expires=timestamp) app_resp.set_cookie('ID', ID, expires=timestamp) Redis.set('OP_ID_%s' % user, ID) Redis.delete(Key_Lock) Redis.delete(Key_Incr) return app_resp else: Redis.incr(Key_Incr) if Incr >= 30: Redis.set(Key_Lock, 'True') Redis.expire(Key_Incr, 60) Redis.expire(Key_Lock, 180) flash('用户名或者密码错误!') URL = url_for('login.login') app_resp = make_response(redirect(URL)) app_resp.set_cookie('user', user) return app_resp except Exception as e: if 'old' not in str(e): flash(str(e)) return render_template('login.html', form=form, verify_incr=Incr)
def update_java(): produce.Async_log(g.user, request.url) K = '%s_%s' %(g.user,g.secret_key) messageKey = '%s_update_java' % K taskKey = 'update_java' form = MyForm.MyForm_updateJboss() if form.submit.data: try: if form.text.data: tags = form.text.data.strip().splitlines() assert len(tags)==1,'Can only execute a project at a time!' project = form.text.data.strip() warname = project.split('-')[0] Action = form.selectAction.data Gray = form.Gray.data Type = 1 dbTable = db_op.java_list #灰度发布 if Gray: ServerList = dbTable.query.with_entities(dbTable.ip, dbTable.user).filter(db_op.DB.and_(dbTable.project == warname, dbTable.type == Type,dbTable.Gray == '1')).limit(1).all() if not ServerList: ServerList = dbTable.query.with_entities(dbTable.ip, dbTable.user).filter(db_op.DB.and_(dbTable.project == warname, dbTable.type == Type)).limit(1).all() loging.write(ServerList[:]) if ServerList: for ip, username in ServerList: dbTable.query.filter(db_op.DB.and_(dbTable.ip == ip, dbTable.user == username)).update({dbTable.Gray:'1'}) else: flash('%s Not found' % warname) return render_template('Message.html') else: ServerList = dbTable.query.with_entities(dbTable.ip,dbTable.user).filter(db_op.DB.and_(dbTable.project == warname,dbTable.type == Type)).all() if ServerList: information = {} information['warname'] = warname information['project'] = project information['ServerList'] = ServerList information['Action'] = Action information['key'] = messageKey information['Gray'] = Gray myRedis.delete(messageKey) myRedis.lpush(taskKey,information) mysql_operation = Mysql.mysql_op(g.user,Action,Type,project,Gray) mysql_operation.op_operation() Scheduler = produce.Scheduler_publish() Scheduler = Scheduler.Scheduler_mem(Scheduler.job_update_java) Scheduler.start() else: flash('%s Not found' % warname) return render_template('Message.html') except Exception as e: flash(e) return render_template('Message.html') return render_template('java_update_show.html') return render_template('java_update.html',form=form)
def publish_log(flow_number=None): produce.Async_log(g.user, request.url) db_publish_log = db_op.publish_log try: if flow_number: flow_logs = db_publish_log.query.with_entities(db_publish_log.record).filter(db_publish_log.fid == int(flow_number)).all() if flow_logs: flow_logs = flow_logs[0][0].splitlines() else: flow_logs = None except Exception as e: logging.error(e) return render_template("publish_log.html",flow_logs = flow_logs)
def platform_token(action=None, id=None, args=None): produce.Async_log(g.user, request.url) db_token = db_op.platform_token tm = time.strftime('%Y-%m-%d', time.localtime()) form = MyForm.Form_platform_token() tables = ['第三方平台', '连接方式', 'Token', '颁发日期', '失效日期', '管理'] if action == 'add': expire_date = "2999-12-30" if id > 0: expire_date = datetime.datetime.now() + datetime.timedelta(days=id) expire_date = expire_date.strftime('%Y-%m-%d') try: c = db_token(platform=args, channel='api', token=Md5.Md5_make(tools.Produce(8, string.digits)), award=tm, expire=expire_date) db_op.DB.session.add(c) db_op.DB.session.commit() return render_template_string('success') except Exception as e: logging.error(e) return render_template_string('fail') if action == 'modify': try: db_token.query.filter(db_token.id == id).update( {db_token.expire: args}) db_op.DB.session.commit() return render_template_string('success') except Exception as e: logging.error(e) return render_template_string('fail') if action == 'drop': try: v = db_token.query.filter(db_token.id == id).all() for c in v: db_op.DB.session.delete(c) db_op.DB.session.commit() return render_template_string('success') except Exception as e: logging.error(e) return render_template_string('fail') vals = db_token.query.with_entities( db_token.id, db_token.platform, db_token.channel, db_token.token, db_token.award, db_token.expire).order_by(desc(db_token.id)).all() return render_template('platform_token.html', form=form, vals=vals, tables=tables, tm=tm)
def login(): form = MyForm.MyForm_login() form.name.label = '用户名:' form.password.label = '密码:' ym = time.strftime('%Y', time.localtime()) if form.submit.data: if form.name.data and form.password.data: user = form.name.data pw = form.password.data try: Key_Incr = '%s_Incr' % user Key_Lock = 'Lock_login_%s' % user if Redis.exists(Key_Incr): Incr = int(Redis.get(Key_Incr)) else: Incr = 1 if Redis.exists(Key_Lock): raise flash('该帐号异常登陆,已被锁定1分钟!') va_p = db_op.idc_users.query.filter( and_(db_op.idc_users.name == user, db_op.idc_users.passwd == Md5.Md5_make(pw))).first() produce.Async_log(user, request.url) if va_p: URL = url_for('index.index') if pw == app.config.get('INIT_OP_PASSWORD'): URL = url_for('pw.pw') flash('请修改初始密码!') timestamp = None if form.remember_me.data: timestamp = check.timestamp(7) ID = produce.Produce(length=24, chars=string.hexdigits) app_resp = make_response(redirect(URL)) app_resp.set_cookie('user', user, expires=timestamp) app_resp.set_cookie('ID', ID, expires=timestamp) Redis.set('OP_ID_%s' % user, ID) return app_resp else: Redis.set(Key_Incr, Incr + 1) if Incr >= 11: Redis.incr(Key_Lock, 'True') Redis.expire(Key_Lock, 60) flash('用户名或者密码错误,还有%s次机会重试!' % (10 - int(Incr))) URL = url_for('login.login') app_resp = make_response(redirect(URL)) app_resp.set_cookie('user', user) return app_resp except Exception as e: if 'old' not in str(e): flash(str(e)) return render_template('login.html', form=form, ym=ym)
def publish(): produce.Async_log(g.user, request.url) importlib.reload(MyForm) secret_key= tools.Produce(length=8, chars=string.digits) session['secret_key'] = secret_key K = '%s_%s' %(g.user,secret_key) Msg_Key = '%s_publish_msg' %K form = MyForm.MyForm_publish() if form.submit.data: try: if Redis.exists(Msg_Key): raise flash('上线操作过于频繁,请稍等%s秒......' %Redis.ttl(Msg_Key)) package_url = form.package_url.data describe = form.describe.data package_md5 = form.package_md5.data package_type = form.package_type.data publish_type = form.publish_type.data check_url = form.check_url.data restart = form.restart.data execute = form.execute.data rb_project = form.project.data rb_version = form.version.data gray = form.gray.data if execute == 'rollback': if not rb_project and not rb_version: raise logging.error("choice can not be empty!") if execute == 'publish': if not package_url or not package_md5 or not check_url or not describe: raise logging.error("input can not be empty!") Package_name = package_url.split('/')[-1] package_name = Package_name.replace('.zip', '') rb_project = '-'.join(package_name.split('-')[:-1]) INFOS = {'package_url': package_url, 'package_md5': package_md5, 'package_type': package_type, 'publish_type': publish_type,'user':g.user,'describe':describe.replace('"','').replace("'",''),'gray':int(gray), 'restart': restart, 'execute': execute, 'check_url': check_url.replace('https','http'), 'project': rb_project, 'version': rb_version,'channel':'web','callback_url':'None','token':'None','timestamp' :int(time.time())} #启动代码分发控制中心 Scheduler = produce.Scheduler_publish() Scheduler = Scheduler.Scheduler_mem(task_publish.Publish_center,[INFOS,Msg_Key,K]) Scheduler.start() return render_template('publish_show.html') except Exception as e: if 'old-style' not in str(e): logging.error(e) return render_template('publish.html',form=form)
def diff_file(): produce.Async_log(g.user, request.url) try: Infos = None if Redis.exists('diff_file'): Infos = Redis.hgetall('diff_file') if Infos: for host in Infos: files = eval(Infos[host]) Infos[host] = files else: flash('检查结果:线上项目均正常!') else: flash('检查结果:线上项目均正常!') except Exception as e: flash(e) return render_template('diff_file.html', Main_Infos=g.main_infos, Infos=Infos)
def update_php(): produce.Async_log(g.user, request.url) K = '%s_%s' % (g.user, g.secret_key) Key = '%s_update_php' % K publish_key = '%s_update_key' % K form = MyForm.MyForm_php() if form.submit.data: try: if Redis.exists(Key): raise flash('项目上线操作正在执行,不能并行上线操作.请稍候......') Redis.lpush(Key, 'check env......') tm = time.strftime('%Y%m%d%H%M%S', time.localtime()) Key_file_list = 'file_list_%s' % tm if form.text.data: List = form.text.data.strip().splitlines() Action = form.selectaction.data Gray = form.Gray.data else: return redirect(url_for('update_php.update_php')) lines = [line.strip() for line in List] lines = str(lines) Redis.set(Key_file_list, lines) Redis.expire(Key_file_list, 1800) Info = {} Type = 1 Info['arg'] = Type Info['action'] = Action Info['Key_file_lis'] = Key_file_list Info['gray'] = Gray Redis.rpush(publish_key, str(Info)) Redis.lpush(Key, ' --->check env pass!') Redis.lpush(Key, '-' * 80 + '\n') mysql_operation = Mysql.mysql_op(g.user, Action, Type, lines, Gray) mysql_operation.op_operation() Scheduler = produce.Scheduler_publish() Scheduler = Scheduler.Scheduler_mem(php_update.php_update, publish_key, Key) Scheduler.start() except Exception as e: Redis.lpush(Key, e) return render_template('php_update_show.html') return render_template('php_update.html', form=form)
def op_log(): produce.Async_log(g.user, request.url) db = db_op.op_log try: val = db.query.with_entities(db.date, db.time, db.ip, db.user, db.access).order_by( desc(db.id)).limit(50).all() if val: tables = ['日期', '时间', 'IP', '用户', '访问页面'] return render_template('examine.html', Main_Infos=g.main_infos, tables=tables, values=val) else: flash('获取数据错误!') return render_template('Message_static.html', Main_Infos=g.main_infos) except Exception as e: flash(e) return render_template('Message_static.html', Main_Infos=g.main_infos)
def code(): produce.Async_log(g.user, request.url) db = db_op.publish_code try: val = db.query.with_entities(db.project, db.code, db.platfrom, db.user, db.Time).order_by( desc(db.id)).limit(30).all() if val: tables = ['项目', '验证码', '平台环境', '使用人', '使用时间'] return render_template('examine.html', Main_Infos=g.main_infos, tables=tables, values=val) else: flash('获取数据错误!') return render_template('Message_static.html', Main_Infos=g.main_infos) except Exception as e: flash(e) return render_template('Message_static.html', Main_Infos=g.main_infos)
def operation(): produce.Async_log(g.user, request.url) db = db_op.op_operation try: val = db.query.with_entities(db.date, db.time, db.user, db.project, db.version, db.grade, db.action, db.Type).order_by( desc(db.id)).limit(50).all() if val: tables = ['日期', '时间', '操作人', '项目', '版本号', '等级', '操作', '发布'] return render_template('examine.html', Main_Infos=g.main_infos, tables=tables, values=val) else: flash('获取数据错误!') return render_template('Message_static.html', Main_Infos=g.main_infos) except Exception as e: flash(e) return render_template('Message_static.html', Main_Infos=g.main_infos)
def backup_mysql_results(): produce.Async_log(g.user, request.url) try: if Redis.exists('finish_backup'): Infos = Redis.lrange('finish_backup', 0, -1) if Infos: Infos = [eval(info) for info in set(Infos)] tt = time.strftime('%Y-%m-%d', time.localtime()) tables = ('日期', '备份服务器', 'MYSQL服务器', '服务器端口', ' 状态') return render_template('backup_mysql_results.html', Main_Infos=g.main_infos, Infos=Infos, tt=tt, tables=tables) else: raise flash('检查结果:线上数据库备份异常!') else: raise flash('检查结果:线上数据库备份异常!') except Exception as e: if 'old' not in str(e): flash(str(e)) return render_template('Message_static.html', Main_Infos=g.main_infos)
def image_update(): try: produce.Async_log(g.user, request.url) reload(MyForm) form = MyForm.Form_k8s_update() if form.submit.data: deployment = form.deployment.data version = form.version.data if version: new_image = "%s/%s:%s" % (docker_registry, deployment, version) new_replicas = form.replicas.data redis_key = 'op_k8s_update_%s' % time.strftime( '%Y%m%d%H%M%S', time.localtime()) session['redis_key'] = redis_key Scheduler = produce.Scheduler_publish() Scheduler = Scheduler.Scheduler_mem( k8s_resource.object_update, [new_image, new_replicas, version, redis_key]) Scheduler.start() return render_template('deploy_show.html') except Exception as e: logging.error(e) return render_template('k8s_update.html', form=form)
def apply(): try: produce.Async_log(g.user, request.url) dt = time.strftime('%Y-%m-%d', time.localtime()) ym = time.strftime('%Y', time.localtime()) db_approval = db_op.user_approval # 判断游客身份 if '11' in g.grade: form = MyForm.MyForm_apply() val = db_approval.query.filter( and_(db_approval.dingId == g.dingId, db_approval.status == '待审批')).all() if val: raise flash('权限还未审批,请耐心等待!') val = db_approval.query.filter( and_(db_approval.dingId == g.dingId, db_approval.status == '审批拒绝')).all() if val: raise flash('权限审批未通过!') if form.submit.data: grade = form.select.data v = db_approval(name=g.user, openid=g.openid, dingId=g.dingId, apply_time=dt, approval_time='', approval_person='', apply_grade=grade, status='待审批') db_op.DB.session.add(v) db_op.DB.session.commit() raise flash('权限申请提交完成、请等待审批!') return render_template('apply.html', form=form, ym=ym) except Exception as e: if 'old-style' not in str(e): flash(str(e)) return redirect(url_for('login.login'))
def check_login(error=None): produce.Async_log(g.user, request.url)
def check_login(exception=None): produce.Async_log(g.user, request.url)
def check_login(error=None): reload(MyForm) produce.Async_log(g.user, request.url)
def sql_query(): form = MyForm.MyForm_sql_run() if form.submit.data: #获取页面相关信息 try: db_name = form.db_name.data.strip() assert db_name, '数据库库名不能为空!' if form.sql_text.data: cmds = form.sql_text.data.strip() else: raise flash('没有SQL语句可执行!') if cmds: if cmds.endswith(';'): cmds = cmds.split(';') if len(cmds) > 6: raise flash('SQL语句查询一次不能大于5条!') #获取库表对应的主库服务器信息 db = db_idc.idc_mysqldb db_table = db_idc.idc_tableinfo for sql_cmd in cmds: if sql_cmd: sql_cmd = sql_cmd.strip() if 'limit' in sql_cmd: if int(sql_cmd.split()[-1]) > 5: raise flash('SQL语句中limit 的值不能大于5') sql_cmd = '%s;' % sql_cmd else: sql_cmd = '%s limit 5;' % sql_cmd if sql_cmd.lower().startswith('select'): table_name = sql_cmd.split('from')[1] table_name = table_name.split()[0] table_name = table_name.replace('`', '') val_ips = db.query.with_entities( db_table.ip).filter( and_(db_table.database_name == db_name, db_table.table_name == table_name)).all() if val_ips: val_ips = set([ip[0] for ip in val_ips]) else: raise flash('没有找到%s表相关信息!' % table_name) val = db.query.with_entities( db.ip, db.port, db.db).filter( and_(db.master == '是', db.ip.in_(val_ips))).all() if val: for info in val: #执行sql语句 master_ip, master_port, master_db = info if db_name in master_db.split('|'): flash('SQL语句:{0}'.format(sql_cmd)) flash('查询结果:') results = Mysql.Query_sql( master_ip, master_port, db_name, sql_cmd) if results: for result in results: result = [ str(re) for re in result ] flash('\t'.join(result)) produce.Async_log( g.user, sql_cmd) flash('--' * 40) else: raise flash('没有找到%s数据库的相关服务器信息!' % db_name) else: raise flash("%s 不符合执行规则!" % sql_cmd) else: raise flash("每条sql语句需要以分号结尾!") except Exception as e: logging.error(e) return render_template('Message_static.html', Main_Infos=g.main_infos) return render_template('mysql_query.html', Main_Infos=g.main_infos, form=form)
def check_login(error=None): produce.Async_log(g.user, request.url) importlib.reload(MyForm)
def publish_java(): produce.Async_log(g.user, request.url) K = '%s_%s' % (g.user, g.secret_key) messageKey = '%s_publish_java' % K publish_key = '%s_publish_key' % K qrcode_url = "https://op.baihe.com/qrcode_java/{0}/{1}".format( g.user, g.grade) form = MyForm.MyForm_publishJboss() if form.submit.data: Action = form.selectAction.data Type = int(form.selectType.data) Gray = form.Gray.data Way = form.selectWay.data code = form.code.data work = form.selectwork.data grade = form.selectgrade.data changelog = form.changelog.data tags = form.text.data.strip().splitlines() if tags and changelog: try: if myRedis.exists(messageKey): raise flash('项目上线操作正在执行,不能并行上线操作.请稍候......') myRedis.lpush(messageKey, 'check env......') assert len(tags) == 1, '错误:只能同时上线一个项目!' warTagName = tags[0] version = '0.0.0' if Action == 'restart': warname = warTagName elif Way == 'SVN': assert '.war.zip' in warTagName, '错误:格式错误!格式应为: baihe-xxxx-x.x.x.war.zip' warname = warTagName.split('-')[:-1] version = warTagName.split('-')[-1].replace('.war.zip', '') warname = '-'.join(warname) + '.war' elif Way == 'GIT': warname = "{0}.war".format(warTagName.split('/')[-1]) except Exception as e: flash(e) else: try: publish_time = time.strftime("%H", time.localtime()) if code: verify_key = "{0}_{1}".format(g.user, g.grade) verify_code = myRedis.get(verify_key) if verify_code == str(code): myRedis.lpush(messageKey, ' --->verify code pass!') myRedis.delete(verify_key) else: raise flash('上线码验证错误!') else: # 用户权限判断 if g.grade >= 2 and Type == 1 and int(grade) >= 5: raise flash('需申请验证码!') if g.grade >= 2 and int(grade) <= 4 and Type == 1 and ( int(publish_time) >= 17 or int(publish_time) <= 9): raise flash('仅允许在10-17点时间段进行自助操作,需申请验证码!') dbTable = db_op.java_list #灰度发布 if Gray: ServerList = dbTable.query.with_entities( dbTable.ip, dbTable.user).filter( db_op.DB.and_( dbTable.project == warname, dbTable.type == Type, dbTable.Gray == '1')).limit(1).all() if not ServerList: ServerList = dbTable.query.with_entities( dbTable.ip, dbTable.user).filter( db_op.DB.and_( dbTable.project == warname, dbTable.type == Type)).limit(1).all() loging.write(ServerList[:]) if ServerList: for ip, username in ServerList: dbTable.query.filter( db_op.DB.and_( dbTable.ip == ip, dbTable.user == username)).update( {dbTable.Gray: '1'}) else: raise flash('%s 没有在上线列表中找到!' % warname) else: ServerList = dbTable.query.with_entities( dbTable.ip, dbTable.user).filter( db_op.DB.and_(dbTable.project == warname, dbTable.type == Type)).all() if Type == 1: ServerList.append(('172.16.4.188', 'java')) if ServerList: myRedis.lpush(messageKey, ' --->check env pass!') myRedis.lpush(messageKey, '-' * 80 + '\n') information = {} information['warname'] = warname information['warTagName'] = warTagName information['ServerList'] = ServerList information['Action'] = Action information['Gray'] = Gray information['Type'] = Type information['Way'] = Way myRedis.lpush(publish_key, information) mysql_operation = Mysql.mysql_op( g.user, Action, Type, warname, version, Gray, work, grade, changelog) mysql_operation.op_operation() Scheduler = produce.Scheduler_publish() Scheduler = Scheduler.Scheduler_mem( java_publish.java_publish, publish_key, messageKey) Scheduler.start() else: raise flash('%s 没有在上线列表中找到!' % warname) except Exception as e: if 'old' not in str(e): flash(e) else: return render_template('java_publish_show.html') else: flash("错误:文本框内容不能为空!") return render_template('java_publish.html', form=form, qrcode_url=qrcode_url)
def update_java(): produce.Async_log(g.user, request.url) K = '%s_%s' % (g.user, g.secret_key) messageKey = '%s_update_java' % K publish_key = '%s_update_key' % K form = MyForm.MyForm_updateJboss() if form.submit.data: try: if form.text.data: if myRedis.exists(messageKey): raise flash('上线操作过于频繁,请稍等%s秒......' % myRedis.ttl(messageKey)) myRedis.lpush(messageKey, 'check env......') tags = form.text.data.strip().splitlines() assert len(tags) == 1, 'Can only execute a project at a time!' project = form.text.data.strip() warname = project.split('-')[0] Action = form.selectAction.data Gray = form.Gray.data Type = 1 dbTable = db_op.java_list #灰度发布 if Gray: ServerList = dbTable.query.with_entities( dbTable.ip, dbTable.user).filter( db_op.DB.and_(dbTable.project == warname, dbTable.type == Type, dbTable.Gray == '1')).limit(1).all() if not ServerList: ServerList = dbTable.query.with_entities( dbTable.ip, dbTable.user).filter( db_op.DB.and_( dbTable.project == warname, dbTable.type == Type)).limit(1).all() if ServerList: for ip, username in ServerList: dbTable.query.filter( db_op.DB.and_( dbTable.ip == ip, dbTable.user == username)).update( {dbTable.Gray: '1'}) else: flash('%s Not found' % warname) return render_template('Message_static.html', Main_Infos=g.main_infos) else: ServerList = dbTable.query.with_entities( dbTable.ip, dbTable.user).filter( db_op.DB.and_(dbTable.project == warname, dbTable.type == Type)).all() if ServerList: myRedis.lpush(messageKey, ' --->check env pass!') myRedis.lpush(messageKey, '-' * 80 + '\n') information = {} information['warname'] = warname information['project'] = project information['ServerList'] = ServerList information['Action'] = Action information['Gray'] = Gray myRedis.lpush(publish_key, information) mysql_operation = Mysql.mysql_op(g.user, Action, Type, project, Gray) mysql_operation.op_operation() Scheduler = produce.Scheduler_publish() Scheduler = Scheduler.Scheduler_mem( java_update.java_update, publish_key, messageKey) Scheduler.start() else: flash('%s Not found' % warname) return render_template('Message_static.html', Main_Infos=g.main_infos) except Exception as e: flash(e) return render_template('Message_static.html', Main_Infos=g.main_infos) return render_template('java_update_show.html', Main_Infos=g.main_infos) return render_template('java_update.html', Main_Infos=g.main_infos, form=form)
def publish_java(): produce.Async_log(g.user, request.url) K = '%s_%s' %(g.user,g.secret_key) messageKey = '%s_publish_java' % K publish_key = '%s_publish_key' % K qrcode_url = None form = MyForm.MyForm_publishJboss() if form.submit.data: Action = form.selectAction.data Type = int(form.selectType.data) Gray = form.Gray.data Way = form.selectWay.data code = form.code.data work = form.selectwork.data changelog = form.changelog.data tags = form.text.data.strip().splitlines() if tags and changelog: try: if myRedis.exists(messageKey): raise flash('上线操作过于频繁,请稍等%s秒......' %myRedis.ttl(messageKey)) assert len(tags) == 1, '错误:只能同时上线一个项目!' warTagName = tags[0] version = '0.0.0' if Action == 'restart': warname = warTagName elif Way == 'SVN': assert '.war.zip' in warTagName, '错误:格式错误!格式应为: baihe-xxxx-x.x.x.war.zip' warname = warTagName.split('-')[:-1] version = warTagName.split('-')[-1].replace('.war.zip','') warname = '-'.join(warname) + '.war' elif Way == 'GIT': warname = "{0}.war".format(warTagName.split('/')[-1]) except Exception as e: flash(e) else: try: project_db = db_op.project_level project_level = project_db.query.with_entities(project_db.level).filter(project_db.project == warname).all() # 测外不强制项目等级 if Type == 2: if project_level: project_level = int(project_level[0][0]) else: project_level = 1 else: if project_level: project_level = int(project_level[0][0]) crypto = Md5.crypto(crypto_key) qrcode_url = "https://op.baihe.com/qrcode_java/{0}/{1}/{2}/{3}".format(crypto.encrypt(g.user),g.grade,crypto.encrypt(warname),project_level) else: raise flash('没有找到该项目的对应项目等级!') publish_time = time.strftime("%H", time.localtime()) if code: verify_key = "{0}_{1}".format(g.user,warname) verify_code = myRedis.get(verify_key) if verify_code == str(code): myRedis.lpush(messageKey, ' --->verify code pass!') myRedis.expire(messageKey,30) myRedis.delete(verify_key) else: raise flash('%s 该上线码验证不通过!' %str(code)) else: # 用户权限及行为判断 tw = int(time.strftime('%w', time.localtime(time.time()))) if g.grade >= 2 and Type == 1 and Action == 'publish': if project_level >= 5: raise flash('该项目等级为%s级,需申请上线码!' % project_level) if tw in (2, 4): if project_level <= 4 and (int(publish_time) >= 17 or int(publish_time) <= 9): raise flash('仅允许在10-17点时间段进行上线操作,需申请上线码!') else: raise flash('4级及以下常规项目只限在周二和周四上线,修复BUG需申请上线码!') if g.grade >= 2 and Action == 'rollback': raise flash('没有权限进行回滚操作!') dbTable = db_op.java_list #灰度发布 if Gray: ServerList = dbTable.query.with_entities(dbTable.ip, dbTable.user).filter(db_op.DB.and_(dbTable.project == warname, dbTable.type == Type,dbTable.Gray == '1')).limit(1).all() if not ServerList: ServerList = dbTable.query.with_entities(dbTable.ip, dbTable.user).filter(db_op.DB.and_(dbTable.project == warname, dbTable.type == Type)).limit(1).all() if ServerList: for ip, username in ServerList: dbTable.query.filter(db_op.DB.and_(dbTable.ip == ip, dbTable.user == username)).update({dbTable.Gray:'1'}) else: raise flash('%s 没有在上线列表中找到!' % warname) else: ServerList = dbTable.query.with_entities(dbTable.ip,dbTable.user).filter(db_op.DB.and_(dbTable.project == warname,dbTable.type == Type)).all() if Type == 1: ServerList.append(('172.16.4.188','java')) if ServerList: myRedis.lpush(messageKey, 'check security policy......') myRedis.expire(messageKey, 30) information = {} information['warname'] = warname information['warTagName'] = warTagName information['ServerList'] = ServerList information['Action'] = Action information['Gray'] = Gray information['Type'] = Type information['Way'] = Way myRedis.lpush(publish_key,information) mysql_operation = Mysql.mysql_op(g.user,Action,Type,warname,version,Gray,work,project_level,changelog) mysql_operation.op_operation() Scheduler = produce.Scheduler_publish() Scheduler = Scheduler.Scheduler_mem(java_publish.java_publish,publish_key,messageKey) Scheduler.start() myRedis.lpush(messageKey, ' --->check pass!') myRedis.lpush(messageKey, '-' * 80 + '\n') else: raise flash('%s 没有在上线列表中找到!' % warname) except Exception as e: if 'old' not in str(e): flash(e) if qrcode_url: return render_template('java_publish.html',Main_Infos=g.main_infos, form=form, qrcode_url=qrcode_url) else: return render_template('java_publish_show.html',Main_Infos=g.main_infos) else: flash("错误:文本框内容不能为空!") return render_template('java_publish.html',Main_Infos=g.main_infos,form=form,qrcode_url=qrcode_url)
def publish_php(): produce.Async_log(g.user, request.url) K = '%s_%s' %(g.user,g.secret_key) Key = '%s_publish_php' %K form = MyForm.MyForm_php() qrcode_url = "https://xxx.baihe.com/xxx/{0}/{1}".format(g.user,g.grade) if form.submit.data: try: Redis.lpush(Key, 'check env......') if form.text.data and form.changelog.data: action = form.selectaction.data Type = int(form.selecttype.data) Way = form.selectWay.data if Type == 1: platfrom = '线上' if Type == 2: platfrom = '测外' Tags = form.text.data.strip().splitlines() Gray = form.Gray.data code = form.code.data work = form.selectwork.data grade = form.selectgrade.data changelog = form.changelog.data if Way == 'SVN': if len(Tags) > 1: raise flash('错误:只能同时上线一个项目!') else: for line in Tags: if line.startswith('#') or not line.split(): continue m = re.match(r'[0-9]', line) if m: raise flash('错误:不能以数字开头!') if not line.startswith('/'): raise flash('错误:' + line + '路径必须以"/"开头!') path = line.strip() path = path.replace('\\', '/') App = path.split('/') if len(App)<4: raise flash('错误:路径错误,无法获取项目名!') App = App[3] if len(path.split('-')) >= 2: version = path.split('-')[-1] else: raise flash('错误:项目名称格式错误!') if version.endswith('.zip'): version = version.replace('.zip', '') elif Way == 'GIT': if len(Tags) != 2: raise flash('错误:GIT上线格式不对!') elif not Tags[0].strip().startswith('http://'): raise flash('错误:' + Tags[0] + '路径需以"http://"开头!') elif not Tags[0].strip().endswith('.git'): raise flash('错误:' + Tags[0] + '应该以".git"结尾!') elif 'tag' not in Tags[1]: raise flash('错误:没有tag版本号!') path = ';'.join(Tags) path = path.replace('http://git.baihe.com/', '/') App = Tags[0].strip().split('/')[-1] App = App.split('.')[0] version = Tags[1].split('-')[-1] else: raise flash('错误:文本框内容不能为空!') except Exception as e: pass else: try: #用户权限判断 if g.grade == 2: if code: verify_key = "{0}_{1}".format(g.user,g.grade) verify_code = Redis.get(verify_key) if verify_code == str(code): Redis.lpush(Key, ' --->verify code pass!') Redis.delete(verify_key) code_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) db = db_op.publish_code db_op.DB.session.add(db(project=App, code=str(code), platfrom=platfrom, user=g.user, Time=code_time)) db_op.DB.session.commit() else: flash('上线码验证错误!') return redirect(url_for('publish_php.publish_php')) else: flash('上线码不能为空!') return redirect(url_for('publish_php.publish_php')) Redis.lpush(Key,' --->check env pass!') Redis.lpush(Key,'-'*80+'\n') db = db_op.php_list if Gray: if App == 'baihePhpGlobalLibrary_publish': val = db.query.with_entities(db.ip).filter(and_(db.Gray == '1',db.operation == 'baihe')).limit(1).all() if not val: val = db.query.with_entities(db.ip).filter(and_(db.type == '%i' % Type,db.operation == 'baihe')).limit(1).all() elif App == 'Baihe': val = db.query.with_entities(db.ip).filter(and_(db.Gray == '1',db.operation == 'hunli')).limit(1).all() if not val: val = db.query.with_entities(db.ip).filter(and_(db.type == '%i' % Type,db.operation == 'hunli')).limit(1).all() else: val = db.query.with_entities(db.ip).filter(and_(db.Gray == '1',db.project == '%s' % App)).limit(1).all() if not val: val = db.query.with_entities(db.ip).filter(and_(db.project == '%s' % App, db.type == '%i' % Type)).limit(1).all() if val: sip = [v[0].encode('UTF-8') for v in val if v] db.query.filter(and_(db.project == App, db.ip == sip[0])).update({db.Gray: '1'}) else: raise flash('%s 没有在上线列表中找到!' % App) else: if App == 'baihePhpGlobalLibrary_publish': val = db.query.with_entities(db.ip).filter(and_(db.type == '%i' %Type,db.operation == 'baihe')).all() elif App == 'Baihe': val = db.query.with_entities(db.ip).filter(and_(db.type == '%i' %Type,db.operation == 'hunli')).all() else: val = db.query.with_entities(db.ip).filter(and_(db.project == '%s' %App,db.type == '%i' %Type)).all() if val: val = set(val) sip = [v[0].encode('UTF-8') for v in val if v] else: raise flash('%s 没有在上线列表中找到!' %App) Redis.delete(Key) Info = {} Info['action'] = action Info['key'] = Key Info['path'] = path Info['app'] = App Info['sip'] = sip Info['gray'] = Gray Info['Type'] = Type Info['Way'] = Way Redis.lpush('publish_php',str(Info)) mysql_operation = Mysql.mysql_op(g.user,action,Type,App,version,Gray,work,grade,changelog) mysql_operation.op_operation() Scheduler = produce.Scheduler_publish() Scheduler = Scheduler.Scheduler_mem(Scheduler.job_publish_php) Scheduler.start() except Exception as e: if 'old' not in str(e): flash(e) Redis.lpush(Key,'End') return render_template('Message.html') return render_template('php_publish_show.html') return render_template('php_publish.html',form=form,qrcode_url = qrcode_url )
def approval(): try: produce.Async_log(g.user, request.url) dt = time.strftime('%Y-%m-%d', time.localtime()) db_approval = db_op.user_approval db_auth = db_op.user_auth db_permission = db_op.permission tables = ('申请人', '申请日期', '申请权限', '审批状态', '操作') action = tools.http_args(request, 'action') id = tools.http_args(request, 'id') status = {'allow': '审批通过', 'deny': '审批拒绝'} # 判断访问参数 if action in ('allow', 'deny') and id: #验证操作人是否真实 val = db_auth.query.filter( and_(db_auth.name == g.user, db_auth.dingId == g.dingId)).all() if val: # 修改申请权限表状态 db_approval.query.filter(and_(db_approval.id == id)).update({ db_approval.status: status[action], db_approval.approval_time: dt, db_approval.approval_person: g.user }) db_op.DB.session.commit() if action == 'allow': # 写入授权列表 vals = db_approval.query.with_entities( db_approval.name, db_approval.openid, db_approval.dingId, db_approval.apply_grade).filter( db_approval.id == id).all() name, openid, dingId, grade = vals[0] if int(grade) == 1: c = db_auth(name=name, openid=openid, dingId=dingId, grade=','.join( [str(x) for x in range(1, 11)]), token='', update_time='') else: c = db_auth(name=name, openid=openid, dingId=dingId, grade='%s,10' % grade, token='', update_time='') db_op.DB.session.add(c) db_op.DB.session.commit() except Exception as e: logging.error(e) db_op.DB.session.rollback() finally: # 获取权限列表 auths = db_permission.query.with_entities(db_permission.authid, db_permission.auth).all() auths = {val[0]: val[1] for val in auths} values = db_approval.query.with_entities( db_approval.id, db_approval.name, db_approval.apply_time, db_approval.apply_grade, db_approval.status).filter(db_approval.status == '待审批').all() return render_template('approval.html', tables=tables, values=values, auths=auths)
def mobile(): produce.Async_log(g.user, request.url) return render_template('mobile/m_index.html')
def deployment_create(): produce.Async_log(g.user, request.url) reload(MyForm) form = MyForm.Form_k8s_deploy() if form.submit.data: project = form.projects.data version = form.version.data object = form.object.data container_port = form.container_port.data ingress_port = form.ingress_port.data replicas = form.replicas.data request_cpu = form.request_cpu.data limit_cpu = form.limit_cpu.data request_mem = form.request_mem.data limit_mem = form.limit_mem.data domain = form.domain.data re_requests = {} re_limits = {} try: if object and version and container_port and replicas: if object.endswith('.war') or object.endswith('.jar'): dm_name = object.split('.')[0] image = "%s/%s:%s" % (docker_registry, dm_name, version) docker_file = "%s/%s" % (dockerfile_path, dm_name) if os.path.exists(docker_file): container_port = [ int(port) for port in container_port.split(',') ] if request_cpu and limit_cpu and request_mem and limit_mem: if float(request_cpu) > float(limit_cpu) or float( request_mem) > float(limit_mem): raise flash('限制资源不能小于请求资源!') else: re_requests = { 'cpu': request_cpu, 'memory': '%sG' % request_mem } re_limits = { 'cpu': limit_cpu, 'memory': '%sG' % limit_mem } if ingress_port: if int(ingress_port) not in [ int(port) for port in container_port ]: raise flash('对外服务端口必须是服务端口其中之一!') redis_key = 'op_k8s_create_%s' % time.strftime( '%Y%m%d%H%M%S', time.localtime()) session['redis_key'] = redis_key Scheduler = produce.Scheduler_publish() Scheduler = Scheduler.Scheduler_mem( k8s_resource.object_deploy, [ project, dm_name, version, image, container_port, ingress_port, replicas, domain, re_requests, re_limits, redis_key ]) Scheduler.start() return render_template('deploy_show.html') else: flash("%s文件路径不存在!" % docker_file) else: flash("%s包名应以.war或者.jar结尾!" % object) else: flash('必填项参数不完整!') return render_template('Message.html') except Exception as e: logging.error(e) return render_template('k8s_deploy.html', form=form)
def webssh(): produce.Async_log(g.user, request.url) url = "http://172.16.69.250:8000/" return render_template('webssh.html', url=url)
def publish_php(): produce.Async_log(g.user, request.url) K = '%s_%s' %(g.user,g.secret_key) Key = '%s_publish_php' %K publish_key = '%s_publish_key' %K qrcode_url = None form = MyForm.MyForm_php() if form.submit.data: try: if Redis.exists(Key): raise flash('上线操作过于频繁,请稍等%s秒......' %Redis.ttl(Key)) if form.text.data and form.changelog.data: action = form.selectaction.data Type = int(form.selecttype.data) Way = form.selectWay.data if Type == 1: platfrom = '线上' if Type == 2: platfrom = '测外' Tags = form.text.data.strip().splitlines() Gray = form.Gray.data code = form.code.data work = form.selectwork.data changelog = form.changelog.data if Way == 'SVN': if len(Tags) > 1: raise flash('错误:只能同时上线一个项目!') else: for line in Tags: if line.startswith('#') or not line.split(): continue m = re.match(r'[0-9]', line) if m: raise flash('错误:不能以数字开头!') if not line.startswith('/'): raise flash('错误:' + line + '路径必须以"/"开头!') path = line.strip() path = path.replace('\\', '/') App = path.split('/') if len(App)<4: raise flash('错误:路径错误,无法获取项目名!') App = App[3] if len(path.split('-')) >= 2: version = path.split('-')[-1] else: raise flash('错误:项目名称格式错误!') if version.endswith('.zip'): version = version.replace('.zip', '') elif Way == 'GIT': if len(Tags) != 2: raise flash('错误:GIT上线格式不对!') elif not Tags[0].strip().startswith('http://'): raise flash('错误:' + Tags[0] + '路径需以"http://"开头!') elif not Tags[0].strip().endswith('.git'): raise flash('错误:' + Tags[0] + '应该以".git"结尾!') elif not Tags[1].strip().startswith('tag-'): raise flash('错误:输入的tag版本号格式错误!') path = ';'.join(Tags) path = path.replace('http://git.baihe.com/', '/') App = Tags[0].strip().split('/')[-1] App = App.split('.')[0] version = Tags[1].split('-')[-1] else: raise flash('错误:文本框内容不能为空!') except Exception as e: if 'old' not in str(e): flash(e) else: try: project_db = db_op.project_level project_level = project_db.query.with_entities(project_db.level).filter(project_db.project == App).all() #测外不强制项目等级 if Type == 2: if project_level: project_level = int(project_level[0][0]) else: project_level = 1 else: if project_level: project_level = int(project_level[0][0]) crypto = Md5.crypto(crypto_key) qrcode_url = "https://op.baihe.com/qrcode_php/{0}/{1}/{2}/{3}".format(crypto.encrypt(g.user),g.grade,crypto.encrypt(App),project_level) else: raise flash('没有找到该项目的对应项目等级!') publish_time = time.strftime("%H", time.localtime()) if code: verify_key = "{0}_{1}".format(g.user,App) verify_code = Redis.get(verify_key) if verify_code == str(code): Redis.lpush(Key, ' --->verify code pass!') Redis.expire(Key, 30) Redis.delete(verify_key) code_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) db = db_op.publish_code db_op.DB.session.add( db(project=App, code=str(code), platfrom=platfrom, user=g.user, Time=code_time)) db_op.DB.session.commit() else: raise flash('%s 该上线码验证不通过!' %str(code)) else: # 用户权限及行为判断 tw = int(time.strftime('%w',time.localtime(time.time()))) if g.grade >= 2 and Type == 1 and action == 'publish': if project_level >= 5: raise flash('该项目等级为%s级,需申请上线码!' % project_level) if tw in (2,4): if project_level <= 4 and (int(publish_time) >= 17 or int(publish_time) <= 9): raise flash('仅允许在10-17点时间段进行上线操作,需申请上线码!') else: raise flash('4级及以下常规项目只限在周二和周四上线,修复BUG需申请上线码!') if g.grade >= 2 and action == 'rollback': raise flash('没有权限进行回滚操作!') db = db_op.php_list if Gray: if App == 'baihePhpGlobalLibrary_publish': val = db.query.with_entities(db.ip).filter(and_(db.Gray == '1',db.operation == 'baihe')).limit(1).all() if not val: val = db.query.with_entities(db.ip).filter(and_(db.type == '%i' % Type,db.operation == 'baihe')).limit(1).all() elif App == 'Baihe': val = db.query.with_entities(db.ip).filter(and_(db.Gray == '1',db.operation == 'hunli')).limit(1).all() if not val: val = db.query.with_entities(db.ip).filter(and_(db.type == '%i' % Type,db.operation == 'hunli')).limit(1).all() else: val = db.query.with_entities(db.ip).filter(and_(db.Gray == '1',db.project == '%s' % App)).limit(1).all() if not val: val = db.query.with_entities(db.ip).filter(and_(db.project == '%s' % App, db.type == '%i' % Type)).limit(1).all() if val: sip = [v[0].encode('UTF-8') for v in val if v] db.query.filter(and_(db.project == App, db.ip == sip[0])).update({db.Gray: '1'}) else: raise flash('%s 没有在上线列表中找到!' % App) else: if App == 'baihePhpGlobalLibrary_publish': val = db.query.with_entities(db.ip).filter(and_(db.type == '%i' %Type,db.operation == 'baihe')).all() elif App == 'Baihe': val = db.query.with_entities(db.ip).filter(and_(db.type == '%i' %Type,db.operation == 'hunli')).all() else: val = db.query.with_entities(db.ip).filter(and_(db.project == '%s' %App,db.type == '%i' %Type)).all() if val: val = set(val) sip = [v[0].encode('UTF-8') for v in val if v] if Type == 1: sip.append('172.16.4.188') else: raise flash('%s 没有在上线列表中找到!' %App) Redis.lpush(Key, 'check security policy......') Redis.expire(Key, 30) Info = {} Info['action'] = action Info['path'] = path Info['app'] = App Info['sip'] = sip Info['gray'] = Gray Info['Type'] = Type Info['Way'] = Way Redis.lpush(publish_key,Info) mysql_operation = Mysql.mysql_op(g.user,action,Type,App,version,Gray,work,project_level,changelog) mysql_operation.op_operation() Scheduler = produce.Scheduler_publish() Scheduler = Scheduler.Scheduler_mem(php_publish.php_publish,publish_key,Key) Scheduler.start() Redis.lpush(Key,' --->check pass!') Redis.lpush(Key,'-'*80+'\n') except Exception as e: if 'old' not in str(e): flash(e) if qrcode_url: return render_template('php_publish.html',Main_Infos=g.main_infos, form=form, qrcode_url=qrcode_url) else: return render_template('php_publish_show.html',Main_Infos=g.main_infos) return render_template('php_publish.html',Main_Infos=g.main_infos,form=form,qrcode_url = qrcode_url)