def server_get(auth_info, **kwargs): res = [] if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] try: output = ['id','hostname','ip','vm_status','st','uuid','manufacturers','server_type','server_cpu','os','server_disk','server_mem','mac_address','manufacture_date','check_update_time','supplier','supplier_phone','idc_id','cabinet_id','cabinet_pos','expire','server_up_time','server_purpose','server_run','host'] data = request.get_json()['params'] fields = data.get('output', output) where = data.get('where',None) if not where: return json.dumps({'code':1, 'errmsg':'must need a condition'}) result = app.config['cursor'].get_one_result('server', fields, where) result['check_update_time'] = str(result['check_update_time']) result['manufacture_date'] = str(result['manufacture_date']) result['expire'] = str(result['expire']) result['server_up_time'] = str(result['server_up_time']) # print result if not result : return json.dumps({'code':1, 'errmsg':'result is null'}) else: util.write_log('api').info(username, "select server by id success") return json.dumps({'code':0,'result':result}) except: util.write_log('api').error('select server by id error: %s' % traceback.format_exc()) return json.dumps({'code':1,'errmsg':'get server failed'})
def switch_select(auth_info, **kwargs): data_result = [] if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] if '1' not in auth_info['r_id']: return json.dumps({'code': 1, 'errmsg': 'you not admin,no cmdb'}) try: fields = ['id', 'ip', 'device', 'port', 'port', 'cabinet', 'idc'] #将角色对应的p_id都转为name,最终返回的结果p_id的值都是name res = app.config['cursor'].get_results('switch', fields) for i in res: if i['idc']: idc = app.config['cursor'].get_one_result( 'idc', ['name'], {"id": int(i["idc"])}) cabinet = app.config['cursor'].get_one_result( 'cabinet', ['name'], {"id": int(i["cabinet"])}) i['idc_name'] = str(idc['name']) i['cabinet_name'] = str(cabinet['name']) data_result.append(i) else: data_result.append(i) util.write_log('api').info(username, 'select switch list success') return json.dumps({'code': 0, 'result': data_result}) except: util.write_log('api').error("select switch list error: %s" % traceback.format_exc()) return json.dumps({'code': 1, 'errmsg': 'get switch failed'})
def login(): try: username = request.args.get('username', None) passwd = request.args.get('passwd', None) passwd = hashlib.md5(passwd).hexdigest() if not (username and passwd): return json.dumps({'code': 1, 'errmsg': "需要输入用户名和密码"}) result = app.config['cursor'].get_one_result( 'user', ['id', 'username', 'password', 'r_id', 'is_lock'], {'username': username}) if not result: return json.dumps({'code': 1, 'errmsg': "用户不存在"}) if result['is_lock'] == 1: return json.dumps({'code': 1, 'errmsg': "用户已被锁定"}) if passwd == result['password']: data = {'last_login': time.strftime('%Y-%m-%d %H:%M:%S')} app.config['cursor'].execute_update_sql('user', data, {'username': username}) token = util.get_validate(result['username'], result['id'], result['r_id'], app.config['passport_key']) return json.dumps({'code': 0, 'authorization': token}) else: return json.dumps({'code': 1, 'errmsg': "输入密码有误"}) except: util.write_log('api').error("login error: %s" % traceback.format_exc()) return json.dumps({'code': 1, 'errmsg': "登录失败"})
def server_select(auth_info,**kwargs): data_result = [] if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] if '1' not in auth_info['r_id']: return json.dumps({'code': 1,'errmsg':'you not admin,no cmdb' }) try: fields = ['id','hostname','ip','vm_status','st','uuid','manufacturers','server_type','server_cpu','os','server_disk','server_mem','mac_address','manufacture_date','check_update_time','server_purpose','server_run','expire','server_up_time','idc_id','cabinet_id','supplier','supplier_phone'] #将角色对应的p_id都转为name,最终返回的结果p_id的值都是name res = app.config['cursor'].get_results('server', fields) print res for i in res: i['check_update_time'] = str(i['check_update_time']) i['manufacture_date'] = str(i['manufacture_date']) i['expire'] = str(i['expire']) i['server_up_time'] = str(i['server_up_time']) if i["idc_id"]: idc = app.config['cursor'].get_one_result('idc', ['name'],{"id":int(i["idc_id"])}) cabinet = app.config['cursor'].get_one_result('cabinet', ['name'],{"id":int(i["cabinet_id"])}) i['idc_name'] = str(idc['name']) i['cabinet_name'] = str(cabinet['name']) i['expire'] = i['expire'].split()[0] i['server_up_time'] = i['server_up_time'].split()[0] data_result.append(i) else: data_result.append(i) util.write_log('api').info(username, 'select server list success') return json.dumps({'code':0,'result':data_result}) except: util.write_log('api').error("select server list error: %s" % traceback.format_exc()) return json.dumps({'code':1,'errmsg':'get serverlist failed'})
def passwd(auth_info): if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] uid = int(auth_info['uid']) r_id = auth_info['r_id'] try: data = request.get_json() if '1' in r_id and data.has_key('user_id'): #管理员修改用户密码,需要传入user_id,不需要输入老密码 user_id = data['user_id'] if not app.config['cursor'].if_id_exist('user',user_id): return json.dumps({'code':1,'errmsg':'User not exist'}) password = hashlib.md5(data['password']).hexdigest() app.config['cursor'].execute_update_sql('user', {'password': password}, {'id': user_id}) else: #用户自己修改密码,需要输入老密码 if not data.has_key("oldpassword") : return json.dumps({'code':1,'errmsg':'need oldpassword'}) oldpassword = hashlib.md5(data['oldpassword']).hexdigest() res = app.config['cursor'].get_one_result('user', ['password'], {'username': username}) if res['password'] != oldpassword: return json.dumps({'code':1,'errmsg':'oldpassword wrong'}) password = hashlib.md5(data['password']).hexdigest() app.config['cursor'].execute_update_sql('user', {'password': password}, {'username': username}) util.write_log('api').info(username,'update user password success') return json.dumps({'code':0,'result':'update user passwd success'}) except: util.write_log('api').error('update user password error : %s' % traceback.format_exc()) return json.dumps({' code':1,'errmsg':'update user password failed'})
def createuser(auth_info,*arg,**kwargs): if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] r_id = auth_info['r_id'] #string, eg: '1,2,3' if '1' not in r_id: #角色id = 1 为sa组,超级管理员 return json.dumps({'code': 1,'errmsg':'you not admin,no power' }) try: data = request.get_json()['params'] #api端对传入端参数验证 if 'r_id' not in data: return json.dumps({'code': 1, 'errmsg': "must need a role!"}) if not app.config['cursor'].if_id_exist('role',data['r_id'].split(',')): return json.dumps({'code': 1, 'errmsg': "Role not exist!"}) if not util.check_name(data['username']): return json.dumps({'code': 1, 'errmsg': "username must be string or num!"}) if data['password'] != data['repwd']: return json.dumps({'code': 1, 'errmsg': "password equal repwd!"}) elif len(data['password']) < 6: return json.dumps({'code': 1, 'errmsg': 'passwd must over 6 string !'}) else: data.pop('repwd') #传入的第二次密码字段不存在,需要删除 data['password'] = hashlib.md5(data['password']).hexdigest() data['join_date'] = time.strftime('%Y-%m-%d %H:%M:%S') app.config['cursor'].execute_insert_sql('user', data) util.write_log('api').info(username, "create_user %s" % data['username']) return json.dumps({'code': 0, 'result': 'create user %s success' % data['username']}) except: util.write_log('api').error("Create user error: %s" % traceback.format_exc()) return json.dumps({'code': 1, 'errmsg': 'Create user failed'})
def getapi(auth_info,**kwargs): if auth_info['code']==1: return json.dumps(auth_info) username = auth_info['username'] if '1' not in auth_info['r_id']: return json.dumps({'code': 1,'errmsg':'you not admin,no power' }) try: output = ['id','ip','hostname','MAC','os','status','gateway','subnet'] data = request.get_json()['params'] fields = data.get('output', output) where = data.get('where',None) if not where: return json.dumps({'code':1,'errmsg':'must need a condition'}) result = app.config['cursor'].get_one_result('cobbler', fields, where) ret_system = system(app.config['cobbler_url'],app.config['cobbler_user'],app.config['cobbler_password'],result['hostname'],result['ip'],result['MAC'],result['os'],result['gateway'],result['subnet']) if str(ret_system['result']) != "True": return json.dumps({'code':1,'errmsg':'please check your system name'}) now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') data_insert = {'ip':result['ip'],'os':result['os'],'install_time':now} ret = app.config['cursor'].execute_insert_sql('install', data_insert) up_date = app.config['cursor'].execute_update_sql('cobbler', {"status":1}, where) util.write_log('api').info(username, 'select permission list success') return json.dumps({'code':0,'result':up_date}) except: util.write_log('api').error("get list permission error: %s" % traceback.format_exc()) return json.dumps({'code':1,'errmsg':'get cobbler failed'})
def getlist(auth_info, **kwargs): if auth_info['code'] == 1: return json.dumps({'code': 1, 'errmsg': '%s' % auth_info['errmsg']}) username = auth_info['username'] if auth_info['role'] != '0': return json.dumps({'code': 1, 'errmsg': '只有管理员才有此权限'}) try: fields = [ 'id', 'name', 'ip', 'type', 'manufacturer_id', 'supplier_id', 'idc_id', 'cabinet_id', 'port_num', 'status', 'store_date', 'expire', 'remark' ] result = app.config['cursor'].get_results('switch', fields) now = int(time.time()) warning_date = int(app.config.get('asset_warning_day', 0)) for asset in result: if 'expire' in asset and asset['expire']: expire = int(time.mktime(asset['expire'].timetuple())) remain_date = (expire - now) / (24 * 60 * 60) asset[ 'warning'] = 2 if remain_date <= 0 else 1 if warning_date > 0 and warning_date > remain_date else 0 util.write_log(username, 'select switch list sucess') return json.dumps({ 'code': 0, 'result': result, 'count': len(result) }, cls=MyEncoder) except: logging.getLogger().error("select Switch list error: %s" % traceback.format_exc()) return json.dumps({'code': 1, 'errmsg': '获取网络设备列表失败'})
def apply_create(auth_info, **kwargs): if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] if '1' not in auth_info['r_id']: return json.dumps({'code': 1,'errmsg':'you not admin,no power' }) r_id = auth_info['r_id'] field = ['project_id','info','applicant','commit','apply_date','status','detail'] try: data = request.get_json()['params'] #project_id,project_name,applicant,info,detail data['commit']='11111' #脚本获取 data['apply_date'] = time.strftime('%Y-%m-%d %H:%M') data['status'] = 1 data['applicant'] = username where = {"project_id":int(data['project_id'])} data.pop('project_username') res = app.config['cursor'].get_one_result('project_apply',field,where) if not res: app.config['cursor'].execute_insert_sql('project_apply', data) else: app.config['cursor'].execute_update_sql('project_apply',data,where) app.config['cursor'].execute_insert_sql('project_deploy',data) util.write_log('api').info(username,{'code':0,'result':'项目申请成功'}) return json.dumps({'code':0,'result':'项目申请成功'}) except: util.write_log('api').error('project apply error: %s' % traceback.format_exc()) return json.dumps({'code':1,'errmsg':'项目申请失败'})
def execute_update_sql(self, table_name, data, where, fields=None): try: sql = self._update_sql(table_name, data, where, fields) if sql: return self._execute(sql) except: util.write_log('api').error("Execute '%s' error: %s" % (sql, traceback.format_exc()))
def update_logdict(loglist, oldlogdict): # Each time we run, we want to re-build our log dictionary. This # helps to ensure we don't carry over stale data. newlogdict = {} for log in loglist: stats = os.stat(log) inode = stats[stat.ST_INO] file_mtime = stats[stat.ST_MTIME] min_mtime = int(time.time() - MAX_MTIME) if file_mtime < min_mtime: # we've got an older file, so update the values in the newlogdict # to the file size file_size = stats[stat.ST_SIZE] newlogdict[log] = {'log_pos': file_size, 'inode': inode} elif oldlogdict.has_key(log): # Check to see if a file we saw before has a new inode # which indicates a new file if inode != oldlogdict[log]['inode']: newlogdict[log] = {'log_pos': 0, 'inode': inode} util.write_log('inode on %s has changed, will scan' % log) else: newlogdict[log] = oldlogdict[log] else: # normal new file newlogdict[log] = {'log_pos': 0, 'inode': inode} return newlogdict
def submit_errors(error_msg): """ submit_errors is used for sending out notifications of errors. We can put in a variety of things here. For now, we have email submission and a quick syslog sent over to verify that we made it into here. """ # If there's no error messages, just get out of here if not error_msg: util.write_log('nothing to submit') return True myhost = util.get_differ_hostname() # email out the message if DIFFER_EMAIL_ERRORS: subject = 'Differ ERRORS: %s' % myhost util.mail_it(RCPT_TO, MAIL_FROM, subject, error_msg, '*****@*****.**') # send to the syslog on DIFFERLOGHOST the fact that we sent out an error # helpful for perhaps getting a quick look at how many servers # were sending out errors human_time = time.strftime('%Y%m%d %H:%M', time.localtime()) try: syslog_msg = '%s errors submitted at %s' % (myhost, human_time) c = syslog_client.syslog_client((DIFFERLOGHOST, 514)) c.log(syslog_msg, facility='local4', priority='info') except: pass
def _select_sql(self, table_name, fields, where=None, order=None, asc_order=True, limit=None): if isinstance(where, dict) and where: conditions = [] for k, v in where.items(): if isinstance(v, list): conditions.append("%s IN (%s)" % (k, ','.join(v))) elif isinstance(v, str) or isinstance(v, unicode): conditions.append("%s='%s'" % (k, v)) elif isinstance(v, int): conditions.append("%s=%s" % (k, v)) sql = "SELECT %s FROM %s WHERE %s" % (','.join(fields), table_name, ' AND '.join(conditions)) elif not where: sql = "SELECT %s FROM %s" % (','.join(fields), table_name) else: sql = "" if order and (isinstance(order, str) or isinstance(order, unicode)): sql = "%s ORDER BY %s %s" % (sql, order, 'ASC' if asc_order else 'DESC') if limit and isinstance(limit, tuple) and len(limit) == 2: sql = "%s LIMIT %s,%s" % (sql, limit[0], limit[1]) util.write_log('api').info("Select sql: %s" % sql) return sql
def project_update(auth_info, **kwargs): if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] if '1' not in auth_info['r_id']: return json.dumps({'code': 1, 'errmsg': 'you not admin,no power'}) try: data = request.get_json()['params'] where = data.get('where', None) data = data.get('data', None) if not where: return json.dumps({'code': 1, 'errmsg': 'must need a condition'}) result = app.config['cursor'].execute_update_sql( 'project', data, where) if not result: return json.dumps({'code': 1, 'errmsg': 'result is null'}) res = gitolite() if res['code'] == 1: return json.dumps(res) util.write_log('api').info('%s:update project success!' % username) return json.dumps({'code': 0, 'result': 'update project scucess'}) except: util.write_log('api').error("update error: %s" % traceback.format_exc()) return json.dumps({'code': 1, 'errmsg': "update project failed "})
def rota_create(auth_info, **kwargs): """ 插入一条值班记录,开始日期只能是周一,结束日期只能是周日 """ if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] if auth_info['role'] != '0': return json.dumps({'code': 1, 'errmsg': '只有管理员才有此权限'}) try: data = request.get_json()['params'] # 将字符串转换为日期格式 start_date = datetime.datetime.strptime(data['start_date'], "%Y-%m-%d") # 算出开始日期的周一的日期 monday = start_date - datetime.timedelta(start_date.weekday()) # 将字符串转换为日期格式 end_date = datetime.datetime.strptime(data['end_date'], "%Y-%m-%d") # 算出结束日期的周日的日期 sunday = end_date + datetime.timedelta(6 - end_date.weekday()) # 判断开始日期是不是周一和结束日期是不是周日 if start_date == monday and end_date == sunday: app.config['cursor'].execute_insert_sql('rota', data) util.write_log(username, {'code': 0, 'result': '添加值班记录成功'}) return json.dumps({'code': 0, 'result': '添加值班记录成功'}) else: util.write_log(username, "输入的日期不是周一或周日") return json.dumps({'code': 1, 'errmsg': '输入的日期不是周一或周日'}) except: logging.getLogger().error('添加值班记录错误: %s' % traceback.format_exc()) return json.dumps({'code': 2, 'errmsg': '添加值班记录失败'})
def zabbix_main_add(auth_info, **kwargs): ret = [] if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] if '1' not in auth_info['r_id']: return json.dumps({'code': 1, 'errmsg': 'you not admin,no cmdb'}) try: data = request.get_json()['params'] # {u'host_id': u'10157,10158', u'name': u'xiaoluo', u'time': u'2'} start = (str(time.time())).split('.')[0] stop = (int(start) + 7200) hostids = data['host_id'].split(',') result = create_maintenance(data['name'], start, stop, hostids, int(data['time'])) for i in hostids: ret.append(app.config['zabbix'].host_status(hostid=i, status='1')) util.write_log('api').info(username, 'select zabbix template list success') return json.dumps({'code': 0, 'result': ret}) except: util.write_log('api').error("create zabbix mainchare error: %s" % traceback.format_exc()) return json.dumps({ 'code': 1, 'errmsg': 'please check you maintenance' })
def zabbix_link_tem(auth_info, **kwargs): result = [] tem = [] template = {} if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] if '1' not in auth_info['r_id']: return json.dumps({'code': 1, 'errmsg': 'you not admin,no cmdb'}) try: data = request.get_json()['params'] # {u'hostids': [u'10157,10158'], u'groupid': u'10001'} data_host = data['hostids'][0].split(',') for i in data_host: if len(app.config['zabbix'].hostid_get_template(i)[0] ['parentTemplates']) == 0: result.append(app.config['zabbix'].link_template( int(i), data['groupid'])) else: template['templateid'] = data['groupid'] data_mu = app.config['zabbix'].hostid_get_template( i)[0]['parentTemplates'] data_mu.append(template) result.append(app.config['zabbix'].link_template( int(i), data_mu)) util.write_log('api').info(username, 'select zabbix template list success') return json.dumps({'code': 0, 'result': result}) except: util.write_log('api').error("link zabbix templeate error: %s" % traceback.format_exc()) return json.dumps({'code': 1, 'errmsg': 'link zabbix template failed'})
def role_select(auth_info, **kwargs): if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] if '1' not in auth_info['r_id']: return json.dumps({'code': 1, 'errmsg': 'you not admin,no power'}) try: output = ['id', 'name', 'name_cn', 'p_id', 'info'] data = request.get_json()['params'] fields = data.get('output', output) #查询权限表,生产id2name的字典 result = app.config['cursor'].get_results('power', ['id', 'name']) power_name = dict([(str(x['id']), x['name']) for x in result]) #将角色对应的p_id都转为name,最终返回的结果p_id的值都是name result = [] res = app.config['cursor'].get_results('role', fields) for x in res: p_name = [ power_name[p_id] for p_id in x['p_id'].split(',') if p_id in power_name ] x['p_id'] = ','.join(p_name) #将原有x['p_id']中的id转为name result.append(x) util.write_log('api').info('%s:select role list success' % username) return json.dumps({'code': 0, 'result': result, 'count': len(result)}) except: util.write_log('api').error("select role list error: %s" % traceback.format_exc()) return json.dumps({'code': 1, 'errmsg': 'get rolelist failed'})
def rota_get(auth_info, **kwargs): """ 获取一条值班记录 """ if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] if auth_info['role'] != '0': return json.dumps({'code': 1, 'errmsg': '只有管理员才有此权限'}) try: output = ['id', 'start_date', 'end_date', 'man_on_duty'] fields = kwargs.get('output', output) where = kwargs.get('where', None) result = app.config['cursor'].get_one_result('rota', fields, where) if result: result['start_date'] = str(result['start_date']) result['end_date'] = str(result['end_date']) util.write_log(username, '获取一条值班记录成功') return json.dumps({'code': 0, 'result': result}) else: util.write_log(username, '获取一条值班记录失败') return json.dumps({'code': 1, 'errmsg': '获取一条值班记录失败'}) except: logging.getLogger().error("获取一条值班记录错误: %s" % traceback.format_exc()) return json.dumps({'code': 1, 'errmsg': '获取一条值班记录错误'})
def selected(auth_info, **kwargs): if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] try: data = request.get_json()['params'] where = data.get('where', None) m_table = data.get('m_table', None) field = data.get('field', None) s_table = data.get('s_table', None) res = app.config['cursor'].get_one_result(m_table, [field], where) res = res[field].split(',') #eg: ['1','2'] result = app.config['cursor'].get_results(s_table, ['id', 'name']) for x in result: #eg: [{'id':1,'name':'sa'},{'id':2,'name':'php'}] for f in res: #if f in str(x['id']): #不能这么干,因为 '1'in '1'是true。 '1' in "11" 也是true if int(f) == int(x['id']): x['selected'] = 'selected="selected"' util.write_log('api').info('%s:selected %s successfully' % (username, s_table)) return json.dumps({'code': 0, 'result': result}) except: util.write_log('api').error('selected error: %s' % traceback.format_exc()) return json.dumps({'code': '1', 'errmsg': 'selected.get error'})
def apply_create(auth_info, **kwargs): if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] r_id = auth_info['r_id'] field = ['project_id','info','applicant','commit','apply_date','status','detail'] try: data = request.get_json()['params'] # project_id,project_name,applicant,info,detail data['commit']='11111' # 脚本获取最新的commit data['apply_date'] = time.strftime('%Y-%m-%d %H:%M') data['status'] = 1 data['applicant'] = username where = {"project_id":int(data['project_id'])} data.pop('project_username') res = app.config['cursor'].get_one_result('project_apply',field,where) if res and res['status'] in (1,2): return json.dumps({'code': 1, 'errmsg': '目前项目状态不可申请'}) if not res: app.config['cursor'].execute_insert_sql('project_apply', data) else: app.config['cursor'].execute_update_sql('project_apply',data,where) app.config['cursor'].execute_insert_sql('project_deploy',data) util.write_log('api').info('%s:项目申请成功' % username) return json.dumps({'code':0,'result':'项目申请成功'}) except: util.write_log('api').error('project apply error: %s' % traceback.format_exc()) return json.dumps({'code':1,'errmsg':'项目申请失败'})
def jigui_select(auth_info, **kwargs): if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] try: data_result = [] ret_json = {} fields = [ 'id', 'vm_status', 'os', 'server_purpose', 'idc_id', 'cabinet_id', 'cabinet_pos', 'host_status', 'ip', 'host_models' ] # host_status 主机是否有报警 #将角色对应的p_id都转为name,最终返回的结果p_id的值都是name data = app.config['cursor'].get_results('server', fields) for i in data: if i["idc_id"]: idc = app.config['cursor'].get_one_result( 'idc', ['name'], {"id": int(i["idc_id"])}) cabinet = app.config['cursor'].get_one_result( 'cabinet', ['name'], {"id": int(i["cabinet_id"])}) i['idc_name'] = str(idc['name']) i['cabinet_name'] = str(cabinet['name']) data_result.append(i) # print data_result util.write_log('api').info(username, 'select jigui list success') return json.dumps({'code': 0, 'result': data_result}) except: util.write_log('api').error("select role list error: %s" % traceback.format_exc()) return json.dumps({'code': 1, 'errmsg': 'get rolelist failed'})
def main(settings_path): heater_poll = Poller(settings_path) while True: start = time.perf_counter() # check each loop for when we are in history current = util.get_now() if (heater_poll.last_current is not None and heater_poll.last_current['day'] != current['day']): logger.info('Entered another day in history.') util.write_log( heater_poll.daily_log_path, { 'date': heater_poll.last_current['formatted_date'], 'time_elapsed': util.format_seconds( heater_poll.time_elapsed) }) heater_poll.time_elapsed = 0 call = time.perf_counter() - start heater_poll.time_elapsed += (heater_poll.poll(current) + call) heater_poll.loop_count += heater_poll.time_to_wait heater_poll.last_current = current
def project_select(auth_info,**kwargs): if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] try: output = ['id','name','path','principal','p_user','p_group','is_lock','comment'] data = request.get_json()['params'] fields = data.get('output', output) #查询用户表,生成id2name的字典 users=util.getinfo('user',['id', 'name']) #查询角色表,生成id2name的字典 roles=util.getinfo('role',['id', 'name']) #查询项目表,把项目表中p_uesr,p_group,principal的ID 转为name projects = app.config['cursor'].get_results('project', fields) for p in projects: #循环项目列表,判断项目表中的p_user的id是否存在,如果存在则id2name p['principal'] = ','.join([users[x] for x in p['principal'].split(',') if x in users]) p['p_user'] = '******'.join([users[u] for u in p['p_user'].split(',') if u in users]) p['p_group'] = ','.join([roles[r] for r in p['p_group'].split(',') if r in roles]) #普通用户只能查看其有权限的项目 if '1' not in auth_info['r_id']: p=util.user_projects(username) #调用公共函数,查出用户的项目id2name{'1':'devops','2':'test'} projects = [pro for pro in projects for pid in p.keys() if pid==pro['id']] #获取对应项目的详情 util.write_log('api').info(username, 'select project list success') return json.dumps({'code':0,'result':projects,'count':len(projects)}) except: util.write_log('api').error("select project list error: %s" % traceback.format_exc()) return json.dumps({ 'code':1,'errmsg':'get projectlist failed'})
def userlist(auth_info, **kwargs): if auth_info['code'] == 1: return json.dump(auth_info) username = auth_info['username'] r_id = auth_info['r_id'] users = [] fields = ['id', 'username', 'name', 'email', 'mobile', 'is_lock', 'r_id'] try: if '1' not in r_id: return json.dumps({'code': 1, 'errmsg': '只有管理员才有此权限'}) #获取角色的id,name并存为字典如:{'1': 'sa', '2': 'php'} rids = app.config['cursor'].get_results('role', ['id', 'name']) rids = dict([(str(x['id']), x['name']) for x in rids]) result = app.config['cursor'].get_results( 'user', fields) #[{'id:1','name':'wd','r_id':'1,2,3'},{},{}] for user in result: #查询user表中的r_id,与role表生成的字典对比,一致则将id替换为name,如,"sa,php" user['r_id'] = ','.join( [rids[x] for x in user['r_id'].split(',') if x in rids]) users.append(user) util.write_log('api').info(username, 'get_all_users') return json.dumps({'code': 0, 'users': users, 'count': len(users)}) except: logging.getLogger().error("Get users list error: %s" % traceback.format_exc()) return json.dumps({'code': 1, 'errmsg': '获取用户列表失败'})
def server_select(auth_info,**kwargs): data_result = [] if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] if '1' not in auth_info['r_id']: return json.dumps({'code': 1,'errmsg':'you not admin,no cmdb' }) try: fields = ['id','hostname','ip','vm_status','st','uuid','manufacturers','server_type','server_cpu','os','server_disk','server_mem','mac_address','manufacture_date','check_update_time','server_purpose','server_run','expire','server_up_time','idc_id','cabinet_id','supplier','supplier_phone'] #将角色对应的p_id都转为name,最终返回的结果p_id的值都是name res = app.config['cursor'].get_results('server', fields) for i in res: i['check_update_time'] = str(i['check_update_time']) i['manufacture_date'] = str(i['manufacture_date']) i['expire'] = str(i['expire']) i['server_up_time'] = str(i['server_up_time']) if i["idc_id"]: idc = app.config['cursor'].get_one_result('idc', ['name'],{"id":int(i["idc_id"])}) cabinet = app.config['cursor'].get_one_result('cabinet', ['name'],{"id":int(i["cabinet_id"])}) i['idc_name'] = str(idc['name']) i['cabinet_name'] = str(cabinet['name']) i['expire'] = i['expire'].split()[0] i['server_up_time'] = i['server_up_time'].split()[0] data_result.append(i) else: data_result.append(i) util.write_log('api').info(username, 'select server list success') return json.dumps({'code':0,'result':data_result}) except: util.write_log('api').error("select server list error: %s" % traceback.format_exc()) return json.dumps({'code':1,'errmsg':'get serverlist failed'})
def create(auth_info, **kwargs): if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] if '1' not in auth_info['r_id']: return json.dumps({'code': 1, 'errmsg': 'you not admin,no power'}) try: data = request.get_json()['params'] if not util.check_name(data['name']): return json.dumps({ 'code': 1, 'errmsg': 'name must be string or num' }) # print data app.config['cursor'].execute_insert_sql('power', data) util.write_log('api').info(username, "create power %s success" % data['name']) return json.dumps({ 'code': 0, 'result': 'create %s success' % data['name'] }) except: util.write_log('api').error('create power error:%s' % traceback.format_exc()) return json.dumps({'code': 1, 'errmsg': 'create power failed'})
def project_get(auth_info, **kwargs): if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] try: output = [ 'id', 'name', 'path', 'principal', 'p_user', 'p_group', 'is_lock', 'comment' ] data = request.get_json()['params'] fields = data.get('output', output) where = data.get('where', None) if not where: return json.dumps({'code': 1, 'errmsg': 'must need a condition'}) result = app.config['cursor'].get_one_result('project', fields, where) if not result: return json.dumps({'code': 1, 'errmsg': 'result is null'}) else: util.write_log('api').info("%s:select project by id success" % username) return json.dumps({'code': 0, 'result': result}) except: util.write_log('api').error('select project by id error: %s' % traceback.format_exc()) return json.dumps({'code': 1, 'errmsg': 'get project failed'})
def git_get(auth_info, **kwargs): if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] role = int(auth_info['role']) if role != 0: return json.dumps({'code': 1, 'errmsg': '只有管理员才有此权限'}) try: output = [ 'id', 'name', 'path', 'principal', 'p_user', 'p_group', 'is_lock', 'comment' ] data = request.get_json()['params'] fields = data.get('output', output) where = data.get('where', None) if not where: return json.dumps({'code': 1, 'errmsg': '需要指定项目'}) result = app.config['cursor'].get_one_result('git', fields, where) if result: util.write_log(username, 'get project success ') return json.dumps({'code': 0, 'result': result}) else: return json.dumps({'code': 1, 'errmsg': '项目不存在'}) except: logging.getLogger().error("select project error: %s " % traceback.format_exc()) return json.dumps({'code': 1, 'errmsg': '查询项目错误'})
def apply_list(auth_info,**kwargs): if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] try: output = ['id','project_id','info','applicant','version','apply_date','commit','status','detail'] data = request.get_json()['params'] fields = data.get('output', output) applyer = app.config['cursor'].get_results('project_apply',fields) #申请人看到的项目列表 for res in applyer: res['apply_date']=str(res['apply_date']) where = {'status':['1','2']} result = app.config['cursor'].get_results('project_apply',fields,where) #只列出申请中和审核中的项目给发布者 #id转换成名字 id2name_project=util.getinfo('project',['id','name']) for res in result: res['project_name'] = id2name_project[str(res['project_id'])] res['apply_date']=str(res['apply_date']) util.write_log('api').info(username, 'get apply list success!') return json.dumps({'code':0,'data': applyer, 'result':result,'count':len(result)}) except: util.write_log('api').error("select apply list error:%s" % traceback.format_exc()) return json.dumps({'code':1,'errmsg':'任务列表获取失败!'})
def applyapi(method): headers['authorization'] = session['author'] data['method'] = 'apply.' + method data['params'] = {"where": {"id": int(request.args.get('id'))}} util.write_log('web').info(data) r = requests.post(get_url(), headers=headers, json=data) return r.text
def _delete_sql(self, table_name, where): if not (where and isinstance(where, dict)): return "" where_cond = ["%s='%s'" % (k, v) for k,v in where.items()] sql = "DELETE FROM %s WHERE %s" % (table_name, ' AND '.join(where_cond)) util.write_log('api').info("Delete sql: %s" % sql) return sql
def execute_delete_sql(self, table_name, where): try: sql = self._delete_sql(table_name, where) if sql: return self._execute(sql) except: util.write_log('api').error("Execute '%s' error: %s" % (sql, traceback.format_exc()))
def gitolite(): git_confile = app.config['git_confile'] api_dir = os.path.dirname(os.path.realpath(__file__)) script_dir = os.path.join(api_dir.rstrip('api'),'script') projects,pro_pri = util.project_members() try : # 将项目和用户信息写入配置文件中 with open(git_confile,'w') as f: str1= "" for k,v in projects.items(): v = list(set(v)-set(pro_pri[k])) # 由于projests中存放了项目所有的成员,包括负责人。需要吧负责人剔除 str1 += "repo %s \n" % k str1 += " RW+ = %s \n" % ' '.join(pro_pri[k]) # 负责人的权限最大 if v: # 如果项目除了负责人外,有其他成员,则设置成员的权限 str1 += " - master = %s \n" %(' '.join(v)) # 项目成员无权操作master分支,其他分支可任意操作 str1 += " RW = %s \n" %(' '.join(v)) f.write(str1) # git add/commit/push生效.路径暂时写死,定版前修改 #stdout=util.run_script_with_timeout("sh %s/git.sh" % script_dir) #print stdout return json.dumps({'code':0,'result':"git操作成功"}) except: util.write_log('api').error("get config error: %s" % traceback.format_exc()) return json.dumps({'code':1,'errmsg':"get config error"})
def selected(auth_info, **kwargs): if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] try: where = kwargs.get('where', None) sel = kwargs.get('selected', None) res = app.config['cursor'].get_one_result(color_selected[sel]['t1'], color_selected[sel]['c1'], where) tmp_list = getid_list([str(res[color_selected[sel]['c1'][0]])]) result = app.config['cursor'].get_results(color_selected[sel]['t2'], color_selected[sel]['c2']) ids = set([str(x['id']) for x in result]) & set(tmp_list) for x in result: if 'name' not in x and 'username' in x: x['name'] = x['username'] x['selected'] = 'selected="selected"' if str( x['id']) in ids else '' util.write_log( username, 'selected %s, %s successfully' % (color_selected[sel]['t1'], color_selected[sel]['c1'])) return json.dumps({'code': 0, 'result': result}) except: logging.getLogger().error('selected.get error: %s' % traceback.format_exc()) return json.dumps({'code': '1', 'errmsg': 'selected.get error'})
def apply_list(auth_info,**kwargs): if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] try: output = ['id','project_id','info','applicant','version','apply_date','commit','status','detail'] data = request.get_json()['params'] fields = data.get('output', output) # 申请者看到的项目列表 applylist = app.config['cursor'].get_results('project_apply',fields) # 审核者看到的申请列表,只显示申请中和审核中的项目 where = {'status':['1','2']} result = app.config['cursor'].get_results('project_apply',fields,where) # id转换成名字 id2name_project=util.getinfo('project',['id','name']) for res in applylist: res['project_name'] = id2name_project[str(res['project_id'])] res['apply_date']=str(res['apply_date']) for res in result: res['project_name'] = id2name_project[str(res['project_id'])] res['apply_date']=str(res['apply_date']) util.write_log('api').info('%s:get apply list success!' % username) return json.dumps({'code':0,'data': applylist, 'result':result,'count':len(result)}) except: util.write_log('api').error("select apply list error:%s" % traceback.format_exc()) return json.dumps({'code':1,'errmsg':'任务列表获取失败!'})
def git_update(auth_info, **kwargs): if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] role = int(auth_info['role']) if role != 0: return json.dumps({'code': 1, 'errmsg': '只有管理员才有此权限'}) try: data = request.get_json()['params'] where = data.get('where', None) data = data.get('data', None) if not where: return json.dumps({'code': 1, 'errmsg': '需要指定更新项目'}) if not data.get('principal', []): return json.dumps({'code': 1, 'errmsg': '必须要指定负责人'}) for k in ['p_user', 'p_group']: if k not in data: data[k] = '' result = app.config['cursor'].get_one_result('git', ['name'], where) if not result: return json.dumps({'code': 1, 'errmsg': '项目不存在'}) app.config['cursor'].execute_update_sql('git', data, where) r = gitolite() if r['code'] == 1: return json.dumps(r) util.write_log(username, 'update project %s success' % result['name']) return json.dumps({'code': 0, 'result': '更新项目%s成功' % result['name']}) except: logging.getLogger().error("update project error: %s" % traceback.format_exc()) return json.dumps({'code': 1, 'errmsg': '更新项目失败'})
def zabbix_maintenance_delete(auth_info,**kwargs): result = [] if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] if '1' not in auth_info['r_id']: return json.dumps({'code': 1,'errmsg':'you not admin,no root' }) try: data = request.get_json()['params'] where = data.get('where',None) if not where: return json.dumps({'code':1, 'errmsg':'must need a condition'}) # result = app.config['zabbix'].del_maintenance(where['id']) ret = app.config['zabbix'].get_maintenance() for i in ret: if int(i['maintenanceid']) == where['id']: for host in i['hosts']: result.append(app.config['zabbix'].host_status(hostid=host['hostid'],status='0')) app.config['zabbix'].del_maintenance(where['id']) if not result : return json.dumps({'code':1, 'errmsg':'result is null'}) util.write_log('api').info(username, 'delete zabbix_maintenance successed') return json.dumps({'code':0,'result':'delete zabbix_maintenance scucess'}) except: util.write_log('api'). error('delete zabbix_maintenance error: %s' % traceback.format_exc()) return json.dumps({'co de':1,'errmsg':'delete zabbix_maintenance failed'})
def idc_get(auth_info, **kwargs): if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] try: output = [ 'id', 'name', 'idc_name', 'address', 'phone', 'email', 'user_interface', 'user_phone', 'rel_cabinet_num', 'pact_cabinet_num' ] data = request.get_json()['params'] fields = data.get('output', output) where = data.get('where', None) # print where if not where: return json.dumps({'code': 1, 'errmsg': 'must need a condition'}) result = app.config['cursor'].get_one_result('idc', fields, where) # print result if not result: return json.dumps({'code': 1, 'errmsg': 'result is null'}) else: util.write_log('api').info(username, "select role by id success") return json.dumps({'code': 0, 'result': result}) except: util.write_log('api').error('select idc by id error: %s' % traceback.format_exc()) return json.dumps({'code': 1, 'errmsg': 'get idc failed'})
def switch_select(auth_info,**kwargs): data_result = [] if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] if '1' not in auth_info['r_id']: return json.dumps({'code': 1,'errmsg':'you not admin,no cmdb' }) try: fields = ['id','ip','device','port','port','cabinet','idc'] #将角色对应的p_id都转为name,最终返回的结果p_id的值都是name res = app.config['cursor'].get_results('switch', fields) for i in res: if i['idc']: idc = app.config['cursor'].get_one_result('idc', ['name'],{"id":int(i["idc"])}) cabinet = app.config['cursor'].get_one_result('cabinet', ['name'],{"id":int(i["cabinet"])}) i['idc_name'] = str(idc['name']) i['cabinet_name'] = str(cabinet['name']) data_result.append(i) else: data_result.append(i) util.write_log('api').info(username, 'select switch list success') return json.dumps({'code':0,'result':data_result}) except: util.write_log('api').error("select switch list error: %s" % traceback.format_exc()) return json.dumps({'code':1,'errmsg':'get switch failed'})
def role_create(auth_info, **kwargs): if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] if '1' not in auth_info['r_id']: return json.dumps({'code': 1, 'errmsg': 'you not admin,no power'}) try: data = request.get_json()['params'] if not data.has_key('p_id'): return json.dumps({'code': 1, 'errmsg': 'must hava p_id'}) if not app.config['cursor'].if_id_exist('power', data['p_id'].split(',')): return json.dumps({'code': 1, 'errmsg': 'p_id not exist'}) if not util.check_name(data['name']): return json.dumps({ 'code': 1, 'errmsg': 'name must be string or int' }) app.config['cursor'].execute_insert_sql('role', data) util.write_log('api').info("%s:create role %s scucess" % (username, data['name'])) return json.dumps({ 'code': 0, 'result': 'create role %s scucess' % data['name'] }) except: util.write_log('api').error("create role error: %s" % traceback.format_exc()) return json.dumps({'code': 1, 'errmsg': 'create role fail'})
def role_select(auth_info,**kwargs): if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] if auth_info['role'] != '0': return json.dumps({'code': 1,'errmsg':'只有管理员才有此权限' }) try: output = ['id','name','name_cn','p_id','comment'] data = request.get_json()['params'] fields = data.get('output', output) result = app.config['cursor'].get_results('permission', ['id', 'name']) perm_name = dict([(x['id'], x['name']) for x in result]) result = [] res = app.config['cursor'].get_results('user_group', fields) for x in res: p_name = [perm_name[int(p_id)] for p_id in x['p_id'].split(',')] x['p_id'] = ','.join(p_name) result.append(x) util.write_log(username, 'select group list success') return json.dumps({'code':0,'result':result,'count':len(result)}) except: logging.getLogger().error("select groups list error: %s" % traceback.format_exc()) return json.dumps({'code':1,'errmsg':'获取组列表失败'})
def _insert_sql(self, table_name, data): fields, values = [], [] for k, v in data.items(): fields.append(k) values.append("'%s'" % v) sql = "INSERT INTO %s (%s) VALUES (%s)" % (table_name, ','.join(fields), ','.join(values)) util.write_log('api').info("Insert sql: %s" % sql) return sql
def execute_insert_sql(self, table_name, data): try: sql = self._insert_sql(table_name, data) if not sql: return None return self._execute(sql) except: util.write_log('api').error("Execute '%s' error: %s" % (sql, traceback.format_exc()))
def get_results(self, table_name, fields, where=None, order=None, asc_order=True, limit=None): try: sql = self._select_sql(table_name, fields, where, order, asc_order, limit) self._execute(sql) result_sets = self._fetchall() return [dict([(k, '' if row[i] is None else row[i]) for i,k in enumerate(fields)]) for row in result_sets] except: util.write_log('api').error("Execute '%s' error: %s" % (sql, traceback.format_exc())) return []
def listapi(): headers['authorization'] = session['author'] method = request.args.get('method') data['method'] = method+".getlist" data['params'] = {} util.write_log('web').info(data) r = requests.post(get_url(),headers=headers,json=data) # print r.text util.write_log('web').info(r.text) return r.text
def userprojects(auth_info,**kwargs): if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] try: res = util.user_projects(username) #{'1':'devops','2':'test'} return json.dumps({'code': 0, 'result': res}) except: util.write_log('api').error("调用userproject函数失败: %s" % traceback.format_exc()) return json.dumps({'code': 1, 'errmsg': '查询项目列表错误'})
def apply_pub(username,data,where): #更新project_apply表 app.config['cursor'].execute_update_sql('project_apply',data,where) util.write_log('api').info(username,"success and update project_apply status %s" % data['status']) #同时将本次操作插入到project_deploy中 fields = ['project_id','info','applicant','status','apply_date','version','commit','detail'] result=app.config['cursor'].get_one_result('project_apply',fields,where) app.config['cursor'].execute_insert_sql('project_deploy',result) util.write_log('api').info(username,"success and insert project_deploy status %s" % data['status'])
def get_where_results(self, table_name,fields,where): try: for k,v in where.items(): sql = "SELECT %s FROM %s WHERE %s=%s" % (','.join(fields),table_name,k,v) self._execute(sql) result_sets = self._fetchall() return [dict([(k, '' if row[i] is None else row[i]) for i,k in enumerate(fields)]) for row in result_sets] except: util.write_log('api').error("Execute '%s' error: %s" % (sql, traceback.format_exc())) return []
def zabbix_template(): headers['authorization'] = session['author'] params = dict(request.form) data['method']= 'zabbix_template.'+str(params['method'][0]) data['params'] = { "hostids": params["hostid"], "templateid": params["templateid"][0] } util.write_log('web').info(data) r = requests.post(get_url(), headers=headers, json=data) return r.content
def _update_sql(self, table_name, data, where, fields=None): if not (where and isinstance(where, dict)): return "" where_cond = ["%s='%s'" % (k, v) for k,v in where.items()] if fields: conditions = ["%s='%s'" % (k, data[k]) for k in fields] else: conditions = ["%s='%s'" % (k, data[k]) for k in data] sql = "UPDATE %s SET %s WHERE %s" % (table_name, ','.join(conditions), ' AND '.join(where_cond)) util.write_log('api').info("Update sql: %s" % sql) return sql
def applyapi(method): headers['authorization'] = session['author'] data['method'] = 'apply.'+method data['params'] = { "where":{ "id":int(request.args.get('id')) } } util.write_log('web').info(data) r = requests.post(get_url(),headers=headers,json=data) return r.text
def get_one_result(self, table_name, fields, where=None, order=None, asc_order=True, limit=None): try: sql = self._select_sql(table_name, fields, where, order, asc_order, limit) if not sql: return None self._execute(sql) result_set = self._fetchone() return dict([(k, '' if result_set[i] is None else result_set[i]) for i,k in enumerate(fields)]) except: util.write_log('api').error("Execute '%s' error: %s" % (sql, traceback.format_exc())) return {}
def wrapper(*arg, **kwargs): try: authorization = request.headers.get('authorization', 'None') res = util.validate(authorization, app.config['passport_key']) res = json.loads(res) if int(res['code']) == 1: util.write_log('api').warning("Request forbiden:%s" % res['errmsg']) return json.dumps({'code': 1, 'errmsg': '%s' % res['errmsg']}) except: util.write_log('api').warning("Validate error: %s" % traceback.format_exc()) return json.dumps({'code': 1, 'errmsg': '验证异常'}) return func(res, *arg, **kwargs)
def main(): """ Just your run of the mill basic loop. All the logic is elsewhere so that it can get pulled into another script and still make sense """ while True: start = time.time() util.write_log('starting scan') run_scan() end = time.time() duration = end - start util.write_log('scan finished in %s seconds, sleeping' % duration) time.sleep(DIFFER_LOOP_TIME)
def deleteapi(): headers['authorization'] = session['author'] method = request.args.get('method') data['method'] = method+".delete" data['params'] = { "where":{ "id":int(request.args.get('id')) } } util.write_log('web').info(data) r = requests.post(get_url(),headers=headers,json=data) return r.text
def apply_success(auth_info,**kwargs): if auth_info['code'] == 1: return json.dumps(auth_info) username = auth_info['username'] try: pid = kwargs.get('where') pid = pid['id'] data,where = {'status':4},{'id':pid} apply_pub(username,data,where) return json.dumps({'code':0,'result':'apply success'}) except: util.write_log('api').error("apply success get failed : %s" % traceback.format_exc()) return json.dumps({'code':1,'errmsg':'正式上线失败,请联系运维人员!'})