-
Notifications
You must be signed in to change notification settings - Fork 849
Expand file tree
/
Copy pathUser.hs
More file actions
442 lines (408 loc) · 15.4 KB
/
Copy pathUser.hs
File metadata and controls
442 lines (408 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -Wno-unused-top-binds -Wno-identities #-}
{-|
Module : Stack.Storage.User
Description : Work with SQLite DB for caches across a user account.
License : BSD-3-Clause
Work with SQLite database used for caches across an entire user account.
-}
module Stack.Storage.User
( initUserStorage
, PrecompiledCacheKey
, PrecompiledCacheParent (..)
, precompiledCacheKey
, loadPrecompiledCache
, savePrecompiledCache
, loadDockerImageExeCache
, saveDockerImageExeCache
, loadCompilerPaths
, saveCompilerPaths
, upgradeChecksSince
, logUpgradeCheck
) where
import qualified Data.Set as Set
import qualified Data.Text as T
import Data.Time.Clock ( UTCTime )
import Database.Persist.Sqlite
( Entity (..), SqlBackend, Unique, (=.), (==.), (>=.), count
, deleteBy, getBy, insert, insert_, selectList, update
, upsert
)
import Database.Persist.TH
( mkMigrate, mkPersist, persistLowerCase, share
, sqlSettings
)
import Distribution.Text ( simpleParse, display )
import Foreign.C.Types ( CTime (..) )
import Pantry.SQLite ( initStorage, withStorage_ )
import Path ( (</>), mkRelFile, parseRelFile )
import Path.IO ( resolveFile', resolveDir' )
import qualified RIO.FilePath as FP
import Stack.Prelude
import Stack.Storage.Util
( handleMigrationException, setUpdateDiff, updateCollection )
import Stack.Types.Cache
( Action (..), GhcSemaphoreProtocolVersion (..)
, PrecompiledCache (..)
)
import Stack.Types.Compiler ( ActualCompiler, compilerVersionText )
import Stack.Types.CompilerBuild ( CompilerBuild )
import Stack.Types.CompilerPaths
( CompilerPaths (..), GhcPkgExe (..) )
import Stack.Types.Config ( Config (..), HasConfig (..) )
import Stack.Types.Storage ( UserStorage (..) )
import System.Posix.Types ( COff (..) )
import System.PosixCompat.Files
( fileSize, getFileStatus, modificationTime )
-- | Type representing exceptions thrown by functions exported by the
-- "Stack.Storage.User" module.
data StorageUserException
= CompilerFileMetadataMismatch
| GlobalPackageCacheFileMetadataMismatch
| GlobalDumpParseFailure
| CompilerCacheArchitectureInvalid Text
| GhcSemaphoreProtocolVersionUnknown
deriving Show
instance Exception StorageUserException where
displayException CompilerFileMetadataMismatch =
"Error: [S-8196]\n"
++ "Compiler file metadata mismatch, ignoring cache."
displayException GlobalPackageCacheFileMetadataMismatch =
"Error: [S-5378]\n"
++ "Global package cache file metadata mismatch, ignoring cache."
displayException GlobalDumpParseFailure =
"Error: [S-2673]\n"
++ "Global dump did not parse correctly."
displayException
(CompilerCacheArchitectureInvalid compilerCacheArch) = concat
[ "Error: [S-8441]\n"
, "Invalid arch: "
, show compilerCacheArch
]
displayException GhcSemaphoreProtocolVersionUnknown =
"Error: [S-9841]\n"
++ "GHC semaphore protocol version unknown, ignoring cache."
share [ mkPersist sqlSettings
, mkMigrate "migrateAll"
]
[persistLowerCase|
PrecompiledCacheParent sql="precompiled_cache"
platformGhcDir FilePath default="(hex(randomblob(16)))"
compiler Text
cabalVersion Text
packageKey Text
optionsHash ByteString
haddock Bool default=0
library FilePath Maybe
UniquePrecompiledCacheParent platformGhcDir compiler cabalVersion packageKey optionsHash haddock sql="unique_precompiled_cache"
deriving Show
PrecompiledCacheSubLib
parent PrecompiledCacheParentId sql="precompiled_cache_id" OnDeleteCascade
value FilePath sql="sub_lib"
UniquePrecompiledCacheSubLib parent value
deriving Show
PrecompiledCacheExe
parent PrecompiledCacheParentId sql="precompiled_cache_id" OnDeleteCaseCascade
value FilePath sql="exe"
UniquePrecompiledCacheExe parent value
deriving Show
DockerImageExeCache
imageHash Text
exePath FilePath
exeTimestamp UTCTime
compatible Bool
DockerImageExeCacheUnique imageHash exePath exeTimestamp
deriving Show
CompilerCache
actualVersion ActualCompiler
arch Text
-- Include ghc executable size and modified time for sanity checking entries
ghcPath FilePath
ghcSize Int64
ghcModified Int64
ghcPkgPath FilePath
runghcPath FilePath
haddockPath FilePath
cabalVersion Text
globalDb FilePath
globalDbCacheSize Int64
globalDbCacheModified Int64
semaphoreVersion GhcSemaphoreProtocolVersion Maybe
info ByteString
-- This is the ugliest part of this table, simply storing a Show/Read version of the
-- data. We could do a better job with normalized data and proper table structure.
-- However, recomputing this value in the future if the data representation changes
-- is very cheap, so we'll take the easy way out for now.
globalDump Text
UniqueCompilerInfo ghcPath
-- Last time certain actions were performed
LastPerformed
action Action
timestamp UTCTime
UniqueAction action
|]
-- | Initialize the database.
initUserStorage ::
HasLogFunc env
=> Path Abs File -- ^ storage file
-> (UserStorage -> RIO env a)
-> RIO env a
initUserStorage fp f = handleMigrationException $
initStorage "Stack" migrateAll fp $ f . UserStorage
-- | Run an action in a database transaction
withUserStorage ::
(HasConfig env, HasLogFunc env)
=> ReaderT SqlBackend (RIO env) a
-> RIO env a
withUserStorage inner = do
storage <- view (configL . to (.userStorage.userStorage))
withStorage_ storage inner
-- | Key used to retrieve the precompiled cache
type PrecompiledCacheKey = Unique PrecompiledCacheParent
-- | Build key used to retrieve the precompiled cache
precompiledCacheKey ::
Path Rel Dir
-> ActualCompiler
-> Version
-> Text
-> ByteString
-> Bool
-> PrecompiledCacheKey
precompiledCacheKey platformGhcDir compiler cabalVersion =
UniquePrecompiledCacheParent
(toFilePath platformGhcDir)
(compilerVersionText compiler)
(T.pack $ versionString cabalVersion)
-- | Internal helper to read the t'PrecompiledCache' from the database
readPrecompiledCache ::
(HasConfig env, HasLogFunc env)
=> PrecompiledCacheKey
-> ReaderT SqlBackend (RIO env) (Maybe ( PrecompiledCacheParentId
, PrecompiledCache Rel))
readPrecompiledCache key = do
mparent <- getBy key
forM mparent $ \(Entity parentId precompiledCacheParent) -> do
library <-
mapM parseRelFile precompiledCacheParent.precompiledCacheParentLibrary
subLibs <-
mapM (parseRelFile . (.precompiledCacheSubLibValue) . entityVal) =<<
selectList [PrecompiledCacheSubLibParent ==. parentId] []
exes <-
mapM (parseRelFile . (.precompiledCacheExeValue) . entityVal) =<<
selectList [PrecompiledCacheExeParent ==. parentId] []
pure
( parentId
, PrecompiledCache
{ library
, subLibs
, exes
}
)
-- | Load t'PrecompiledCache' from the database.
loadPrecompiledCache ::
(HasConfig env, HasLogFunc env)
=> PrecompiledCacheKey
-> RIO env (Maybe (PrecompiledCache Rel))
loadPrecompiledCache key =
withUserStorage $ fmap snd <$> readPrecompiledCache key
-- | Insert or update t'PrecompiledCache' to the database.
savePrecompiledCache ::
(HasConfig env, HasLogFunc env)
=> PrecompiledCacheKey
-> PrecompiledCache Rel
-> RIO env ()
savePrecompiledCache
key@( UniquePrecompiledCacheParent
precompiledCacheParentPlatformGhcDir
precompiledCacheParentCompiler
precompiledCacheParentCabalVersion
precompiledCacheParentPackageKey
precompiledCacheParentOptionsHash
precompiledCacheParentHaddock
)
new
= withUserStorage $ do
let precompiledCacheParentLibrary = fmap toFilePath new.library
(parentId, mold) <- readPrecompiledCache key >>= \case
Nothing -> (, Nothing) <$> insert PrecompiledCacheParent
{ precompiledCacheParentPlatformGhcDir
, precompiledCacheParentCompiler
, precompiledCacheParentCabalVersion
, precompiledCacheParentPackageKey
, precompiledCacheParentOptionsHash
, precompiledCacheParentHaddock
, precompiledCacheParentLibrary
}
Just (parentId, old) -> do
update
parentId
[ PrecompiledCacheParentLibrary =.
precompiledCacheParentLibrary
]
pure (parentId, Just old)
updateCollection
(setUpdateDiff PrecompiledCacheSubLibValue)
(PrecompiledCacheSubLib parentId)
[PrecompiledCacheSubLibParent ==. parentId]
(maybe Set.empty (toFilePathSet . (.subLibs)) mold)
(toFilePathSet new.subLibs)
updateCollection
(setUpdateDiff PrecompiledCacheExeValue)
(PrecompiledCacheExe parentId)
[PrecompiledCacheExeParent ==. parentId]
(maybe Set.empty (toFilePathSet . (.exes)) mold)
(toFilePathSet new.exes)
where
toFilePathSet = Set.fromList . map toFilePath
-- | Get the record of whether an executable is compatible with a Docker image
loadDockerImageExeCache ::
(HasConfig env, HasLogFunc env)
=> Text
-> Path Abs File
-> UTCTime
-> RIO env (Maybe Bool)
loadDockerImageExeCache imageId exePath exeTimestamp = withUserStorage $
fmap ((.dockerImageExeCacheCompatible) . entityVal) <$>
getBy (DockerImageExeCacheUnique imageId (toFilePath exePath) exeTimestamp)
-- | Sets the record of whether an executable is compatible with a Docker image
saveDockerImageExeCache ::
(HasConfig env, HasLogFunc env)
=> Text
-> Path Abs File
-> UTCTime
-> Bool
-> RIO env ()
saveDockerImageExeCache imageId exePath exeTimestamp compatible = void $
withUserStorage $
upsert
( DockerImageExeCache
imageId
(toFilePath exePath)
exeTimestamp
compatible
)
[]
-- | Type-restricted version of 'fromIntegral' to ensure we're making the value
-- bigger, not smaller.
sizeToInt64 :: COff -> Int64
sizeToInt64 (COff i) = fromIntegral i -- fromIntegral added for 32-bit systems
-- | Type-restricted version of 'fromIntegral' to ensure we're making the value
-- bigger, not smaller.
timeToInt64 :: CTime -> Int64
timeToInt64 (CTime i) = fromIntegral i -- fromIntegral added for 32-bit systems
-- | Load compiler information, if available, and confirm that the referenced
-- files are unchanged. May throw exceptions!
loadCompilerPaths ::
HasConfig env
=> Path Abs File -- ^ compiler executable
-> CompilerBuild
-> Bool -- ^ sandboxed?
-> RIO env (Maybe CompilerPaths)
loadCompilerPaths compiler build sandboxed = do
mres <- withUserStorage $ getBy $ UniqueCompilerInfo $ toFilePath compiler
for mres $ \(Entity _ compilerCache) -> do
compilerStatus <- liftIO $ getFileStatus $ toFilePath compiler
when
( compilerCache.compilerCacheGhcSize /=
sizeToInt64 (fileSize compilerStatus)
|| compilerCache.compilerCacheGhcModified /=
timeToInt64 (modificationTime compilerStatus)
)
(throwIO CompilerFileMetadataMismatch)
globalDbStatus <- liftIO $
getFileStatus $ compilerCache.compilerCacheGlobalDb FP.</> "package.cache"
when
( compilerCache.compilerCacheGlobalDbCacheSize /=
sizeToInt64 (fileSize globalDbStatus)
|| compilerCache.compilerCacheGlobalDbCacheModified /=
timeToInt64 (modificationTime globalDbStatus)
)
(throwIO GlobalPackageCacheFileMetadataMismatch)
-- We could use parseAbsFile instead of resolveFile' below to bypass some
-- system calls, at the cost of some really wonky error messages in case
-- someone screws up their GHC installation
pkg <- GhcPkgExe <$> resolveFile' compilerCache.compilerCacheGhcPkgPath
interpreter <- resolveFile' compilerCache.compilerCacheRunghcPath
haddock <- resolveFile' compilerCache.compilerCacheHaddockPath
globalDB <- resolveDir' compilerCache.compilerCacheGlobalDb
cabalVersion <- parseVersionThrowing $
T.unpack compilerCache.compilerCacheCabalVersion
globalDump <-
case readMaybe $ T.unpack compilerCache.compilerCacheGlobalDump of
Nothing -> throwIO GlobalDumpParseFailure
Just globalDump -> pure globalDump
arch <-
case simpleParse $ T.unpack compilerCache.compilerCacheArch of
Nothing -> throwIO $
CompilerCacheArchitectureInvalid compilerCache.compilerCacheArch
Just arch -> pure arch
semaphoreVersion <- maybe
(throwIO GhcSemaphoreProtocolVersionUnknown)
( \case
Unsupported -> pure Nothing
Supported spv -> pure $ Just spv
)
compilerCache.compilerCacheSemaphoreVersion
pure CompilerPaths
{ compiler
, compilerVersion = compilerCache.compilerCacheActualVersion
, arch
, build
, pkg
, interpreter
, haddock
, sandboxed
, cabalVersion
, globalDB
, ghcInfo = compilerCache.compilerCacheInfo
, semaphoreVersion
, globalDump
}
-- | Save compiler information. May throw exceptions!
saveCompilerPaths ::
HasConfig env
=> CompilerPaths
-> RIO env ()
saveCompilerPaths cp = withUserStorage $ do
deleteBy $ UniqueCompilerInfo $ toFilePath cp.compiler
compilerStatus <- liftIO $ getFileStatus $ toFilePath cp.compiler
globalDbStatus <- liftIO $
getFileStatus $ toFilePath $ cp.globalDB </> $(mkRelFile "package.cache")
let GhcPkgExe pkgexe = cp.pkg
insert_ CompilerCache
{ compilerCacheActualVersion = cp.compilerVersion
, compilerCacheGhcPath = toFilePath cp.compiler
, compilerCacheGhcSize = sizeToInt64 $ fileSize compilerStatus
, compilerCacheGhcModified = timeToInt64 $ modificationTime compilerStatus
, compilerCacheGhcPkgPath = toFilePath pkgexe
, compilerCacheRunghcPath = toFilePath cp.interpreter
, compilerCacheHaddockPath = toFilePath cp.haddock
, compilerCacheCabalVersion = T.pack $ versionString cp.cabalVersion
, compilerCacheGlobalDb = toFilePath cp.globalDB
, compilerCacheGlobalDbCacheSize = sizeToInt64 $ fileSize globalDbStatus
, compilerCacheGlobalDbCacheModified =
timeToInt64 $ modificationTime globalDbStatus
, compilerCacheSemaphoreVersion = Just $
maybe Unsupported Supported cp.semaphoreVersion
, compilerCacheInfo = cp.ghcInfo
, compilerCacheGlobalDump = tshow cp.globalDump
, compilerCacheArch = T.pack $ Distribution.Text.display cp.arch
}
-- | How many upgrade checks have occurred since the given timestamp?
upgradeChecksSince :: HasConfig env => UTCTime -> RIO env Int
upgradeChecksSince since = withUserStorage $ count
[ LastPerformedAction ==. UpgradeCheck
, LastPerformedTimestamp >=. since
]
-- | Log in the database that an upgrade check occurred at the given time.
logUpgradeCheck :: HasConfig env => UTCTime -> RIO env ()
logUpgradeCheck time = withUserStorage $ void $ upsert
(LastPerformed UpgradeCheck time)
[LastPerformedTimestamp =. time]