-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Add build option to reduce final image size #16729
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
StormLiangMS
merged 2 commits into
sonic-net:master
from
Staphylo:master-reduce-image-size
Oct 24, 2023
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,253 @@ | ||
| #!/usr/bin/env python3 | ||
|
|
||
| import argparse | ||
| import hashlib | ||
| import os | ||
| import shutil | ||
| import subprocess | ||
| import sys | ||
|
|
||
| from collections import defaultdict | ||
| from functools import cached_property | ||
|
|
||
| DRY_RUN = False | ||
| def enable_dry_run(enabled): | ||
| global DRY_RUN # pylint: disable=global-statement | ||
| DRY_RUN = enabled | ||
|
|
||
| class File: | ||
| def __init__(self, path): | ||
| self.path = path | ||
|
|
||
| def __str__(self): | ||
| return self.path | ||
|
|
||
| def rmtree(self): | ||
| if DRY_RUN: | ||
| print(f'rmtree {self.path}') | ||
| return | ||
| shutil.rmtree(self.path) | ||
|
|
||
| def hardlink(self, src): | ||
| if DRY_RUN: | ||
| print(f'hardlink {self.path} {src}') | ||
| return | ||
| st = self.stats | ||
| os.remove(self.path) | ||
| os.link(src.path, self.path) | ||
| os.chmod(self.path, st.st_mode) | ||
| os.chown(self.path, st.st_uid, st.st_gid) | ||
| os.utime(self.path, times=(st.st_atime, st.st_mtime)) | ||
|
|
||
| @property | ||
| def name(self): | ||
| return os.path.basename(self.path) | ||
|
|
||
| @cached_property | ||
| def stats(self): | ||
| return os.stat(self.path) | ||
|
|
||
| @cached_property | ||
| def size(self): | ||
| return self.stats.st_size | ||
|
|
||
| @cached_property | ||
| def checksum(self): | ||
| with open(self.path, 'rb') as f: | ||
| return hashlib.md5(f.read()).hexdigest() | ||
|
|
||
| class FileManager: | ||
| def __init__(self, path): | ||
| self.path = path | ||
| self.files = [] | ||
| self.folders = [] | ||
| self.nindex = defaultdict(list) | ||
| self.cindex = defaultdict(list) | ||
|
|
||
| def add_file(self, path): | ||
| if not os.path.isfile(path) or os.path.islink(path): | ||
| return | ||
| f = File(path) | ||
| self.files.append(f) | ||
|
|
||
| def load_tree(self): | ||
| self.files = [] | ||
| self.folders = [] | ||
| for root, _, files in os.walk(self.path): | ||
| self.folders.append(File(root)) | ||
| for f in files: | ||
| self.add_file(os.path.join(root, f)) | ||
| print(f'loaded {len(self.files)} files and {len(self.folders)} folders') | ||
|
|
||
| def generate_index(self): | ||
| print('Computing file hashes') | ||
| for f in self.files: | ||
| self.nindex[f.name].append(f) | ||
| self.cindex[(f.name, f.checksum)].append(f) | ||
|
|
||
| def create_hardlinks(self): | ||
| print('Creating hard links') | ||
| for files in self.cindex.values(): | ||
| if len(files) <= 1: | ||
| continue | ||
| orig = files[0] | ||
| for f in files[1:]: | ||
| f.hardlink(orig) | ||
|
|
||
| class FsRoot: | ||
| def __init__(self, path): | ||
| self.path = path | ||
|
|
||
| def iter_fsroots(self): | ||
| yield self.path | ||
| dimgpath = os.path.join(self.path, 'var/lib/docker/overlay2') | ||
| for layer in os.listdir(dimgpath): | ||
| yield os.path.join(dimgpath, layer, 'diff') | ||
|
|
||
| def collect_fsroot_size(self): | ||
| cmd = ['du', '-sb', self.path] | ||
| p = subprocess.run(cmd, text=True, check=False, | ||
| stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) | ||
| return int(p.stdout.split()[0]) | ||
|
|
||
| def _remove_root_paths(self, relpaths): | ||
| for root in self.iter_fsroots(): | ||
| for relpath in relpaths: | ||
| path = os.path.join(root, relpath) | ||
| if os.path.isdir(path): | ||
| if DRY_RUN: | ||
| print(f'rmtree {path}') | ||
| else: | ||
| shutil.rmtree(path) | ||
|
|
||
| def remove_docs(self): | ||
| self._remove_root_paths([ | ||
| 'usr/share/doc', | ||
| 'usr/share/doc-base', | ||
| 'usr/local/share/doc', | ||
| 'usr/local/share/doc-base', | ||
| ]) | ||
|
|
||
| def remove_mans(self): | ||
| self._remove_root_paths([ | ||
| 'usr/share/man', | ||
| 'usr/local/share/man', | ||
| ]) | ||
|
|
||
| def remove_licenses(self): | ||
| self._remove_root_paths([ | ||
| 'usr/share/common-licenses', | ||
| ]) | ||
|
|
||
| def hardlink_under(self, path): | ||
| fm = FileManager(os.path.join(self.path, path)) | ||
| fm.load_tree() | ||
| fm.generate_index() | ||
| fm.create_hardlinks() | ||
|
|
||
| def remove_platforms(self, filter_func): | ||
| devpath = os.path.join(self.path, 'usr/share/sonic/device') | ||
| for platform in os.listdir(devpath): | ||
| if not filter_func(platform): | ||
| path = os.path.join(devpath, platform) | ||
| if DRY_RUN: | ||
| print(f'rmtree platform {path}') | ||
| else: | ||
| shutil.rmtree(path) | ||
|
|
||
| def remove_modules(self, modules): | ||
| modpath = os.path.join(self.path, 'lib/modules') | ||
| kversion = os.listdir(modpath)[0] | ||
| kmodpath = os.path.join(modpath, kversion) | ||
| for module in modules: | ||
| path = os.path.join(kmodpath, module) | ||
| if os.path.isdir(path): | ||
| if DRY_RUN: | ||
| print(f'rmtree module {path}') | ||
| else: | ||
| shutil.rmtree(path) | ||
|
|
||
| def remove_firmwares(self, firmwares): | ||
| fwpath = os.path.join(self.path, 'lib/firmware') | ||
| for fw in firmwares: | ||
| path = os.path.join(fwpath, fw) | ||
| if os.path.isdir(path): | ||
| if DRY_RUN: | ||
| print(f'rmtree firmware {path}') | ||
| else: | ||
| shutil.rmtree(path) | ||
|
|
||
|
|
||
| def specialize_aboot_image(self): | ||
| fp = lambda p: '-' not in p or 'arista' in p or 'common' in p | ||
| self.remove_platforms(fp) | ||
| self.remove_modules([ | ||
| 'kernel/drivers/gpu', | ||
| 'kernel/drivers/infiniband', | ||
| ]) | ||
| self.remove_firmwares([ | ||
| 'amdgpu', | ||
| 'i915', | ||
| 'mediatek', | ||
| 'nvidia', | ||
| 'radeon', | ||
| ]) | ||
|
|
||
| def specialize_image(self, image_type): | ||
| if image_type == 'aboot': | ||
| self.specialize_aboot_image() | ||
|
|
||
| def parse_args(args): | ||
| parser = argparse.ArgumentParser() | ||
| parser.add_argument('fsroot', | ||
| help="path to the fsroot build folder") | ||
| parser.add_argument('-s', '--stats', action='store_true', | ||
| help="show space statistics") | ||
| parser.add_argument('--hardlinks', action='append', | ||
| help="path where similar files need to be hardlinked") | ||
| parser.add_argument('--remove-docs', action='store_true', | ||
| help="remove documentation") | ||
| parser.add_argument('--remove-licenses', action='store_true', | ||
| help="remove license files") | ||
| parser.add_argument('--remove-mans', action='store_true', | ||
| help="remove manpages") | ||
| parser.add_argument('--image-type', default=None, | ||
| help="type of image being built") | ||
| parser.add_argument('--dry-run', action='store_true', | ||
| help="only display what would happen") | ||
| return parser.parse_args(args) | ||
|
|
||
| def main(args): | ||
| args = parse_args(args) | ||
|
|
||
| enable_dry_run(args.dry_run) | ||
|
|
||
| fs = FsRoot(args.fsroot) | ||
| if args.stats: | ||
| begin = fs.collect_fsroot_size() | ||
| print(f'fsroot size is {begin} bytes') | ||
|
|
||
| if args.remove_docs: | ||
| fs.remove_docs() | ||
|
|
||
| if args.remove_mans: | ||
| fs.remove_mans() | ||
|
|
||
| if args.remove_licenses: | ||
| fs.remove_licenses() | ||
|
|
||
| if args.image_type: | ||
| fs.specialize_image(args.image_type) | ||
|
|
||
| for path in args.hardlinks: | ||
| fs.hardlink_under(path) | ||
|
|
||
| if args.stats: | ||
| end = fs.collect_fsroot_size() | ||
| pct = 100 - end / begin * 100 | ||
| print(f'fsroot reduced to {end} from {begin} {pct:.2f}') | ||
|
|
||
| return 0 | ||
|
|
||
| if __name__ == '__main__': | ||
| sys.exit(main(sys.argv[1:])) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe some actions can be enabled by default.
E.g. we clean up /usr/share/doc here:
sonic-buildimage/build_debian.sh
Line 748 in fe24c26
I think it's possible to remove other directories with docs/mans/licensses without any conditons.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Some of these cleanup, especially the removal ones could definitely be added as part of the general build.
However this would have to be more than just here, since it would also need to apply to all docker images.
On top of that the removal of licenses could have some legal implication for public/redistributable builds such as the community ones.
This should however not be a problem for internal/private images.
Most of the savings of this change actually come from the hardlinking steps.
And for Aboot images the removal of other platforms and unneeded kernel modules and firmwares.
This mitigation, even if it merges in master, has 202305 as the main target for 4GB systems.
It therefore felt simpler to centralize the cleanup under a postprocessing script hidden behind a toggle instead of touching tens of files.
This script also has the advantage of cleaning up behind newly introduced code that forgot the cleanup steps.
Until there is some checks and tooling in place to prevent new code from contributing to bloat, things will slip and become a maintenance burden.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
To add to your comment, the proper thing to do here would be to add an
/etc/dpkg/dpkg.conf.d/01_sonicconf instead of removing files like it's currently done in build_debian.shIn this configuration you can specify things like
path-exclude=/usr/share/dochowever that will not retroactively apply the previously installed packages.In the case of docker, that means that the debian base image will retain these files no matter what.
If you decide to remove them as part of the build of a child Dockerfile, this is actually going to create whiteout files which consumes space instead of the final goal being to release space.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is already done for docker containers:
sonic-buildimage/dockers/docker-base-bullseye/Dockerfile.j2
Line 12 in be7a95b
sonic-buildimage/dockers/docker-base-bullseye/Dockerfile.j2
Line 29 in be7a95b
So my suggestion was only about host system.
We keep copyright files in docker containers but remove them from host system.
Probably we shouldn't remove these files from /usr/share/doc on host system.
There was my old PR #14417 to fix it. I can reopen it, but I'm still not sure should we keep these files or not.