packages feed

nova-nix-0.11.0.0 / src / Nix / Profile / Generation.hs

{-# LANGUAGE CPP #-}{-# LANGUAGE ScopedTypeVariables #-}-- | A profile: a link to its current generation, which a switch made here-- always makes the newest; each generation a link to a store path holding-- the profile's tree and its @manifest.json@, and each a root the-- collector keeps, in upstream Nix's layout.---- A user's profiles are in @profiles@ under the state directory:-- @$NIX_STATE_HOME@, else @$XDG_STATE_HOME\/nix@, else-- @~\/.local\/state\/nix@, and on Windows @\<Local AppData\>\\nix\\state@-- (@getStateDir@ in users.cc, @getStateHome@ in xdg-dirs.cc).  The default-- profile is @profiles\/profile@, which @~\/.nix-profile@, or-- @\<state\>\/profile@ under @use-xdg-base-directories@, links to-- (@getDefaultProfile@ in profiles.cc).  Upstream keeps root's profiles under-- its state directory instead; here every user's are where a user's are.---- A profile named @P@ has generations @P-1-link@, @P-2-link@ and on beside-- it, and @P@ links to one of them by its bare name.  A new generation is-- one past the highest, unless the highest already names the path, which-- it then stays (@createGeneration@ in profiles.cc).  Each is linked as-- @nova-nix build@ links its output ('Nix.Store.Ops.soAddOutLinkRoot',-- upstream's @addPermRoot@), so it is an indirect root of the store it names.---- A change to a profile reads the profile's link, makes the new-- generation's store path with no lock held, then takes the profile's-- lock and starts again if the link moved meanwhile, as @nix-env@ does-- (@createUserEnv@ in user-env.cc).  Upstream's @nix profile@ takes no lock,-- so two changes at once can both start from one manifest and the later-- switch drop what the earlier added.  The lock file stays once it is-- released, as every lock file nova-nix takes does ("Nix.Store.Lock"), where-- upstream deletes it.---- A rollback switches the profile's link to the newest generation below-- the current one, or to the one asked for, and wiping the history-- deletes the link of every generation but the current one, or of those-- made before a cutoff but the newest of them, each holding the-- profile's lock, as upstream does.  A generation's time is its link's own-- modification time.  A deleted generation's root record stays until the-- next collection finds its link gone, removes the record, and takes what-- only that generation kept.---- The location, the names and the decisions are pure; the IO below lists-- the profile's directory, reads its links and their times, takes its-- lock, and makes and removes its links.module Nix.Profile.Generation  ( -- * Where profiles are    StateHome (..),    ProfileEnvironment (..),    ProfileLinkPlace (..),    stateDirectory,    profilesDirectory,    profileLinkPath,    defaultProfilePath,    absolutePath,    readProfileEnvironment,    resolveDefaultProfile,    -- * Generations    GenerationNumber (..),    Generation (..),    generationName,    parseGenerationName,    generationsIn,    currentGeneration,    NextGeneration (..),    nextGeneration,    listGenerations,    -- * When generations were made    EpochSeconds (..),    DatedGeneration (..),    generationDate,    currentEpochSeconds,    findGenerations,    -- * Rolling back and wiping history    Changes (..),    RollbackTarget (..),    rollbackPlan,    readGenerationNumber,    Days (..),    parseOlderThan,    cutoffBefore,    WipeScope (..),    WipeStep (..),    wipePlan,    switchGeneration,    wipeHistory,    -- * A generation's store path    NarTargets (..),    hostNarTargets,    narLinkTarget,    generationNar,    generationStoreName,    -- * Changing a profile    ProfileFailure (..),    Change (..),    Updated (..),    readManifest,    checkProfileStore,    updateProfile,  )whereimport Control.Exception (IOException, bracket, catch, mask_, onException, try)import Control.Monad (unless, when)import Control.Monad.Except (ExceptT (..), runExceptT, throwError)import Control.Monad.IO.Class (liftIO)import Data.Bifunctor (first)import Data.ByteString (ByteString)import qualified Data.ByteString as BSimport qualified Data.ByteString.Char8 as BS8import Data.Char (isAsciiLower, isAsciiUpper, isDigit, toUpper)import Data.Either (fromRight)import Data.Foldable (traverse_)import Data.Int (Int32, Int64)import Data.List (isPrefixOf, sort, sortOn, stripPrefix, unsnoc)import qualified Data.Map.Strict as Mapimport Data.Maybe (fromMaybe, isJust, listToMaybe, mapMaybe)import Data.Text (Text)import qualified Data.Text as Timport Data.Time.Clock.POSIX (getPOSIXTime, posixSecondsToUTCTime)import Data.Time.Format (defaultTimeLocale, formatTime)import Data.Word (Word64)import Nix.Environment (EnvLookup (..), lookupEnvBytes)import Nix.HostPath (absolutePath, hostPathBytes, hostPathFromBytes, hostPathText)import Nix.Logger (Logger, logMessage, logWarning)import Nix.Profile.Manifest (Conflict, Manifest, ManifestError, attributeConflict, emptyManifest, manifestPackages, manifestReferences, parseManifest, renderManifest)import Nix.Profile.Tree (BuildEnvFailure (..), Built (..), Node (..), Package (..), Tree, buildProfile, storeTreeReader, warningText)import Nix.Store.Handle (canonicalStoreDir)import Nix.Store.Lock (LockMode (..), acquireLockFileWith, lockFileSuffix, releasePathLock)import Nix.Store.Metadata (nodeModificationTime)import Nix.Store.Ops (StoreOps (..))import Nix.Store.Path (StoreDir (..), StorePath, parseStorePathPrefix, storePathToFilePath)import qualified NovaCache.NAR as NARimport qualified System.Directory.OsPath as OsDirimport System.IO.Error (isAlreadyExistsError, isDoesNotExistError)import qualified System.Infoimport System.OsPath (OsPath, (</>))import qualified System.OsPath as OPimport Text.Read (readMaybe)#if defined(mingw32_HOST_OS)import Foreign.Ptr (nullPtr)import System.Win32.Shell (cSIDL_LOCAL_APPDATA, sHGFP_TYPE_CURRENT, sHGetFolderPath)#elseimport Foreign.C.Error (Errno (..), eNOTDIR)import GHC.IO.Exception (IOException (ioe_errno))import System.Posix.Files.ByteString (fileOwner, getFileStatus)import System.Posix.User (getEffectiveUserID)import System.Posix.User.ByteString (getUserEntryForID, homeDirectory)#endif-- ----------------------------------------------------------------------------- Where profiles are-- ----------------------------------------------------------------------------- | What names a user's state directory.data StateHome  = -- | @NIX_STATE_HOME@, which names it.    NixStateHome !OsPath  | -- | On Unix, when @NIX_STATE_HOME@ is unset: @XDG_STATE_HOME@, when    -- that is set, under which it is @nix@.    XdgStateHome !(Maybe OsPath)  | -- | On Windows, when @NIX_STATE_HOME@ is unset: the Local AppData    -- folder, under which it is @nix\\state@.    LocalAppDataHome !OsPath  deriving (Eq, Show)-- | What decides where a user's profiles are.data ProfileEnvironment = ProfileEnvironment  { peStateHome :: !StateHome,    -- | The user's home: upstream's @getHome@, @HOME@ on Unix and    -- @USERPROFILE@ on Windows.    peHome :: !OsPath  }  deriving (Eq, Show)-- | Where the link to the default profile is, as-- @use-xdg-base-directories@ chooses (@useXDGBaseDirectories@ in-- globals.hh, @getDefaultProfile@ in profiles.cc).data ProfileLinkPlace  = -- | @~\/.nix-profile@, upstream's default.    HomeProfileLink  | -- | @\<state\>\/profile@.    StateProfileLink  deriving (Eq, Show)-- | The state directory (@getStateDir@ in users.cc).  A variable is used-- as it is set, an empty one included, as upstream's @getEnv@ reads it.stateDirectory :: ProfileEnvironment -> OsPathstateDirectory env = case peStateHome env of  NixStateHome dir -> dir  XdgStateHome (Just dir) -> dir </> ascii "nix"  XdgStateHome Nothing -> peHome env </> ascii ".local" </> ascii "state" </> ascii "nix"  LocalAppDataHome dir -> dir </> ascii "nix" </> ascii "state"-- | The directory a user's profiles are in (@profilesDir@ in profiles.cc).profilesDirectory :: ProfileEnvironment -> OsPathprofilesDirectory env = stateDirectory env </> ascii "profiles"-- | The link to the default profile.profileLinkPath :: ProfileLinkPlace -> ProfileEnvironment -> OsPathprofileLinkPath place env = case place of  HomeProfileLink -> peHome env </> ascii ".nix-profile"  StateProfileLink -> stateDirectory env </> ascii "profile"-- | The default profile the link is made to: @profiles\/profile@.defaultProfilePath :: ProfileEnvironment -> OsPathdefaultProfilePath env = profilesDirectory env </> ascii "profile"-- | Read where this user's profiles are from the environment, as upstream-- does: @NIX_STATE_HOME@, then on Unix @XDG_STATE_HOME@ and on Windows-- the Local AppData known folder, which is asked only when-- @NIX_STATE_HOME@ is unset; and the home, with any warning finding it-- gives told to the logger.readProfileEnvironment :: Logger -> IO (Either Text ProfileEnvironment)readProfileEnvironment logger = runExceptT $ do  nixStateHome <- ExceptT (variablePath "NIX_STATE_HOME")  stateHome <- case nixStateHome of    Just dir -> pure (NixStateHome dir)    Nothing -> ExceptT hostStateHome  ProfileEnvironment stateHome <$> ExceptT (readHome logger)-- | A variable's value as a host path, 'Nothing' when it is unset.variablePath :: ByteString -> IO (Either Text (Maybe OsPath))variablePath name = do  found <- lookupEnvBytes name  pure $ case found of    EnvUnset -> Right Nothing    EnvValue bytes -> maybe (Left (variableName <> " is not valid UTF-8, so it names no Windows path")) (Right . Just) (hostPathFromBytes bytes)    EnvUnpairedSurrogate -> Left (variableName <> " holds an unpaired UTF-16 surrogate, which has no UTF-8 form")  where    variableName = T.pack (BS8.unpack name)-- | What names the state directory on this host when @NIX_STATE_HOME@-- does not.hostStateHome :: IO (Either Text StateHome)#if defined(mingw32_HOST_OS)hostStateHome = do  -- SHGetFolderPath's CSIDL_LOCAL_APPDATA is the folder  -- SHGetKnownFolderPath's FOLDERID_LocalAppData names, which upstream  -- asks (getLocalAppData in windows/known-folders.cc); neither reads  -- LOCALAPPDATA.  found <- try (sHGetFolderPath nullPtr cSIDL_LOCAL_APPDATA nullPtr sHGFP_TYPE_CURRENT)  case found of    Left (failure :: IOException) -> pure (Left ("failed to get known folder path: " <> T.pack (show failure)))    Right dir -> Right . LocalAppDataHome <$> OP.encodeFS dir#elsehostStateHome = fmap XdgStateHome <$> variablePath "XDG_STATE_HOME"#endif-- | The user's home, as upstream's @getHome@ finds it, any warning told-- to the logger.readHome :: Logger -> IO (Either Text OsPath)#if defined(mingw32_HOST_OS)-- @USERPROFILE@, else the default user's profile, collapsed-- (@getHome@ in windows/users.cc).readHome _ = do  found <- variablePath "USERPROFILE"  cwd <- OsDir.getCurrentDirectory  pure (absolutePath cwd . fromMaybe defaultUserProfile <$> found)  where    defaultUserProfile = ascii "C:\\Users\\Default"#else-- @HOME@, unless what it names exists and another user owns it, or its-- status cannot be read for a reason other than its absence, which-- @ENOENT@ and @ENOTDIR@ are (@maybeStat@ in file-system.cc), when the-- password database's home is used, with upstream's warning (@getHome@ in-- unix/users.cc).readHome logger = do  found <- lookupEnvBytes "HOME"  case found of    EnvValue bytes -> do      probed <- try (getFileStatus bytes)      user <- getEffectiveUserID      case probed of        Right status          | fileOwner status /= user -> passwordHome (Just bytes)          | otherwise -> pure (homePath bytes)        Left (failure :: IOException)          | isDoesNotExistError failure || fmap Errno (ioe_errno failure) == Just eNOTDIR -> pure (homePath bytes)          | otherwise -> do              logWarning logger ("couldn't stat $HOME ('" <> shown bytes <> "') for reason other than not existing, falling back to the one defined in the 'passwd' file: " <> T.pack (show failure))              passwordHome Nothing    _ -> passwordHome Nothing  where    homePath bytes = maybe (Left "HOME names no path") Right (hostPathFromBytes bytes)    shown = T.pack . BS8.unpack    passwordHome unowned = do      entry <- tryIO (getUserEntryForID =<< getEffectiveUserID)      case entry of        Right found          | not (BS.null (homeDirectory found)) -> do              let home = homeDirectory found              case unowned of                Just given                  | given /= home ->                      logWarning logger ("$HOME ('" <> shown given <> "') is not owned by you, falling back to the one defined in the 'passwd' file ('" <> shown home <> "')")                _ -> pure ()              pure (homePath home)        _ -> pure (Left "cannot determine user's home directory")#endif-- | Resolve the default profile, making its directory and its link when-- they are absent, as upstream's @getDefaultProfile@ does-- (profiles.cc): the link's target, made absolute against the link's-- directory, or the link itself when the directory or the link cannot be made-- or the link cannot be read.  Absence is by @lstat@ (@pathExists@ in-- file-system.cc), so a link that leads nowhere is kept.  Under-- 'StateProfileLink' the state directory is made first, and a failure to make-- it is the result.resolveDefaultProfile :: ProfileLinkPlace -> ProfileEnvironment -> IO (Either Text OsPath)resolveDefaultProfile place env = do  made <- case place of    StateProfileLink -> first creating <$> tryIO (OsDir.createDirectoryIfMissing True (stateDirectory env))    HomeProfileLink -> pure (Right ())  case made of    Left failure -> pure (Left failure)    Right () -> do      resolved <- try $ do        OsDir.createDirectoryIfMissing True (profilesDirectory env)        absent <- linkAbsent link        linked <- if absent then replaceLink link (defaultProfilePath env) else pure (Right ())        case linked of          Left _ -> pure link          Right () -> absolutePath (OP.takeDirectory link) <$> OsDir.getSymbolicLinkTarget link      pure (Right (either (\(_ :: IOException) -> link) id resolved))  where    link = profileLinkPath place env    creating failure = "creating directory \"" <> hostPathText (stateDirectory env) <> "\": " <> T.pack (show failure)-- ----------------------------------------------------------------------------- Generations-- ----------------------------------------------------------------------------- | A generation's number (upstream's @GenerationNumber@, a 64-bit-- unsigned integer).newtype GenerationNumber = GenerationNumber Word64  deriving (Eq, Ord, Show)-- | A generation: its number and its link's path.data Generation = Generation  { generationNumber :: !GenerationNumber,    generationPath :: !OsPath  }  deriving (Eq, Show)-- | The link of a profile's generation: the profile's path with-- @-N-link@ appended (@makeName@ in profiles.cc).generationName :: OsPath -> GenerationNumber -> OsPathgenerationName profile (GenerationNumber n) = profile <> ascii ("-" <> show n <> "-link")-- | The generation a name in the profile's directory is, given the-- profile's own name, as upstream's @parseName@ reads one-- (profiles.cc): the profile's name and @-@, then what precedes the-- first @-link@ after them, read as a 64-bit unsigned number is by-- @string2Int@ in util.cc, which takes digits after an optional-- @+@.  Whatever follows the first @-link@ is ignored, so-- @profile-3-link.tmp@ is generation 3 too.parseGenerationName :: OsPath -> OsPath -> Maybe GenerationNumberparseGenerationName profileName name = do  rest <- stripPrefix (OP.unpack profileName ++ [OP.unsafeFromChar '-']) (OP.unpack name)  let chars = map OP.toChar rest  number <- listToMaybe [take n chars | n <- [0 .. length chars], linkSuffix `isPrefixOf` drop n chars]  GenerationNumber <$> unsignedDecimal number  where    linkSuffix = "-link"-- | A profile's current generation, from what its link names as the link-- spells it: the generation that names when it parses as one of the-- profile's, as a switch writes it, by the generation's bare name, and-- none for an absolute or other target, or for a profile with no link,-- as upstream reads it.currentGeneration :: OsPath -> Maybe OsPath -> Maybe GenerationNumbercurrentGeneration profile target = target >>= parseGenerationName (OP.takeFileName profile)-- | Digits after an optional @+@, within 64 bits, as upstream reads an-- unsigned number.unsignedDecimal :: String -> Maybe Word64unsignedDecimal given = within =<< decimal (fromMaybe given (stripPrefix "+" given))  where    within :: Integer -> Maybe Word64    within n      | n <= toInteger (maxBound :: Word64) = Just (fromInteger n)      | otherwise = Nothing-- | Digits after an optional @+@ or @-@, within 32 bits, as upstream reads-- an int.signedDecimal :: String -> Maybe Int32signedDecimal given = within =<< signed  where    signed = case given of      '-' : digits -> negate <$> decimal digits      '+' : digits -> decimal digits      digits -> decimal digits    within :: Integer -> Maybe Int32    within n      | n >= toInteger (minBound :: Int32) && n <= toInteger (maxBound :: Int32) = Just (fromInteger n)      | otherwise = Nothing-- | One or more decimal digits, and nothing else.decimal :: String -> Maybe Integerdecimal digits  | not (null digits), all isDigit digits = readMaybe digits  | otherwise = Nothing-- | The generations of a profile among the names of its directory, in-- order of number (@findGenerations@ in profiles.cc).  Names are taken in-- sorted order, so of two names for one number, as @profile-3-link@ and-- @profile-3-link.tmp@ are, the later in that order counts as the later-- generation; upstream takes them in @readdir@ order.generationsIn :: OsPath -> [OsPath] -> [Generation]generationsIn profile names =  sortOn generationNumber [Generation number (OP.takeDirectory profile </> name) | name <- sort names, Just number <- [parseGenerationName (OP.takeFileName profile) name]]-- | What a new generation for a store path is.data NextGeneration  = -- | The newest generation, which already names the path.    ReuseGeneration !Generation  | -- | A new one, by number.    NewGeneration !GenerationNumber  deriving (Eq, Show)-- | The generation a profile switches to for a store path, given its-- newest generation with that generation's raw target, and the path as-- the store spells it on disk (@createGeneration@ in profiles.cc).nextGeneration :: Maybe (Generation, OsPath) -> OsPath -> NextGenerationnextGeneration newest target = case newest of  Just (generation, linked)    | linked == target -> ReuseGeneration generation    | GenerationNumber n <- generationNumber generation -> NewGeneration (GenerationNumber (n + 1))  Nothing -> NewGeneration (GenerationNumber 1)-- | A profile's generations, from a listing of its directory.listGenerations :: OsPath -> IO (Either ProfileFailure [Generation])listGenerations profile = do  listed <- try (OsDir.listDirectory dir)  pure $ case listed of    Left (failure :: IOException) -> Left (ProfileIOFailed ("cannot read directory \"" <> hostPathText dir <> "\": " <> T.pack (show failure)))    Right names -> Right (generationsIn profile names)  where    dir = OP.takeDirectory profile-- ----------------------------------------------------------------------------- A generation's store path-- ----------------------------------------------------------------------------- | The name a generation's store path has (@ProfileManifest::build@ in-- profile.cc).generationStoreName :: TextgenerationStoreName = "profile"-- | The file a generation's manifest is in (@ProfileManifest::build@ in-- profile.cc).manifestFileName :: StringmanifestFileName = "manifest.json"-- | The file a profile @nix-env@ made holds its manifest in-- (the @ProfileManifest@ constructor in profile.cc).nixEnvManifestFileName :: StringnixEnvManifestFileName = "manifest.nix"-- | How a host's link targets are written in a NAR.data NarTargets  = -- | As their bytes, on every host but Windows.    TargetBytes  | -- | With @/@ for each @\\@, on Windows: a reparse point holds    -- backslashes, and nova-cache's serialiser writes the target it reads    -- from disk with slashes (@symlinkTargetBytes@), so a NAR is    -- host-independent.    SlashedTargets  deriving (Eq, Show)-- | How this host's link targets are written in a NAR.hostNarTargets :: NarTargetshostNarTargets  | onWindows = SlashedTargets  | otherwise = TargetBytes-- | A link target's bytes as a NAR holds them.  A backslash is one byte,-- @0x5C@, which no multi-byte UTF-8 sequence contains, so the replacement-- is exact on a target's UTF-8.narLinkTarget :: NarTargets -> ByteString -> ByteStringnarLinkTarget targets bytes = case targets of  TargetBytes -> bytes  SlashedTargets -> BS8.map (\c -> if c == '\\' then '/' else c) bytes-- | The NAR of a generation: the tree, and @manifest.json@ holding the-- manifest's bytes, as upstream dumps the directory it makes-- (@ProfileManifest::build@ in profile.cc).  A name and a link target are the-- bytes the tree holds for them ('hostPathBytes'), a target written as the-- host's serialiser writes it ('narLinkTarget'), so the NAR is the one the-- tree unpacked from it serialises to.  'Left' for a name with no UTF-8 form.generationNar :: NarTargets -> Tree -> ByteString -> Either Text NAR.NarEntrygenerationNar targets tree manifest = NAR.NarDirectory . ((BS8.pack manifestFileName, NAR.NarRegular False manifest) :) <$> entries tree  where    entries sub = traverse entry (Map.toList sub)    entry (name, node) = (,) <$> bytesOf name <*> nodeEntry node    nodeEntry node = case node of      Link target _ -> NAR.NarSymlink . narLinkTarget targets <$> bytesOf target      Directory sub -> NAR.NarDirectory <$> entries sub    bytesOf path = maybe (Left ("'" <> hostPathText path <> "' has no UTF-8 form")) Right (hostPathBytes path)-- ----------------------------------------------------------------------------- Changing a profile-- ----------------------------------------------------------------------------- | Why a profile could not be read or changed.data ProfileFailure  = -- | A file of the profile's could not be read or made, and why.    ProfileIOFailed !Text  | -- | The manifest, at this path, could not be read.    ManifestFailed !OsPath !ManifestError  | -- | A profile @nix-env@ made: it holds @manifest.nix@ and no    -- @manifest.json@, and @nix-env@'s manifest is not read here.    NixEnvProfile !OsPath  | -- | A profile whose current generation is outside the opened store:    -- the profile, and the path its links lead to.    ForeignGeneration !OsPath !OsPath  | -- | The tree could not be built.    TreeFailed !BuildEnvFailure  | -- | Two files of one priority conflict, by the elements they came from.    TreeConflict !Conflict  | -- | The store refused the generation's path or its root.    StoreRefused !Text  | -- | A rollback to a generation the profile does not have.    NoSuchGeneration !GenerationNumber  | -- | A rollback to the generation before the current one, which the    -- profile does not have: the current one, when there is one.    NoOlderGeneration !(Maybe GenerationNumber)  deriving (Eq, Show)-- | What a change makes of a profile's manifest.data Change  = -- | Nothing: the profile keeps its generation.    Unchanged  | -- | The manifest of the profile's next generation.    Changed !Manifest  deriving (Eq, Show)-- | What a change to a profile did.data Updated  = -- | Nothing: the change made none.    NothingChanged  | -- | The profile links to this generation.    SwitchedTo !Generation  deriving (Eq, Show)-- | How one attempt at a change ends.data Attempt = Restart | Finished !Updated-- | Read a profile's manifest (the @ProfileManifest@ constructor in-- profile.cc): @manifest.json@ through the profile's links, none for a-- profile that is not there or holds neither manifest, and a refusal for one-- only @nix-env@'s @manifest.nix@ describes.readManifest :: OsPath -> IO (Either ProfileFailure Manifest)readManifest profile = do  contents <- try (OP.decodeFS path >>= BS.readFile)  case contents of    Right bytes -> pure (first (ManifestFailed path) (parseManifest bytes))    Left (failure :: IOException)      | isDoesNotExistError failure -> do          nixEnv <- OsDir.doesPathExist (profile </> ascii nixEnvManifestFileName)          pure (if nixEnv then Left (NixEnvProfile profile) else Right emptyManifest)      | otherwise -> pure (Left (ProfileIOFailed ("reading file \"" <> hostPathText path <> "\": " <> T.pack (show failure))))  where    path = profile </> ascii manifestFileName-- | Change a profile: read its link and its manifest, apply the change,-- make the new generation's store path, then under the profile's lock-- make and switch to the generation, starting again, with upstream's-- line, when the link moved since it was read (@createUserEnv@ in-- user-env.cc).  A profile whose current generation lies outside the store-- ('checkProfileStore') is refused before anything is made: a generation of-- another store read against this one would name paths it does not hold.  The-- store directory is taken in the spelling the store's handle keys it by-- ('canonicalStoreDir'), which the tree's links and the generations' targets-- are written in.  The line, the tree's warnings and a wait on the-- profile's lock go to the logger.updateProfile :: Logger -> StoreOps IO -> StoreDir -> OsPath -> (Manifest -> IO Change) -> IO (Either ProfileFailure Updated)updateProfile logger ops givenStoreDir profile change = canonicalStoreDir givenStoreDir >>= attempting  where    attempting storeDir = do      attempted <- runExceptT (attempt storeDir)      case attempted of        Left failure -> pure (Left failure)        Right (Finished updated) -> pure (Right updated)        Right Restart -> do          logMessage logger ("profile \"" <> hostPathText profile <> "\" changed while we were busy; restarting")          attempting storeDir    attempt storeDir = do      token <- ExceptT (profileToken profile)      ExceptT (checkProfileStore storeDir profile)      manifest <- ExceptT (readManifest profile)      changed <- liftIO (change manifest)      case changed of        Unchanged -> pure (Finished NothingChanged)        Changed next -> do          path <- makeGeneration logger ops storeDir profile next          ExceptT . withProfileLock logger profile . runExceptT $ do            now <- ExceptT (profileToken profile)            if now /= token              then pure Restart              else do                generation <- createGeneration ops storeDir profile path                ExceptT (first ProfileIOFailed <$> replaceLink profile (OP.takeFileName (generationPath generation)))                pure (Finished (SwitchedTo generation))-- | What a profile's link names, its raw target, or 'Nothing' when there-- is no link: upstream's @optimisticLockProfile@ in profiles.cc.profileToken :: OsPath -> IO (Either ProfileFailure (Maybe OsPath))profileToken profile = do  absent <- try (linkAbsent profile)  case absent of    Left (failure :: IOException) -> pure (Left (readingLink failure))    Right True -> pure (Right Nothing)    Right False -> do      target <- tryIO (OsDir.getSymbolicLinkTarget profile)      pure (either (Left . readingLink) (Right . Just) target)  where    readingLink failure = ProfileIOFailed ("reading symbolic link \"" <> hostPathText profile <> "\": " <> T.pack (show failure))-- | Refuse a profile whose current generation, the path its links lead-- to, exists outside the store.  The store directory is resolved through-- its links as the profile is, so a store reached through a linked-- directory, as macOS's @\/tmp@ and @\/var@ are, is its own.  A profile-- that is not there, or whose links lead nowhere, has no generation to-- refuse.checkProfileStore :: StoreDir -> OsPath -> IO (Either ProfileFailure ())checkProfileStore storeDir profile = do  resolved <- tryIO (OsDir.canonicalizePath profile)  case resolved of    Left _ -> pure (Right ())    Right path -> do      present <- OsDir.doesPathExist path      spelled <- OP.decodeFS path      store <- resolvedStoreDir storeDir      pure $        if not present || isJust (parseStorePathPrefix store (T.pack spelled))          then Right ()          else Left (ForeignGeneration profile path)-- | A store directory with every link on it resolved, as-- @canonicalizePath@ resolves one, which is how the tree resolves a link-- it expands; the directory as given when it cannot be resolved.resolvedStoreDir :: StoreDir -> IO StoreDirresolvedStoreDir storeDir = StoreDir . fromRight (unStoreDir storeDir) <$> tryIO (OP.encodeFS (unStoreDir storeDir) >>= OsDir.canonicalizePath >>= OP.decodeFS)-- | Make a generation's store path from its manifest: the tree of its-- active elements' paths, with the warnings the tree gives logged, and-- @manifest.json@, added as 'generationStoreName' with every element's-- paths as its references (@ProfileManifest::build@ in profile.cc).  The-- tree's warnings name entries under the profile's path.  A conflict is-- attributed under the store directory as given and as the tree resolves it.makeGeneration :: Logger -> StoreOps IO -> StoreDir -> OsPath -> Manifest -> ExceptT ProfileFailure IO StorePathmakeGeneration logger ops storeDir profile manifest = do  packages <- liftIO (traverse package (manifestPackages manifest))  Built warnings built <- liftIO (buildProfile (storeTreeReader storeDir) profile packages)  liftIO (mapM_ (logWarning logger . warningText) warnings)  tree <- case built of    Right tree -> pure tree    Left (FileConflict existing incoming priority) -> do      resolvedDir <- liftIO (resolvedStoreDir storeDir)      throwError (maybe (TreeFailed (FileConflict existing incoming priority)) TreeConflict (attributeConflict storeDir resolvedDir manifest existing incoming priority))    Left failure -> throwError (TreeFailed failure)  nar <- either (throwError . ProfileIOFailed) pure (generationNar hostNarTargets tree (renderManifest manifest))  ExceptT (first StoreRefused <$> soAddSourceTree ops generationStoreName (manifestReferences manifest) nar)  where    package (path, priority) = (`Package` priority) <$> OP.encodeFS (storePathToFilePath storeDir path)-- | The generation a profile switches to for a store path: the newest,-- when it already names the path, or the next, linked and rooted as an-- out-link is (@createGeneration@ in profiles.cc).createGeneration :: StoreOps IO -> StoreDir -> OsPath -> StorePath -> ExceptT ProfileFailure IO GenerationcreateGeneration ops storeDir profile path = do  generations <- ExceptT (listGenerations profile)  target <- liftIO (OP.encodeFS (storePathToFilePath storeDir path))  newest <- traverse withTarget (listToMaybe (reverse generations))  case nextGeneration newest target of    ReuseGeneration generation -> pure generation    NewGeneration number -> do      let link = generationName profile number      linkText <- liftIO (OP.decodeFS link)      rooted <- liftIO (soAddOutLinkRoot ops linkText path)      either (throwError . StoreRefused) (const (pure (Generation number link))) rooted  where    withTarget :: Generation -> ExceptT ProfileFailure IO (Generation, OsPath)    withTarget generation = do      linked <- liftIO (tryIO (OsDir.getSymbolicLinkTarget (generationPath generation)))      case linked of        Left failure -> throwError (ProfileIOFailed ("reading symbolic link \"" <> hostPathText (generationPath generation) <> "\": " <> T.pack (show failure)))        Right target -> pure (generation, target)-- | Run an action holding a profile's lock, @\<profile\>.lock@-- (@PathLocks::lockPaths@ in unix\/pathlocks.cc), with upstream's line-- when another holds it (@lockProfile@ in profiles.cc).  A lock file that-- cannot be opened, as in a directory that is not there, is the failure.withProfileLock :: Logger -> OsPath -> IO (Either ProfileFailure a) -> IO (Either ProfileFailure a)withProfileLock logger profile action = do  lockPath <- OP.decodeFS (profile <> ascii lockFileSuffix)  bracket (tryIO (acquireLockFileWith logger LockExclusive waiting lockPath)) (traverse_ releasePathLock) (either (pure . Left . opening lockPath) (const action))  where    waiting = "waiting for lock on profile \"" <> hostPathText profile <> "\""    opening lockPath failure = ProfileIOFailed ("opening lock file \"" <> T.pack lockPath <> "\": " <> T.pack (show failure))-- ----------------------------------------------------------------------------- When generations were made-- ----------------------------------------------------------------------------- | A moment, in whole seconds since the epoch.newtype EpochSeconds = EpochSeconds Int64  deriving (Eq, Ord, Show)-- | A generation and when it was made: its link's own modification time.data DatedGeneration = DatedGeneration  { datedGeneration :: !Generation,    datedTime :: !EpochSeconds  }  deriving (Eq, Show)-- | The day a moment falls on in UTC, as @YYYY-MM-DD@, which a profile's-- history shows for each generation.generationDate :: EpochSeconds -> TextgenerationDate (EpochSeconds seconds) = T.pack (formatTime defaultTimeLocale "%Y-%m-%d" (posixSecondsToUTCTime (fromIntegral seconds)))-- | Now, rounded down to its second.currentEpochSeconds :: IO EpochSecondscurrentEpochSeconds = EpochSeconds . floor <$> getPOSIXTime-- | A profile's generations in order of number, each with its link's own-- modification time, and its current generation, as upstream finds them:-- the directory is listed first, each generation's link read without-- following it, and then the profile's link.findGenerations :: OsPath -> IO (Either ProfileFailure ([DatedGeneration], Maybe GenerationNumber))findGenerations profile = runExceptT $ do  generations <- ExceptT (listGenerations profile)  dated <- traverse dating generations  current <- currentGeneration profile <$> ExceptT (profileToken profile)  pure (dated, current)  where    dating :: Generation -> ExceptT ProfileFailure IO DatedGeneration    dating generation = do      let path = generationPath generation      time <- liftIO (tryIO (OP.decodeFS path >>= nodeModificationTime))      case time of        Left failure -> throwError (ProfileIOFailed ("getting status of \"" <> hostPathText path <> "\": " <> T.pack (show failure)))        Right seconds -> pure (DatedGeneration generation (EpochSeconds seconds))-- ----------------------------------------------------------------------------- Rolling back and wiping history-- ----------------------------------------------------------------------------- | Whether a command changes the profile, or with @--dry-run@ only says-- what it would change.data Changes = MakeChanges | DryRun  deriving (Eq, Show)-- | The generation a rollback switches to.data RollbackTarget  = -- | The newest below the current one.    PreviousGeneration  | -- | The one of this number, which @--to@ gives.    GenerationAt !GenerationNumber  deriving (Eq, Show)-- | The generation a rollback switches to among a profile's generations-- in order of number, given its current one: the last listed that the-- target names, as upstream picks it.  A profile with no current-- generation has none below it.rollbackPlan :: RollbackTarget -> Maybe GenerationNumber -> [Generation] -> Either ProfileFailure GenerationrollbackPlan target current generations = case reverse (filter (named target . generationNumber) generations) of  chosen : _ -> Right chosen  [] -> Left (refusal target)  where    named PreviousGeneration number = maybe False (number <) current    named (GenerationAt wanted) number = number == wanted    refusal PreviousGeneration = NoOlderGeneration current    refusal (GenerationAt wanted) = NoSuchGeneration wanted-- | A @--to@ value, as upstream reads one: an unsigned number of 64 bits,-- whose last character, when it is a letter, is a binary unit, @K@, @M@,-- @G@ or @T@ in either case, the number before it multiplied by 2^10,-- 2^20, 2^30 or 2^40 and wrapping past 64 bits as upstream's unsigned-- product does.  Any other letter, or a number that does not read, is-- refused in upstream's words, the number named without its unit.readGenerationNumber :: String -> Either Text GenerationNumberreadGenerationNumber given = case unsnoc given of  Just (number, unit)    | isAsciiUpper unit || isAsciiLower unit -> do        let spelled = toUpper unit        multiplier <- maybe (Left ("invalid unit specifier '" <> T.singleton spelled <> "'")) Right (lookup spelled unitMultipliers)        GenerationNumber . (* multiplier) <$> unsigned number  _ -> GenerationNumber <$> unsigned given  where    unsigned number = maybe (Left ("'" <> T.pack number <> "' is not an integer")) Right (unsignedDecimal number)-- | The binary units a number upstream reads may end in, each with what-- it multiplies by.unitMultipliers :: [(Char, Word64)]unitMultipliers = [('K', 2 ^ (10 :: Int)), ('M', 2 ^ (20 :: Int)), ('G', 2 ^ (30 :: Int)), ('T', 2 ^ (40 :: Int))]-- | A number of days, as @--older-than@ gives one.newtype Days = Days Int32  deriving (Eq, Show)-- | An @--older-than@ value, as upstream reads one: a number of days,-- an int of at least 1, followed by @d@, refused in upstream's two-- messages otherwise.parseOlderThan :: String -> Either Text DaysparseOlderThan spec = case unsnoc spec of  Just (count, 'd') -> maybe (Left ("invalid number of days specifier '" <> T.pack spec <> "'")) (Right . Days) (signedDecimal count >>= atLeastOne)  _ -> Left ("invalid number of days specifier '" <> T.pack spec <> "', expected something like '14d'")  where    atLeastOne days      | days >= 1 = Just days      | otherwise = Nothing-- | The moment a number of days before another.  The product is taken in-- 64 bits, where upstream takes it in an int, which more than 24855 days-- overflow.cutoffBefore :: EpochSeconds -> Days -> EpochSecondscutoffBefore (EpochSeconds now) (Days days) = EpochSeconds (now - fromIntegral days * secondsPerDay)  where    secondsPerDay = 24 * 60 * 60-- | Which generations wiping a profile's history deletes.data WipeScope  = -- | Every one but the current one.    WipeEveryOld  | -- | Those made before this moment but the newest of them, and never    -- the current one.    WipeOlderThan !EpochSeconds  deriving (Eq, Show)-- | One step of wiping a profile's history.data WipeStep  = -- | Delete this generation.    RemoveGeneration !GenerationNumber  | -- | Keep this generation, made after the cutoff though a later one    -- was made before it, with upstream's warning.    KeepNewerGeneration !GenerationNumber  deriving (Eq, Show)-- | The steps of wiping a profile's history, given its generations in-- order of number with when each was made, and its current one, as-- upstream takes them.  Every generation but the current one goes, in-- order of number, or under a cutoff the generations are taken newest-- first: those down to the newest made before the cutoff stay, that one-- too, since the profile held it at the cutoff and can be rolled back to-- it, and of those after it each made before the cutoff goes, unless it-- is the current one, and each made after it stays with a warning, as a-- clock that was wrong or a copy that dropped the times leaves one.  A-- profile with no current generation keeps none for being current.wipePlan :: WipeScope -> Maybe GenerationNumber -> [DatedGeneration] -> [WipeStep]wipePlan scope current dated = case scope of  WipeEveryOld -> [RemoveGeneration number | number <- map numberOf dated, notCurrent number]  WipeOlderThan cutoff ->    let older entry = datedTime entry < cutoff        pastNewestOlder = drop 1 (dropWhile (not . older) (reverse dated))     in mapMaybe (olderStep older) pastNewestOlder  where    numberOf = generationNumber . datedGeneration    notCurrent number = Just number /= current    olderStep older entry      | not (older entry) = Just (KeepNewerGeneration (numberOf entry))      | notCurrent (numberOf entry) = Just (RemoveGeneration (numberOf entry))      | otherwise = Nothing-- | Switch a profile to the generation a rollback names, holding its lock,-- with upstream's line naming the two generations, the current one 0 when-- there is none; with 'DryRun' only the line.  The line and a wait on the-- lock go to the logger.switchGeneration :: Logger -> OsPath -> RollbackTarget -> Changes -> IO (Either ProfileFailure ())switchGeneration logger profile target changes = withProfileLock logger profile . runExceptT $ do  (dated, current) <- ExceptT (findGenerations profile)  destination <- ExceptT (pure (rollbackPlan target current (map datedGeneration dated)))  liftIO (logMessage logger ("switching profile from version " <> numberText (fromMaybe (GenerationNumber 0) current) <> " to " <> numberText (generationNumber destination)))  case changes of    DryRun -> pure ()    MakeChanges -> ExceptT (first ProfileIOFailed <$> replaceLink profile (OP.takeFileName (generationPath destination)))-- | Wipe a profile's history as 'wipePlan' plans it, holding its lock,-- with upstream's line for each generation deleted and its warning for-- each kept; with 'DryRun' the line says the generation would be deleted,-- and none is.  A generation is deleted by its name for its number, as-- upstream deletes one.  The lines, the warnings and a wait on the lock go-- to the logger.wipeHistory :: Logger -> OsPath -> WipeScope -> Changes -> IO (Either ProfileFailure ())wipeHistory logger profile scope changes = withProfileLock logger profile . runExceptT $ do  (dated, current) <- ExceptT (findGenerations profile)  traverse_ apply (wipePlan scope current dated)  where    apply step = case (step, changes) of      (KeepNewerGeneration number, _) ->        liftIO (logWarning logger ("not removing profile version " <> numberText number <> " because it is newer than the cutoff, even though a later version is older"))      (RemoveGeneration number, DryRun) -> liftIO (logMessage logger ("would remove profile version " <> numberText number))      (RemoveGeneration number, MakeChanges) -> do        liftIO (logMessage logger ("removing profile version " <> numberText number))        ExceptT (removeGenerationLink (generationName profile number))-- | A generation's number, as a message shows it.numberText :: GenerationNumber -> TextnumberText (GenerationNumber n) = T.pack (show n)-- | Unlink what is at a generation's name, as upstream does: a link-- itself and never what it leads to, or a file, and nothing when nothing-- is there.  No call made here removes a directory's contents, so one-- that stands there, even put there while this runs, is a failure, as-- unlinking it is.  On Windows a directory link goes by RemoveDirectory,-- and anything else there by DeleteFile, which a directory refuses.removeGenerationLink :: OsPath -> IO (Either ProfileFailure ())removeGenerationLink path = do  removed <-    try $      if onWindows        then OsDir.removeDirectoryLink path `catch` \(failure :: IOException) -> unless (isDoesNotExistError failure) (OsDir.removeFile path)        else OsDir.removeFile path  pure $ case removed of    Right () -> Right ()    Left (failure :: IOException)      | isDoesNotExistError failure -> Right ()      | otherwise -> Left (ProfileIOFailed ("removing \"" <> hostPathText path <> "\": " <> T.pack (show failure)))-- ----------------------------------------------------------------------------- Links-- ----------------------------------------------------------------------------- | Whether nothing is at a path, by @lstat@: a link that leads nowhere is-- there.linkAbsent :: OsPath -> IO BoollinkAbsent path = do  probed <- try (OsDir.pathIsSymbolicLink path)  case probed of    Right _ -> pure False    Left (failure :: IOException)      | isDoesNotExistError failure -> pure True      | otherwise -> ioError failure-- | Point a link at a target, replacing what is there.  Every link here-- leads to a directory, so on Windows each is a directory link whether-- or not its target exists yet.  On Unix the link is made under a-- temporary name beside it and renamed over the path, upstream's-- @replaceSymlink@ in file-system.cc, which, as @rename@ does,-- replaces a link or a file there and fails on a directory.  On Windows a-- rename cannot replace a directory link, so a link there is removed and-- the new one made, as an out-link is replaced ("Nix.Store.GC"), and-- anything else there is refused.  The two steps run with asynchronous-- exceptions masked, and a link that cannot be made puts the old one-- back, so a profile is absent only while the switch runs.  The callers-- replace only a link or nothing: the default profile's link is made-- only where nothing is, and a profile's link is switched only after its-- target was read ('profileToken'), which fails on anything but a link.replaceLink :: OsPath -> OsPath -> IO (Either Text ())replaceLink link target  | onWindows = do      absent <- linkAbsent link      isLink <- if absent then pure False else OsDir.pathIsSymbolicLink link      if not absent && not isLink        then pure (Left ("cannot replace \"" <> hostPathText link <> "\", which is not a symbolic link"))        else mask_ $ do          previous <- if isLink then Just <$> OsDir.getSymbolicLinkTarget link else pure Nothing          when isLink (OsDir.removePathForcibly link)          made <- tryIO (OsDir.createDirectoryLink target link)          case made of            Right () -> pure (Right ())            Left failure -> do              traverse_ (\old -> tryIO (OsDir.createDirectoryLink old link)) previous              pure (Left (creatingLink link failure))  | otherwise = viaRename (0 :: Int)  where    viaRename n = do      let staging = OP.takeDirectory link </> (ascii ("." <> show n <> "_") <> OP.takeFileName link)      made <- try (OsDir.createDirectoryLink target staging)      case made of        Left failure          | isAlreadyExistsError failure -> viaRename (n + 1)          | otherwise -> pure (Left (creatingLink staging failure))        Right () -> do          renamed <- try (OsDir.renamePath staging link `onException` OsDir.removeFile staging)          pure (first (\failure -> "renaming \"" <> hostPathText staging <> "\" to \"" <> hostPathText link <> "\": " <> T.pack (show (failure :: IOException))) renamed)    creatingLink path failure = "creating symlink \"" <> hostPathText path <> "\" -> \"" <> hostPathText target <> "\": " <> T.pack (show (failure :: IOException)) <> windowsHint    windowsHint      | onWindows = " (on Windows this needs Developer Mode or elevation)"      | otherwise = ""-- | Whether this is Windows, where a link's flavour and its replacement-- differ.  A plain comparison rather than CPP, so both branches are-- checked on every host.onWindows :: BoolonWindows = System.Info.os == "mingw32"-- | 'try' for the one exception file system calls throw.tryIO :: IO a -> IO (Either IOException a)tryIO = try-- | An 'OsPath' spelled from ASCII, which 'OP.unsafeFromChar' narrows to-- one path unit per character without loss.ascii :: String -> OsPathascii = OP.pack . map OP.unsafeFromChar