简体   繁体   English

如何创建一个“适合”子目录中文件的块设备?

[英]How to create a block device that “just fits” files in a subdirectory?

I need to create and format a block device and copy all the files in a subdirectory into it. 我需要创建并格式化块设备,然后将子目录中的所有文件复制到其中。 Ideally there will be just enough space on the formatted block device to fit the files. 理想情况下,格式化块设备上将只有足够的空间来容纳文件。 It doesn't matter if it's not a precise fit but it should be fairly close - within tens of megabytes ideally. 它是否精确匹配并不重要,但是应该相当接近-理想情况下在几十兆字节以内。

But its not as easy as it sounds. 但这并不像听起来那么容易。 First I need to measure the size of the files in the subdirectory, and then need to create a block device. 首先,我需要测量子目录中文件的大小,然后需要创建一个块设备。

But the block device cannot be the same size as the files because some space will be taken up by formatting information I assume. 但是块设备的大小不能与文件大小相同,因为格式化所需的信息会占用一些空间。 Also some space will be taken up because presumably files don't necessarily use all the available space within each disk block. 另外,由于假定文件不一定使用每个磁盘块中的所有可用空间,因此会占用一些空间。

I don't think it matters much what sort of block device I am creating but in case you think it is important, I am creating an EBS volume on Amazon EC2. 我认为创建哪种类型的块设备并不重要,但是如果您认为它很重要,那么我将在Amazon EC2上创建EBS卷。

So does anyone have any comments on how best to do this? 那么,有人对如何最好地做到这一点有何评论?

Here's my Python code for calculating size of the directory: 这是我用于计算目录大小的Python代码:

def get_directory_size(start_path=None):
    print(start_path)
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames + dirnames:
            fp = os.path.join(dirpath, f)
            if os.path.islink(fp):
                # ignore symbolic links
                continue
            total_size += os.path.getsize(fp)
    return total_size

If you are using a filesystem in the ext family (eg, ext3 or ext4), you can start with a filesystem that's larger than needed, then use resize2fs -M to resize the filesystem to its minimum size. 如果使用ext系列中的文件系统(例如ext3或ext4),则可以从大于所需文件系统的文件系统开始,然后使用resize2fs -M将文件系统调整为最小大小。 This will only resize the filesystem, not its containing block device, but you can resize the partition afterwards, or copy the data to a new block device of the appropriate size, if you want. 这只会调整文件系统的大小,而不会调整其包含的块设备的大小,但是之后您可以调整分区的大小,或者根据需要将数据复制到适当大小的新块设备。

If it's acceptable for the resulting filesystem to be read-only, you could use something like SquashFS , which will create the filesystem at its target size in a single step. 如果生成的文件系统为只读是可以接受的,则可以使用SquashFS之类的东西,它将在一个步骤中以目标大小创建文件系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM