def get_webhook_by_id(webhook_id): """ Return a webhook given the id. :param webhook_id: ID of the webhook :type webhook_id: str :returns: <Webhook> :rtype: dict """ try: document = webhook_manager.get_webhook_by_id(webhook_id) except PyMongoError: return gen_json_error( { "description": "Can not retrieve the webhook data from " "database, contact your administrator." }, HTTP_ERROR) if document is None: return gen_json_error( {"description": "No webhook found with ID " + webhook_id}, HTTP_ERROR) return gen_json(document)
def create_webhook(): """ Create a new webhook. :returns: ID of the webhook :rtype: string """ try: webhook = request.json except ValueError: return gen_json_error({'description': 'Invalid JSON'}, HTTP_ERROR) if webhook is None or not isinstance(webhook, dict): return gen_json_error({'description': 'Nothing to create'}, HTTP_ERROR) if '_id' not in webhook: webhook['_id'] = str(uuid.uuid4()) try: return webhook_manager.create_webhook(webhook) except CollectionError as ce: ws.logger.error('Webhook creation error : {}'.format(ce)) return gen_json_error( {'description': 'Error while creating an webhook'}, HTTP_ERROR)
def update_webhook_by_id(webhook_id): """ Update an existing webhook. :param webhook_id: ID of the webhook :type webhook_id: str :rtype: dict """ try: webhook = request.json except ValueError: return gen_json_error({'description': 'Invalid JSON'}, HTTP_ERROR) if webhook is None or not isinstance(webhook, dict): return gen_json_error({'description': 'Nothing to update'}, HTTP_ERROR) try: ok = webhook_manager.update_webhook_by_id(webhook, webhook_id) except CollectionError as ce: ws.logger.error('Webhook update error : {}'.format(ce)) return gen_json_error( {'description': 'Error while updating an webhook'}, HTTP_ERROR) if not ok: return gen_json_error({'description': 'Failed to update webhook'}, HTTP_ERROR) return gen_json({})
def create_ticketapi(): """ Create a new ticketapi. :returns: nothing """ try: element = request.json except ValueError: return gen_json_error({'description': 'invalid JSON'}, HTTP_ERROR) if element is None or not isinstance(element, dict): return gen_json_error({'description': 'nothing to insert'}, HTTP_ERROR) try: TicketApi(**TicketApi.convert_keys(element)) except TypeError: return gen_json_error({'description': 'invalid ticketapi format'}, HTTP_ERROR) try: ok = ticketapi_manager.create(ticketapi=element) except CollectionError as ce: ws.logger.error('TicketApi creation error : {}'.format(ce)) return gen_json_error( {'description': 'error while creating an ticketapi'}, HTTP_ERROR) if not ok: return gen_json_error( {'description': 'failed to create ticketapi'}, HTTP_ERROR) return gen_json({})
def update_rule(rule_id): try: rule = rule_manager.get_by_id(rule_id) except AutoReconnect as e: return gen_json_error({ 'description': e.message }, HTTP_ERROR) if not rule: return gen_json_error({ 'description': 'No rule with id: {0}'.format(rule_id) }, HTTP_NOT_FOUND) try: request_body = request.json except ValueError as verror: return gen_json_error({ 'description': 'Malformed JSON: {0}'.format(verror) }, HTTP_ERROR) if not request_body: return gen_json_error({ 'description': 'Empty request' }, HTTP_ERROR) try: rule_manager.update(rule_id, request_body) except (InvalidRuleError, CollectionError) as e: return gen_json_error({ 'description': e.message }, HTTP_ERROR) return gen_json({})
def update(rule_id): try: body = request.json except ValueError: return gen_json_error({'description': 'invalid JSON'}, HTTP_ERROR) try: rule = DynamicInfosRule.new_from_dict(body, get_username(), int(time.time())) except (TypeError, ValueError, KeyError) as exception: return gen_json_error( { 'description': 'invalid dynamic infos: {}'.format(exception.message) }, HTTP_ERROR) try: success = manager.update(rule_id, rule) except ValueError as exception: return gen_json_error( { 'description': 'failed to update dynamic infos: {}'.format( exception.message) }, HTTP_ERROR) except NotFoundError as exception: return gen_json_error({"description": exception.message}, HTTP_NOT_FOUND) if not success: return gen_json_error( {"description": "failed to update dynamic infos"}, HTTP_ERROR) return gen_json(rule.as_dict())
def update_group(group_id): if not group_adapter.exists(group_id): return gen_json_error({ 'description': 'No group with id: {0}'.format(group_id) }, HTTP_NOT_FOUND) try: request_body = request.json except ValueError as verror: return gen_json_error({ 'description': 'Malformed JSON: {0}'.format(verror) }, HTTP_ERROR) if not request_body: return gen_json_error({ 'description': 'Empty request' }, HTTP_ERROR) try: group_adapter.update(group_id, request_body) except InvalidGroupError as e: return gen_json_error({ 'description': e.message }, HTTP_ERROR) return gen_json({})
def get_canopsis_version(): """ Get Canopsis version. :returns: ``200 OK`` if success or ``404 Not Found`` if Canopsis version info not found or ``400 Bad Request`` if database error. """ try: store = MongoStore.get_default() collection = \ store.get_collection(name=CanopsisVersionManager.COLLECTION) document = CanopsisVersionManager(collection).\ find_canopsis_version_document() except PyMongoError: return gen_json_error( {"description": "can not retrieve the canopsis version from " "database, contact your administrator."}, HTTP_ERROR) if not document: return gen_json_error( {"description": "canopsis version info not found."}, HTTP_NOT_FOUND) return gen_json( document, allowed_keys=[CanopsisVersionManager.VERSION_FIELD])
def insert_associativetable(name): """ Create an associative table. :param str name: name of the associative table :returns: bool """ # element is a full AssociativeTable (dict) to upsert element = request.json if element is None or not isinstance(element, dict): return gen_json_error( {'description': 'nothing to insert'}, HTTP_ERROR) assoctable = atmanager.get(name) if assoctable is not None: return gen_json_error( {'description': 'already exist'}, HTTP_ERROR) assoctable = atmanager.create(name) for key, val in element.items(): assoctable.set(key, val) return gen_json(atmanager.save(assoctable))
def get_message_by_id(playlist_id): """ Return a message given the id. :param playlist_id: ID of the message :type playlist_id: str :returns: <message> :rtype: dict """ try: document = playlist_manager.get_playlist_by_id(playlist_id) except PyMongoError: return gen_json_error( { "description": "Can not retrieve the playlist data from " "database, contact your administrator." }, HTTP_ERROR) if document is None: return gen_json_error( {"description": "No message found with ID " + playlist_id}, HTTP_ERROR) return gen_json(document)
def update_view(view_id): if not view_adapter.get_by_id(view_id): return gen_json_error({ 'description': 'No view with id: {0}'.format(view_id) }, HTTP_NOT_FOUND) try: request_body = request.json except ValueError as verror: return gen_json_error({ 'description': 'Malformed JSON: {0}'.format(verror) }, HTTP_ERROR) if not request_body: return gen_json_error({ 'description': 'Empty request' }, HTTP_ERROR) try: view_adapter.update(view_id, request_body) except InvalidViewError as e: return gen_json_error({ 'description': e.message }, HTTP_ERROR) return gen_json({})
def update_rule(rule_id): try: rule = rule_manager.get_by_id(rule_id) except AutoReconnect as e: return gen_json_error({'description': e.message}, HTTP_ERROR) if not rule: return gen_json_error( {'description': 'No rule with id: {0}'.format(rule_id)}, HTTP_NOT_FOUND) try: request_body = request.json except ValueError as verror: return gen_json_error( {'description': 'Malformed JSON: {0}'.format(verror)}, HTTP_ERROR) if not request_body: return gen_json_error({'description': 'Empty request'}, HTTP_ERROR) try: rule_manager.update(rule_id, request_body) except (InvalidRuleError, CollectionError) as e: return gen_json_error({'description': e.message}, HTTP_ERROR) return gen_json({})
def create_message(): """ Create a new message. :returns: ID of the message :rtype: string """ try: message = request.json except ValueError: return gen_json_error({'description': 'Invalid JSON'}, HTTP_ERROR) if message is None or not isinstance(message, dict): return gen_json_error({'description': 'Nothing to create'}, HTTP_ERROR) try: message = sanitize_payload(message) except Exception as e: ws.logger.error('message creation error : {}'.format(e)) return gen_json_error({'description': 'Invalid payload'}, HTTP_ERROR) if '_id' not in message: message['_id'] = str(uuid.uuid4()) try: _id = playlist_manager.create_playlist(message) return {'_id': _id} except CollectionError as ce: ws.logger.error('message creation error : {}'.format(ce)) return gen_json_error( {'description': 'Error while creating an message'}, HTTP_ERROR)
def create(): try: body = request.json except ValueError: return gen_json_error({'description': 'invalid JSON'}, HTTP_ERROR) try: rule = DynamicInfosRule.new_from_dict(body, get_username(), int(time.time())) except (TypeError, ValueError, KeyError) as exception: return gen_json_error( { 'description': 'invalid dynamic infos: {}'.format(exception.message) }, HTTP_ERROR) try: manager.create(rule) except ValueError as exception: return gen_json_error( { 'description': 'failed to create dynamic infos: {}'.format( exception.message) }, HTTP_ERROR) return gen_json(rule.as_dict())
def create_heartbeat(): """Create a new heartbeat. Read the body of the request to extract the heartbeat as a json. :rtype: a dict with the status (name) of the request and ID of created Heartbeat as description. """ try: json = request.json except ValueError: return gen_json_error({'description': "invalid json."}, HTTP_ERROR) try: model = HeartBeat(json) except ValueError: return gen_json_error( {"description": "invalid heartbeat payload."}, HTTP_ERROR) try: heartbeat_id = manager.create(model) except HeartbeatPatternExistsError: return gen_json_error( {"description": "heartbeat pattern already exists"}, HTTP_ERROR) except (PyMongoError, CollectionError): return gen_database_error() return gen_json({ "name": "heartbeat created", "description": heartbeat_id })
def create(): """ Create a idle_rule. """ try: elements = request.json except ValueError: return gen_json_error( {'description': 'invalid JSON'}, HTTP_ERROR ) try: rule = IdleRule.new_from_dict( elements, rh_idle_rule.get_username(), int(time.time())) except (TypeError, ValueError, KeyError) as exception: return gen_json_error( {'description': 'invalid idle rule: {}'.format( exception.message)}, HTTP_ERROR) try: idle_rule_manager.create(rule) except ValueError as exception: return gen_json_error( {'description': 'failed to create idle rule: {}'.format( exception.message)}, HTTP_ERROR) return gen_json(rule.as_dict())
def update_action(action_id): """ Update an existing alarm action. :param action_id: ID of the action :type action_id: str :returns: nothing """ try: element = request.json except ValueError: return gen_json_error({'description': 'invalid JSON'}, HTTP_ERROR) if element is None or not isinstance(element, dict) or len(element) <= 0: return gen_json_error({'description': 'wrong update dict'}, HTTP_ERROR) try: Action(**Action.convert_keys(element)) except TypeError: return gen_json_error({'description': 'invalid action format'}, HTTP_ERROR) try: ok = action_manager.update_id(id_=action_id, action=element) except CollectionError as ce: ws.logger.error('Action update error : {}'.format(ce)) return gen_json_error( {'description': 'error while updating an action'}, HTTP_ERROR) if not ok: return gen_json_error({'description': 'failed to update action'}, HTTP_ERROR) return gen_json({})
def create_action(): """ Create a new action. :returns: nothing """ try: element = request.json except ValueError: return gen_json_error({'description': 'invalid JSON'}, HTTP_ERROR) if element is None or not isinstance(element, dict): return gen_json_error({'description': 'nothing to insert'}, HTTP_ERROR) try: Action(**Action.convert_keys(element)) except TypeError: return gen_json_error({'description': 'invalid action format'}, HTTP_ERROR) try: ok = action_manager.create(action=element) except CollectionError as ce: ws.logger.error('Action creation error : {}'.format(ce)) return gen_json_error( {'description': 'error while creating an action'}, HTTP_ERROR) if not ok: return gen_json_error({'description': 'failed to create action'}, HTTP_ERROR) return gen_json({})
def create_v2(): """ Create a pbehavior. required keys: name str, filter dict, comments list of dict with author message, tstart int, tstop int, author str optionnal keys: rrule str, enabled bool, _id str :raises ValueError: invalid keys sent. """ try: elements = request.json except ValueError: return gen_json_error( {'description': 'invalid JSON'}, HTTP_ERROR ) if elements is None: return gen_json_error( {'description': 'nothing to insert'}, HTTP_ERROR ) invalid_keys = [] # keep compatibility with APIv1 if 'filter' in elements: elements['filter_'] = elements.pop('filter') for key in elements.keys(): if key not in VALID_PBEHAVIOR_PARAMS: invalid_keys.append(key) elements.pop(key) if len(invalid_keys) != 0: ws.logger.error('Invalid keys {} in payload'.format(invalid_keys)) replace_expired = False try: replace_expired = int(request.params['replace_expired']) == 1 except: pass try: elements['replace_expired'] = replace_expired return rhpb.create(**elements) except TypeError: return gen_json_error( {'description': 'The fields name, filter, author, tstart, tstop are required.'}, HTTP_ERROR ) except ValueError as exc: return gen_json_error( {'description': '{}'.format(exc.message)}, HTTP_ERROR )
def delete(rule_id): try: success = manager.delete(rule_id) except NotFoundError as exception: return gen_json_error({"description": exception.message}, HTTP_NOT_FOUND) if not success: return gen_json_error( {"description": "failed to delete dynamic infos"}, HTTP_ERROR) return gen_json({})
def get_rule(rule_id): try: rule = rule_manager.get_by_id(rule_id) except AutoReconnect as e: return gen_json_error({'description': e.message}, HTTP_ERROR) if rule: return gen_json(rule) else: return gen_json_error( {'description': 'No rule with id: {0}'.format(rule_id)}, HTTP_NOT_FOUND)
def update_internal_interface(): try: interface = request.json except ValueError: return gen_json_error( {'description': 'invalid JSON'}, HTTP_ERROR ) if interface is None: return gen_json_error( {'description': 'nothing to insert'}, HTTP_ERROR ) for key in interface.keys(): if key not in VALID_USER_INTERFACE_PARAMS: interface.pop(key) elif key == 'popup_timeout': # set default value for popup_timeout interface[key]['info'] = sanitize_popup_timeout(interface[key].get('info')) interface[key]['error'] = sanitize_popup_timeout(interface[key].get('error')) # set default value for popup_timeout if 'popup_timeout' not in interface.keys(): interface['popup_timeout'] = dict(info={ 'unit': 's', 'interval': DEFAULT_INTERVAL_VALUE }, error={ 'unit': 's', 'interval': DEFAULT_INTERVAL_VALUE }) if 'allow_change_severity_to_info' not in interface.keys() or \ not isinstance(interface['allow_change_severity_to_info'], bool): interface['allow_change_severity_to_info'] = False language = interface.get('language', None) if language is not None and language not in VALID_CANOPSIS_LANGUAGES: ws.logger.error( "language is an invalid value : {}".format(language)) return gen_json_error( {'description': "language is an invalid value : {}".format( language)}, HTTP_ERROR ) if len(interface) > 0: return gen_json(user_interface_manager.update(interface)) return gen_json_error( {'description': 'nothing to insert'}, HTTP_ERROR )
def remove_group(group_id): if not group_adapter.exists(group_id): return gen_json_error( {'description': 'No group with id: {0}'.format(group_id)}, HTTP_NOT_FOUND) try: group_adapter.remove_with_id(group_id) except NonEmptyGroupError: return gen_json_error({'description': 'The group is not empty'}, HTTP_ERROR) return gen_json({})
def send_event_post(): try: events = request.json except ValueError as verror: return gen_json_error( {'description': 'malformed JSON : {0}'.format(verror)}, HTTP_ERROR) if events is None: return gen_json_error({'description': 'nothing to return'}, HTTPError) return send_events(ws, events)
def remove_group(group_id): if not group_adapter.exists(group_id): return gen_json_error({ 'description': 'No group with id: {0}'.format(group_id) }, HTTP_NOT_FOUND) try: group_adapter.remove_with_id(group_id) except NonEmptyGroupError: return gen_json_error({ 'description': 'The group is not empty' }, HTTP_ERROR) return gen_json({})
def create_group(): try: request_body = request.json except ValueError as verror: return gen_json_error( {'description': 'Malformed JSON: {0}'.format(verror)}, HTTP_ERROR) try: group_id = group_adapter.create(request_body) except InvalidGroupError as e: return gen_json_error({'description': e.message}, HTTP_ERROR) return gen_json({GroupField.id: group_id})
def get_rule(rule_id): try: rule = rule_manager.get_by_id(rule_id) except AutoReconnect as e: return gen_json_error({ 'description': e.message }, HTTP_ERROR) if rule: return gen_json(rule) else: return gen_json_error({ 'description': 'No rule with id: {0}'.format(rule_id) }, HTTP_NOT_FOUND)
def create_view(): try: request_body = request.json except ValueError as verror: return gen_json_error( {'description': 'Malformed JSON: {0}'.format(verror)}, HTTP_ERROR) try: view_id = view_adapter.create(request_body) except InvalidViewError as e: return gen_json_error({'description': e.message}, HTTP_ERROR) return gen_json({ViewField.id: view_id})
def create_v2(): """ Create a pbehavior. required keys: name str, filter dict, comments list of dict with author message, tstart int, tstop int, author str optionnal keys: rrule str, enabled bool :raises ValueError: invalid keys sent. """ try: elements = request.json except ValueError: return gen_json_error( {'description': 'invalid JSON'}, HTTP_ERROR ) if elements is None: return gen_json_error( {'description': 'nothing to insert'}, HTTP_ERROR ) invalid_keys = [] # keep compatibility with APIv1 if 'filter' in elements: elements['filter_'] = elements.pop('filter') for key in elements.keys(): if key not in VALID_PBEHAVIOR_PARAMS: invalid_keys.append(key) elements.pop(key) if len(invalid_keys) != 0: ws.logger.error('Invalid keys {} in payload'.format(invalid_keys)) try: return rhpb.create(**elements) except TypeError: return gen_json_error( {'description': 'The fields name, filter, author, tstart, tstop are required.'}, HTTP_ERROR ) except ValueError as exc: return gen_json_error( {'description': '{}'.format(exc.message)}, HTTP_ERROR )
def list_rules(): search = request.query.search or "" search_fields = [ field.strip() for field in request.query.search_fields.split(',') if field.strip() ] try: limit = int(request.query.limit or '0') except ValueError: return gen_json_error( {"description": "limit should be an integer"}, HTTP_ERROR) try: skip = int(request.query.skip or '0') except ValueError: return gen_json_error({"description": "skip should be an integer"}, HTTP_ERROR) sort_key = request.query.sort_key sort_dir = request.query.sort_dir if not sort_dir: sort_dir = manager.SORT_DIRECTION_ASC if sort_dir not in [ None, manager.SORT_DIRECTION_ASC, manager.SORT_DIRECTION_DESC ]: return gen_json_error( {"description": "sort_dir should be either ASC or DESC"}, HTTP_ERROR) try: count = manager.count(search, search_fields) rules = manager.list(search, search_fields, limit, skip, sort_key, sort_dir) except CollectionError: return gen_json_error( { "description": "Cannot retrieve the dynamic infos list from " "the database, please contact your " "administrator." }, HTTP_ERROR) except ValueError as exception: return gen_json_error({"description": exception.message}, HTTP_ERROR) return gen_json({ 'count': count, 'rules': rules, })
def send_event_post(): try: events = request.json except ValueError as verror: return gen_json_error({'description': 'malformed JSON : {0}'.format(verror)}, HTTP_ERROR) if events is None: return gen_json_error( {'description': 'nothing to return'}, HTTPError ) return send_events(ws, events)
def get_group(group_id): name = request.query.getunicode(ViewField.name) title = request.query.getunicode(ViewField.title) try: group = group_adapter.get_by_id(group_id, name, title) except InvalidFilterError as e: return gen_json_error({'description': e.message}, HTTP_ERROR) if not group: return gen_json_error( {'description': 'No group with id: {0}'.format(group_id)}, HTTP_NOT_FOUND) return gen_json(group)
def get_entities_with_open_alarms(query=None, limit=0, offset=0): """ Return the entities filtered with a mongo filter. Each entity can contain an open alarm, if it exists. """ def stringify_query_keys(dic): for key, val in dic.iteritems(): if isinstance(val, dict): stringify_query_keys(val) if not isinstance(key, basestring): dic[str(key)] = val del dic[key] return dic try: if query is None: query = {} if isinstance(query, basestring): query = stringify_query_keys(eval(query)) res = manager.get_entities_with_open_alarms(query, limit, offset) return res except Exception as err: return gen_json_error({'description': str(repr(err))}, HTTP_ERROR)
def done_action(): """ Trigger done action. For json payload, see doc/docs/fr/guide_developpeur/apis/v2/alerts.md :rtype: dict """ dico = request.json if dico is None or not isinstance(dico, dict) or len(dico) <= 0: return gen_json_error({'description': 'wrong done dict'}, HTTP_ERROR) author = dico.get(am.AUTHOR) event = forger(event_type=Check.EVENT_TYPE, author=author, connector=dico.get('connector'), connector_name=dico.get('connector_name'), component=dico.get('component'), output=dico.get('comment')) if dico.get('source_type', None) == 'resource': event['resource'] = dico['resource'] event['source_type'] = 'resource' ws.logger.debug('Received done action: {}'.format(event)) entity_id = am.context_manager.get_id(event) retour = am.execute_task('alerts.useraction.done', event=event, author=author, entity_id=entity_id) return gen_json(retour)
def get_group(group_id): name = request.query.getunicode(ViewField.name) title = request.query.getunicode(ViewField.title) try: group = group_adapter.get_by_id(group_id, name, title) except InvalidFilterError as e: return gen_json_error({ 'description': e.message }, HTTP_ERROR) if not group: return gen_json_error({ 'description': 'No group with id: {0}'.format(group_id) }, HTTP_NOT_FOUND) return gen_json(group)
def update_v2(pbehavior_id): """ Update a pbehavior. :raises ValueError: invalid keys sent. """ try: elements = request.json except ValueError: return gen_json_error( {'description': 'invalid JSON'}, HTTP_ERROR ) if elements is None: return gen_json_error( {'description': 'nothing to update'}, HTTP_ERROR ) invalid_keys = [] # keep compatibility with APIv1 if 'filter' in elements: elements['filter_'] = elements.pop('filter') for key in elements.keys(): if key not in VALID_PBEHAVIOR_PARAMS: invalid_keys.append(key) elements.pop(key) if len(invalid_keys) != 0: ws.logger.error('Invalid keys {} in payload'.format(invalid_keys)) try: return rhpb.update_v2(pbehavior_id, **elements) except TypeError as te: return gen_json_error( {'description': str( 'The fields name, filter, author, tstart, tstop are required.')}, HTTP_ERROR ) except ValueError as exc: return gen_json_error( {'description': '{}'.format(exc.message)}, HTTP_ERROR )
def create_rule(): try: request_body = request.json except ValueError as verror: return gen_json_error( {'description': 'Malformed JSON: {0}'.format(verror)}, HTTP_ERROR) if not request_body: return gen_json_error({'description': 'Empty request'}, HTTP_ERROR) try: rule_id = rule_manager.create(request_body) except (InvalidRuleError, CollectionError) as e: return gen_json_error({'description': e.message}, HTTP_ERROR) return gen_json({RuleField.id: rule_id})
def remove_rule(rule_id): try: rule = rule_manager.get_by_id(rule_id) except AutoReconnect as e: return gen_json_error({'description': e.message}, HTTP_ERROR) if not rule: return gen_json_error( {'description': 'No rule with id: {0}'.format(rule_id)}, HTTP_NOT_FOUND) try: rule_manager.remove_with_id(rule_id) except CollectionError as e: return gen_json_error({'description': e.message}, HTTP_ERROR) return gen_json({})
def list_views(): name = request.query.getunicode(ViewField.name) title = request.query.getunicode(ViewField.title) try: return gen_json(view_adapter.list(name, title)) except InvalidFilterError as e: return gen_json_error({'description': e.message}, HTTP_ERROR)
def remove_view(view_id): if not view_adapter.get_by_id(view_id): return gen_json_error({ 'description': 'No view with id: {0}'.format(view_id) }, HTTP_NOT_FOUND) view_adapter.remove_with_id(view_id) return gen_json({})
def get_view(view_id): view = view_adapter.get_by_id(view_id) if view: return gen_json(view) else: return gen_json_error({ 'description': 'No view with id: {0}'.format(view_id) }, HTTP_NOT_FOUND)
def delete_entity_v2(entity_id): """ Remove entity from context """ try: res = manager.delete_entity(entity_id) except ValueError as vale: return gen_json_error({'description': str(vale)}, HTTP_ERROR) return gen_json(res)
def list_views(): name = request.query.getunicode(ViewField.name) title = request.query.getunicode(ViewField.title) try: return gen_json(view_adapter.list(name, title)) except InvalidFilterError as e: return gen_json_error({ 'description': e.message }, HTTP_ERROR)
def create_watcher(): """ Create a new watcher. Required data: JSON as text: { "mfilter": "JSON-encoded filter that applies on default_entities", "display_name": "watcher_name", "_id": "uniq_id" } :returns: nothing """ # element is a full Watcher (dict) to insert element = request.json if element is None: return gen_json_error({'description': 'nothing to insert'}, HTTP_ERROR) try: watcher_create = watcher.create_watcher(body=element) except ValueError as ex: return gen_json_error({'description': 'value error: {}'.format(ex)}, HTTP_ERROR) except KeyError as ex: return gen_json_error({'description': 'key error: {}'.format(ex)}, HTTP_ERROR) except TypeError: return gen_json_error({'description': 'type error: mfilter '\ 'should be a string'}, HTTP_ERROR) if watcher_create is None: return gen_json_error( {'description': 'can\'t decode mfilter'}, HTTP_ERROR ) return gen_json({})
def get_entity_id(): """ Get the generated id tfrom an event. """ event = request.json if event is None: return gen_json_error({'description': 'no event givent'}, HTTP_ERROR) return gen_json(ContextGraph.get_id(event))
def update_filter(entity_id): """ Update an existing alam filter. :param entity_id: Entity ID of the alarm-filter :type entity_id: str :returns: <AlarmFilter> :rtype: dict """ dico = request.json if dico is None or not isinstance(dico, dict) or len(dico) <= 0: return gen_json_error( {'description': 'wrong update dict'}, HTTP_ERROR) af = am.alarm_filters.update_filter(filter_id=entity_id, values=dico) if not isinstance(af, AlarmFilter): return gen_json_error({'description': 'failed to update filter'}, HTTP_ERROR) return gen_json(af.serialize())
def remove_rule(rule_id): try: rule = rule_manager.get_by_id(rule_id) except AutoReconnect as e: return gen_json_error({ 'description': e.message }, HTTP_ERROR) if not rule: return gen_json_error({ 'description': 'No rule with id: {0}'.format(rule_id) }, HTTP_NOT_FOUND) try: rule_manager.remove_with_id(rule_id) except CollectionError as e: return gen_json_error({ 'description': e.message }, HTTP_ERROR) return gen_json({})
def auth_internal(json_response=False, **kwargs): # When we arrive here, the Bottle plugins in charge of authentication # should have initialized the session. if json_response: return gen_json_error({ 'description': 'Wrong login or password' }, HTTP_FORBIDDEN) else: # Redirect to /?logerror=1. If the session was initialized, the # user will be redirected to the index of canopsis. If not, an # error message will be shown. redirect('/?logerror=1')
def get_watcher(watcher_id): """ Get this particular watcher. :param str watcher_id: Entity ID of the watcher :returns: <Watcher> """ watcher_obj = watcher.get_watcher(watcher_id) if watcher_obj is None: return gen_json_error({'description': 'nothing to return'}, HTTP_ERROR) return gen_json(watcher_obj)
def update_action(action_id): """ Update an existing alarm action. :param action_id: ID of the action :type action_id: str :returns: nothing """ try: element = request.json except ValueError: return gen_json_error( {'description': 'invalid JSON'}, HTTP_ERROR ) if element is None or not isinstance(element, dict) or len(element) <= 0: return gen_json_error( {'description': 'wrong update dict'}, HTTP_ERROR) try: Action(**Action.convert_keys(element)) except TypeError: return gen_json_error( {'description': 'invalid action format'}, HTTP_ERROR) try: ok = action_manager.update_id(id_=action_id, action=element) except CollectionError as ce: ws.logger.error('Action update error : {}'.format(ce)) return gen_json_error( {'description': 'error while updating an action'}, HTTP_ERROR ) if not ok: return gen_json_error({'description': 'failed to update action'}, HTTP_ERROR) return gen_json({})
def update_ticketapi(ticketapi_id): """ Update an existing ticketapi. :param ticketapi_id: ID of the ticketapi :type ticketapi_id: str :returns: nothing """ try: element = request.json except ValueError: return gen_json_error( {'description': 'invalid JSON'}, HTTP_ERROR ) if element is None or not isinstance(element, dict) or len(element) <= 0: return gen_json_error( {'description': 'wrong update dict'}, HTTP_ERROR) try: TicketApi(**TicketApi.convert_keys(element)) except TypeError: return gen_json_error( {'description': 'invalid ticketapi format'}, HTTP_ERROR) try: ok = ticketapi_manager.update_id(id_=ticketapi_id, ticketapi=element) except CollectionError as ce: ws.logger.error('TicketApi update error : {}'.format(ce)) return gen_json_error( {'description': 'error while updating an ticketapi'}, HTTP_ERROR ) if not ok: return gen_json_error({'description': 'failed to update ticketapi'}, HTTP_ERROR) return gen_json({})
def create_view(): try: request_body = request.json except ValueError as verror: return gen_json_error({ 'description': 'Malformed JSON: {0}'.format(verror) }, HTTP_ERROR) if not request_body: return gen_json_error({ 'description': 'Empty request' }, HTTP_ERROR) try: view_id = view_adapter.create(request_body) except InvalidViewError as e: return gen_json_error({ 'description': e.message }, HTTP_ERROR) return gen_json({ ViewField.id: view_id })
def get_filter(entity_id): """ Get all filters linked with an alarm. :param str entity_id: Entity ID of the alarm-filter :returns: a list of <AlarmFilter> """ filters = am.alarm_filters.get_filter(entity_id) if filters is None: return gen_json_error({'description': 'nothing to return'}, HTTP_ERROR) return gen_json([l.serialize() for l in filters])
def create_rule(): try: request_body = request.json except ValueError as verror: return gen_json_error({ 'description': 'Malformed JSON: {0}'.format(verror) }, HTTP_ERROR) if not request_body: return gen_json_error({ 'description': 'Empty request' }, HTTP_ERROR) try: rule_id = rule_manager.create(request_body) except (InvalidRuleError, CollectionError) as e: return gen_json_error({ 'description': e.message }, HTTP_ERROR) return gen_json({ RuleField.id: rule_id })
def create_ticketapi(): """ Create a new ticketapi. :returns: nothing """ try: element = request.json except ValueError: return gen_json_error( {'description': 'invalid JSON'}, HTTP_ERROR ) if element is None or not isinstance(element, dict): return gen_json_error( {'description': 'nothing to insert'}, HTTP_ERROR) try: TicketApi(**TicketApi.convert_keys(element)) except TypeError: return gen_json_error( {'description': 'invalid ticketapi format'}, HTTP_ERROR) try: ok = ticketapi_manager.create(ticketapi=element) except CollectionError as ce: ws.logger.error('TicketApi creation error : {}'.format(ce)) return gen_json_error( {'description': 'error while creating an ticketapi'}, HTTP_ERROR ) if not ok: return gen_json_error({'description': 'failed to create ticketapi'}, HTTP_ERROR) return gen_json({})
def create_action(): """ Create a new action. :returns: nothing """ try: element = request.json except ValueError: return gen_json_error( {'description': 'invalid JSON'}, HTTP_ERROR ) if element is None or not isinstance(element, dict): return gen_json_error( {'description': 'nothing to insert'}, HTTP_ERROR) try: Action(**Action.convert_keys(element)) except TypeError: return gen_json_error( {'description': 'invalid action format'}, HTTP_ERROR) try: ok = action_manager.create(action=element) except CollectionError as ce: ws.logger.error('Action creation error : {}'.format(ce)) return gen_json_error( {'description': 'error while creating an action'}, HTTP_ERROR ) if not ok: return gen_json_error({'description': 'failed to create action'}, HTTP_ERROR) return gen_json({})
def get_ticketapi(ticketapi_id): """ Get an existing ticketapi. :param ticketapi_id: ID of the ticketApiConfig :type ticketapi_id: str :returns: <TicketApi> :rtype: dict """ ticketapi = ticketapi_manager.get_id(id_=ticketapi_id) if not isinstance(ticketapi, TicketApi): return gen_json_error({'description': 'failed to get ticketapi'}, HTTP_ERROR) return gen_json(ticketapi.to_dict())