Ejemplo n.º 1
0
    def ensure_image_deleted(self, force_delete=False) -> None:
        if self.image_exists():
            image = None
            yn = "n"

            if force_delete is True:
                yn = "y"
            else:
                print(
                    ConsoleColor.colorline("The image already exists",
                                           ConsoleColors.FAIL))
                yn = singlecharinput(
                    "Do you want to really delete the existing image file (y/n)?",
                    ConsoleColors.OKGREEN)

            if yn == "y":
                if force_delete is False:
                    print(
                        ConsoleColor.colorline(
                            "Deleting image '{}'".format(str(self._imagepath)),
                            ConsoleColors.FAIL))

                imagefilepath = str(self._imagepath.absolute())
                remove(imagefilepath)
                image = Path(str(imagefilepath))

                if image.exists():
                    raise Exception(
                        "Could not delete image '{}'".format(imagefilepath))
                else:
                    self._imagepath = image
Ejemplo n.º 2
0
def sevenzip(interactive: bool, compress_type: str, inputfilepath: str, outputfilepath: str=None):
	if string_is_empty(inputfilepath):
		raise Exception("No input file path provided")

	if string_is_empty(compress_type):
		if interactive is True:
			compress_type = strip(
				input(
					"Type the name of the compression algorithm (7z or zip)\n"
				)
			).lower()
		else:
			compress_type = "zip"

	if string_is_empty(compress_type):
		raise Exception("No compression algorithm chosen")

	if compress_type != "zip" and compress_type != "7z":
		raise Exception("Wrong compression algorithm (use 7z or zip)")

	if string_is_empty(outputfilepath):
		if interactive is True:
			outputfilepath = strip(input("Type the path of the compressed image file\n"))
		else:
			outputfilepath = inputfilepath + "." + compress_type

	if string_is_empty(outputfilepath):
		raise Exception("File path empty")

	cancelled = False

	p = Path(outputfilepath)

	if p.exists():
		yn = singlecharinput(
			"The file '{}' exists. Do you want to delete it?".format(
				outputfilepath
			), ConsoleColors.WARNING
		)
		if yn == "n":
			cancelled = True
			print(ConsoleColor.colorline("Cancelling compress process", ConsoleColors.OKBLUE))
		else:
			print(ConsoleColor.colorline("Deleting '{}'".format(outputfilepath), ConsoleColors.FAIL))
			if Path(outputfilepath).exists():
				print(ConsoleColor.colorline(
					"Could not delete '{}'".format(
						outputfilepath
					), ConsoleColors.FAIL)
				)
				cancelled = True

	if cancelled is False:
		sz = local["7z"]
		sz.run(["a", str(p.absolute()), inputfilepath])
Ejemplo n.º 3
0
    def print_pre_dd_info(self):
        print(
            ConsoleColor.colorline(
                "Approximate image size: {}".format(
                    self.get_target_image_sizehuman()),
                ConsoleColors.UNDERLINE))

        print(
            ConsoleColor.colorline(
                "Free space on image partition: {}".format(
                    self.get_image_mountpoint_sizeinfo()["free_h"]),
                ConsoleColors.UNDERLINE))
Ejemplo n.º 4
0
def singlecharinput(msg, color: ConsoleColors):
    nmsg = None

    if color is not ConsoleColors.NONE:
        nmsg = ConsoleColor.colorline(msg + " ", color)
    else:
        nmsg = msg

    return strip(input(nmsg)).lower()
Ejemplo n.º 5
0
def backup(configfile, backuptype, group, ignoreoptions):
    try:
        factory = LoggerFactory("backup")
        if backuptype == "image":
            b = ImageBackupUnit(configfile, factory)
        elif backuptype == "ssh":
            b = FileBackupUnit(configfile, True, factory, group, ignoreoptions)
        else:
            raise Exception("Backup-Unit-Type invalid")
        b.run()
    except Exception as e:
        print(
            ConsoleColor.colorline(
                get_reformatted_exception("Error in backup-function", e),
                ConsoleColors.FAIL))
        print(ConsoleColor.colorline(str(e), ConsoleColors.FAIL))
        return 2
    except (KeyboardInterrupt, SystemExit):
        print(
            ConsoleColor.colorline("Application killed via CTRL+C",
                                   ConsoleColors.FAIL))
        return 3
    else:
        return 1
    def run(self):

        if self._interactive is True:
            self._imagebackup.set_device()
        self._imagebackup.assert_devicepath_is_valid()

        if self._interactive is True:
            if self._imagebackup.set_image_path() is False:
                print(ConsoleColor.colorline("Cancelled",
                                             ConsoleColors.OKBLUE))
                return

        self._imagebackup.assert_imagepath_is_valid()

        self._imagebackup.ensure_image_deleted()

        if self._interactive is True:
            self._imagebackup.print_pre_dd_info()

        self._imagebackup.assert_free_space(self._safe_free_targetspace_margin)
        self._bencher.startbench()
        self._imagebackup.start_dd(True, self._ddbatchsize, self._finished)
