Exemplo n.º 1
0
    def _create_method(self, command_name):
        """
        Create a botcmd decorated method for our dynamic shell object
        """
        self.log.debug("Adding shell command '{}'".format(command_name))

        def new_method(self, msg, args, command_name=command_name):
            # Get who ran the command
            user = msg.frm.userid
            # The full command to run
            os_cmd = join(self.command_path, command_name + ".sh")
            q = queue.Queue()
            proc = procrun.ProcRun(os_cmd, self.command_path,
                                   self.command_logs_path, q)
            print("args: " + str(args))
            t = threading.Thread(target=procrun.ProcRun.run_async,
                                 args=(proc, user),
                                 kwargs={'arg_str': args})
            t.start()
            time.sleep(0.5)
            snippets = False
            while t.isAlive() or not q.empty():
                lines = []
                while not q.empty():
                    line = q.get()
                    if line is None:
                        break
                    lines.append(line.rstrip())
                while len(lines) > 0:
                    if len(lines) >= 25:
                        snippets = True
                    chunk = lines[:100]
                    if snippets:
                        self.slack_upload(msg, '\n'.join(chunk))
                    else:
                        buf = '\`\`\`' + '\n'.join(chunk) + '\`\`\`'
                        self.log.debug(buf)
                        yield buf
                    lines = lines[100:]
                time.sleep(2)
            t.join()
            yield "[{}] completed {}".format(command_name,
                                             status_to_string(proc.rc))

        self.log.debug("Updating metadata on command {} type {}".format(
            command_name, type(command_name)))
        new_method.__name__ = str(command_name)
        new_method.__doc__ = self._get_command_help(command_name)

        # Decorate the method
        return botcmd(new_method)
Exemplo n.º 2
0
    def _create_method(self, command_name):
        """
        Create a botcmd decorated method for our dynamic shell object
        """
        self.log.debug("Adding shell command '{}'".format(command_name))

        def new_method(self, msg, args, command_name=command_name):
            # Get who ran the command
            user = msg.frm.userid
            # The full command to run
            os_cmd = join(self.command_path, command_name + ".sh")
            q = queue.Queue()
            proc = procrun.ProcRun(os_cmd, self.command_path, self.command_logs_path, q)
            print("args: " + str(args))
            t = threading.Thread(target=procrun.ProcRun.run_async,
                args=(proc, user), kwargs={'arg_str':args})
            t.start()
            time.sleep(0.5)
            snippets = False
            while t.isAlive() or not q.empty():
                lines = []
                while not q.empty():
                    line = q.get()
                    if line is None:
                        break
                    lines.append(line.rstrip())
                while len(lines) > 0:
                    if len(lines) >= 25:
                        snippets = True
                    chunk = lines[:100]
                    if snippets:
                       self.slack_upload(msg,'\n'.join(chunk))
                    else:
                       buf = '\`\`\`' + '\n'.join(chunk) + '\`\`\`'
                       self.log.debug(buf)
                       yield buf
                    lines = lines[100:]
                time.sleep(2)
            t.join()
            yield "[{}] completed {}".format(command_name, status_to_string(proc.rc))

        self.log.debug("Updating metadata on command {} type {}".format(command_name, type(command_name)))
        new_method.__name__ = str(command_name)
        new_method.__doc__ = self._get_command_help(command_name)

        # Decorate the method
        return botcmd(new_method)
Exemplo n.º 3
0
 def __new__(mcs, name, bases, classDict):
     newClassDict = dict(classDict.items() +
                         [('directions_%s' % mode, botcmd(generate(mode)))
                         for mode in mcs.MODES])
     return super(DirectionsBuilder, mcs).__new__(mcs, name, bases, newClassDict)
Exemplo n.º 4
0
def generate(mode):
    f = lambda self, mess, args: self.bare_directions(args, mode)
    f.__name__ = 'directions_%s' % mode
    f.__doc__ = "Returns the %s directions from origin to destination using Google directions api.\n!directions_%s origin -> destination" % (mode, mode)
    return botcmd(f, split_args_with='->')
