Exemplo n.º 1
0
    def post(self, target_environment):
        self.parser.add_argument('topsenders',
                                 type=str,
                                 action='append',
                                 required=True)
        self.parser.add_argument('queue', type=str, required=True)
        self.parser.add_argument('server', type=str, required=True)
        reqdata = self.parser.parse_args()

        event = Event(queue=ast.literal_eval(reqdata['queue']),
                      server=reqdata['server'],
                      environment=target_environment)

        for sender_dict in reqdata['topsenders']:
            sender = ast.literal_eval(sender_dict)
            topsender = EventTopSender(email=sender['email'],
                                       quantity=sender['quantity'])
            event.topsenders.append(topsender)

        try:
            # if an event exist for that server it will remove first and then create a new one.
            self.delete(target_environment, reqdata['server'])
            event.save()

            return {
                'response':
                'event sucessfully created [%s]' % reqdata['server']
            }, 201
        except Exception, e:
            logger.error('Error trying to create event %s: %s' %
                         (reqdata['server'], e))
            abort(500,
                  message='Error trying to create event {}'.format(
                      reqdata['server']))
Exemplo n.º 2
0
    def put(self, target_environment):
        environment = abort_if_obj_doesnt_exist(self.filter_by,
                                                str(target_environment),
                                                Environment,
                                                blame_for_all=False)

        self.parser.add_argument('taskid', type=str, required=True)
        self.parser.add_argument('status', type=str)
        self.parser.add_argument('response', type=str)

        reqdata = self.parser.parse_args()

        try:
            task = Task.objects(taskid=str(reqdata['taskid'])).first()
            if reqdata['status']:
                task.update(status=str(reqdata['status']))

            if reqdata['response']:
                task.update(response=str(reqdata['response']))

            return {
                'response':
                'task sucessfully updated taskid:[%s]' % reqdata['taskid']
            }, 201
        except Exception, e:
            logger.error('Error trying to update task %s' % e)
            abort(404,
                  message='Error trying to update task %s' % reqdata['taskid'])
Exemplo n.º 3
0
  def post(self, target_environment):
    self.parser.add_argument('topsenders', type=str, action='append', required=True)
    self.parser.add_argument('queue', type=str, required=True)
    self.parser.add_argument('server', type=str , required=True)
    reqdata = self.parser.parse_args()
    

    event = Event(
      queue = ast.literal_eval(reqdata['queue']),
      server = reqdata['server'],
      environment = target_environment
    )


    for sender_dict in reqdata['topsenders']:
      sender = ast.literal_eval(sender_dict)
      topsender = EventTopSender(email = sender['email'], quantity = sender['quantity'])
      event.topsenders.append(topsender)

    try:
      # if an event exist for that server it will remove first and then create a new one.
      self.delete(target_environment, reqdata['server'])
      event.save()

      return {
        'response': 'event sucessfully created [%s]' % reqdata['server']
      }, 201
    except Exception, e:
      logger.error('Error trying to create event %s: %s' % (reqdata['server'], e))
      abort(500, message='Error trying to create event {}'.format(reqdata['server']))
Exemplo n.º 4
0
  def post(self):
    self.parser.add_argument('token', type=str, required=True)
    self.parser.add_argument('team_id', type=str)
    self.parser.add_argument('team_domain', type=str)
    self.parser.add_argument('channel_id', type=str)
    self.parser.add_argument('channel_name', type=str)
    self.parser.add_argument('user_id', type=str)
    self.parser.add_argument('user_name', type=str)
    self.parser.add_argument('command', type=str)
    self.parser.add_argument('text', type=str)
    reqdata = self.parser.parse_args()

    # 
    # validation
    slack = Slack.objects(token=reqdata['token'], 
                          team_id=reqdata['team_id'],
                          channel_id=reqdata['channel_id']).first()
    
    print "token:%s\nteam_id:%s\nchannel_id:%s\ncommand:%s\ntext:%s\n" % (reqdata['token'], reqdata['team_id'], reqdata['channel_id'], reqdata['command'], reqdata['text'])
    if slack:
      try:
        slackcmd = SlackCommand(slack)
        res = slackcmd.run(reqdata['command'], reqdata['text'], 'post')
      except Exception, e:
        logger.error('something went wrong trying to execute slack command: %s' % e)
        return {
          'response' : 'Internal Server Error'
        }, 500


      return res, 200
Exemplo n.º 5
0
  def post(self):
    self.parser.add_argument('token', type=str, required=True)
    self.parser.add_argument('team_domain', type=str, required=True)
    self.parser.add_argument('team_id', type=str, required=True)
    self.parser.add_argument('channel_id', type=str, required=True)
    self.parser.add_argument('command', type=str, required=True)
    self.parser.add_argument('environment', type=str, action='append', required=True)
    reqdata = self.parser.parse_args()

    if Slack.objects(team_id = reqdata['team_id'], channel_id = reqdata['channel_id'], token=reqdata['token']):
      abort(400, message='team:[%s] and channel:[%s] already configured. Update it instead.' %
        (reqdata['team_id'], reqdata['channel_id']))

    slack = Slack(
      token = reqdata['token'],
      team_domain = reqdata['team_domain'],
      team_id = reqdata['team_id'],
      channel_id = reqdata['channel_id'],
      command = reqdata['command'],
      environment = reqdata['environment']
    )

    try:
      slack.save()
      return {
        'response': 'credentials sucessfully created for channel:[%s]' % reqdata['channel_id']
      }, 201
    except Exception, e:
      logger.error('could not create channel:[%s] credentials: %s' % (reqdata['channel_id'], e)) 
      abort(500, message='could not create team credentials.')
Exemplo n.º 6
0
  def get(self, target_environment, reqdata=None):

    environment = abort_if_obj_doesnt_exist(self.filter_by, str(target_environment), Environment, blame_for_all=False)
    
    ret_data = {
      'topsenders': {},
      'queue' : {
        'active' : 0,
        'bounce' : 0,
        'hold' : 0,
        'deferred' : 0
      },
      'no_events': [],
      'servers' : []
    }

    buffer_tops = {}

    if not reqdata:
      self.parser.add_argument('tag', type=str, action='append', location='args')
      self.parser.add_argument('server', type=str, action='append', location='args')
      reqdata = self.parser.parse_args()
    
    
    data = []
    for server in environment.servers:
      # filter by server
      if reqdata['server'] and server.name not in reqdata['server']:
        continue
      # filter by tag
      if reqdata['tag'] and server.tags  not in reqdata['tag']:
        continue

      try:
        events = Event.objects(server = server.name, environment = environment.name)

        # let me know when an server doesn't have any event stored.
        if not events:
          ret_data['no_events'].append(server.name)
        else:
          ret_data['servers'].append(server.name)
        for event in events:
          # sum queues
          ret_data['queue']['deferred'] += event.queue.deferred
          ret_data['queue']['active'] += event.queue.active
          ret_data['queue']['hold'] += event.queue.hold
          ret_data['queue']['bounce'] += event.queue.bounce
          
          # buffer for sorting top senders latter.
          for sender in event.topsenders:
            try:
              buffer_tops[sender.email] += sender.quantity
            except:
              buffer_tops[sender.email] = sender.quantity
      except Exception, e:
        logger.error('Error trying to retrieve event %s' %  e)
        ret_data['no_events'].append(server.name)
        continue
Exemplo n.º 7
0
  def post(self, target_environment, reqdata=None):

    environment = abort_if_obj_doesnt_exist(self.filter_by, str(target_environment), Environment, blame_for_all=False)

    
    if not reqdata:
      self.parser.add_argument('server', type=str)
      self.parser.add_argument('action', type=str, required=True)
      self.parser.add_argument('destination', type=str, required=True)
      self.parser.add_argument('status', type=str, default='pending')
      self.parser.add_argument('response', type=str, default='')
      reqdata = self.parser.parse_args()

    # when called from inside reqdata is already filled so the above if block 
    # is skipped and cannot set default value of pending if not defined. 
    # The code bellow check and set it.
    if 'status' not in reqdata:
      reqdata['status'] = 'pending'
    if 'response' not in reqdata:
      reqdata['response'] = ''


    # if server not null it will create only one task itself. Otherwise
    # will create one task for each environment's server.
    servers = []
    if reqdata['server']:
      servers = [reqdata['server']]
    else:
      for server in environment.servers:
        print 'server:%s\n\n\n\n\n\n\n\n\n' % server.name
        servers.append(server.name)

    for server in servers:

      taskid = str(uuid.uuid4())
      task = Task(
        taskid = taskid,
        action = reqdata['action'],
        destination = reqdata['destination'],
        status = reqdata['status'] or 'pending',
        response = reqdata['response'] or '',
        environment = environment.name,
        server = server
      )

      # it will try sava or update task.  
      try:
        task.save()
        
      except Exception, e:
        logger.error('Error trying to create task %s' %  e)
        abort(500, message='Error trying to create task')

      return {
        'response': 'task sucessfully created taskid:[%s]' % taskid
      }, 201
