コード例 #1
0
    def doit(self, tarball):
        """ really restore data """

        # create full path
        fullpath = re.sub('\.tar\.bzip2', '', tarball)  # noqa
        topath = Path(fullpath).absolute()
        # untar Backup
        print("\nExtracting tarball ... in progress ...")

        if os.path.isdir(fullpath) is False:
            #tar -xf $HOME/etc.backup.tar -C /tmp/data
            #-C extract to Dir
            os.system("mkdir -p %s" % fullpath)

            cmd = "tar xfj %s -C %s" % (tarball, topath)
            os.system(cmd)
            print("done ...")
        else:
            print("Tarball is already extracted ... skipping ...")

        files = self.search_files(fullpath, "*.sql")

        if self.debug is False:
            for f in files:
                print("Importing %s ..." % os.path.basename(f))
                filename, file_extension = os.path.splitext(
                    os.path.basename(f))  # noqa
                dbname = filename

                # first drop DB
                self.doMySQL("DROP DATABASE IF EXISTS %s;" % dbname)

                # create DB new
                self.doMySQL("CREATE DATABASE %s;" % dbname)

                sleep(0.5)
                # now import new one
                cmd = "mysql --defaults-extra-file=%s %s < %s" % (
                    self.extrafile, dbname, f)
                os.system(cmd)

        # change to InnoDB
        #self.doMySQL("ALTER TABLE mysql.db ENGINE=InnoDB;")
        #self.doMySQL("ALTER TABLE mysql.columns_priv ENGINE=InnoDB;")

        # restoring User Privileges
        # read yaml File
        path = os.path.join(fullpath, 'users.yaml')
        with open(path, 'rt') as f:
            users = yaml.safe_load(f.read())

        self.Users = []
        for block in users.values():
            u = User()

            for k, v in block.items():
                if k in "username":
                    u.set_username(v)
                if k in "hosts":
                    u.set_hosts(v)
                if k in "pwd":
                    u.set_pwd(v)

                if k in "privs":
                    u.set_privileges(v)
            self.Users.append(u)

        for u in self.Users:
            print("Creating User: %s" % u.get_username())

            # delete user if exists
            self.doMySQL("DROP USER IF EXISTS \"%s\"@\"%s\";" %
                         (u.get_username(), u.get_hosts()))

            self.doMySQL("CREATE USER \"%s\"@\"%s\" IDENTIFIED BY \"%s\";" %
                         (u.get_username(), u.get_hosts(), u.get_pwd()))
            self.doMySQL(
                "ALTER USER \"%s\"@\"%s\" IDENTIFIED WITH mysql_native_password BY \"%s\";"
                % (u.get_username(), u.get_hosts(), u.get_pwd()))

            for p in u.get_privileges():
                # replace ' with "
                p = re.sub('\'', '"', p)  # noqa
                self.doMySQL(p)

            self.doMySQL("FLUSH PRIVILEGES;")