Ejemplo n.º 1
0
	def _process_snapshot(self, snapshot_path, pixfmt="yuv420p"):
		hflip  = self._settings.global_get_boolean(["webcam", "flipH"])
		vflip  = self._settings.global_get_boolean(["webcam", "flipV"])
		rotate = self._settings.global_get_boolean(["webcam", "rotate90"])
		ffmpeg = self._settings.global_get(["webcam", "ffmpeg"])
		
		if not ffmpeg or not os.access(ffmpeg, os.X_OK) or (not vflip and not hflip and not rotate):
			return

		ffmpeg_command = [ffmpeg, "-y", "-i", snapshot_path]

		rotate_params = ["format={}".format(pixfmt)] # workaround for foosel/OctoPrint#1317
		if rotate:
			rotate_params.append("transpose=2") # 90 degrees counter clockwise
		if hflip:
			rotate_params.append("hflip") 		# horizontal flip
		if vflip:
			rotate_params.append("vflip")		# vertical flip

		ffmpeg_command += ["-vf", sarge.shell_quote(",".join(rotate_params)), snapshot_path]
		self._logger.info("Running: {}".format(" ".join(ffmpeg_command)))

		p = sarge.run(ffmpeg_command, stdout=sarge.Capture(), stderr=sarge.Capture())
		if p.returncode == 0:
			self._logger.info("Rotated/flipped image with ffmpeg")
		else:
			self._logger.warn("Failed to rotate/flip image with ffmpeg, "
			                  "got return code {}: {}, {}".format(p.returncode,
			                                                      p.stdout.text,
			                                                      p.stderr.text))
Ejemplo n.º 2
0
    def _start(self):
        """Start work task running in the background.  User should not need to call this directly.
        Work with your subclasses `run` method instead.
        """
        self._results = None

        if not self.command:
            raise ValueError('command not defined')

        # Pre-existing process ID?
        if self.is_running:
            if self.verbose:
                print('\nProcess already running with PID: {:d}'.format(
                    self.pid))
            return self.pid

        # Instantiate command and run it
        self._proc = sarge.Command(self.command,
                                   stdout=sarge.Capture(),
                                   stderr=sarge.Capture(),
                                   shell=True)
        self._proc.run(async=True)

        if not self.is_running:
            raise ValueError('Problem starting process: {}'.format(
                self.fname_exe))
Ejemplo n.º 3
0
    def autodetect_pip(cls):
        commands = [
            [sys.executable, "-m", "pip"],
            [
                os.path.join(os.path.dirname(sys.executable),
                             "pip.exe" if sys.platform == "win32" else "pip")
            ],

            # this should be our last resort since it might fail thanks to using pip programmatically like
            # that is not officially supported or sanctioned by the pip developers
            [
                sys.executable, "-c",
                "import sys; sys.argv = ['pip'] + sys.argv[1:]; import pip; pip.main()"
            ]
        ]

        for command in commands:
            p = sarge.run(command + ["--version"],
                          stdout=sarge.Capture(),
                          stderr=sarge.Capture())
            if p.returncode == 0:
                logging.getLogger(__name__).info(
                    "Using \"{}\" as command to invoke pip".format(
                        " ".join(command)))
                return command

        return None
Ejemplo n.º 4
0
    def generate_password(self):
        """Generates an org password with the sfdx utility. """

        if self.password_failed:
            self.logger.warn(
                "Skipping resetting password since last attempt failed")
            return

        # Set a random password so it's available via cci org info
        command = sarge.shell_format(
            "sfdx force:user:password:generate -u {0}", self.username)
        self.logger.info(
            "Generating scratch org user password with command {}".format(
                command))
        p = sarge.Command(
            command,
            stdout=sarge.Capture(buffer_size=-1),
            stderr=sarge.Capture(buffer_size=-1),
            shell=True,
        )
        p.run()

        stdout = []
        for line in p.stdout:
            stdout.append(line)
        stderr = []
        for line in p.stderr:
            stderr.append(line)

        if p.returncode:
            self.config["password_failed"] = True
            # Don't throw an exception because of failure creating the
            # password, just notify in a log message
            self.logger.warn("Failed to set password: \n{}\n{}".format(
                "\n".join(stdout), "\n".join(stderr)))