Exemplo n.º 8
0
    def post(self, target_environment, reqdata=None):

        environment = abort_if_obj_doesnt_exist(self.filter_by,
                                                str(target_environment),
                                                Environment,
                                                blame_for_all=False)

        if not reqdata:
            self.parser.add_argument('server', type=str)
            self.parser.add_argument('action', type=str, required=True)
            self.parser.add_argument('destination', type=str, required=True)
            self.parser.add_argument('status', type=str, default='pending')
            self.parser.add_argument('response', type=str, default='')
            reqdata = self.parser.parse_args()

        # when called from inside reqdata is already filled so the above if block
        # is skipped and cannot set default value of pending if not defined.
        # The code bellow check and set it.
        if 'status' not in reqdata:
            reqdata['status'] = 'pending'
        if 'response' not in reqdata:
            reqdata['response'] = ''

        # if server not null it will create only one task itself. Otherwise
        # will create one task for each environment's server.
        servers = []
        if reqdata['server']:
            servers = [reqdata['server']]
        else:
            for server in environment.servers:
                print 'server:%s\n\n\n\n\n\n\n\n\n' % server.name
                servers.append(server.name)

        for server in servers:

            taskid = str(uuid.uuid4())
            task = Task(taskid=taskid,
                        action=reqdata['action'],
                        destination=reqdata['destination'],
                        status=reqdata['status'] or 'pending',
                        response=reqdata['response'] or '',
                        environment=environment.name,
                        server=server)

            # it will try sava or update task.
            try:
                task.save()

            except Exception, e:
                logger.error('Error trying to create task %s' % e)
                abort(500, message='Error trying to create task')

            return {
                'response': 'task sucessfully created taskid:[%s]' % taskid
            }, 201
Exemplo n.º 9
0
  def delete(self):
    self.parser.add_argument('team_id', type=str, required=True)
    self.parser.add_argument('channel_id', type=str, required=True)
    
    reqdata = self.parser.parse_args()

    slack = Slack.objects(team_id = reqdata['team_id'], channel_id = reqdata['channel_id'])
    if slack:
      try:
        slack.delete()
        return {
          'response' : 'sucessfully deleted [%s]' % reqdata['team_id']
        }, 204
      except Exception, e:
        logger.error('c')
        abort(501, message='could not delete slack credentials %s.' % reqdata['team_id'])
Exemplo n.º 10
0
    def run(self, cmd, args, method):
        """
    Description:
      This method parse the command and arguments from Slack and use POPS API to retrieve information or create tasks.

    Args:
      cmd (str) : 'command' requested. 'command' payload or url arg.
      args (str)) : command arguments. 'text' payload or url arg.
    """
        if not self.is_valid:
            logger.error('slack object not valid is_valid = %s' %
                         self.is_valid)
            abort(401, message='Unauthorized')

        # check if slack object has sufficient permission to run the command.
        logger.info("trying:[%s == %s] token[%s]" %
                    (cmd, self.slack.command, self.slack.token))
        if not cmd == self.slack.command:
            logger.error('Unauthorized: command allowed in slack object: %s' %
                         cmd)
            abort(401, message='Unauthorized')

        # Parsing arguments
        reqdata = {}
        parser = argparse.ArgumentParser(conflict_handler='resolve')
        # common arguments
        parser.add_argument('-environment', action='append')
        parser.add_argument('-server', action='append')

        if cmd == '/getqueue':
            parser.add_argument('--tag', action='append')
            resource = QueueResource()
        elif cmd == '/gettasks':
            parser.add_argument('-action', action='append')
            parser.add_argument('-status', action='append')
            resource = TaskResource()
        elif cmd == '/createtask':
            parser.add_argument('-action', required=True)
            parser.add_argument('-user', required=True)
            resource = TaskResource()
        else:
            logger.error('command not supported: %s' % cmd)
            abort(400, message='command not supported %s' % cmd)
        try:
            argument = parser.parse_args(args.split())
        except Exception, e:
            logger.error('something went wrong: %s' % e)
            return self._slack_usage()