Exemplo n.º 5
0
 def __new__(mcs, name, bases, classDict):
     newClassDict = dict(classDict.items() +
                         [(character, botcmd(generate(character)))
                         for character in DieHard.CHARACTERS])
     return super(DieHardBotBuilder, mcs).__new__(mcs, name, bases,
                                                  newClassDict)
Exemplo n.º 6
0
import subprocess
import os
import time


from errbot import BotPlugin, botcmd
from errbot.backends.base import RoomNotJoinedError


admincmd = botcmd(admin_only=True)


class GitError(Exception):
    pass

class ConfigError(Exception):
    pass


def sitecmd(method):
    """Decorate methods that need to run commands locally in the SITE_PATH

    This decorator handles checking config and properly manipulating the working
    directory to successfully run commands from within SITE_PATH, but without
    affecting other bot operations.
    """
    def wrapper(self, *args, **kwargs):
        if not self.config['SITE_PATH']:
            raise ConfigError("I cannot comply, I have not been configured with a site path yet.")

        oldpath = os.getcwd()
Exemplo n.º 7
0
 def __new__(mcs, name, bases, classDict):
     newClassDict = dict(classDict.items() +
                         [(character, botcmd(generate(character)))
                          for character in DieHard.CHARACTERS])
     return super(DieHardBotBuilder, mcs).__new__(mcs, name, bases,
                                                  newClassDict)
Exemplo n.º 8
0
    def _create_method(self, command_name):
        """
        Create a botcmd decorated method for our dynamic shell object
        """
        self.log.debug("Adding shell command '{}'".format(command_name))

        def new_method(self, msg, args, command_name=command_name):
            # Get who ran the command
            user = msg.frm.user_id
            # The full command to run
            os_cmd = join(self.command_path, command_name + ".sh")
            q = queue.Queue()
            proc = ProcRun(os_cmd, self.command_path, self.command_logs_path,
                           q)
            t = threading.Thread(target=ProcRun.run_async,
                                 args=(proc, user),
                                 kwargs={'arg_str': args})
            t.start()
            time.sleep(1)
            snippets = True
            sleeptime = 2

            clines = 0
            bufs = []
            NPRESTR = '@' + msg.frm.username + ' ' + PRESTR
            while t.isAlive() or not q.empty():
                lines = []
                while not q.empty():
                    line = q.get()
                    if line is None:
                        break
                    lines.append(line.rstrip())

                while len(lines) > 0:
                    chunk = lines[:MAX_LINES]

                    bufs += chunk
                    clines += len(chunk)

                    if clines > SEND_MAX_LINES and snippets:
                        snippets = False
                        buf = NPRESTR + "[{}] starting ...\n".format(
                            command_name)
                        buf += '```' + '\n'.join(bufs[:SEND_MAX_LINES]) + '```'
                        self.log.debug(buf)
                        yield buf

                    if clines > MAX_LINES:
                        self.slack_upload(msg, bufs)
                        clines = 0
                        bufs = []

                    lines = lines[MAX_LINES:]
                time.sleep(sleeptime)

            t.join()
            if snippets:
                buf = NPRESTR + "[{}] starting ...\n".format(command_name)
                buf += '```' + '\n'.join(bufs[:SEND_MAX_LINES]) + '```'
                self.log.debug(buf)
                yield buf
            else:
                self.slack_upload(msg, bufs)
            yield NPRESTR + "[{}] completed {}".format(
                command_name, status_to_string(proc.rc))

        self.log.debug("Updating metadata on command {} type {}".format(
            command_name, type(command_name)))
        new_method.__name__ = str(command_name)
        new_method.__doc__ = self._get_command_help(command_name)

        # Decorate the method
        return botcmd(new_method)