def get_associativetable(name): """ Get this particular associative table. :param str name: name of the associative table :returns: <AssociativeTable> """ content = atmanager.get(name) if content is None: return gen_json({}) return gen_json(content.get_all())
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 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_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(): """ 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 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 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 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_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 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 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 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_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(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_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_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 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_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 delete_associativetable(name): """ Delete a associative table, based on his id. :param str name: name of the associative table :rtype: bool """ return gen_json(atmanager.delete(name))
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 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_rule(rule_id): try: result = rh_idle_rule.delete(rule_id) except NotFoundError as exception: return gen_json_error( {"description": exception.message}, HTTP_NOT_FOUND) return gen_json(result)
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 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_by_id(rule_id): rule = manager.get_by_id(rule_id) if rule is None: return gen_json_error( { "description": "no dynamic infos rule with id {}".format(rule_id) }, HTTP_NOT_FOUND) return gen_json(rule)
def read(rule_id=None): result = rh_idle_rule.read(rule_id) if result is None: return gen_json_error( { 'name': rule_id, 'description': 'Rule not found', }, HTTP_NOT_FOUND) return gen_json(result)
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 compute_watchers_links(): """ Force compute of all watchers, once per 10s :rtype: bool """ ws.logger.info('Force compute of watcher links') build_all_links(watcher.context_graph) return gen_json(True)
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 sessionstart(): """ Start a new session. """ try: id_beaker_session, username = get_info() session_manager.session_start(id_beaker_session, username) return gen_json({'description': "Session Start"}) except SessionError as e: return gen_json_error({'description': e.value}, HTTP_ERROR)
def compute_pbehaviors(): """ Force compute of all pbehaviors, once per 10s :rtype: bool """ ws.logger.info('Force compute on all pbehaviors') pbm.compute_pbehaviors_filters() pbm.launch_update_watcher(watcher_manager) return gen_json(True)
def delete_v2(pbehavior_id): """Delete the pbehaviour that match the _id :param pbehavior_id: the pbehaviour id :return: a dict with two field. "acknowledged" that True if the delete is a sucess. False, otherwise. :rtype: dict """ ws.logger.info('Delete pbehavior : {}'.format(pbehavior_id)) return gen_json(rhpb.delete(pbehavior_id))
def list_heartbeats(): """ Return every heartbeats stored in database. :rtype: a json representation as a list of every heartbeats stored in or a dict with the status (name) and the description of the issue encountered. """ try: return gen_json(manager.get()) except PyMongoError: return gen_database_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_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 delete_id(action_id): """ Delete a action, based on his id. :param action_id: ID of the action :type action_id: str :rtype: bool """ ws.logger.info('Delete action : {}'.format(action_id)) return gen_json(action_manager.delete_id(id_=action_id))
def delete_id(entity_id): """ Delete a filter, based on his id. :param entity_id: Entity ID of the alarm-filter :type entity_id: str :rtype: dict """ ws.logger.info('Delete alarm-filter : {}'.format(entity_id)) return gen_json(am.alarm_filters.delete_filter(entity_id))
def delete_id(ticketapi_id): """ Delete a ticketApiConfig, based on his id. :param ticketapi_id: ID of the ticketApiConfig :type ticketapi_id: str :rtype: bool """ ws.logger.info('Delete ticketapi : {}'.format(ticketapi_id)) return gen_json(ticketapi_manager.delete_id(id_=ticketapi_id))
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 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 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 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 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())
def get_healthcheck(): """ Get healthcheck status report. :returns: <Healthcheck> """ criticals = request.query.criticals.split(',') or None if criticals == ['']: criticals = None health_obj = healthcheckManager.check(criticals=criticals) if health_obj is None: return gen_json_error({'description': 'Healthcheck is empty !'}, HTTP_ERROR) return gen_json(health_obj)
def get_action(action_id): """ Get an existing action. :param action_id: ID of the alarm-action :type action_id: str :returns: <Action> :rtype: dict """ action = action_manager.get_id(id_=action_id) if not isinstance(action, Action): return gen_json_error({'description': 'failed to get action'}, HTTP_ERROR) return gen_json(action.to_dict())
def update_watcher(watcher_id): """ Update an existing watcher. :param watcher_id: Entity ID of the watcher :type watcher_id: str :returns: nothing """ 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) watcher.update_watcher(watcher_id=watcher_id, updated_field=dico) return gen_json({})
def create_filter(): """ Create a new alarm filter. :returns: an <AlarmFilter> """ # element is a full AlarmFilter (dict) to insert element = request.json if element is None: return gen_json_error( {'description': 'nothing to insert'}, HTTP_ERROR) new = am.alarm_filters.create_filter(element=element) new.save() return gen_json(new.serialize())
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)