Exemplo n.º 11
0
  def put(self, target_environment):
    environment = abort_if_obj_doesnt_exist(self.filter_by, str(target_environment), Environment, blame_for_all=False)

    self.parser.add_argument('taskid', type=str, required=True)
    self.parser.add_argument('status', type=str)
    self.parser.add_argument('response', type=str)

    reqdata = self.parser.parse_args()
  
    try:
      task = Task.objects(taskid=str(reqdata['taskid'])).first()
      if reqdata['status']:
        task.update(status = str(reqdata['status']))

      if reqdata['response']:
        task.update(response = str(reqdata['response']))

      return {
       'response': 'task sucessfully updated taskid:[%s]' % reqdata['taskid']
      }, 201
    except Exception, e:
      logger.error('Error trying to update task %s' %  e)
      abort(404, message='Error trying to update task %s' % reqdata['taskid'])
Exemplo n.º 12
0
  def run(self, cmd, args, method):
    """
    Description:
      This method parse the command and arguments from Slack and use POPS API to retrieve information or create tasks.

    Args:
      cmd (str) : 'command' requested. 'command' payload or url arg.
      args (str)) : command arguments. 'text' payload or url arg.
    """
    if not self.is_valid:
      logger.error('slack object not valid is_valid = %s' % self.is_valid)
      abort(401, message='Unauthorized')
    
    # check if slack object has sufficient permission to run the command.
    logger.info("trying:[%s == %s] token[%s]" % (cmd, self.slack.command, self.slack.token))
    if not cmd == self.slack.command:
      logger.error('Unauthorized: command allowed in slack object: %s' % cmd)
      abort(401, message='Unauthorized')
    

    # Parsing arguments
    reqdata = {}
    parser = argparse.ArgumentParser(conflict_handler='resolve')
    # common arguments
    parser.add_argument('-environment', action='append')
    parser.add_argument('-server', action='append')

    if cmd == '/getqueue':
      parser.add_argument('--tag', action='append')
      resource = QueueResource()
    elif cmd == '/gettasks':
      parser.add_argument('-action', action='append')
      parser.add_argument('-status', action='append')
      resource = TaskResource()
    elif cmd == '/createtask':
      parser.add_argument('-action', required=True)
      parser.add_argument('-user', required=True)
      resource = TaskResource()
    else:
      logger.error('command not supported: %s' % cmd )
      abort(400, message='command not supported %s' % cmd)
    try:
      argument = parser.parse_args(args.split())
    except Exception, e:
      logger.error('something went wrong: %s' % e)
      return self._slack_usage()
Exemplo n.º 13
0
    def get(self, target_environment, reqdata=None):

        environment = abort_if_obj_doesnt_exist(self.filter_by,
                                                str(target_environment),
                                                Environment,
                                                blame_for_all=False)

        ret_data = {
            'topsenders': {},
            'queue': {
                'active': 0,
                'bounce': 0,
                'hold': 0,
                'deferred': 0
            },
            'no_events': [],
            'servers': []
        }

        buffer_tops = {}

        if not reqdata:
            self.parser.add_argument('tag',
                                     type=str,
                                     action='append',
                                     location='args')
            self.parser.add_argument('server',
                                     type=str,
                                     action='append',
                                     location='args')
            reqdata = self.parser.parse_args()

        data = []
        for server in environment.servers:
            # filter by server
            if reqdata['server'] and server.name not in reqdata['server']:
                continue
            # filter by tag
            if reqdata['tag'] and server.tags not in reqdata['tag']:
                continue

            try:
                events = Event.objects(server=server.name,
                                       environment=environment.name)

                # let me know when an server doesn't have any event stored.
                if not events:
                    ret_data['no_events'].append(server.name)
                else:
                    ret_data['servers'].append(server.name)
                for event in events:
                    # sum queues
                    ret_data['queue']['deferred'] += event.queue.deferred
                    ret_data['queue']['active'] += event.queue.active
                    ret_data['queue']['hold'] += event.queue.hold
                    ret_data['queue']['bounce'] += event.queue.bounce

                    # buffer for sorting top senders latter.
                    for sender in event.topsenders:
                        try:
                            buffer_tops[sender.email] += sender.quantity
                        except:
                            buffer_tops[sender.email] = sender.quantity
            except Exception, e:
                logger.error('Error trying to retrieve event %s' % e)
                ret_data['no_events'].append(server.name)
                continue
