def minimize_size()

in antlir/loopback.py [0:0]


    def minimize_size(self) -> int:
        """
        Minimizes the loopback as much as possibly by inspecting
        the btrfs internals and resizing the filesystem explicitly.

        Returns the new size of the loopback in bytes.
        """
        min_size_out = subprocess.check_output(
            nsenter_as_root(
                self._unshare,
                "btrfs",
                "inspect-internal",
                "min-dev-size",
                # pyre-fixme[6]: Expected `List[Variable[typing.AnyStr <: [str,
                #  bytes]]]` for 5th param but got `Optional[Path]`.
                self._mount_dir,
            )
        ).split(b" ")
        assert min_size_out[1] == b"bytes"
        maybe_min_size_bytes = int(min_size_out[0])
        # Btrfs filesystems cannot be resized below a certain limit, if if we
        # have a smaller fs than the limit, we just use the limit.
        min_size_bytes = (
            maybe_min_size_bytes
            if maybe_min_size_bytes >= MIN_SHRINK_BYTES
            else MIN_SHRINK_BYTES
        )

        if min_size_bytes >= self._size_bytes:
            log.info(
                f"Nothing to do: the minimum resize limit {min_size_bytes} "
                "is no less than the current filesystem size of "
                f"{self._size_bytes} bytes."
            )
            return self._size_bytes

        log.info(
            f"Shrinking {self._image_path} to the btrfs minimum: "
            f"{min_size_bytes} bytes."
        )
        run_stdout_to_err(
            nsenter_as_root(
                self._unshare,
                "btrfs",
                "filesystem",
                "resize",
                str(min_size_bytes),
                # pyre-fixme[6]: Expected `List[Variable[typing.AnyStr <: [str,
                #  bytes]]]` for 6th param but got `Optional[Path]`.
                self._mount_dir,
            ),
            check=True,
        )

        fs_bytes = int(
            subprocess.check_output(
                nsenter_as_user(
                    self._unshare,
                    "findmnt",
                    "--bytes",
                    "--noheadings",
                    "--output",
                    "SIZE",
                    # pyre-fixme[6]: Expected `List[Variable[typing.AnyStr <: [str,
                    #  bytes]]]` for 7th param but got `Optional[Path]`.
                    self._mount_dir,
                )
            )
        )
        self._create_or_resize_image_file(fs_bytes)
        run_stdout_to_err(
            # pyre-fixme[16]: `BtrfsLoopbackVolume` has no attribute
            # `_loop_dev`.
            ["sudo", "losetup", "--set-capacity", self._loop_dev],
            check=True,
        )

        assert min_size_bytes == fs_bytes

        self._size_bytes = min_size_bytes
        return self._size_bytes