Ejemplo n.º 7
0
    def start_dd(self,
                 interactive: bool = False,
                 ddbatchsize: str = None,
                 finished_handler: Callable = None) -> int:
        retcode = None
        devpath = str(self._devicepath.absolute())
        imagepath = str(self._imagepath.absolute())

        param_if = "if={}".format(devpath.replace(" ", "\\ "))
        param_of = "of={}".format(imagepath.replace(" ", "\\ "))
        param_status = "status=progress"

        # todo: make configurable batch size
        if ddbatchsize is not None:
            param_bs = "bs={}".format(ddbatchsize)
        else:
            param_bs = "bs=1M"

        if interactive is True:
            yn = "y"
        else:
            print(
                ConsoleColor.colorline(
                    "Will execute \"{}\"".format("sudo dd {} {} {} {}".format(
                        param_if, param_of, param_status, param_bs)),
                    ConsoleColors.OKGREEN))

            yn = singlecharinput(
                "Confirm the creation of image '{}' from device '{}' (y/n)!".
                format(imagepath, devpath), ConsoleColors.OKGREEN)

        if yn == "n":
            if interactive is True:
                print(
                    ConsoleColor.colorline(
                        "Cancelled image creation on your wish",
                        ConsoleColors.OKBLUE))
            return -1
        elif yn == "y":
            sudo = local["sudo"]
            dd = local["dd"]

            starttime = datetime.now()

            p = sudo[dd[param_if, param_of, param_status,
                        param_bs]].popen(stderr=PIPE)
            line = ''
            # retcode = 0

            # Intention is not to get the first "\r" from dd-output
            # sleep(1)
            if interactive is True:
                print()

            target_image_sizehuman = self.get_target_image_sizehuman()
            target_image_sizebytes = self.get_target_image_sizebytes()

            if interactive is False:
                p._proc.communicate()
            else:
                while True:
                    retcode = p.poll()
                    if retcode is None:
                        out = p.stderr.read(1).decode("utf-8",
                                                      errors="replace")
                        if out == '':
                            break
                        else:
                            if out == '\r':
                                line = strip(line)
                                if not string_is_empty(line):
                                    dd_info = parse_dd_info(line)
                                    currenttime = datetime.now()
                                    deltatime = currenttime - starttime

                                    print(
                                        "{0:10}{1:4}{2:9}{3:3}{4:10}{5:4}{6:8}{7:3}{8}"
                                        .format(
                                            bytes_to_unit(
                                                dd_info["size_b"], True, True,
                                                False), "of",
                                            target_image_sizehuman, "|",
                                            dd_info["time_h"], "of",
                                            humantime(
                                                predict_job_time(
                                                    dd_info["time"],
                                                    target_image_sizebytes,
                                                    dd_info["size_b"])), "|",
                                            "Total time: {}".format(
                                                humantime(deltatime.
                                                          total_seconds()))),
                                        end="\r")

                                line = ''
                            else:
                                line = line + out
                    else:
                        break

            retcode = retcode if retcode is not None else p._proc.returncode

            if interactive is True:
                print()

                currenttime = datetime.now()
                deltatime = currenttime - starttime
                print(
                    ConsoleColor.colorline(
                        "Total time: {}".format(
                            humantime(deltatime.total_seconds())),
                        ConsoleColors.OKGREEN))

                st = stat(imagepath)
                print(
                    ConsoleColor.colorline(
                        "Final image size: {}".format(
                            bytes_to_unit(st.st_size, True, True, False)),
                        ConsoleColors.OKGREEN))
                if retcode == 0:
                    print(
                        ConsoleColor.colorline("Successfully created image!",
                                               ConsoleColors.OKGREEN))
                else:
                    print(
                        ConsoleColor.colorline(
                            "No Result from dd (image might be ok)!",
                            ConsoleColors.WARNING))
            finished_handler(retcode, imagepath)
            return retcode