Ejemplo n.º 5
0
def executeSystemCommand(source, command):
    logger = logging.getLogger(__name__)

    if command == "divider":
        return make_response("Dividers cannot be executed", 400)

    command_spec = _get_command_spec(source, command)
    if not command_spec:
        return make_response("Command {}:{} not found".format(source, command),
                             404)

    if not "command" in command_spec:
        return make_response(
            "Command {}:{} does not define a command to execute, can't proceed"
            .format(source, command), 500)

    async = command_spec["async"] if "async" in command_spec else False
    ignore = command_spec["ignore"] if "ignore" in command_spec else False
    logger.info("Performing command for {}:{}: {}".format(
        source, command, command_spec["command"]))
    try:
        # we run this with shell=True since we have to trust whatever
        # our admin configured as command and since we want to allow
        # shell-alike handling here...
        p = sarge.run(command_spec["command"],
                      stdout=sarge.Capture(),
                      stderr=sarge.Capture(),
                      shell=True,
                      async=async)
Ejemplo n.º 6
0
def run(cmd,
        raise_on_error=True,
        capture_output=True,
        suppress_output=False,
        **kwargs):
    """
    Wrapper around sarge.run that can raise errors and capture stdout.
    """
    if capture_output:
        kwargs['stdout'] = sarge.Capture()
        kwargs['stderr'] = sarge.Capture()
    result = sarge.run(cmd, **kwargs)
    code = result.returncode
    if code and raise_on_error:
        raise RuntimeError('Command failed, exit code %s' % code)
    if capture_output:
        stdout = result.stdout.read()
        result.stdout_lines = stdout.decode().split('\n')
        if result.stdout_lines[-1] == '':
            result.stdout_lines = result.stdout_lines[:-1]
        if not suppress_output:
            if stdout:
                click.echo(stdout)
            stderr = result.stderr.read()
            if stderr:
                click.echo(stderr, err=True)
    return result
Ejemplo n.º 7
0
def execute(command, cwd=None, evaluate_returncode=True, **kwargs):
    do_async = kwargs.get("do_async", kwargs.get("async", False))

    import sarge
    p = None

    try:
        p = sarge.run(command,
                      cwd=cwd,
                      stdout=sarge.Capture(),
                      stderr=sarge.Capture(),
                      async_=do_async)
    except:
        logging.getLogger(__name__).exception(
            "Error while executing command: {}".format(command))
        returncode = p.returncode if p is not None else None
        stdout = p.stdout.text if p is not None and p.stdout is not None else ""
        stderr = p.stderr.text if p is not None and p.stderr is not None else ""
        raise ScriptError(returncode, stdout, stderr)

    if evaluate_returncode and p.returncode != 0:
        raise ScriptError(p.returncode, p.stdout.text, p.stderr.text)

    if not do_async:
        return p.returncode, p.stdout.text, p.stderr.text
def run_command_with_logging(args):

    logger.info(f"Running command: {args}")

    with sarge.Capture(buffer_size=1) as stdout, sarge.Capture(
            buffer_size=1) as stderr:
        pipeline = sarge.run(args, async_=True, stdout=stdout, stderr=stderr)

        while pipeline.commands[-1].poll() == None:

            stdout_result = stdout.read(block=False)
            if stdout_result != b'':
                logger.info(stdout_result)
            stderr_result = stderr.read(block=False)
            if stderr_result != b'':
                logger.error(stderr_result)

            if stdout_result != b'' or stderr_result != b'':
                time.sleep(0.1)

        stdout_result = stdout.read()
        if stdout_result != b'':
            logger.info(stdout_result)
        stderr_result = stderr.read()
        if stderr_result != b'':
            logger.error(stderr_result)

        if pipeline.commands[-1].poll() != 0:
            raise CmError(args, stdout, stderr)
Ejemplo n.º 9
0
    def _render(self, template_filename):
        render_config = self.render_config(template_filename)
        if self.badge_instance:
            url = reverse(
                "main:instance-filename",
                kwargs={
                    "slug": self.badge_template.slug,
                    "pk": self.badge_instance.pk,
                    "filename": template_filename,
                },
            )
        else:
            url = reverse(
                "main:preview-filename",
                kwargs={
                    "slug": self.badge_template.slug,
                    "filename": template_filename,
                },
            )

        file_format = render_config.get("format", "png")
        if file_format == "pdf":
            f = tempfile.NamedTemporaryFile(delete=False)
            tmppdf = f.name
            f.close()

            cmd = (
                "node {chrome_pdf_bin} "
                "--paper-width 8.27 --paper-height 11.69"
                "--no-margins --landscape --include-background --url {url} --pdf {tmppdf}"
                .format(
                    chrome_pdf_bin=settings.CHROME_PDF_BIN,
                    tmppdf=tmppdf,
                    url="{}{}".format(settings.RENDER_PREFIX_URL, url),
                ))
            sarge.run(cmd, stdout=sarge.Capture())

            f = open(tmppdf, "rb")
            image = f.read()
            f.close()
            os.unlink(f.name)

        else:
            cmd = ("{capture_bin} {url} --width={width} --height={height} "
                   "--type={type} --element={element} --no-default-background".
                   format(
                       width=render_config.get("screen_width", 1000),
                       height=render_config.get("screen_height", 1000),
                       type=file_format,
                       element=sarge.shell_quote(
                           render_config.get("element", ".screenshot")),
                       url="{}{}".format(settings.RENDER_PREFIX_URL, url),
                       capture_bin=settings.CAPTURE_BIN,
                   ))
            p = sarge.run(cmd, stdout=sarge.Capture())

            image = p.stdout.bytes

        mime = magic.from_buffer(image, mime=True)
        return image, mime
