Beispiel #1
0
    def test_chain_command_success(self):
        if os.name == 'nt':
            prog = "C:\\Windows\\System32\\cmd.exe"
            args = ["/c", "ECHO %date%"]
        else:
            prog = "/bin/sh"
            args = ["-c", "echo $(date)"]

        result = self.loop.run_until_complete(
            client.command.chain_execution(commands=[{
                'method': 'execute',
                'uuid': 'thisisunique',
                'arguments': {
                    'pid': random.choice(string.digits),
                    'own_uuid': uuid4().hex,
                    'path': prog,
                    'arguments': args
                },
            }]))

        response = Status(
            Status.ID_OK,
            {
                'method': 'execute',
                'result': '0',
            },
            'thisisunique',
        )

        self.assertEqual(Status(**result[0]), response)
Beispiel #2
0
    def test_chain_command_one_failed(self):
        if os.name == 'nt':
            prog = "C:\\Windows\\System32\\cmd.exe"
            args = ["/c", "ECHO %date%"]
        else:
            prog = "/bin/sh"
            args = ["-c", "echo $(date)"]

        result = self.loop.run_until_complete(
            client.command.chain_execution(commands=[{
                'method': 'execute',
                'uuid': 0,
                'arguments': {
                    'pid': 1,
                    'own_uuid': 0,
                    'path': prog,
                },
            }, {
                'method': 'execute',
                'uuid': 1,
                'arguments': {
                    'pid': 1,
                    'own_uuid': 1,
                    'path': prog,
                    'arguments': args
                },
            }]))

        response1 = Status(
            Status.ID_ERR,
            {
                'method':
                'execute',
                'result':
                "execute() missing 1 required positional argument: 'arguments'",
            },
            'uniqueidforfirst',
        )

        response2 = Status(
            Status.ID_ERR,
            {
                'method':
                'execute',
                'result':
                'Could not execute because earlier command was not successful.',
            },
            'uniqueidforsecond',
        )

        self.assertEqual(Status(**result[0]), response1)
        self.assertEqual(Status(**result[1]), response2)
        def execute_call(cmd):
            """
            Handles an incoming message in a seperat task
            """
            callable_command = Rpc.get(cmd.method)
            logging.debug("Found correct function ... calling.")

            try:
                result = yield from asyncio.coroutine(callable_command)(
                    **cmd.arguments)
                status_code = Status.ID_OK
                logging.debug(
                    'method %s with args: %s returned %s.',
                    cmd.method,
                    cmd.arguments,
                    result,
                )
            except Exception as err:  # pylint: disable=W0703
                result = str(err)
                status_code = Status.ID_ERR
                logging.info('Function raise Exception(%s)', result)

            return Status(status_code, {
                'method': cmd.method,
                'result': result
            }, cmd.uuid)
    def __init__(self, index, url, qn, path, spider, block_size=10*1024*1024):

        self.index = index
        self.url = url
        self.qn = qn
        self.path = "{}.{:03}".format(path, index)
        self.spider = spider
        self.block_size = 10*1024*1024

        self.name = os.path.split(self.path)[-1]
        self.status = Status()
    def __init__(self, page, name, path, cid, spider):

        self.page = page
        self.name = name
        self.path = path
        self.cid = cid
        self.spider = spider

        self.video = None
        self.audio = None
        self.total = 0
        self.status = Status()
Beispiel #6
0
    def __init__(self, id, neighbor_count=0, device_count=0):
        self.id = id

        self.neighbor_count = neighbor_count
        self.device_count = device_count

        self.global_results = Queue()

        self.device_hash = Hash(self.device_count)
        self.results_hash = Hash(self.neighbor_count)
        self.receive_hash = Hash(self.neighbor_count)
        self.neighbor_map = Hash(self.neighbor_count)

        self.mutex = Lock()
        self.status = Status(running=True)
    def __init__(self, type, url, qn, path, spider):

        self.type = type
        self.url = url
        self.qn = qn
        self.path = '{}_{}.m4s'.format(os.path.splitext(path)[0], self.type)
        self.spider = spider

        self.block_size = 10*1024*1024
        self.name = os.path.split(self.path)[-1]
        self.total = 0
        self.get_total()

        print("[Info] 正在下载{},大小:{}MB".format(self.name, round(self.total / (1024*1024), 2)))
        self.blocks = []
        self.get_blocks()
        self.status = Status()
Beispiel #8
0
def handle_chain_execution(status):
    """
    This function handles incoming responses for the method `chain_execution`.
    The `Status` object consists of multiple `Status` objects. For all `Status`
    objects the appropriate handler will be called.

    Parameters
    ----------
        status: Status
            The `Status` object that was send by the slave

    """
    LOGGER.info("Handle chain execution %s", dict(status))

    if status.is_ok():
        LOGGER.info("chain_execution results: %s", dict(status))

        for result in status.payload["result"]:
            select_method(Status(**result))
    else:
        LOGGER.error(
            "Received Status.err for chain_execution, but this function can not raise errors. (payload: %s)",
            status.payload,
        )