Exemplo n.º 14
0
class SlackCommand(object):
    def __init__(self, slack):
        """ 
    Description:
      Initializes valididating the proper permissions to execute a command.

    Args:
      slack (object): popsapi.models.Slack object. Used to load permissions.
    """

        self.is_valid = False
        # check if slack object is exists
        if not slack:
            abort(401, message='Unauthorized')

        # auth ok
        self.is_valid = True
        self.slack = slack

    def _slack_usage(self):
        return "      Supported Custom Slack Commands:\
        getqueue:   Get queues from single/multiple servers or entire environment.\
                  You may use filters throught tags.\
                \
                  slack usage: /getqueue [options]\
                  options:\
                    -environment [environment] : environment name.\
                    -server [environment] : server name.\
                    -tag [tag] : tag name.\
                  \
                  examples:\
                    /getqueue\
                    /getqueue -environment corporation\
                    /getqueue -server mta-in.mailserver.com -server mta-out.mailserver.com\
                    /getqueue -environment corporation -tag inbound\
                    /getqueue -tag outbound -tag inbound\
\
        gettasks:   Get tasks from single/multiple servers or entire environment. You may \
                  apply filters in your search.\
      \
                  slack usage: /gettasks [options]\
                  options:\
                    -environment [environment] : environment name.\
                    -server [environment] : server name.\
                    -status [pending|completed|error] : task status.\
                    -action %s : task action.\
                  examples:\
                    /gettasks\
                    /gettasks -environment corporation -status pending\
                    /gettasks -server mta-in.mailserver.com\
                    /gettasks -action purge\
                    /gettasks -environment -action purge\
  " % cfg['slack']['actions']

    def run(self, cmd, args, method):
        """
    Description:
      This method parse the command and arguments from Slack and use POPS API to retrieve information or create tasks.

    Args:
      cmd (str) : 'command' requested. 'command' payload or url arg.
      args (str)) : command arguments. 'text' payload or url arg.
    """
        if not self.is_valid:
            logger.error('slack object not valid is_valid = %s' %
                         self.is_valid)
            abort(401, message='Unauthorized')

        # check if slack object has sufficient permission to run the command.
        logger.info("trying:[%s == %s] token[%s]" %
                    (cmd, self.slack.command, self.slack.token))
        if not cmd == self.slack.command:
            logger.error('Unauthorized: command allowed in slack object: %s' %
                         cmd)
            abort(401, message='Unauthorized')

        # Parsing arguments
        reqdata = {}
        parser = argparse.ArgumentParser(conflict_handler='resolve')
        # common arguments
        parser.add_argument('-environment', action='append')
        parser.add_argument('-server', action='append')

        if cmd == '/getqueue':
            parser.add_argument('--tag', action='append')
            resource = QueueResource()
        elif cmd == '/gettasks':
            parser.add_argument('-action', action='append')
            parser.add_argument('-status', action='append')
            resource = TaskResource()
        elif cmd == '/createtask':
            parser.add_argument('-action', required=True)
            parser.add_argument('-user', required=True)
            resource = TaskResource()
        else:
            logger.error('command not supported: %s' % cmd)
            abort(400, message='command not supported %s' % cmd)
        try:
            argument = parser.parse_args(args.split())
        except Exception, e:
            logger.error('something went wrong: %s' % e)
            return self._slack_usage()

        # definie environments to lookup.
        environments = []
        all_rule = False
        # all environments allowed
        if 'all' in self.slack.environment:
            for envobj in Environment.objects.only('name'):
                environments.append(str(envobj.name))
            all_rule = True
        # when not specified takes the ones in slack object.
        if not argument.environment:
            environments = self.slack.environment
        # only lookup the environments specified.
        else:
            environments = argument.environment

        for environment in environments:
            # check if command can be performed in the current environment scope.
            if environment not in self.slack.environment and all_rule == False:
                logger.error('Forbidden. Environment not allowed: %s' %
                             environment)
                abort(403,
                      message='Forbidden: Environment not allowed %s' %
                      environment)

            # add server
            try:
                reqdata['server'] = argument.server
            except:
                pass

            # add tag
            try:
                reqdata['tag'] = argument.tag
            except:
                pass

            # add action
            try:
                reqdata['action'] = argument.action
            except:
                pass

            # # add status
            try:
                reqdata['status'] = argument.status
            except:
                pass

            # add destination
            try:
                reqdata['destination'] = argument.user
            except:
                pass

            if method == 'get':
                response = resource.get(environment, reqdata)
            if method == 'post':
                response = resource.post(environment, reqdata)
            return response