Ejemplo n.º 10
0
def _prepareCapture(encoding, *, wantOut=False, wantErr=False):
    ret = {}
    if wantOut:
        ret["stdout"] = sarge.Capture(encoding=encoding)
    if wantErr:
        ret["stderr"] = sarge.Capture(encoding=encoding)

    return ret
Ejemplo n.º 11
0
	def _render(self):
		"""Rendering runnable."""

		ffmpeg = settings().get(["webcam", "ffmpeg"])
		bitrate = settings().get(["webcam", "bitrate"])
		if ffmpeg is None or bitrate is None:
			self._logger.warn("Cannot create movie, path to ffmpeg or desired bitrate is unset")
			return

		input = os.path.join(self._capture_dir,
		                     self._capture_format.format(prefix=self._prefix,
		                                                 postfix=self._postfix if self._postfix is not None else ""))
		output = os.path.join(self._output_dir,
		                      self._output_format.format(prefix=self._prefix,
		                                                 postfix=self._postfix if self._postfix is not None else ""))

		for i in range(4):
			if os.path.exists(input % i):
				break
		else:
			self._logger.warn("Cannot create a movie, no frames captured")
			self._notify_callback("fail", output, returncode=0, stdout="", stderr="", reason="no_frames")
			return

		hflip = settings().getBoolean(["webcam", "flipH"])
		vflip = settings().getBoolean(["webcam", "flipV"])
		rotate = settings().getBoolean(["webcam", "rotate90"])

		watermark = None
		if settings().getBoolean(["webcam", "watermark"]):
			watermark = os.path.join(os.path.dirname(__file__), "static", "img", "watermark.png")
			if sys.platform == "win32":
				# Because ffmpeg hiccups on windows' drive letters and backslashes we have to give the watermark
				# path a special treatment. Yeah, I couldn't believe it either...
				watermark = watermark.replace("\\", "/").replace(":", "\\\\:")

		# prepare ffmpeg command
		command_str = self._create_ffmpeg_command_string(ffmpeg, self._fps, bitrate, self._threads, input, output,
		                                                 hflip=hflip, vflip=vflip, rotate=rotate, watermark=watermark)
		self._logger.debug("Executing command: {}".format(command_str))

		with self.render_job_lock:
			try:
				self._notify_callback("start", output)
				p = sarge.run(command_str, stdout=sarge.Capture(), stderr=sarge.Capture())
				if p.returncode == 0:
					self._notify_callback("success", output)
				else:
					returncode = p.returncode
					stdout_text = p.stdout.text
					stderr_text = p.stderr.text
					self._logger.warn("Could not render movie, got return code %r: %s" % (returncode, stderr_text))
					self._notify_callback("fail", output, returncode=returncode, stdout=stdout_text, stderr=stderr_text, reason="returncode")
			except:
				self._logger.exception("Could not render movie due to unknown error")
				self._notify_callback("fail", output, reason="unknown")
			finally:
				self._notify_callback("always", output)
Ejemplo n.º 12
0
	def call(self, command, **kwargs):
		if isinstance(command, (list, tuple)):
			joined_command = " ".join(command)
		else:
			joined_command = command
		self._logger.debug(u"Calling: {}".format(joined_command))
		self.on_log_call(joined_command)

		kwargs.update(dict(async=True, stdout=sarge.Capture(), stderr=sarge.Capture()))
