git-annex/Remote/Glacier.hs

358 lines
11 KiB
Haskell
Raw Normal View History

{- Amazon Glacier remotes.
-
- Copyright 2012-2020 Joey Hess <id@joeyh.name>
-
- Licensed under the GNU AGPL version 3 or higher.
-}
module Remote.Glacier (remote, jobList, checkSaneGlacierCommand) where
import qualified Data.Map as M
import qualified Data.Text as T
import qualified Data.ByteString.Lazy as L
import Annex.Common
import Types.Remote
import qualified Git
import Config
import Config.Cost
import Annex.SpecialRemote.Config
import Remote.Helper.Special
2015-08-17 14:42:14 +00:00
import Remote.Helper.Messages
2019-02-20 19:55:01 +00:00
import Remote.Helper.ExportImport
import qualified Remote.Helper.AWS as AWS
import Creds
import Utility.Metered
import qualified Annex
import Annex.UUID
import Utility.Env
import Types.ProposedAccepted
type Vault = String
type Archive = FilePath
remote :: RemoteType
remote = specialRemoteType $ RemoteType
{ typename = "glacier"
, enumerate = const (findSpecialRemotes "glacier")
, generate = gen
, configParser = mkRemoteConfigParser
[ optionalStringParser datacenterField
(FieldDesc "S3 datacenter to use")
, optionalStringParser vaultField
(FieldDesc "name to use for vault")
, optionalStringParser fileprefixField
(FieldDesc "prefix to add to filenames in the vault")
, optionalStringParser AWS.s3credsField HiddenField
]
, setup = glacierSetup
, exportSupported = exportUnsupported
2019-02-20 19:55:01 +00:00
, importSupported = importUnsupported
}
datacenterField :: RemoteConfigField
datacenterField = Accepted "datacenter"
vaultField :: RemoteConfigField
vaultField = Accepted "vault"
fileprefixField :: RemoteConfigField
fileprefixField = Accepted "fileprefix"
gen :: Git.Repo -> UUID -> RemoteConfig -> RemoteGitConfig -> RemoteStateHandle -> Annex (Maybe Remote)
gen r u rc gc rs = new
<$> parsedRemoteConfig remote rc
<*> remoteCost gc veryExpensiveRemoteCost
2012-11-30 04:55:59 +00:00
where
new c cst = Just $ specialRemote' specialcfg c
(store this)
(retrieve this)
(remove this)
(checkKey this)
this
2012-11-30 04:55:59 +00:00
where
2014-12-16 19:26:13 +00:00
this = Remote
{ uuid = u
, cost = cst
, name = Git.repoDescribe r
, storeKey = storeKeyDummy
, retrieveKeyFile = retrieveKeyFileDummy
, retrieveKeyFileCheap = Nothing
-- glacier-cli does not follow redirects and does
-- not support file://, as far as we know, but
-- there's no guarantee that will continue to be
-- the case, so require verifiable keys.
, retrievalSecurityPolicy = mkRetrievalVerifiableKeysSecure gc
2014-12-16 19:26:13 +00:00
, removeKey = removeKeyDummy
, lockContent = Nothing
2014-12-16 19:26:13 +00:00
, checkPresent = checkPresentDummy
, checkPresentCheap = False
, exportActions = exportUnsupported
2019-02-20 19:55:01 +00:00
, importActions = importUnsupported
2014-12-16 19:26:13 +00:00
, whereisKey = Nothing
, remoteFsck = Nothing
, repairRepo = Nothing
, config = c
, getRepo = return r
2014-12-16 19:26:13 +00:00
, gitconfig = gc
, localpath = Nothing
, readonly = False
, appendonly = False
2014-12-16 19:26:13 +00:00
, availability = GloballyAvailable
, remotetype = remote
, mkUnavailable = return Nothing
, getInfo = includeCredsInfo c (AWS.creds u) $
[ ("glacier vault", getVault c) ]
, claimUrl = Nothing
, checkUrl = Nothing
, remoteStateHandle = rs
2014-12-16 19:26:13 +00:00
}
specialcfg = (specialRemoteCfg c)
-- Disabled until jobList gets support for chunks.
{ chunkConfig = NoChunks
}
glacierSetup :: SetupStage -> Maybe UUID -> Maybe CredPair -> RemoteConfig -> RemoteGitConfig -> Annex (RemoteConfig, UUID)
glacierSetup ss mu mcreds c gc = do
u <- maybe (liftIO genUUID) return mu
glacierSetup' ss u mcreds c gc
glacierSetup' :: SetupStage -> UUID -> Maybe CredPair -> RemoteConfig -> RemoteGitConfig -> Annex (RemoteConfig, UUID)
glacierSetup' ss u mcreds c gc = do
fix embedcreds=yes reversion Fix bug that made enableremote of S3 and webdav remotes, that have embedcreds=yes, fail to set up the embedded creds, so accessing the remotes failed. (Regression introduced in version 7.20200202.7 in when reworking all the remote configs to be parsed.) Root problem is that parseEncryptionConfig excludes all other config keys except encryption ones, so it is then unable to find the credPairRemoteField. And since that field is not required to be present, it proceeds as if it's not, rather than failing in any visible way. This causes it to not find any creds, and so it does not cache them. When when the S3 remote tries to make a S3 connection, it finds no creds, so assumes it's being used in no-creds mode, and tries to find a public url. With no public url available, it fails, but the failure doesn't say a lack of creds is the problem. Fix is to provide setRemoteCredPair with a ParsedRemoteConfig, so the full set of configs of the remote can be parsed. A bit annoying to need to parse the remote config before the full config (as returned by setRemoteCredPair) is available, but this avoids the problem. I assume webdav also had the problem by inspection, but didn't try to reproduce it with it. Also, getRemoteCredPair used getRemoteConfigValue to get a ProposedAccepted String, but that does not seem right. Now that it runs that code, it crashed saying it had just a String. Remotes that have already been enableremoted, and so lack the cached creds file will work after this fix, because getRemoteCredPair will extract the creds from the remote config, writing the missing file. This commit was sponsored by Ilya Shlyakhter on Patreon.
2020-05-21 18:34:29 +00:00
(c', encsetup) <- encryptionSetup (c `M.union` defaults) gc
pc <- either giveup return . parseRemoteConfig c'
=<< configParser remote c'
c'' <- setRemoteCredPair encsetup pc gc (AWS.creds u) mcreds
pc' <- either giveup return . parseRemoteConfig c''
=<< configParser remote c''
case ss of
fix embedcreds=yes reversion Fix bug that made enableremote of S3 and webdav remotes, that have embedcreds=yes, fail to set up the embedded creds, so accessing the remotes failed. (Regression introduced in version 7.20200202.7 in when reworking all the remote configs to be parsed.) Root problem is that parseEncryptionConfig excludes all other config keys except encryption ones, so it is then unable to find the credPairRemoteField. And since that field is not required to be present, it proceeds as if it's not, rather than failing in any visible way. This causes it to not find any creds, and so it does not cache them. When when the S3 remote tries to make a S3 connection, it finds no creds, so assumes it's being used in no-creds mode, and tries to find a public url. With no public url available, it fails, but the failure doesn't say a lack of creds is the problem. Fix is to provide setRemoteCredPair with a ParsedRemoteConfig, so the full set of configs of the remote can be parsed. A bit annoying to need to parse the remote config before the full config (as returned by setRemoteCredPair) is available, but this avoids the problem. I assume webdav also had the problem by inspection, but didn't try to reproduce it with it. Also, getRemoteCredPair used getRemoteConfigValue to get a ProposedAccepted String, but that does not seem right. Now that it runs that code, it crashed saying it had just a String. Remotes that have already been enableremoted, and so lack the cached creds file will work after this fix, because getRemoteCredPair will extract the creds from the remote config, writing the missing file. This commit was sponsored by Ilya Shlyakhter on Patreon.
2020-05-21 18:34:29 +00:00
Init -> genVault pc' gc u
_ -> return ()
fix embedcreds=yes reversion Fix bug that made enableremote of S3 and webdav remotes, that have embedcreds=yes, fail to set up the embedded creds, so accessing the remotes failed. (Regression introduced in version 7.20200202.7 in when reworking all the remote configs to be parsed.) Root problem is that parseEncryptionConfig excludes all other config keys except encryption ones, so it is then unable to find the credPairRemoteField. And since that field is not required to be present, it proceeds as if it's not, rather than failing in any visible way. This causes it to not find any creds, and so it does not cache them. When when the S3 remote tries to make a S3 connection, it finds no creds, so assumes it's being used in no-creds mode, and tries to find a public url. With no public url available, it fails, but the failure doesn't say a lack of creds is the problem. Fix is to provide setRemoteCredPair with a ParsedRemoteConfig, so the full set of configs of the remote can be parsed. A bit annoying to need to parse the remote config before the full config (as returned by setRemoteCredPair) is available, but this avoids the problem. I assume webdav also had the problem by inspection, but didn't try to reproduce it with it. Also, getRemoteCredPair used getRemoteConfigValue to get a ProposedAccepted String, but that does not seem right. Now that it runs that code, it crashed saying it had just a String. Remotes that have already been enableremoted, and so lack the cached creds file will work after this fix, because getRemoteCredPair will extract the creds from the remote config, writing the missing file. This commit was sponsored by Ilya Shlyakhter on Patreon.
2020-05-21 18:34:29 +00:00
gitConfigSpecialRemote u c'' [("glacier", "true")]
return (c'', u)
where
remotename = fromJust (lookupName c)
defvault = remotename ++ "-" ++ fromUUID u
defaults = M.fromList
[ (datacenterField, Proposed $ T.unpack $ AWS.defaultRegion AWS.Glacier)
, (vaultField, Proposed defvault)
]
store :: Remote -> Storer
store r k b p = do
checkNonEmpty k
byteStorer (store' r) k b p
checkNonEmpty :: Key -> Annex ()
checkNonEmpty k
| fromKey keySize k == Just 0 =
giveup "Cannot store empty files in Glacier."
| otherwise = return ()
2012-11-25 17:42:28 +00:00
store' :: Remote -> Key -> L.ByteString -> MeterUpdate -> Annex ()
store' r k b p = go =<< glacierEnv c gc u
2012-11-25 17:27:20 +00:00
where
2012-11-30 04:55:59 +00:00
c = config r
gc = gitconfig r
2012-11-25 17:27:20 +00:00
u = uuid r
params = glacierParams c
[ Param "archive"
, Param "upload"
, Param "--name", Param $ archive r k
2012-11-30 04:55:59 +00:00
, Param $ getVault $ config r
2012-11-25 17:27:20 +00:00
, Param "-"
]
go Nothing = giveup "Glacier not usable."
go (Just e) = liftIO $ do
let cmd = (proc "glacier" (toCommand params)) { env = Just e }
withHandle StdinHandle createProcessSuccess cmd $ \h ->
meteredWrite p h b
retrieve :: Remote -> Retriever
retrieve = byteRetriever . retrieve'
retrieve' :: Remote -> Key -> (L.ByteString -> Annex ()) -> Annex ()
retrieve' r k sink = go =<< glacierEnv c gc u
2012-11-25 17:42:28 +00:00
where
2012-11-30 04:55:59 +00:00
c = config r
gc = gitconfig r
2012-11-25 17:42:28 +00:00
u = uuid r
params = glacierParams c
[ Param "archive"
, Param "retrieve"
2012-11-25 17:42:28 +00:00
, Param "-o-"
2012-11-30 04:55:59 +00:00
, Param $ getVault $ config r
, Param $ archive r k
]
go Nothing = giveup "cannot retrieve from glacier"
go (Just environ) = do
let p = (proc "glacier" (toCommand params))
{ env = Just environ
, std_out = CreatePipe
}
bracketIO (createProcess p) cleanupProcess (go' p)
go' p (_, Just h, _, pid) = do
let cleanup = liftIO $ do
hClose h
forceSuccessProcess p pid
flip finally cleanup $ do
-- Glacier cannot store empty files, so if
-- the output is empty, the content is not
-- available yet.
whenM (liftIO $ hIsEOF h) $
giveup "Content is not available from glacier yet. Recommend you wait up to 4 hours, and then run this command again."
sink =<< liftIO (L.hGetContents h)
go' _ _ = error "internal"
remove :: Remote -> Remover
2020-05-14 18:08:09 +00:00
remove r k = unlessM go $
giveup "removal from glacier failed"
where
go = glacierAction r
[ Param "archive"
, Param "delete"
, Param $ getVault $ config r
, Param $ archive r k
]
checkKey :: Remote -> CheckPresent
checkKey r k = do
2015-08-17 14:42:14 +00:00
showChecking r
go =<< glacierEnv (config r) (gitconfig r) (uuid r)
where
go Nothing = giveup "cannot check glacier"
2012-11-25 17:27:20 +00:00
go (Just e) = do
{- glacier checkpresent outputs the archive name to stdout if
- it's present. -}
s <- liftIO $ readProcessEnv "glacier" (toCommand params) (Just e)
let probablypresent = serializeKey k `elem` lines s
if probablypresent
then ifM (Annex.getFlag "trustglacier")
( return True, giveup untrusted )
else return False
params = glacierParams (config r)
[ Param "archive"
, Param "checkpresent"
2012-11-30 04:55:59 +00:00
, Param $ getVault $ config r
2012-11-21 23:35:28 +00:00
, Param "--quiet"
, Param $ archive r k
]
untrusted = unlines
[ "Glacier's inventory says it has a copy."
, "However, the inventory could be out of date, if it was recently removed."
, "(Use --trust-glacier if you're sure it's still in Glacier.)"
, ""
]
glacierAction :: Remote -> [CommandParam] -> Annex Bool
glacierAction r = runGlacier (config r) (gitconfig r) (uuid r)
runGlacier :: ParsedRemoteConfig -> RemoteGitConfig -> UUID -> [CommandParam] -> Annex Bool
runGlacier c gc u params = go =<< glacierEnv c gc u
where
go Nothing = return False
2012-11-25 17:27:20 +00:00
go (Just e) = liftIO $
boolSystemEnv "glacier" (glacierParams c params) (Just e)
glacierParams :: ParsedRemoteConfig -> [CommandParam] -> [CommandParam]
2012-11-25 17:27:20 +00:00
glacierParams c params = datacenter:params
where
datacenter = Param $ "--region=" ++
fromMaybe (giveup "Missing datacenter configuration")
(getRemoteConfigValue datacenterField c)
glacierEnv :: ParsedRemoteConfig -> RemoteGitConfig -> UUID -> Annex (Maybe [(String, String)])
glacierEnv c gc u = do
liftIO checkSaneGlacierCommand
go =<< getRemoteCredPairFor "glacier" c gc creds
where
go Nothing = return Nothing
go (Just (user, pass)) = do
2012-11-25 17:27:20 +00:00
e <- liftIO getEnvironment
return $ Just $ addEntries [(uk, user), (pk, pass)] e
creds = AWS.creds u
(uk, pk) = credPairEnvironment creds
getVault :: ParsedRemoteConfig -> Vault
getVault = fromMaybe (giveup "Missing vault configuration")
. getRemoteConfigValue vaultField
archive :: Remote -> Key -> Archive
archive r k = fileprefix ++ serializeKey k
where
fileprefix = fromMaybe "" $
getRemoteConfigValue fileprefixField $ config r
genVault :: ParsedRemoteConfig -> RemoteGitConfig -> UUID -> Annex ()
genVault c gc u = unlessM (runGlacier c gc u params) $
giveup "Failed creating glacier vault."
where
params =
[ Param "vault"
, Param "create"
, Param $ getVault c
]
{- Partitions the input list of keys into ones which have
- glacier retieval jobs that have succeeded, or failed.
-
- A complication is that `glacier job list` will display the encrypted
- keys when the remote is encrypted.
-
- Dealing with encrypted chunked keys would be tricky. However, there
- seems to be no benefit to using chunking with glacier, so chunking is
- not supported.
-}
jobList :: Remote -> [Key] -> Annex ([Key], [Key])
jobList r keys = go =<< glacierEnv (config r) (gitconfig r) (uuid r)
where
params = [ Param "job", Param "list" ]
nada = ([], [])
2012-11-30 04:55:59 +00:00
myvault = getVault $ config r
go Nothing = return nada
go (Just e) = do
v <- liftIO $ catchMaybeIO $
readProcessEnv "glacier" (toCommand params) (Just e)
maybe (return nada) extract v
extract s = do
let result@(succeeded, failed) =
parse nada $ (map words . lines) s
if result == nada
then return nada
else do
enckeys <- forM keys $ \k ->
2014-07-27 00:21:36 +00:00
maybe k (\(_, enck) -> enck k)
<$> cipherKey (config r) (gitconfig r)
let keymap = M.fromList $ zip enckeys keys
2013-09-26 03:19:01 +00:00
let convert = mapMaybe (`M.lookup` keymap)
return (convert succeeded, convert failed)
parse c [] = c
parse c@(succeeded, failed) ((status:_date:vault:key:[]):rest)
| vault == myvault =
case deserializeKey key of
Nothing -> parse c rest
Just k
| "a/d" `isPrefixOf` status ->
parse (k:succeeded, failed) rest
| "a/e" `isPrefixOf` status ->
parse (succeeded, k:failed) rest
| otherwise ->
parse c rest
parse c (_:rest) = parse c rest
-- boto's version of glacier exits 0 when given a parameter it doesn't
-- understand. See https://github.com/boto/boto/issues/2942
checkSaneGlacierCommand :: IO ()
checkSaneGlacierCommand =
whenM ((Nothing /=) <$> catchMaybeIO shouldfail) $
giveup wrongcmd
where
test = proc "glacier" ["--compatibility-test-git-annex"]
shouldfail = withQuietOutput createProcessSuccess test
wrongcmd = "The glacier program in PATH seems to be from boto, not glacier-cli. Cannot use this program."