Beispiel #9
0
    def __init__(self, debug=False):
        # Super
        QMainWindow.__init__(self)
        self.locked = False
        self.last_path = None
        self.input_file = None
        self.xml_modified = False

        # Initialize UI class
        self.ui = ui_mainwindow.Ui_mainWindow()
        self.ui.setupUi(self)

        # Handles to text editors
        self.textEditors = []
        self.xmlEditor = None

        # Initialize status
        self.status = Status(self.statusBar())

        # Setup backend thread to connect with xml2rfc library
        self.status('Loading backend...')
        self.handler = XmlRfcHandler(debug=debug)

        # Connect backend thread signals
        self.connect(self.handler, SIGNAL('finished()'), self.unlockWidgets)
        self.connect(self.handler, SIGNAL('terminated()'), self.unlockWidgets)
        self.connect(self.handler, SIGNAL('stdout(QString)'),
                     self.stdOutCallback)
        self.connect(self.handler, SIGNAL('stderr(QString)'),
                     self.stdErrCallback)
        self.connect(self.handler, SIGNAL('viewDocument(int, QString)'),
                     self.viewDocument)
        self.connect(self.handler, SIGNAL('finished(int)'),
                     self.convertFinished)
        self.connect(self.handler, SIGNAL('error(QString, int)'),
                     self.recieveError)
        self.connect(self.handler, SIGNAL('status(QString)'),
                     self.status.__call__)

        # Create Settings instance
        self.status('Loading settings...')
        self.settings = Settings(self,
                                 self.handler,
                                 versionstring='.'.join(map(str, VERSION)))
        self.status('Ready')

        # Connect main actions
        self.connect(self.ui.actionQuit, SIGNAL('triggered()'), self.close)
        self.connect(self.ui.actionHelp, SIGNAL('triggered()'), self.showHelp)
        self.connect(self.ui.actionAbout, SIGNAL('triggered()'),
                     self.showAbout)
        self.connect(self.ui.actionAboutQt, SIGNAL('triggered()'),
                     self.showAboutQt)
        self.connect(self.ui.actionOpen, SIGNAL('triggered()'), self.openFile)
        self.connect(self.ui.actionSave, SIGNAL('triggered()'), self.saveFile)
        self.connect(self.ui.actionInstallCLI, SIGNAL('triggered()'),
                     self.installCLI)
        self.connect(self.ui.actionPreferences, SIGNAL('triggered()'),
                     self.settings.showPreferences)

        # Connect persistent UI settings
        self.connect(self.ui.actionOptionVerbose, SIGNAL('toggled(bool)'),
                     self.settings.setVerbose)

        # Connect any other widgets
        self.connect(self.ui.convertButton, SIGNAL('clicked()'), self.convert)
        self.connect(self.ui.textConsole, SIGNAL('anchorClicked(const QUrl&)'),
                     self.consoleLinkClicked)
        self.connect(self.ui.tabWidget, SIGNAL('currentChanged(int)'),
                     self.tabChanged)

        # Label data
        self.formatLabels = {
            self.handler.XML: 'XML',
            self.handler.PAGED: 'Paginated Text',
            self.handler.RAW: 'Raw Text',
            self.handler.HTML: 'HTML',
            self.handler.NROFF: 'Nroff',
        }

        # Maintain a list of widgets to lock during batch processing
        self.lockableWidgets = [
            self.ui.formatRaw, self.ui.formatPaged, self.ui.formatHtml,
            self.ui.formatNroff, self.ui.convertButton
        ]

        # Was input file passed on commandline?
        if len(sys.argv) > 1:
            path = sys.argv[1]
            if os.access(path, os.R_OK):
                self.input_file = path
                self.ui.sourceLabel.setText(path)
                self.deleteTabs()
                self.viewDocument(self.handler.XML, path)

        # CLI install script behavior
        if debug or not 'darwin' in sys.platform:
            self.ui.actionInstallCLI.setEnabled(False)
        else:
            self.checkCLIOnFirstLaunch()
Beispiel #10
0
 def __init__(self, id, node, target=None):
     self.node = node
     self.results = Queue()
     self.status = Status(running=True)
     self.thread = Process(target=target, args=(self, ))
Beispiel #11
0
def chain_execution(commands):
    """
    Executes given commands sequential. If one commands fails all other commands fail
    too.
    """
    result = []
    error = False

    for command in commands:
        try:
            cmd = Command(command["method"],
                          uuid=command["uuid"],
                          **command["arguments"])
        except Exception as err:  #pylint: disable=W0703
            print(err)
            continue

        if error:
            ret = Status(
                Status.ID_ERR,
                {
                    'method':
                    cmd.method,
                    'result':
                    "Could not execute because earlier command was not successful."
                },
                cmd.uuid,
            )

            result.append(dict(ret))
        else:

            try:
                fun = Rpc.get(cmd.method)
                print(dict(cmd))
                ret = yield from asyncio.coroutine(fun)(**cmd.arguments)

                ret = Status(
                    Status.ID_OK,
                    {
                        'method': cmd.method,
                        'result': ret
                    },
                    cmd.uuid,
                )

                result.append(dict(ret))
            except Exception as err:  #pylint: disable=W0703
                ret = Status(
                    Status.ID_ERR,
                    {
                        'method': cmd.method,
                        'result': str(err)
                    },
                    cmd.uuid,
                )

                result.append(dict(ret))
                error = True

    return result