Ejemplo n.º 13
0
    def _get_pip_version(self, pip_command):
        # Debugging this with PyCharm/IntelliJ with Python plugin and no output is being
        # generated? PyCharm bug. Disable "Attach to subprocess automatically when debugging"
        # in IDE Settings or patch pydevd.py
        # -> https://youtrack.jetbrains.com/issue/PY-18365#comment=27-1290453

        pip_command_str = pip_command
        if isinstance(pip_command_str, list):
            pip_command_str = " ".join(pip_command_str)

        if not self.ignore_cache and pip_command_str in _cache["version"]:
            self._logger.debug(
                "Using cached pip version information for {}".format(
                    pip_command_str))
            return _cache["version"][pip_command_str]

        sarge_command = self.to_sarge_command(pip_command, "--version")
        p = sarge.run(sarge_command,
                      stdout=sarge.Capture(),
                      stderr=sarge.Capture())

        if p.returncode != 0:
            self._logger.warn(
                "Error while trying to run pip --version: {}".format(
                    p.stderr.text))
            return None, None

        output = PipCaller._preprocess(p.stdout.text)
        # output should look something like this:
        #
        #     pip <version> from <path> (<python version>)
        #
        # we'll just split on whitespace and then try to use the second entry

        if not output.startswith("pip"):
            self._logger.warn(
                "pip command returned unparseable output, can't determine version: {}"
                .format(output))

        split_output = [x.strip() for x in output.split()]
        if len(split_output) < 2:
            self._logger.warn(
                "pip command returned unparseable output, can't determine version: {}"
                .format(output))

        version_segment = split_output[1]

        try:
            pip_version = pkg_resources.parse_version(version_segment)
        except:
            self._logger.exception(
                "Error while trying to parse version string from pip command")
            return None, None

        result = pip_version, version_segment
        _cache["version"][pip_command_str] = result
        return result
Ejemplo n.º 14
0
    def run(self) -> (int, str):
        cancelled = False
        finished = False
        capture_out = sarge.Capture()
        capture_err = sarge.Capture()
        captured_out = []
        captured_err = []

        logger.debug("Process executed: %s", self._cmd)
        pipeline = sarge.run(self._cmd, async=True, stdout=capture_out, stderr=capture_err, shell=False)

        def kill_all_if_cancelled():
            process_is_running = 2
            while process_is_running:
                if finished:
                    process_is_running = process_is_running - 1
                while True:
                    line_out_bin = capture_out.readline(block=False)
                    line_out = str(line_out_bin, encoding='utf-8')
                    line = line_out.replace('\n', '').replace('\r', '').replace('\0', '')
                    if not line_out or ord(line_out[0]) == 0:
                        break
                    else:
                        captured_out.append(line)
                        if not self.get_parameters()['dont_log_stdout']:
                            logger.debug(f"| {line}")
                while True:
                    line_out_bin = capture_err.readline(block=False)
                    line_err = str(line_out_bin, encoding='utf-8')
                    line = line_err.replace('\n', '').replace('\r', '').replace('\0', '')
                    if not line_out or ord(line_out[0]) == 0:
                        break
                    else:
                        captured_err.append(line)
                        if not self.get_parameters()['dont_log_stderr']:
                            logger.warning(f"| {line}")
                if self._is_cancelled():
                    nonlocal cancelled
                    cancelled = True
                    for c in pipeline.commands:
                        c.terminate()
                time.sleep(0.1)

        if self.get_parameters()['async']:
           return 0, '', ''

        watchdog = threading.Thread(target=kill_all_if_cancelled, name='process-watchdog', daemon=True)
        watchdog.start()

        pipeline.wait()
        finished = True
        watchdog.join()
        if cancelled:
            raise UserCancelledError()

        return pipeline.returncode, '\n'.join(captured_out), '\n'.join(captured_err)
Ejemplo n.º 15
0
def _erase_dfuprog(self):
    dfuprog_path = self.get_profile_setting("dfuprog_path")
    dfuprog_avrmcu = self.get_profile_setting("dfuprog_avrmcu")

    working_dir = os.path.dirname(dfuprog_path)

    dfuprog_erasecommand = self.get_profile_setting("dfuprog_erasecommandline")
    dfuprog_erasecommand = dfuprog_erasecommand.replace(
        "{dfuprogrammer}", dfuprog_path)
    dfuprog_erasecommand = dfuprog_erasecommand.replace(
        "{mcu}", dfuprog_avrmcu)

    import sarge
    self._logger.info(u"Running '{}' in {}".format(dfuprog_erasecommand,
                                                   working_dir))
    self._console_logger.info(dfuprog_erasecommand)
    try:
        p = sarge.run(dfuprog_erasecommand,
                      cwd=working_dir,
                      async_=True,
                      stdout=sarge.Capture(buffer_size=1),
                      stderr=sarge.Capture(buffer_size=1))
        p.wait_events()

        while p.returncode is None:
            output = p.stderr.read(timeout=0.5).decode('utf-8')
            if not output:
                p.commands[0].poll()
                continue

            for line in output.split("\n"):
                if line.endswith("\r"):
                    line = line[:-1]
                self._console_logger.info(u"> {}".format(line))

                if DFUPROG_ERASING in line:
                    self._logger.info(u"Erasing memory...")
                    self._send_status("progress", subtype="erasing")
                elif DFUPROG_NODEVICE in line:
                    raise FlashException("No device found")

        if p.returncode == 0:
            return True
        else:
            raise FlashException(
                "dfu-programmer returned code {returncode}".format(
                    returncode=p.returncode))

    except FlashException as ex:
        self._logger.error(u"Erasing failed. {error}.".format(error=ex.reason))
        self._send_status("flasherror", message=ex.reason)
        return False
    except:
        self._logger.exception(u"Erasing failed. Unexpected error.")
        self._send_status("flasherror")
        return False
