def delete(self, app, name): """ delete strategy by its name and app @API summary: delete strategy by its name and app notes: delete an strategy by its name and app tags: - default parameters: - name: app in: path required: true type: string description: the app of the strategy - name: name in: path required: true type: string description: the name of the strategy produces: - application/json """ self.set_header('content-type', 'application/json') try: StrategyDefaultDao().delete_strategy_by_app_and_name(app, name) self.finish(json_dumps({"status": 0, "msg": "ok", "values": []})) except Exception as err: logger.error(err) self.finish( json_dumps({ "status": -1, "msg": "fail to get data from database" }))
def delete(self, app, name): """ 删除一个指定的变量 @API summary: 删除一个指定的变量 notes: 删除一个指定的变量 tags: - platform parameters: - name: app in: path required: true type: string description: 变量的app - name: name in: path required: true type: string description: 变量的名称 produces: - application/json """ self.set_header('content-type', 'application/json') try: VariableModelCustDao().delete_model_by_app_name(app, name) self.finish(json_dumps({"status": 0, "msg": "ok", "values": []})) except Exception as err: logger.error(err) self.finish(json_dumps({"status": -1, "msg": str(err)}))
def delete(self, app, name): """ 删除一个特定的event @API summary: 删除一个特定的event notes: 根据app和名称删除一个特定的event tags: - default parameters: - name: app in: path required: true type: string description: event的app - name: name in: path required: true type: string description: event的名称 produces: - application/json """ self.set_header('content-type', 'application/json') try: EventModelDefaultDao().delete_model_by_app_name(app, name) self.finish(json_dumps({"status": 0, "msg": "ok", "values": []})) except Exception as err: logger.error(err) self.finish(json_dumps({"status": -1, "msg": str(err)}))
def delete(self): """ 删除相应的event配置 @API summary: 删除满足条件的event notes: 根据类型和app tags: - default parameters: - name: app in: query required: false type: string description: event的app,空表示所有 - name: type in: query required: false type: string description: event的类型,为空表示所有 produces: - application/json """ app = self.get_argument("app", default="") type = self.get_argument("type", default="") self.set_header('content-type', 'application/json') try: EventModelDefaultDao().delete_model_list_by_app_type(app, type) self.finish(json_dumps({"status": 0, "msg": "ok", "values": []})) except Exception as err: logger.error(err) self.finish(json_dumps({"status": -1, "msg": str(err)}))
def delete(self): """ delete proper strategies @API summary: delete proper strategies notes: delete strategies belong to some app tags: - default parameters: - name: app in: query required: false type: string description: the app of the strategies that belong to produces: - application/json """ app = self.get_argument("app", default="") self.set_header('content-type', 'application/json') try: StrategyDefaultDao().delete_strategy_list_by_app(app) self.finish(json_dumps({"status": 0, "msg": "ok", "values": []})) except Exception as err: logger.error(err) self.finish( json_dumps({ "status": -1, "msg": "fail to delete data in database" }))
def get(self, app, name): """ 获取一个特定的event @API summary: 获取一个特定的event notes: 根据app和name准确的定位一个event tags: - default parameters: - name: app in: path required: true type: string description: event的app - name: name in: path required: true type: string description: event的名称 - name: simple in: query required: false type: boolean default: false description: 是否采用精简模式输出 produces: - application/json """ simple = self.get_argument('simple', default="false") simple = simple == 'true' self.set_header('content-type', 'application/json') try: result = EventModelDefaultDao().get_model_by_app_name(app, name) if result: if simple: self.finish( json_dumps({ "status": 0, "msg": "ok", "values": [result.get_simplified_ordered_dict()] })) else: self.finish( json_dumps({ "status": 0, "msg": "ok", "values": [result.get_ordered_dict()] })) else: self.finish(json_dumps({"status": 404, "msg": "not exist"})) except Exception as err: logger.error(err) self.finish(json_dumps({"status": -1, "msg": str(err)}))
def get(self, key): """ get config by its key @API summary: get config by its key notes: get config by its key tags: - default parameters: - name: key in: path required: true type: string description: the key of the config item produces: - application/json """ self.set_header('content-type', 'application/json') try: result = ConfigDefaultDao().get_config_by_key(key) if result: self.finish(json_dumps({"status": 0, "msg": "ok", "values": [result]})) else: self.process_error(404, "not found") except Exception as err: logger.error(err) self.finish(json_dumps({"status": -1, "msg": "fail to get data from database"}))
def get(self): """ get all config items list @API summary: get all config items list notes: get all config items tags: - platform parameters: produces: - application/json """ self.set_header('content-type', 'application/json') try: result = ConfigCustDao().list_all_config() self.finish( json_dumps({ "status": 0, "msg": "ok", "values": result })) except Exception as err: logger.error(err) self.finish( json_dumps({ "status": -1, "msg": "fail to get data from database" }))
def delete(self, key): """ delete config by its key @API summary: delete config by its key notes: delete config by its key tags: - default parameters: - name: key in: path required: true type: string description: the key of the config item produces: - application/json """ self.set_header('content-type', 'application/json') try: ConfigDefaultDao().remove_config(key) self.finish(json_dumps({"status": 0, "msg": "ok", "values": []})) except Exception as err: logger.error(err) self.finish(json_dumps({"status": -1, "msg": "fail to delete data in database"}))
def get(self, tag_id): """ 根据id获取tag @API summary: 根据id获取tag notes: 根据id获取tag tags: - nebula parameters: - name: tag_id in: path required: true type: int description: the id of the tag produces: - application/json """ try: tag_id = int(tag_id) except Exception as err: logger.error(err) self.finish(json_dumps({"status": -1, "msg": "invalid tag id"})) dao = TagDao() try: result = dao.get_tag(tag_id) if result: self.finish(json_dumps({"status": 0, "msg": "ok", "values": [result, ]})) else: self.finish(json_dumps({"status": 404, "msg": "not exist"})) except Exception as err: logger.error(err) self.finish(json_dumps({"status": -1, "msg": "fail to get data from database"}))
def post(self): """ change status of one strategy @API summary: add or modify a specific strategy notes: add or modify an strategy according to its app and name tags: - nebula parameters: - name: strategies in: body required: true type: json description: the list of dict include app, name, newstatus args produces: - application/json """ # 所有策略的修改都要检查 @todo self.set_header('content-type', 'application/json') body = self.request.body request_data = json.loads(body) for d in request_data: if not d.get("app") or not d.get("name") or not d.get("newstatus"): return self.process_error(400, u"列表中每项参数app, name 和 newstatus有缺失。") try: fail_msgs = [] dao = StrategyCustDao() for d in request_data: app = d.get("app") name = d.get("name") newstatus = d.get("newstatus") while True: s = dao.get_strategy_by_app_and_name(app, name) if not s: fail_msgs.append(u"app: %s, name: %s 的策略不存在。" % (app, name)) break oldstatus = s.status if not isStatusChangeAllowed(oldstatus, newstatus): fail_msgs.append(u"app: %s, name: %s 的策略状态不能从 %s 转换为 %s 。" % (app, name, oldstatus, newstatus) ) break dao.change_status(app, name, oldstatus, newstatus) s = dao.get_strategy_by_app_and_name(app, name) if s.status == newstatus: break # not successful, retry if len(fail_msgs) < len(request_data): self.finish(json_dumps({"status": 0, "msg": "\n".join(fail_msgs), "values": []})) else: self.finish(json_dumps({"status": 400, "msg": "\n".join(fail_msgs)})) except Exception: logger.error(traceback.format_exc()) self.finish(json_dumps({"status": -1, "msg": "fail to get data from database, %s" % traceback.format_exc()}))
def get(self): """ Get the latest notices meet the give conditions, and this handler only returns timestamp instead of full information. @API summary: get notice list with only timestamp information notes: get notices that meet the given conditions tags: - platform parameters: - name: limit in: query required: false type: int default: 10 description: the max number of records that should be return - name: key in: query required: false type: string description: if this value is given, it means we need all the notices on some key - name: fromtime in: query required: false type: long description: the result notices should have timestamp greater than fromtime - name: endtime in: query required: false type: long description: the result notices should have timestamp smaller than fromtime produces: - application/json """ limit = self.get_argument("limit", default=None) key = self.get_argument("key", default=None) fromtime = self.get_argument("fromtime", default=None) endtime = self.get_argument("endtime", default=None) self.set_header('content-type', 'application/json') try: notices = NoticeDao().list_notices(key=key, limit=limit, fromtime=fromtime, endtime=endtime) notices = notices or [] notices = [_.get_dict() for _ in notices] notices = [{"timestamp": _["timestamp"]} for _ in notices] self.finish(json_dumps({"status": 0, "msg": "ok", "values": notices})) except Exception as err: logger.error(err) self.finish(json_dumps({"status": -1, "msg": "fail to get data from database"}))
def get(self, app, name): """ get a specific strategy @API summary: get a specific strategy notes: get an strategy according to its app and name tags: - nebula parameters: - name: app in: path required: true type: string description: the app of the strategy - name: name in: path required: true type: string description: the name of the strategy produces: - application/json """ self.set_header('content-type', 'application/json') try: # get_strategy_by_app_and_name 增加group_ids 列表查询字段 strategy = StrategyCustDao().get_strategy_by_app_and_name(app, name).get_dict() # 超级管理员不能查看策略 # 管理员可以查看所有策略 # 普通用户组可以查看本组策略,及允许查看的用户组策略 if self.group.is_root(): self.process_error(-1, "root用户组没有权限查询策略") elif self.group.is_manager(): self.finish(json_dumps({"status": 200, "msg": "ok", "values": [strategy]})) else: view_strategy = GroupPermissionDao().get_group_strategy_block(self.group.id) be_block_groups_ids = view_strategy.get('be_blocked', []) # 筛选被禁止查看的用户组策略 # 只有管理员可以看见权重 if strategy['group_id'] not in be_block_groups_ids: strategy.pop('score') else: strategy = {} self.finish(json_dumps({"status": 200, "msg": "ok", "values": [strategy]})) except Exception as err: logger.error(err) self.finish(json_dumps({"status": -1, "msg": "fail to get data from database"}))
def get(self): """ 查询黑白名单的key(ip/phone/email)列列表 - test: 可选值: true , false , false代表生产, true代表测试。 - decision: 可选值: accept, reject, accept代表白名单, reject代表黑名单。 - check_type: 可选值: ip, email, mobile, 返回key值的类型分别代表ip, 邮箱, 和手机号。 ex. test=true&decision=reject&check_type=mobile 代表测试环境的手机黑名单 test=false&decision=accept&check_type=ip 代表正式 环境ip白名单 @API summary: get black/white ip/phone/email list notes: get non-expire-black-or-white-ip-or-phonenumber-or-email-list, default is black ip list tags: - platform parameters: - name: test in: query required: false type: boolean default: false description: if check in test data - name: decision in: query required: false type: string description: 'reject' for blacklist 'accept' for white list - name: check_type in: query required: false type: string description: 'ip' or 'mobile' or 'email' list to looking for produces: - application/json """ iftest = self.get_argument("test", default="false") test = True if iftest == 'true' else False logger.error('%s %s' % (test, type(test)) ) check_type = self.get_argument("check_type", default='ip') decision = self.get_argument("decision", default='reject') self.set_header('content-type', 'application/json') if check_type not in ('ip', 'mobile', 'email') or \ decision not in ('reject', 'accept'): self.finish(json_dumps({"status": -1, "msg": "avalid query, check check_type and decision"})) try: notices = NoticeDao().white_or_black(test=test, check_type=check_type, decision=decision) self.finish(json_dumps({"status": 0, "msg": "ok", "values": notices})) except Exception as err: logger.error(err) self.finish(json_dumps({"status": -1, "msg": "fail to get data from database"}))
def get(self): """ list proper strategies @API summary: get proper strategy notes: "get strategies belong to some app or have some specific status" tags: - default parameters: - name: app in: query required: false type: string description: the app of the strategies that belong to - name: status in: query required: false type: string description: the status of the strategy that should be produces: - application/json """ app = self.get_argument("app", default="") status = self.get_argument("status", default="") self.set_header('content-type', 'application/json') try: result = StrategyDefaultDao().list_all_strategies() if app: result = filter(lambda s: s.app == app or s.app == "__all__", result) if status: result = filter(lambda s: s.status == status, result) self.finish( json_dumps({ "status": 0, "msg": "ok", "values": [_.get_dict() for _ in result] })) except Exception as err: logger.error(err) self.finish( json_dumps({ "status": -1, "msg": "fail to get data from database" }))
def delete(self): """ Remove notices that meet given conditions. @API summary: delete notices notes: Remove notices that meet given conditions. tags: - default parameters: - name: key in: query required: false type: string description: if this value is given, it means we need all the notices on some key - name: fromtime in: query required: false type: long description: the result notices should have timestamp greater than fromtime - name: endtime in: query required: false type: long description: the result notices should have timestamp smaller than fromtime produces: - application/json """ key = self.get_argument("key", default=None) fromtime = self.get_argument("fromtime", default=None) endtime = self.get_argument("endtime", default=None) self.set_header('content-type', 'application/json') try: NoticeDao().remove_notices(key=key, fromtime=fromtime, endtime=endtime) self.finish(json_dumps({"status": 0, "msg": "ok", "values": []})) except Exception as err: logger.error(err) self.finish( json_dumps({ "status": -1, "msg": "fail to delete data in database" }))
def post(self): """ add a list of new config items @API summary: add a list of new config items notes: add a list of new config items tags: - default parameters: - name: configs in: body required: true type: json description: the list of the config json item produces: - application/json """ self.set_header('content-type', 'application/json') body = self.request.body try: items = json.loads(body) except Exception as error: return self.process_error(404, "invalid request body: {}".format(error.message)) try: dao = ConfigDefaultDao() for item in items: dao.add_config(item["key"], item["value"]) self.finish(json_dumps({"status": 0, "msg": "ok", "values": []})) except Exception as error: return self.process_error(500, "fail to add notice to database: {}".format(error.message))
def post(self, key): """ add a new config @API summary: add a new config notes: add a new config tags: - default parameters: - name: value in: body required: true type: string description: the json of the config item produces: - application/json """ self.set_header('content-type', 'application/json') body = self.request.body try: dao = ConfigDefaultDao() dao.add_config(key, body) self.finish(json_dumps({"status": 0, "msg": "ok", "values": []})) except Exception as error: return self.process_error(500, "fail to add notice to database: {}".format(error.message))
def get(self): """ get config list as in properties format @API summary: get config list as in properties format notes: get config list as in properties format tags: - platform parameters: produces: - application/json """ self.set_header('content-type', 'application/json') try: result = ConfigCustDao().list_all_config() items = [ "{}={}".format(_["key"], _["value"]) for _ in result if _["value"] ] response = "\n".join(items) self.finish(response) except Exception as err: logger.error(err) self.finish( json_dumps({ "status": -1, "msg": "fail to get data from database" }))
def post(self): """ add a list of new config items in properties format @API summary: add a list of new config items in properties format notes: add a list of new config items in properties format tags: - default parameters: - name: configs in: body required: true type: json description: the list of the config json item produces: - application/json """ self.set_header('content-type', 'application/json') body = self.request.body items = body.split("\n") items = [_.strip().split("=") for _ in items] try: dao = ConfigDefaultDao() for item in items: dao.add_config(item[0], item[1]) self.finish(json_dumps({"status": 0, "msg": "ok", "values": []})) except Exception as error: return self.process_error(500, "fail to add notice to database: {}".format(error.message))
def get(self): """ Get top 10 cities notice stats @API summary: Get top 10 cities notice stats notes: get top 10 cities with more notices than others tags: - default parameters: - name: duration in: query required: false type: long default: 3600 description: the result notices should have timestamp in the past duration produces: - application/json """ duration = self.get_argument("duration", default=3600) duration = int(duration) self.set_header('content-type', 'application/json') self.finish(json_dumps(get_notice_stats(duration))) return
def post(self): """ 美化一组variable @API summary: 美化一组variable notes: 美化一组variable tags: - platform parameters: - name: variable in: body required: true type: json description: 一组variable的json表示 produces: - application/json """ self.set_header('content-type', 'application/json') body = self.request.body try: variables = list() for _ in json.loads(body): variable = VariableModel.from_dict(_) variables.append(variable) variables = [_.get_simplified_ordered_dict() for _ in variables] self.finish(json_dumps({"status": 0, "msg": "ok", "values": variables})) except Exception as err: print_exc() return self.process_error(400, str(err))
def get(self): """ get metrics via influxdb proxy @API summary: get metrics via influxdb proxy notes: get metrics via influxdb proxy tags: - platform parameters: produces: - application/json """ self.set_header('content-type', 'application/json') u = self.request.uri unquoted = urllib.unquote_plus(u) print u, unquoted if "list series" in unquoted: result = [{"name": "list_series_result", "columns": ["time", "name"], "points":[]}] elif "select *" in unquoted: result = [{"points": [], "name": "", "columns": ["time", "value"]}] elif "select" in unquoted: result = influxdbproxy.get_metrics(u) else: result = {} self.finish(json_dumps(result))
def get(self): """ Get the alarm statistics for the specified period of time @API summary: alarm statistics notes: Get the alarm statistics for the specified period of time tags: - platform parameters: - name: fromtime in: query required: true type: integer description: start time - name: endtime in: query required: true type: integer description: end time produces: - application/json """ fromtime = int(self.get_argument('fromtime', 0)) endtime = int(self.get_argument('endtime', 0)) statistics_result = None try: notice_dao = NoticeDao() # 查询生产数据 production_counts = notice_dao.get_statistic_count( fromtime, endtime, 0) production_counts_map = { int(ts): int(count) for ts, count in production_counts } # 查询测试数据 test_counts = notice_dao.get_statistic_count(fromtime, endtime, 1) test_counts_map = { int(ts): int(count) for ts, count in test_counts } # 按照时间戳顺序解析alarm结果 alarm_statistics = [{ 'production_count': production_counts_map.get(ts, 0), 'test_count': test_counts_map.get(ts, 0), 'time_frame': ts } for ts in range(fromtime, endtime, 3600000)] self.finish(json_dumps(alarm_statistics)) except Exception as e: logger.error(e) self.process_error(-1, 'fail to get metrics')
def get(self, id): """ get a specific incident detail @API summary: get a specific incident detail notes: get a specific incident detail tags: - platform parameters: - name: id in: path required: true type: integer description: id of the incident """ self.set_header('content-type', 'application/json') try: incident = IncidentDao().get_incident_by_id(id).to_dict() self.finish( json_dumps({ 'status': 0, 'msg': 'ok', 'values': incident })) except Exception as e: logger.error(e) self.process_error(400, 'fail to get incident from database')
def get(self): """ Get the valid alarm count @API summary: valid alarm count notes: Get the valid alarm count tags: - platform produces: - application/json """ # 查询redis metrics有效报警数量 try: notice_dao = NoticeDao() valid_counts = { decision: count for decision, count in notice_dao.get_valid_notices() } valid_alarms = { 'incident_list': valid_counts.get('review', 0) + valid_counts.get('reject', 0), 'white_list': valid_counts.get('accept', 0) } self.finish(json_dumps(valid_alarms)) except Exception as e: logger.error(e) self.process_error(-1, 'fail to get valid alarms')
def post(self): """ 新增tag @API summary: add a list of tags notes: add new tags tags: - nebula parameters: - name: tags in: body required: true type: json description: the list of the tags json produces: - application/json """ body = self.request.body try: tags = [ dict(app='nebula', name=_['name']) for _ in json.loads(body)] except Exception as err: return self.process_error(400, "invalid request body: {}".format(err.message)) try: dao = TagDao() for t in tags: dao.add_tag(t) self.finish(json_dumps({"status": 0, "msg": "ok", "values": []})) except Exception as err: traceback.print_exc() return self.process_error(500, err.message)
def put(self, id): """ update a specific incident detail @API summary: update a specific incident detail notes: update a specific incident detail tags: - platform parameters: - name: id in: path required: true type: integer description: id of the incident - name: status in: body required: true type: integer description: status of the incident """ self.set_header('content-type', 'application/json') body = json.loads(self.request.body) status = str(body.get('status', 0)) try: IncidentDao().update_status(incident_id=id, status=status) self.finish((json_dumps({'status': 0, 'msg': 'ok', 'values': []}))) except Exception as e: logger.error(e) self.process_error(400, 'fail to update incident to database')
def get(self): """ list all incidents @API summary: list all incidents notes: get details for incidents tags: - platform responses: '200': description: incidents schema: $ref: '#/definitions/Incident' default: description: Unexcepted error schema: $ref: '#/definitions/Error' """ self.set_header('content-type', 'application/json') try: incident_list = IncidentDao().get_incident_list() self.finish( json_dumps({ 'status': 0, 'msg': 'ok', 'values': incident_list })) except Exception as e: logger.error(e) self.process_error(400, 'fail to get incidents from database')
def get(self): """ get nebula online events @API summary: get nebula online events notes: get nebula online events for online kv tags: - nebula parameters: produces: - application/json """ self.set_header('content-type', 'application/json') try: result = EventModelCustDao().list_all_models() result = [_.get_dict() for _ in result] self.finish( json_dumps({ "status": 0, "msg": "ok", "values": result })) except Exception as err: self.process_error(500, err.message)