{-# LANGUAGE ScopedTypeVariables #-}-- | Garbage collection: roots, the reachability walk, the sweep, and the-- checked delete of named paths.---- == Roots---- A root is a store path the collector keeps, together with everything-- it references transitively. Roots live under the store's metadata-- directory, @\<store\>\/.nova-nix\/gcroots@. Upstream keeps them under-- its state directory (@\/nix\/var\/nix\/gcroots@); this store has no-- state directory apart from @.nova-nix@, so its roots are beside its-- database. A store copied or moved as one directory takes them along,-- but its rows still name each path under the old directory's spelling,-- so at the new one no path is valid (see the spelling section below).-- Two kinds:---- * __Permanent roots__ are entries anywhere under @gcroots@ except-- @auto@: a symlink whose target lies in the store roots the store-- path it lies in (the path itself or anything beneath it, upstream's-- @toStorePath@), and a regular file named @\<hash\>-\<name\>@ roots-- the path of that name. Both are upstream's own forms (its-- @findRoots@ reads a symlink's target and takes a regular file's-- basename), and the file form is the one that works everywhere,-- since a symlink on Windows needs Developer Mode. Nothing in-- nova-nix creates a permanent root; they are for the operator.---- * __Indirect roots__ are what @build@ registers for the link it makes-- to its output ('addOutLinkRoot', upstream's @addPermRoot@): the-- out-link @PATH -> \<store path\>@, @.\/result@ unless @--out-link@-- names another path, plus a record-- @gcroots\/auto\/\<sha256 of PATH\>@ holding the bytes of PATH's-- absolute spelling. Upstream's record is a symlink to the out-link;-- here it is a regular file with the same content, because the record-- must be writable on every platform the store runs on. The out-link-- itself is a native symlink everywhere, with the Developer Mode-- requirement the README states for symlinks. A record whose out-link-- no longer exists is stale and removed by the next walk, as upstream-- removes its stale @auto@ links; one whose out-link exists but no-- longer points into the store is simply not a root.---- Upstream also finds runtime roots (open files and mapped executables-- of running processes, through @\/proc@ on Linux and @lsof@ elsewhere)-- and per-process temporary roots. Neither exists here: the lock below-- covers builds in flight, and a program running out of an unrooted-- store path is not protected. Upstream's @keep-derivations@, on by-- default, keeps a @.drv@ while an output that names it as its deriver-- is live, and @keep-outputs@ keeps a path while a @.drv@ that outputs-- it is live (gc.cc at 2.24.9). Neither is implemented here, so a-- @.drv@ is kept only while something references it, and an unrooted-- @.drv@ and the sources only it references are collected.---- == Reachability and the sweep---- 'reachableFrom' is the pure walk over the references map: a root is-- live, and so is everything a live path references. Every valid path-- outside that set is dead. 'sweepPlan', also pure, turns the valid-- set, the live set and the store directory's entries into what to-- remove: the dead rows, and every directory entry that is neither live-- nor the metadata directory, which is what upstream's sweep removes-- too (a dead path's tree, a store-shaped tree with no row from a build-- interrupted before registration, junk, and a dead path's lock file).-- A live path's lock file stays. Upstream's holders delete their lock-- files on release, so a leftover one is crash debris its sweep-- reclaims; here holders never delete ("Nix.Store.Lock"), a live-- path's lock file is its normal state, and only the path's death makes-- the file debris. The collector may delete lock files at all because-- under the exclusive lock no process has the store open, and every-- per-path lock in this tool is taken by a process holding a store-- handle, so no holder or waiter exists for a deleted file to strand.---- 'collectGarbage' is the IO boundary: dead rows go in one database-- transaction ('unregisterPathRows'), then trees one by one. Rows-- before trees for the reason 'deleteStorePathRaw' gives: a-- tree without a row is inert debris, a row without a tree is a lie-- existence checks believe. A dead row with no tree is unregistered-- without a line or a count: upstream's sweep walks the directory and-- never meets it, and what is announced and counted here is what-- upstream announces and counts, the directory entries removed.---- == The store directory's spelling---- The database keys every row by the store directory's spelling at-- registration ("Nix.Store.DB"), and the collector compares that text-- with paths derived from the handle's directory.-- 'Nix.Store.Handle.openStore' canonicalises the spelling, so one-- directory named two ways keys the same rows, and a store with rows but-- none under the directory it is opened at is refused at the open-- ('Nix.Store.DB.storeRowRange'). A database that holds a row under the-- opened directory and another registered under another spelling (a-- symlinked parent, or a store used at two directories) would make that-- row look dead, so the collector and the checked delete refuse when any-- row lies outside the opened directory ('validPathsUnder') rather than-- sweep a rooted closure over a text mismatch.---- == A store upstream Nix also manages---- Upstream registers its paths in its own database and keeps its roots-- under its own state directory, so in a directory upstream also uses,-- no row or root here keeps an upstream path, and the sweep would take-- every one for an unregistered tree. The collector and the checked-- delete refuse such a store before the lock is taken, as-- "Nix.Store.Upstream" recognises it.---- == Deleting named paths---- Upstream's @nix-store --delete@ is a collection whose action is-- @gcDeleteSpecific@ (@opDelete@ at 2.24.9), and the checked delete-- here is one too: it holds the exclusive lock, reads the roots once,-- and checks every path it is given against that live set-- ('deleteStorePaths' for a batch in argument order,-- 'deleteStorePathRaw' for one path). The live set is made and-- consumed inside the call, so a delete always checks the roots of its-- own store as they stand under the lock it holds.---- == The lock---- Upstream serialises collection against writers with a store-wide-- @gc.lock@, held exclusively by the collector and shared by every-- writer, plus a socket through which a writer registers roots with a-- running collector. nova-nix keeps the lock and drops the socket:-- every open t'Store' handle holds the shared lock from-- 'Nix.Store.Handle.openStore' to 'Nix.Store.Handle.closeStore'-- ("Nix.Store.Handle"), and 'collectGarbage' and the checked delete-- trade the handle's shared lease for the exclusive lock for the-- duration. A collection therefore runs only while no other process has-- the store open, and a process opening the store while one runs waits-- for it to finish. That is coarser than the per-path locks the builder-- and substituter hold, and deliberately so: a per-path lock covers a-- path while it is being produced, but not the window between a-- dependency's registration and the build that consumes it, nor the-- writers that register without one (the @.drv@ closure, the eval-time-- store writes). Under the exclusive lock no writer is active, so the-- collector takes no per-path lock and creates no lock file.-- 'findRoots' alone needs only the handle's shared lease: a listing-- changes nothing another handle reads, and upstream's @--print-roots@-- takes no collector lock either.module Nix.Store.GC ( -- * Roots GcRoot (..), findRoots, addOutLinkRoot, LinkRooting (..), makeOutLinkRoot, addIndirectRoot, gcRootsDir, autoRootsDir, gcRootsDirName, autoRootsDirName, indirectRootRecordName, -- * Reachability (pure) referencesMap, reachableFrom, referrersFirst, -- * Collection GcResults (..), collectGarbage, SweepPlan (..), sweepPlan, showFreedBytes, gcSummaryLine, -- * Deleting named paths StoreEntryName, storeEntryName, storeEntryNameText, DeleteOutcome (..), deleteStorePaths, deleteStorePathRaw, deleteSpecificPaths, -- * Messages findingRootsMessage, stillAliveMessage, specificStillAliveMessage, )whereimport Control.Exception (IOException, catch, throwIO, try)import Control.Monad (join, unless, when)import Control.Monad.Except (ExceptT (..), runExceptT, throwError)import Control.Monad.IO.Class (liftIO)import Data.ByteString (ByteString)import qualified Data.ByteString as BSimport Data.Foldable (foldlM, traverse_)import Data.List (isPrefixOf, sort)import Data.Map.Strict (Map)import qualified Data.Map.Strict as Mapimport Data.Maybe (catMaybes, isJust, listToMaybe, mapMaybe)import Data.Set (Set)import qualified Data.Set as Setimport Data.Text (Text)import qualified Data.Text as Timport qualified Data.Text.Encoding as TEimport GHC.IO.Exception (IOErrorType (InappropriateType))import Nix.Hash (sha256Digest)import Nix.HostPath (absolutePath, hostPathBytes, hostPathFromBytes)import Nix.Logger (Logger, logMessage)import Nix.Store.DB (UnregisterResult (..), isValidPath, metaDirName, queryAllReferences, queryAllValidPaths, queryReferences, queryReferrers, unregisterPathRow, unregisterPathRows)import Nix.Store.Handle (Store (..), withCollectorLock)import Nix.Store.Lock (lockFileSuffix, lockedPathOf, withLockFile)import Nix.Store.Path (StoreDir (..), StorePath, defaultStoreDir, parseStorePath, parseStorePathBaseName, parseStorePathPrefix, platformStoreDir, storePathToFilePath, storePathToText)import Nix.Store.Symlink (WalkNode (..), classifyWalkNode, createSymlinkOfKind)import Nix.Store.Upstream (UpstreamHazard (..), upstreamManagedRefusal, upstreamStateDir)import qualified NovaCache.Base32 as Base32import System.Directory (createDirectoryIfMissing, doesPathExist, getFileSize, getSymbolicLinkTarget, listDirectory, pathIsSymbolicLink, removePathForcibly, renamePath)import qualified System.Directory.OsPath as OsDirimport System.FilePath (normalise, splitDirectories, takeDirectory, takeFileName, (</>))import qualified System.FilePath.Windows as Windowsimport System.IO.Error (ioeGetErrorType, isDoesNotExistError, isPermissionError)import System.OsPath (decodeFS, encodeFS)import Text.Printf (printf)-- ----------------------------------------------------------------------------- Layout-- ----------------------------------------------------------------------------- | Upstream's name for the roots directory.gcRootsDirName :: FilePathgcRootsDirName = "gcroots"-- | Upstream's name for the indirect-root records under 'gcRootsDirName'.autoRootsDirName :: FilePathautoRootsDirName = "auto"-- | The roots directory of a store, under its metadata directory.gcRootsDir :: StoreDir -> FilePathgcRootsDir dir = unStoreDir dir </> metaDirName </> gcRootsDirName-- | The indirect-root records directory of a store.autoRootsDir :: StoreDir -> FilePathautoRootsDir dir = gcRootsDir dir </> autoRootsDirName-- | The record name for an out-link, given the bytes of its absolute-- spelling ('Nix.HostPath.hostPathBytes'): nix-base32 of their SHA-256,-- so one out-link has one record however often it is re-registered.-- Upstream hashes with SHA-1; the digest is an internal key and the store-- has no SHA-1 primitive to spend on it.indirectRootRecordName :: BS.ByteString -> FilePathindirectRootRecordName link = T.unpack (Base32.encode (sha256Digest link))-- | Where a record is written before it is renamed into @auto@: under-- the metadata directory, which the roots walk never enters, so a-- listing under the shared lease sees a record whole or not at all.recordStagingPath :: StoreDir -> BS.ByteString -> FilePathrecordStagingPath dir link = unStoreDir dir </> metaDirName </> indirectRootRecordName link <> stagingSuffix-- | The suffix of a record still being written.stagingSuffix :: FilePathstagingSuffix = ".tmp"-- ----------------------------------------------------------------------------- Messages-- ----------------------------------------------------------------------------- | Upstream's first progress line of a collection or a checked delete.findingRootsMessage :: TextfindingRootsMessage = "finding garbage collector roots..."-- | Upstream's progress line before the sweep.deletingGarbageMessage :: TextdeletingGarbageMessage = "deleting garbage..."-- | Upstream's per-path line of the sweep, the path in single quotes,-- since upstream formats this store path as a string, not as a path.deletingPathMessage :: Text -> TextdeletingPathMessage path = "deleting '" <> path <> "'"-- | Upstream's line for an indirect-root record whose out-link is gone.removingStaleLinkMessage :: FilePath -> FilePath -> TextremovingStaleLinkMessage record outLink = "removing stale link from " <> quotedPath record <> " to " <> quotedPath outLink-- | Upstream's line for a symlink root naming a path the database does-- not hold, with the target as the link spells it.skippingInvalidRootMessage :: FilePath -> FilePath -> TextskippingInvalidRootMessage link target = "skipping invalid root from " <> quotedPath link <> " to " <> quotedPath target-- | Upstream's line for a roots-directory entry it cannot read.unreadableRootMessage :: FilePath -> TextunreadableRootMessage path = "cannot read potential root " <> quotedPath path-- | Upstream's refusal to delete a path a root keeps alive, the path in-- single quotes, since upstream formats it as a string. Upstream's-- hint names @nix-store --query --roots@ and @--query --referrers@;-- this tool has @store gc --print-roots@ for the first and lists-- referrers in its own refusal for the second, so the hint names what-- exists.stillAliveMessage :: Text -> TextstillAliveMessage path = "Cannot delete path '" <> path <> "' since it is still alive. To find out why, use: nova-nix store gc --print-roots"-- | Upstream's refusal, in its own words, of a path a delete of named-- paths leaves alive ('deleteSpecificPaths'), which a client of-- upstream's reads.specificStillAliveMessage :: Text -> TextspecificStillAliveMessage path = "Cannot delete path '" <> path <> "' since it is still alive. To find out why, use: nix-store --query --roots and nix-store --query --referrers"-- | Upstream's progress line before a delete of named paths.deletingSpecifiedMessage :: TextdeletingSpecifiedMessage = "deleting specified paths..."-- | Upstream's refusal of an out-link inside the store, with this tool's-- command in the parenthetical.rootInsideStoreMessage :: FilePath -> TextrootInsideStoreMessage link = "creating a garbage collector root (" <> quotedPath link <> ") in the Nix store is forbidden (are you running nova-nix build inside the store?)"-- | The refusal of a Windows out-link holding an unpaired surrogate,-- which has no bytes for its record to hold.unrecordableLinkMessage :: FilePath -> TextunrecordableLinkMessage link = "cannot register '" <> T.pack link <> "' as a garbage collector root: its name has no UTF-8 form"-- | Upstream's refusal to clobber something that is not a store link.alreadyExistsMessage :: FilePath -> TextalreadyExistsMessage link = "cannot create symlink " <> quotedPath link <> "; already exists"-- | A path as upstream's messages show one: between double quotes, with-- nothing inside escaped.quotedPath :: FilePath -> TextquotedPath path = "\"" <> T.pack path <> "\""-- | The refusal of a collection or a checked delete over a database-- keyed under another spelling of the store directory.storeSpellingMismatchMessage :: FilePath -> Text -> TextstoreSpellingMismatchMessage dir row = "the store was opened as '" <> T.pack dir <> "' but its database holds '" <> row <> "': the paths were registered under another spelling of the directory, and a collection would sweep every such path as dead"-- ----------------------------------------------------------------------------- Roots-- ----------------------------------------------------------------------------- | One root: the link (or record) that names it, for reporting, and the-- store path it keeps, spelled as the database spells paths. Ordered-- by link, then path: the order @--print-roots@ lists them in.data GcRoot = GcRoot { grLink :: !FilePath, grPath :: !Text } deriving (Eq, Ord, Show)-- | A root candidate before the validity check: where it was found, the-- parsed path, and the target text to report if the database does not-- hold the path. Upstream reports a symlink's invalid target with the-- target as written and drops a regular file's silently, so only the-- symlink forms carry a report.data RootCandidate = RootCandidate { rcLink :: !FilePath, rcPath :: !StorePath, rcInvalidReport :: !(Maybe FilePath) }-- | Every root the store has, valid paths only, each link once and-- sorted as @--print-roots@ prints them: those under the store's own-- roots directory and, for a store where upstream's local store would-- keep its own, those under upstream's @gcroots@ and @profiles@ in its-- state directory ('rootDirectories'). A symlink root naming a path-- the database does not hold is reported and dropped, a regular-file-- root naming one is dropped silently, both as upstream does. Stale-- indirect-root records are removed on the way, and an entry that-- cannot be read is reported and skipped. The handle's shared lease is-- enough: a listing changes nothing another handle reads, and a record-- is published by rename, so a concurrent 'addOutLinkRoot' is seen-- whole or not at all. The collector runs this under the exclusive-- lock as the first step of a collection.findRoots :: Store -> IO [GcRoot]findRoots store = do candidates <- concat <$> mapM (walkRoots (stLogger store) (stDir store)) (rootDirectories (stDir store)) Set.toAscList . Set.fromList . catMaybes <$> mapM validOnly candidates where validOnly candidate = do valid <- isValidPath (stDB store) (rcPath candidate) if valid then pure (Just (GcRoot (rcLink candidate) (T.pack (storePathToFilePath (stDir store) (rcPath candidate))))) else do mapM_ (logMessage (stLogger store) . skippingInvalidRootMessage (rcLink candidate)) (rcInvalidReport candidate) pure Nothing-- | The directories a store's roots are found under: its own roots-- directory, and for a store in a directory upstream's local store uses-- ('upstreamStateDir'), upstream's @gcroots@ and @profiles@ beside its-- database, where upstream's clients keep their roots and profiles, as-- upstream's collector reads them. A directory that is not there holds-- no root.rootDirectories :: StoreDir -> [FilePath]rootDirectories dir = gcRootsDir dir : maybe [] (\state -> [state </> gcRootsDirName, state </> upstreamProfilesDirName]) (upstreamStateDir (unStoreDir dir))-- | Upstream's directory of profiles in its state directory.upstreamProfilesDirName :: FilePathupstreamProfilesDirName = "profiles"-- | Walk the roots directory. A directory recurses; a symlink into the-- store is a permanent root, and any other symlink is followed one hop-- as upstream follows it; a regular file is an indirect-root record-- under @auto@ and a basename-named permanent root elsewhere. An entry-- that cannot be read (permission denied, vanished, not a directory-- after all) is reported with upstream's line and contributes nothing;-- any other failure propagates, as upstream's does. What the walk-- reports goes to the logger.walkRoots :: Logger -> StoreDir -> FilePath -> IO [RootCandidate]walkRoots logger storeDir path = walk `catch` unreadable where walk = do node <- classifyWalkNode path case node of WalkDirectory -> do entries <- listDirectory path concat <$> mapM (walkRoots logger storeDir . (path </>)) (sort entries) WalkSymlink -> do target <- getSymbolicLinkTarget path case parseStoreTarget storeDir target of Just sp -> pure [RootCandidate path sp (Just target)] Nothing -> followIndirect logger storeDir path (takeDirectory path </> target) WalkRegular | isUnderDir (autoRootsDir storeDir) path -> do recorded <- BS.readFile path -- A record holding bytes no host path has, which on Windows -- only a hand edit leaves, names no out-link. outLink <- traverse decodeFS (hostPathFromBytes recorded) maybe (pure []) (followIndirect logger storeDir path) outLink | otherwise -> pure [RootCandidate path sp Nothing | Just sp <- [parseStorePathBaseName (T.pack (takeFileName path))]] WalkAbsent -> pure [] unreadable :: IOException -> IO [RootCandidate] unreadable e | isPermissionError e || isDoesNotExistError e || ioeGetErrorType e == InappropriateType = do logMessage logger (unreadableRootMessage path) pure [] | otherwise = throwIO e-- | The second hop of an indirect root: the out-link the record names.-- A symlink into the store is the root (reported under the out-link's-- own path, which is what the user created); an absent out-link makes-- a record under @auto@ stale, and it is removed; anything else is not-- a root. The removal is reported to the logger.followIndirect :: Logger -> StoreDir -> FilePath -> FilePath -> IO [RootCandidate]followIndirect logger storeDir record outLink = do node <- classifyWalkNode outLink case node of WalkSymlink -> do target <- getSymbolicLinkTarget outLink pure [RootCandidate outLink sp (Just target) | Just sp <- [parseStoreTarget storeDir target]] WalkAbsent | isUnderDir (autoRootsDir storeDir) record -> do logMessage logger (removingStaleLinkMessage record outLink) removePathForcibly record pure [] _ -> pure []-- | The store path a link target names: upstream's @toStorePath@ after-- its @isInStore@, so a target that is a store path, a trailing-separator-- spelling of one, or anything beneath one names that path. Tried under-- the opened store, the platform store and the canonical store: the-- three spellings a link written by this tool or by hand can carry.parseStoreTarget :: StoreDir -> FilePath -> Maybe StorePathparseStoreTarget storeDir target = listToMaybe (mapMaybe (`parseStorePathPrefix` targetText) [storeDir, platformStoreDir, defaultStoreDir]) where targetText = T.pack target-- | Whether a path is the directory or lies beneath it, by normalised-- components: upstream's @isInDir@, without the separator games.isUnderDir :: FilePath -> FilePath -> BoolisUnderDir dir path = splitDirectories (normalise dir) `isPrefixOf` splitDirectories (normalise path)-- | Register an out-link as an indirect root in a local store:-- 'makeOutLinkRoot' over the handle's canonical store directory. The-- store's lease already holds collection off while the link is made, so a-- path needs no temporary root first. The record is written under the-- metadata directory and renamed into @auto@, so a listing under the-- shared lease never reads a torn one, and a record already holding the-- link is left alone, since its content is a function of its name.addOutLinkRoot :: Store -> FilePath -> StorePath -> IO (Either Text FilePath)addOutLinkRoot store = makeOutLinkRoot (stDir store) (LinkRooting (\_ -> pure (Right ())) (\bytes -> Right () <$ publishRecord (stDir store) bytes))-- | How a store keeps an out-link's path from collection: while the link-- is made, and once it is.data LinkRooting = LinkRooting { -- | Keep a path from collection until the link exists. lrHold :: !(StorePath -> IO (Either Text ())), -- | Record the link as a root, given the bytes of its absolute -- spelling. lrRecord :: !(ByteString -> IO (Either Text ())) }-- | Make an out-link and root it, over a store directory: upstream's-- @addPermRoot@. The link's spelling is made absolute and collapsed-- without resolving symlinks ('absolutePath', upstream's @canonPath@), so-- a @..@ cannot spell a link into the store past the refusal. The-- spelling is the link's own bytes throughout, so a link no text can spell-- is created, recorded and found again under the name it was given; on-- Windows one holding an unpaired surrogate, which has no bytes to record,-- is refused. A link inside the store is refused, as is clobbering-- anything that is not already a symlink into the store; an existing store-- link is replaced. The link's parent directories are created, as-- upstream's @makeSymlink@ creates them.---- The path is held ('lrHold') after those refusals and before the link is-- looked at, and the record is made ('lrRecord') once the link exists, so-- a failed link (Windows without Developer Mode) leaves no record naming-- it. Whichever of the two fails is the answer. Upstream replaces the-- link atomically through a temporary name and a rename; a rename cannot-- replace a directory symlink on Windows, so the old link is removed and-- the new one created, one code path for every platform, and the link is-- briefly absent rather than briefly two things.makeOutLinkRoot :: StoreDir -> LinkRooting -> FilePath -> StorePath -> IO (Either Text FilePath)makeOutLinkRoot dir rooting rawLink sp = do cwd <- OsDir.getCurrentDirectory spelled <- absolutePath cwd <$> encodeFS rawLink link <- decodeFS spelled runExceptT $ do when (isUnderDir (unStoreDir dir) link) (throwError (rootInsideStoreMessage link)) linkBytes <- maybe (throwError (unrecordableLinkMessage link)) pure (hostPathBytes spelled) ExceptT (lrHold rooting sp) node <- liftIO (classifyWalkNode link) replaceable <- liftIO $ case node of WalkAbsent -> pure True WalkSymlink -> isJust . parseStoreTarget dir <$> getSymbolicLinkTarget link _ -> pure False unless replaceable (throwError (alreadyExistsMessage link)) liftIO $ do when (node == WalkSymlink) (removePathForcibly link) createDirectoryIfMissing True (takeDirectory link) target <- liftIO (encodeFS (storePathToFilePath dir sp)) ExceptT (createSymlinkOfKind spelled target) ExceptT (lrRecord rooting linkBytes) pure link-- | Record a link someone else made as a root, by the bytes of its-- absolute spelling, as upstream records an indirect root: what-- the link names is kept for as long as it names a store path, and a-- record whose link has gone is removed as roots are found.addIndirectRoot :: Store -> BS.ByteString -> IO ()addIndirectRoot store = publishRecord (stDir store)-- | Write an out-link's record into @auto@ by rename, given the bytes of-- the link's spelling, unless a record with that content is already-- there.publishRecord :: StoreDir -> BS.ByteString -> IO ()publishRecord dir content = do let record = autoRootsDir dir </> indirectRootRecordName content staging = recordStagingPath dir content createDirectoryIfMissing True (autoRootsDir dir) existing <- try (BS.readFile record) :: IO (Either IOException BS.ByteString) when (existing /= Right content) $ do BS.writeFile staging content renamePath staging record-- ----------------------------------------------------------------------------- Reachability-- ----------------------------------------------------------------------------- | The references map from the edge list 'queryAllReferences' returns.referencesMap :: [(Text, Text)] -> Map Text [Text]referencesMap edges = Map.fromListWith (flip (++)) [(referrer, [reference]) | (referrer, reference) <- edges]-- | Every path reachable from the roots over the references map: the-- roots themselves and, transitively, everything they reference. A-- root or a reference the map does not know is still reachable (it is-- named), just a dead end; cycles terminate on the visited set.reachableFrom :: Map Text [Text] -> [Text] -> Set TextreachableFrom refs = go Set.empty where go !seen [] = seen go !seen (path : pending) | Set.member path seen = go seen pending | otherwise = go (Set.insert path seen) (Map.findWithDefault [] path refs ++ pending)-- | Paths ordered so that each comes before every one of them it-- references, as upstream orders the paths it deletes:-- a depth-first walk over the references from each path in order, each-- path placed after what it references, the whole reversed. A reference-- outside the paths, or from a path to itself, is not followed, and a-- cycle among them is cut where the walk meets a path it entered.referrersFirst :: Map Text [Text] -> Set Text -> [Text]referrersFirst references paths = snd (foldl' visit (Set.empty, []) (Set.toAscList paths)) where visit (seen, placed) path | Set.member path seen = (seen, placed) | otherwise = let followed = [r | r <- sort (Map.findWithDefault [] path references), r /= path, Set.member r paths] (seenAfter, placedAfter) = foldl' visit (Set.insert path seen, placed) followed in (seenAfter, path : placedAfter)-- ----------------------------------------------------------------------------- The live set-- ----------------------------------------------------------------------------- | The live set at one moment under the exclusive collector lock: the-- roots' closure over the references map. Only 'withLiveSet' makes-- one, and no export takes or returns one, so a checked delete holding-- it holds the lock it was made under and the roots of its own store.newtype LiveSet = LiveSet (Set Text)-- | Whether the live set holds a path, spelled as the database spells it.isLive :: LiveSet -> Text -> BoolisLive (LiveSet live) path = Set.member path live-- | Run a checked delete under the exclusive collector lock with the-- live set as it stands, the extra roots given among its roots, after-- upstream's roots line. Refused, with the action not run, for a store-- upstream Nix's database may also manage, before the lock is taken,-- and when the database holds a path outside the opened directory.-- Every caller consumes the set inside the action and returns no part-- of it.withLiveSet :: Store -> Set StorePath -> (LiveSet -> IO a) -> IO (Either Text a)withLiveSet store extraRoots act = unlessUpstreamManaged store $ withCollectorLock store $ do checked <- validPathsUnder store case checked of Left err -> pure (Left err) Right _ -> do logMessage (stLogger store) findingRootsMessage live <- liveSetOf store extraRoots Right <$> act live-- | The closure of the roots as they stand and the extra roots given,-- which a caller keeps alive for the paths it is working with, as-- upstream's temporary roots are; the caller holds the collector lock.liveSetOf :: Store -> Set StorePath -> IO LiveSetliveSetOf store extraRoots = do roots <- findRoots store refs <- referencesMap <$> queryAllReferences (stDB store) let extra = [T.pack (storePathToFilePath (stDir store) sp) | sp <- Set.toList extraRoots] pure (LiveSet (reachableFrom refs (map grPath roots <> extra)))-- | Run a collection or a checked delete unless upstream Nix's database-- may also manage the store, as the handle spells its directory or as-- its links resolve ("Nix.Store.Upstream"). The paths upstream-- registers have no row here and the roots it keeps are not read, so-- every one would be deleted as an unregistered tree. The look reads-- nothing of this store's, so it runs before the collector lock and a-- refusal does not wait behind an open handle.unlessUpstreamManaged :: Store -> IO (Either Text a) -> IO (Either Text a)unlessUpstreamManaged store act = upstreamManagedRefusal DeletesUpstreamPaths (stDir store) >>= maybe act (pure . Left)-- | Every valid path as the database spells it, refused when one lies-- outside the opened directory: the collector and the checked delete-- compare row text with paths derived from the handle's directory, and-- a row registered under another spelling of the directory would-- compare as dead and be swept with its tree.-- 'Nix.Store.Handle.openStore' canonicalises the spelling, so this fires-- only for a store whose rows and directory genuinely disagree.validPathsUnder :: Store -> IO (Either Text (Set Text))validPathsUnder store = do valid <- queryAllValidPaths (stDB store) pure $ case filter (not . isUnderDir dir . T.unpack) valid of [] -> Right (Set.fromList valid) (stray : _) -> Left (storeSpellingMismatchMessage dir stray) where dir = unStoreDir (stDir store)-- ----------------------------------------------------------------------------- Collection-- ----------------------------------------------------------------------------- | What a collection removed: every store directory entry deleted,-- which is what upstream announces and counts, and the bytes those-- trees held. A dead row with no tree is unregistered without either.data GcResults = GcResults { gcrDeleted :: ![Text], gcrBytesFreed :: !Integer } deriving (Eq, Show)-- | What a sweep removes, each list sorted.data SweepPlan = SweepPlan { -- | Every valid path outside the live set, to unregister in one -- transaction whether or not its tree exists. spDeadRows :: ![Text], -- | Every store directory entry to delete: a dead path's tree, a -- store-shaped tree with no row (a build interrupted before -- registration), junk, and the lock file of a path that is not -- live. The metadata directory, every live path and a live path's -- lock file stay. spTrees :: ![Text] } deriving (Eq, Show)-- | The sweep plan over the valid set, the live set and the store-- directory's entries. The lock-file test is the one-- 'deleteStorePathRaw' makes: a lock-shaped name with no row-- is a lock file, since only the rows can tell one from a store object-- that happens to be called @flake.lock@, so a dead row's tree goes-- whatever its name, and an unregistered lock-shaped entry stays only-- while the path it guards is live.sweepPlan :: StoreDir -> Set Text -> Set Text -> [Text] -> SweepPlansweepPlan storeDir valid live entries = SweepPlan { spDeadRows = Set.toAscList (Set.difference valid live), spTrees = Set.toAscList (Set.fromList [fullPath entry | entry <- entries, swept entry]) } where fullPath entry = T.pack (unStoreDir storeDir </> T.unpack entry) swept entry = entry /= T.pack metaDirName && not (Set.member (fullPath entry) live) && (Set.member (fullPath entry) valid || not (guardsLivePath entry)) guardsLivePath entry = maybe False (\guarded -> Set.member (fullPath guarded) live) (lockedPathOf entry)-- | Collect garbage: find the roots, the extra roots given among them,-- walk the references, remove every dead row in one transaction, then-- every dead or unregistered tree. Holds the collector lock throughout.-- Refused for a store upstream Nix's database may also manage, before-- the lock is taken, and over a database keyed under another spelling of-- the directory. The progress lines are upstream's, told to the-- handle's logger; the summary is the caller's to print-- ('gcSummaryLine').collectGarbage :: Store -> Set StorePath -> IO (Either Text GcResults)collectGarbage store extraRoots = unlessUpstreamManaged store $ withCollectorLock store $ do checked <- validPathsUnder store case checked of Left err -> pure (Left err) Right valid -> Right <$> sweep valid where sweep valid = do logMessage (stLogger store) findingRootsMessage LiveSet live <- liveSetOf store extraRoots entries <- map T.pack <$> listDirectory (unStoreDir (stDir store)) let plan = sweepPlan (stDir store) valid live entries logMessage (stLogger store) deletingGarbageMessage unregistered <- unregisterPathRows (stDB store) (spDeadRows plan) case unregistered of RowReferenced referrers -> -- Unreachable under the exclusive lock: a referrer outside the -- dead set would have made its reference live. Loud, not silent. throwIO (userError ("collectGarbage: live paths reference dead ones: " <> show referrers)) _ -> pure () freed <- foldlIO 0 (spTrees plan) (deleteTree store) pure GcResults {gcrDeleted = spTrees plan, gcrBytesFreed = freed}-- | Remove a store directory entry's tree, given the bytes freed so far,-- with upstream's line for it, and answer the bytes freed with it.deleteTree :: Store -> Integer -> Text -> IO IntegerdeleteTree store !acc path = do logMessage (stLogger store) (deletingPathMessage path) let target = T.unpack path node <- classifyWalkNode target case node of WalkAbsent -> pure acc _ -> do bytes <- treeBytes target removePathForcibly target pure (acc + bytes)-- | The bytes a tree holds, links as leaves: a regular file's size, a-- symlink's target length (upstream counts a link's @st_size@, which is-- that), nothing for a directory itself. Upstream skips files with-- three or more hard links as shared with its @.links@ optimisation;-- this store has no such optimisation, so every file counts.treeBytes :: FilePath -> IO IntegertreeBytes path = do node <- classifyWalkNode path case node of WalkRegular -> getFileSize path WalkSymlink -> fromIntegral . BS.length . TE.encodeUtf8 . T.pack <$> getSymbolicLinkTarget path WalkDirectory -> do entries <- listDirectory path foldlIO 0 entries (\acc entry -> (acc +) <$> treeBytes (path </> entry)) WalkAbsent -> pure 0-- | Strict left fold over a list in IO: the accumulator is forced each-- step so a sweep over a large store builds no thunk chain.foldlIO :: a -> [b] -> (a -> b -> IO a) -> IO afoldlIO z [] _ = pure zfoldlIO z (x : xs) f = do !acc <- f z x foldlIO acc xs f-- | Upstream's @showBytes@ at 2.24.9: mebibytes to two places.showFreedBytes :: Integer -> TextshowFreedBytes bytes = T.pack (printf "%.2f MiB" (fromIntegral bytes / (1024 * 1024) :: Double))-- | Upstream's summary line (@PrintFreed@), plural as it prints it-- whatever the count.gcSummaryLine :: GcResults -> TextgcSummaryLine results = T.pack (show (length (gcrDeleted results))) <> " store paths deleted, " <> showFreedBytes (gcrBytesFreed results) <> " freed"-- ----------------------------------------------------------------------------- Deleting named paths-- ----------------------------------------------------------------------------- | What deleting one entry removed.data DeleteOutcome = DeleteOutcome { -- | A ValidPaths row (with its outgoing reference edges) was removed. doRowRemoved :: !Bool, -- | An on-disk tree was removed. doTreeRemoved :: !Bool } deriving (Eq, Show)-- | The name of one entry of a store directory, which is how a delete-- names its target. Joined to the directory, it names an entry directly-- inside it, never the directory itself, a path above it or a path-- elsewhere. 'storeEntryName' is the only way to make one.newtype StoreEntryName = StoreEntryName Text deriving (Eq, Show)-- | The store entry a name spells, or why it spells none. Refused: the-- empty name, which joins to the directory itself; a @\/@ or a @\\@,-- the separators of either host, refused on both so a name means the-- same on every host; a dot-leading name, which covers @.@, @..@ and the-- store's own metadata directory and is never a store path, since a-- store path's name starts with its hash; a @:@, which on Windows makes-- @C:x@ a path on drive C and @name:x@ a stream of the file @name@; and-- a NUL, which no file name holds. The name is not checked as a store-- path name: the entries a delete exists to remove are the ones current-- name rules reject.storeEntryName :: Text -> Either Text StoreEntryNamestoreEntryName name | T.null name = Left "empty store path name" | T.any Windows.isPathSeparator name = Left (name <> ": a path separator is not valid in a store path name") | T.isPrefixOf "." name = Left (name <> ": dot-leading names are not store paths") | T.any (== ':') name = Left (name <> ": ':' is not valid in a store path name") | T.any (== '\NUL') name = Left (name <> ": NUL is not valid in a store path name") | otherwise = Right (StoreEntryName name)-- | The name as text.storeEntryNameText :: StoreEntryName -> TextstoreEntryNameText (StoreEntryName name) = name-- | Delete store entries by name in the order given, each as-- 'deleteStorePathRaw' deletes one, under one collector lock and one-- live set, after upstream's roots line, printed once for the call.-- The action reports each deletion as it completes, before the next-- begins, and runs under the collector lock. The first entry whose-- delete returns 'Left' ends the call with that reason: the entries-- before it are deleted and reported, and those after it are untouched.-- The order is what deletes a reference chain leaf-first in one call: a-- referrer named earlier is unregistered before the path it references-- is checked. Refused, with nothing deleted or reported, for a store-- upstream Nix's database may also manage and over a database keyed-- under another spelling of the directory.deleteStorePaths :: Store -> [StoreEntryName] -> (StoreEntryName -> DeleteOutcome -> IO ()) -> IO (Either Text ())deleteStorePaths store names report = join <$> withLiveSet store Set.empty (\live -> runExceptT (traverse_ (deleteAndReport live) names)) where deleteAndReport live name = do removed <- ExceptT (deleteStorePathChecked store live name) liftIO (report name removed)-- | Delete one store entry by name: its registration row and its-- on-disk tree, under the collector lock with the live set as it-- stands, after upstream's roots line. Row first, tree second: an-- orphan tree left by a failed removal is inert debris, while a-- still-registered row whose tree is gone would be adopted as valid by-- existence checks. A row without a tree and a tree without a row both-- delete (the repair cases); only a target with neither is an error.-- An unregistered lock file of a store path is refused, since lock-- files coordinate concurrent store access.---- Liveness is upstream's rule for a specific delete: a path reachable-- from a root is refused with its words. The referrer refusal that-- follows is this tool's own in wording and in shape. Upstream refuses-- a path with an unrooted referrer with the same still-alive line-- unless that referrer is named in the same invocation (its-- @pathsToDelete@ set in 2.24.9's @deleteReferrersClosure@), in which-- case the named set deletes referrer-first; this delete removes-- exactly the path named and lists the referrers that stand in the way,-- so a chain deletes leaf-first in argument order through-- 'deleteStorePaths', which shares one lock and one live set among the-- entries it is given. Refused, with nothing deleted, for a store-- upstream Nix's database may also manage and over a database keyed-- under another spelling of the directory.deleteStorePathRaw :: Store -> StoreEntryName -> IO (Either Text DeleteOutcome)deleteStorePathRaw store name = join <$> withLiveSet store Set.empty (\live -> deleteStorePathChecked store live name)-- | Delete store paths as upstream's collector deletes the paths it is-- named, with the extra roots given kept alive as upstream's temporary-- roots are: each path in path order together with the paths that-- reference it, which must all be among those named, the referrers-- first ('referrersFirst'), each with upstream's line. A path that is-- live, or that a path not named references, is left, and the delete-- stops there with upstream's refusal ('specificStillAliveMessage'), the-- paths before it deleted. So a path and the paths that reference it-- delete together in whatever order they are named. A path the-- database does not hold has no referrers, and its tree is deleted.-- Naming no path deletes nothing and takes no lock, as upstream returns-- at once; otherwise it is refused, with nothing deleted, as-- 'collectGarbage' refuses.deleteSpecificPaths :: Store -> Set StorePath -> Set StorePath -> IO (Either Text GcResults)deleteSpecificPaths store extraRoots targets | Set.null targets = pure (Right (GcResults [] 0)) | otherwise = join <$> withLiveSet store extraRoots deleteNamed where pathText = T.pack . storePathToFilePath (stDir store) named = Set.map pathText targets deleteNamed live = do logMessage (stLogger store) deletingSpecifiedMessage outcome <- runExceptT (foldlM (deleteWithReferrers live) (GcResults [] 0, Set.empty) (Set.toAscList targets)) pure (fst <$> outcome) deleteWithReferrers :: LiveSet -> (GcResults, Set Text) -> StorePath -> ExceptT Text IO (GcResults, Set Text) deleteWithReferrers live (results, dead) sp = do closure <- liftIO (referrerClosure live dead (pathText sp)) (deleted, deadAfter) <- case closure of Nothing -> pure (results, dead) Just visited -> do references <- liftIO (Map.fromList <$> traverse (\path -> (,) path <$> referencesOf path) (Set.toList visited)) let order = referrersFirst references visited unregistered <- liftIO (unregisterPathRows (stDB store) order) case unregistered of -- Unreachable: the closure holds every path that references -- one of its paths. Loud, since the trees would go next. RowReferenced referrers -> throwError ("paths outside the delete reference it: " <> T.intercalate ", " referrers) _ -> pure () freed <- liftIO (foldlIO (gcrBytesFreed results) order (deleteTree store)) pure (GcResults (gcrDeleted results <> order) freed, Set.union dead visited) if Set.member (pathText sp) deadAfter then pure (deleted, deadAfter) else throwError (specificStillAliveMessage (storePathToText defaultStoreDir sp)) -- The path with every path that references it, transitively, when -- none is live and all are named; paths already deleted are passed. referrerClosure :: LiveSet -> Set Text -> Text -> IO (Maybe (Set Text)) referrerClosure live dead start = go Set.empty [start] where go visited pending = case pending of [] -> pure (Just visited) path : rest | Set.member path visited || Set.member path dead -> go visited rest | isLive live path || not (Set.member path named) -> pure Nothing | otherwise -> do referrers <- referrersOf path go (Set.insert path visited) (rest <> referrers) referrersOf, referencesOf :: Text -> IO [Text] referrersOf path = maybe (pure []) (queryReferrers (stDB store)) (parseStorePath (stDir store) path) referencesOf path = maybe (pure []) (queryReferences (stDB store)) (parseStorePath (stDir store) path)-- | The delete of one entry given the live set, which stands for the-- collector lock being held. Inside the collector lock the sequence-- also holds the target's per-path lock - the same file a substituter-- of the path locks, as upstream's deletePath does - so a holder that-- is not a store handle (nothing in this tool, but nothing forbids one)-- still cannot have its delete-materialize-register torn apart by this-- delete.deleteStorePathChecked :: Store -> LiveSet -> StoreEntryName -> IO (Either Text DeleteOutcome)deleteStorePathChecked store live (StoreEntryName basename) | isLive live (T.pack target) = pure (Left (stillAliveMessage (T.pack target))) | otherwise = deleteUnderPathLock where target = unStoreDir (stDir store) </> T.unpack basename deleteUnderPathLock = withLockFile (stLogger store) (target <> lockFileSuffix) $ \_ -> do -- A holder never deletes a lock file (the 'Nix.Store.Lock' -- header), and neither does this delete. A target is one when -- stripping the suffix leaves a well-formed store basename AND no -- registration row bears the full name: names like @flake.lock@ -- are legal store-path names, so a registered object of this -- exact name deletes normally, and only the rows can tell the two -- apart. The check precedes the row removal below, which is -- destructive. registered <- case parseStorePathBaseName basename of Just sp -> isValidPath (stDB store) sp Nothing -> pure False case (registered, lockedPathOf basename) of (False, Just guardedPath) -> pure ( Left ( basename <> ": names the lock file of " <> guardedPath <> "; lock files coordinate concurrent store access" <> " and are never deleted here (store gc removes it," <> " and any unregistered store object of this exact" <> " name, once " <> guardedPath <> " is not live)" ) ) _ -> deleteRowAndTree deleteRowAndTree = do rowResult <- unregisterPathRow (stDB store) (T.pack target) case rowResult of RowReferenced referrers -> pure ( Left ( basename <> " is referenced by:" <> T.concat ["\n " <> r | r <- referrers] ) ) _ -> do -- 'doesPathExist' follows links, so a dangling top-level symlink -- would read as absent; links are leaves here (as in store walks), -- and leftover link debris must still be removable. treeExisted <- do onDisk <- doesPathExist target if onDisk then pure True else pathIsSymbolicLink target `catch` \(_ :: IOException) -> pure False when treeExisted (removePathForcibly target) let rowRemoved = rowResult == RowUnregistered if rowRemoved || treeExisted then pure (Right DeleteOutcome {doRowRemoved = rowRemoved, doTreeRemoved = treeExisted}) else pure (Left (basename <> ": not in this store (no registration row, no tree on disk)"))