Ejemplo n.º 16
0
def executeSystemCommand(source, command):
    logger = logging.getLogger(__name__)

    if command == "divider":
        return make_response("Dividers cannot be executed", 400)

    command_spec = _get_command_spec(source, command)
    if not command_spec:
        return make_response("Command {}:{} not found".format(source, command),
                             404)

    if not "command" in command_spec:
        return make_response(
            "Command {}:{} does not define a command to execute, can't proceed"
            .format(source, command), 500)

    do_async = command_spec.get("async", False)
    do_ignore = command_spec.get("ignore", False)
    logger.info("Performing command for {}:{}: {}".format(
        source, command, command_spec["command"]))

    try:
        if "before" in command_spec and callable(command_spec["before"]):
            command_spec["before"]()
    except Exception as e:
        if not do_ignore:
            error = "Command \"before\" failed: {}".format(str(e))
            logger.warn(error)
            return make_response(error, 500)

    try:
        # we run this with shell=True since we have to trust whatever
        # our admin configured as command and since we want to allow
        # shell-alike handling here...
        p = sarge.run(command_spec["command"],
                      stdout=sarge.Capture(),
                      stderr=sarge.Capture(),
                      shell=True,
                      async=do_async)
        if not do_async:
            if not do_ignore and p.returncode != 0:
                returncode = p.returncode
                stdout_text = p.stdout.text
                stderr_text = p.stderr.text

                error = "Command failed with return code {}:\nSTDOUT: {}\nSTDERR: {}".format(
                    returncode, stdout_text, stderr_text)
                logger.warn(error)
                return make_response(error, 500)
    except Exception as e:
        if not do_ignore:
            error = "Command failed: {}".format(str(e))
            logger.warn(error)
            return make_response(error, 500)

    return NO_CONTENT
Ejemplo n.º 17
0
def _execute(command, **kwargs):
	import sarge

	if isinstance(command, (list, tuple)):
		joined_command = " ".join(command)
	else:
		joined_command = command
	_log_call(joined_command)

	kwargs.update(dict(async=True, stdout=sarge.Capture(), stderr=sarge.Capture()))
Ejemplo n.º 18
0
    def execute(self, *args):
        if self.refresh:
            self.trigger_refresh()

        if self._command is None:
            raise UnknownPip()

        command = [self._command] + list(args)
        if self._use_sudo:
            command = ["sudo"] + command

        joined_command = " ".join(command)
        self._logger.debug(u"Calling: {}".format(joined_command))
        self.on_log_call(joined_command)

        p = sarge.run(command,
                      async=True,
                      stdout=sarge.Capture(),
                      stderr=sarge.Capture())
        p.wait_events()

        all_stdout = []
        all_stderr = []
        try:
            while p.returncode is None:
                lines = p.stderr.readlines(timeout=0.5)
                if lines:
                    lines = self._convert_lines(lines)
                    self._log_stderr(*lines)
                    all_stderr += lines

                lines = p.stdout.readlines(timeout=0.5)
                if lines:
                    lines = self._convert_lines(lines)
                    self._log_stdout(*lines)
                    all_stdout += lines

                p.commands[0].poll()

        finally:
            p.close()

        lines = p.stderr.readlines()
        if lines:
            lines = map(self._convert_line, lines)
            self._log_stderr(*lines)
            all_stderr += lines

        lines = p.stdout.readlines()
        if lines:
            lines = map(self._convert_line, lines)
            self._log_stdout(*lines)
            all_stdout += lines

        return p.returncode, all_stdout, all_stderr
Ejemplo n.º 19
0
    def execute(self, *args):
        if self.refresh:
            self.trigger_refresh()

        if self._command is None:
            raise UnknownPip()

        command = [self._command] + list(args)
        if self._use_sudo:
            command = ["sudo"] + command

        joined_command = " ".join(command)
        self._logger.debug(u"Calling: {}".format(joined_command))
        self.on_log_call(joined_command)

        p = sarge.run(command,
                      async=True,
                      stdout=sarge.Capture(),
                      stderr=sarge.Capture())
        p.wait_events()

        all_stdout = []
        all_stderr = []
        try:
            while p.returncode is None:
                line = p.stderr.readline(timeout=0.5)
                if line:
                    line = to_unicode(line, errors="replace")
                    self._log_stderr(line)
                    all_stderr.append(line)

                line = p.stdout.readline(timeout=0.5)
                if line:
                    line = to_unicode(line, errors="replace")
                    self._log_stdout(line)
                    all_stdout.append(line)

                p.commands[0].poll()

        finally:
            p.close()

        stderr = p.stderr.text
        if stderr:
            split_lines = stderr.split("\n")
            self._log_stderr(*split_lines)
            all_stderr += split_lines

        stdout = p.stdout.text
        if stdout:
            split_lines = stdout.split("\n")
            self._log_stdout(*split_lines)
            all_stdout += split_lines

        return p.returncode, all_stdout, all_stderr
