# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-## Copyright 2021 Canonical Ltd.## This program is free software; you can redistribute it and/or# modify it under the terms of the GNU Lesser General Public# License version 3 as published by the Free Software Foundation.## This program is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU# Lesser General Public License for more details.## You should have received a copy of the GNU Lesser General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>."""Overlay handling helpers.Relevant OCI documentation available at:https://github.com/opencontainers/image-spec/blob/main/layer.md"""importloggingimportosfrompathlibimportPathlogger=logging.getLogger(__name__)
[docs]defvisible_in_layer(lower_dir:Path,upper_dir:Path)->tuple[set[str],set[str]]:"""Determine the files and directories that are visible in a layer. Given a pair of directories containing lower and upper layer entries, list the files and subdirectories in the lower layer that would be directly visible when the layers are stacked (i.e. the visibility is not "blocked" by an entry with the same name that exists in the upper directory). The upper directory may contain OCI whiteout files and opaque dirs. :param lower_dir: The lower directory. :param upper_dir: The upper directory. :returns: A tuple containing the sets of files and directories that are visible. """visible_files:set[str]=set()visible_dirs:set[str]=set()logger.debug("check layer visibility in %s",lower_dir)forroot,directories,filesinos.walk(lower_dir,topdown=True):forfile_nameinfiles:path=Path(root,file_name)relpath=path.relative_to(lower_dir)ifnot_is_path_visible(upper_dir,relpath):continueupper_path=upper_dir/relpathifnotupper_path.exists()andnotoci_whiteout(upper_path).exists():visible_files.add(str(relpath))fordirectoryindirectories:path=Path(root,directory)relpath=path.relative_to(lower_dir)ifnot_is_path_visible(upper_dir,relpath):continueupper_path=upper_dir/relpathifnotupper_path.exists():ifpath.is_symlink():visible_files.add(str(relpath))else:visible_dirs.add(str(relpath))elifis_oci_opaque_dir(upper_path):logger.debug("is opaque dir: %s",relpath)# Don't descend into this directory, overridden by opaquedirectories.remove(directory)logger.debug("layer visibility files=%r, dirs=%r",visible_files,visible_dirs)returnvisible_files,visible_dirs
def_is_path_visible(root:Path,relpath:Path)->bool:"""Verify if any element of the given path is not whited out. :param root: The root directory, not included in the verification. :param relpath: The relative path to verify. :returns: Whether the final element of the path is visible. """logger.debug("check if path is visible: root=%s, relpath=%s",root,relpath)levels=len(relpath.parts)forlevelinrange(levels):path=Path(root,os.path.join(*relpath.parts[:level+1]))ifoci_whiteout(path).exists()oris_oci_opaque_dir(path):logger.debug("is whiteout or opaque: %s",path)returnFalsereturnTrue
[docs]defis_oci_opaque_dir(path:Path)->bool:"""Verify if the given path corresponds to an opaque directory. :param path: The path of the file to verify. :returns: Whether the given path is an overlayfs opaque directory. """ifnotpath.is_dir()orpath.is_symlink():returnFalsereturnoci_opaque_dir(path).exists()
[docs]defis_oci_whiteout_file(path:Path)->bool:"""Verify if the given path corresponds to an OCI whiteout file. :param path: The path of the file to verify. :returns: Whether the given path is an OCI whiteout file. """returnpath.name.startswith(".wh.")andpath.name!=".wh..wh..opq"
[docs]defoci_whiteout(path:Path)->Path:"""Convert the given path to an OCI whiteout file name. :param path: The file path to white out. :returns: The corresponding OCI whiteout file name. """returnpath.parent/(".wh."+path.name)
[docs]defoci_whited_out_file(whiteout_file:Path)->Path:"""Find the whited out file corresponding to a whiteout file. :param whiteout_file: The whiteout file to process. :returns: The file that was whited out. """ifnotwhiteout_file.name.startswith(".wh."):raiseValueError("argument is not an OCI whiteout file")returnwhiteout_file.parent/whiteout_file.name[4:]
[docs]defoci_opaque_dir(path:Path)->Path:"""Return the OCI opaque directory marker. :param path: The directory to mark as opaque. :returns: The corresponding OCI opaque directory marker path. """returnpath/".wh..wh..opq"