Ejemplo n.º 20
0
    def _flash_worker_from_path(self, hex_path, selected_port):

        if self._printer.is_operational():
            self._printer.disconnect()

        avrdude_path = self._settings.get(["avrdude_path"])
        working_dir = os.path.dirname(avrdude_path)
        avrdude_command = [
            avrdude_path, "-v", "-p", "m2560", "-c", "wiring", "-P",
            selected_port, "-U", "flash:w:" + hex_path + ":i", "-D"
        ]

        import sarge
        self._logger.info(u"Running %r in %s" %
                          (' '.join(avrdude_command), working_dir))
        try:
            p = sarge.run(avrdude_command,
                          cwd=working_dir,
                          async=True,
                          stdout=sarge.Capture(),
                          stderr=sarge.Capture())
            p.wait_events()

            while p.returncode is None:
                line = p.stderr.read(timeout=0.5)
                if not line:
                    p.commands[0].poll()
                    continue
                if "avrdude: writing" in line:
                    self._logger.info(u"Writing memory...")
                elif "avrdude: verifying ..." in line:
                    self._logger.info(u"Verifying memory...")
                elif "timeout communicating with programmer" in line:
                    e_msg = "Timeout communicating with programmer"
                    raise AvrdudeException
                elif "avrdude: ERROR:" in line:
                    e_msg = "AVRDUDE error: " + line[
                        line.find("avrdude: ERROR:") +
                        len("avrdude: ERROR:"):].strip()
                    raise AvrdudeException

            if p.returncode == 0:
                self._logger.info(u"Flashing successful.")
            else:
                e_msg = "Avrdude returned code {returncode}".format(
                    returncode=p.returncode)
                raise AvrdudeException

        except AvrdudeException:
            self._logger.error(
                u"Flashing failed. {error}.".format(error=e_msg))
        except:
            self._logger.exception(u"Flashing failed. Unexpected error.")
        finally:
            self.isUpdating = False
Ejemplo n.º 21
0
def get_git_config(config_key):
    p = sarge.Command(
        sarge.shell_format('git config --get "{0!s}"', config_key),
        stderr=sarge.Capture(buffer_size=-1),
        stdout=sarge.Capture(buffer_size=-1),
        shell=True,
    )
    p.run()
    config_value = io.TextIOWrapper(p.stdout).read().strip()

    return config_value if config_value and not p.returncode else None
Ejemplo n.º 22
0
def sh(cmd, show_cmd=False, CaptureOutput = False, Timeout = -1):
  if show_cmd:
    print(cmd)
  try:
    if CaptureOutput:
      if Timeout > -1:
        P = sarge.run(cmd, shell=True, stdout=sarge.Capture(), stderr=sarge.Capture(), async_=True)
        # sleep(3)
        try:
          CMD = P.commands[0] #type: sarge.Command # FIXME: This line generates index exception sometime
          timed_out = util.wait_process(Timeout, CMD)
          if timed_out:
            util.print_color('The command "%s" is timed out!'%cmd, util.tty_colors_cmds.On_Red)
          util.kill_alive_process(CMD)
        except:
          pass
      else:
        P = sarge.run(cmd, shell=True, stdout=sarge.Capture(), stderr=sarge.Capture())
    else:
      if Timeout > -1:
        P = sarge.run(cmd, shell=True, async_=True)
        # sleep(3)
        try:
          CMD = P.commands[0] #type: sarge.Command # FIXME: This line generates index exception sometime
          timed_out = util.wait_process(Timeout, CMD)
          if timed_out:
            util.print_color('The command "%s" is timed out!'%cmd, util.tty_colors_cmds.On_Red)
          util.kill_alive_process(CMD)
        except:
          pass
      else:
        P = sarge.run(cmd, shell=True)
    
    outputs = ''

    if P.stdout and len(P.stdout.text) > 0:
      outputs = P.stdout.text
    if P.stderr and len(P.stderr.text) > 0:
      if outputs == '':
        outputs = P.stderr.text
      else:
        outputs += '\n' + P.stderr.text
    return P.returncode == 0, outputs
  except:
    if util.get_makefile_var('Debug') == True:
      util.Print_Debuging_messages()
  
    return False, ''
Ejemplo n.º 23
0
    def callScript(self, panValue, tiltValue):
        self.panValue = max(
            self._settings.get(["pan", "minValue"]),
            min(self._settings.get(["pan", "maxValue"]), panValue))
        self.tiltValue = max(
            self._settings.get(["tilt", "minValue"]),
            min(self._settings.get(["tilt", "maxValue"]), tiltValue))

        # if there are anly pantilt handlers, loop through them, then return
        if len(self.pantiltHandlers) > 0:
            values = {
                'pan': self.panValue,
                'panMin': self._settings.get(["pan", "minValue"]),
                'panMax': self._settings.get(["pan", "maxValue"]),
                'tilt': self.tiltValue,
                'tiltMin': self._settings.get(["tilt", "minValue"]),
                'tiltMax': self._settings.get(["tilt", "maxValue"])
            }
            for name, handler in self.pantiltHandlers.items():
                handler(values)
            return

        script = self._settings.get(["pathToScript"])
        if script == "":
            return

        self._logger.info("Performing command: {}".format(script))
        try:
            # we run this with shell=True since we have to trust whatever
            # our admin configured as command and since we want to allow
            # shell-alike handling here...
            p = sarge.run(sarge.shell_format('{0} {1} {2}', script, panValue,
                                             tiltValue),
                          stdout=sarge.Capture(),
                          stderr=sarge.Capture(),
                          shell=True,
                          async=False)
            if p.returncode != 0:
                returncode = p.returncode
                stdout_text = p.stdout.text
                stderr_text = p.stderr.text

                error = "Command failed with return code {}:\nSTDOUT: {}\nSTDERR: {}".format(
                    returncode, stdout_text, stderr_text)
                self._logger.warn(error)
        except Exception, e:
            error = "Command failed: {}".format(str(e))
            self._logger.warn(error)
Ejemplo n.º 24
0
def battery():
    result = {
        "battery_perc": -1,
        "remaining_seconds": -1,
        "temperature_c": -1,
        "adapter_on": None
    }
    p = sarge.run("acpi --everything", stdout=sarge.Capture())
    output = p.stdout.text

    first_line = output.splitlines()[0].strip()
    print(first_line)
    batt_perc_raw = re.findall("(\d\d\d?)%", first_line)
    print(batt_perc_raw)
    result["battery_perc"] = int(batt_perc_raw[0])

    try:
        batt_remain_time = re.findall("(\d\d):(\d\d):(\d\d)", first_line)
        result["remaining_seconds"] = (
            lambda x: x[0] * 3600 + x[1] * 60 + x[2])(list(
                map(int, batt_remain_time[0])))
    except IndexError:
        result["remaining_seconds"] = -1

    temperature_raw = re.findall("Thermal .+(\d\d\.\d) degrees C", output)
    print("temp", temperature_raw)
    result["temperature_c"] = float(temperature_raw[0])

    adapter_on_raw = re.findall("Adapter \d: (on-line|off-line)", output)[0]
    print(adapter_on_raw)
    result["adapter_on"] = (adapter_on_raw == "on-line") and True or False

    return json_response(result, status_code=200)
Ejemplo n.º 25
0
def performSystemAction():
    if "action" in request.values.keys():
        action = request.values["action"]
        available_actions = s().get(["system", "actions"])
        for availableAction in available_actions:
            if availableAction["action"] == action:
                command = availableAction["command"]
                if command:
                    logger = logging.getLogger(__name__)

                    logger.info("Performing command: %s" % command)
                    try:
                        p = sarge.run(command, stderr=sarge.Capture())
                        if p.returncode != 0:
                            returncode = p.returncode
                            stderr_text = p.stderr.text
                            logger.warn(
                                "Command failed with return code %i: %s" %
                                (returncode, stderr_text))
                            return make_response(
                                ("Command failed with return code %i: %s" %
                                 (returncode, stderr_text), 500, []))
                        else:
                            return OK

                    except Exception, e:
                        logger.warn("Command failed: %s" % e)
                        return make_response(
                            ("Command failed: %s" % e, 500, []))

                else:
                    break
Ejemplo n.º 26
0
    def delete_org(self):
        """ Uses sfdx force:org:delete to delete the org """
        if not self.created:
            self.logger.info(
                "Skipping org deletion: the scratch org has not been created")
            return

        command = sarge.shell_format("sfdx force:org:delete -p -u {0}",
                                     self.username)
        self.logger.info(
            "Deleting scratch org with command {}".format(command))
        p = sarge.Command(command,
                          stdout=sarge.Capture(buffer_size=-1),
                          shell=True)
        p.run()

        org_info = None
        stdout = []
        for line in p.stdout:
            stdout.append(line)
            if line.startswith("An error occurred deleting this org"):
                self.logger.error(line)
            else:
                self.logger.info(line)

        if p.returncode:
            message = "Failed to delete scratch org: \n{}".format(
                "".join(stdout))
            raise ScratchOrgException(message)

        # Flag that this org has been created
        self.config["created"] = False
        self.config["username"] = None
Ejemplo n.º 27
0
                    def executeCommand(command, logger):
                        timeSleeping = 0.5
                        #if shutdown send message to plugin
                        if action == "reboot" or action == "shutdown":
                            eventManager().fire(Events.SHUTTING_DOWN,
                                                {'status': action})
                            timeSleeping = 1
                        time.sleep(
                            timeSleeping
                        )  #add a small delay to make sure the response is sent

                        try:
                            p = sarge.run(command, stderr=sarge.Capture())
                            if p.returncode != 0:
                                returncode = p.returncode
                                stderr_text = p.stderr.text
                                logger.warn(
                                    "Command failed with return code %i: %s" %
                                    (returncode, stderr_text))
                                if action == "reboot" or action == "shutdown":
                                    eventManager().fire(
                                        Events.SHUTTING_DOWN, {'status': None})
                            else:
                                logger.info("Command executed sucessfully")

                        except Exception, e:
                            logger.warn("Command failed: %s" % e)
                            if command == "reboot" or command == "shutdown":
                                eventManager().fire(Events.SHUTTING_DOWN,
                                                    {'status': None})
Ejemplo n.º 28
0
    def delete_org(self):
        """ Uses sfdx force:org:delete to create the org """
        if not self.created:
            self.logger.info(
                'Skipping org deletion: the scratch org has not been created')
            return

        command = 'sfdx force:org:delete -p -u {}'.format(self.username)
        self.logger.info(
            'Deleting scratch org with command {}'.format(command))
        p = sarge.Command(command, stdout=sarge.Capture(buffer_size=-1))
        p.run()

        org_info = None
        stdout = []
        for line in p.stdout:
            stdout.append(line)
            if line.startswith('An error occurred deleting this org'):
                self.logger.error(line)
            else:
                self.logger.info(line)

        if p.returncode:
            message = 'Failed to delete scratch org: \n{}'.format(
                ''.join(stdout))
            raise ScratchOrgException(message)

        # Flag that this org has been created
        self.config['created'] = False
        self.config['username'] = None
Ejemplo n.º 29
0
def remove_cref(tex, cwd):
    """
    """
    sty_file = cwd+'/dynlearn.sty'

    # add poorman to cleveref import
    cref_regex1 = (r'usepackage\{cleveref\}', r'usepackage[poorman]{cleveref}')
    cref_regex2 = (r'usepackage\[(\w*)\]\{cleveref\}', r'usepackage[\g<1>,poorman]{cleveref}')

    with open(sty_file) as dynlearn:
        source = dynlearn.read()

    for exp, repl in [cref_regex1, cref_regex2]:
        source = re.sub(exp, repl, source)


    with open(sty_file, 'w') as dynlearn:
        dynlearn.write(source)


    # generate and run the sed script
    compile_tex(tex, cwd)

    sed_cmd = sarge.shell_format("sed -f {0}.sed {0}.tex", tex.split('.')[0])
    cleaned = RUN_CMD(sed_cmd, cwd=cwd, stdout=sarge.Capture())

    with (pathlib.Path(cwd) / tex).open('w') as output:
        output.write(cleaned.stdout.text)

    # remove the cleveref import
    cref_regex3 = r'\\usepackage\[.*\]\{cleveref\}'
    comment_lines(sty_file, [cref_regex3])
Ejemplo n.º 30
0
    def create_org(self):
        """ Uses heroku force:org:create to create the org """
        if not self.config_file:
            # FIXME: raise exception
            return
        if not self.scratch_org_type:
            self.config['scratch_org_type'] = 'workspace'

        command = 'heroku force:org:create -t {} -f {}'.format(
            self.scratch_org_type, self.config_file)
        self.logger.info(
            'Creating scratch org with command {}'.format(command))
        p = sarge.Command(command, stdout=sarge.Capture(buffer_size=-1))
        p.run()

        org_info = None
        re_obj = re.compile(
            'Successfully created workspace org: (.+), username: (.+)')
        for line in p.stdout:
            match = re_obj.search(line)
            if match:
                self.config['org_id'] = match.group(1)
                self.config['username'] = match.group(2)
            self.logger.info(line)

        if p.returncode:
            # FIXME: raise exception
            raise ConfigError('Failed to create scratch org: {}'.format(
                '\n'.join(p.stdout)))

        # Flag that this org has been created
        self.config['created'] = True