@@ -6,6 +6,8 @@ module GHC.RTS.Events.Sort
6
6
( GHC.RTS.Events.Sort. sortEvents
7
7
) where
8
8
9
+ import Control.Exception
10
+ import Data.IORef
9
11
import Data.Traversable
10
12
import Data.Coerce
11
13
import Data.Function (on )
@@ -46,6 +48,25 @@ instance Ord OnTime where
46
48
instance Eq OnTime where
47
49
(==) = coerce ((==) `on` evTime)
48
50
51
+ -- | C
52
+ cleanupFiles :: ((FilePath -> IO () ) -> IO a )
53
+ -- ^ a continuation accepting an action to register a file to
54
+ -- be cleaned up.
55
+ -> IO a
56
+ cleanupFiles cont =
57
+ bracket start finish (cont . register)
58
+ where
59
+ start :: IO (IORef [FilePath ])
60
+ start = newIORef []
61
+ finish :: IORef [FilePath ] -> IO ()
62
+ finish ref = do
63
+ files <- readIORef ref
64
+ mapM_ removeFile files
65
+ register :: IORef [FilePath ] -> FilePath -> IO ()
66
+ register ref path = do
67
+ atomicModifyIORef ref (\ paths -> (path : paths, () ))
68
+ return ()
69
+
49
70
-- | @sortEvents tmpDir outPath eventlog@ sorts @eventlog@ via on-disk merge
50
71
-- sort, using @tmpDir@ for intermediate data. The sorted eventlog is written
51
72
-- to @eventlog@.
@@ -54,10 +75,11 @@ sortEvents :: FilePath -- ^ temporary directory
54
75
-> EventLog -- ^ eventlog to sort
55
76
-> IO ()
56
77
sortEvents _tmpDir _outPath (EventLog _ (Data [] )) = fail " sortEvents: no events"
57
- sortEvents tmpDir outPath (EventLog hdr (Data events0)) = do
78
+ sortEvents tmpDir outPath (EventLog hdr (Data events0)) = cleanupFiles $ \ cleanupFile -> do
58
79
chunks <- toSortedChunks events0
80
+ mapM_ cleanupFile chunks
59
81
hdl <- openBinaryFile outPath WriteMode
60
- mergeChunks' hdl chunks
82
+ mergeChunks' cleanupFile hdl chunks
61
83
hClose hdl
62
84
return ()
63
85
where
@@ -67,8 +89,8 @@ sortEvents tmpDir outPath (EventLog hdr (Data events0)) = do
67
89
. mapM (writeTempChunk . sortEventsInMem)
68
90
. chunksOf cHUNK_SIZE
69
91
70
- mergeChunks' :: Handle -> S. Seq SortedChunk -> IO ()
71
- mergeChunks' destFile chunks
92
+ mergeChunks' :: ( FilePath -> IO () ) -> Handle -> S. Seq SortedChunk -> IO ()
93
+ mergeChunks' cleanupFile destFile chunks
72
94
| S. null chunks =
73
95
fail " sortEvents: this can't happen"
74
96
| S. length chunks <= fAN_IN = do
@@ -78,10 +100,11 @@ sortEvents tmpDir outPath (EventLog hdr (Data events0)) = do
78
100
| otherwise = do
79
101
chunksss <- flip mapM (nChunks fAN_IN chunks) $ \ fps -> do
80
102
(fp, hdl) <- createTempChunk
81
- mergeChunks' hdl fps
103
+ cleanupFile fp
104
+ mergeChunks' cleanupFile hdl fps
82
105
mapM_ removeFile fps
83
106
return fp
84
- mergeChunks' destFile (S. fromList chunksss)
107
+ mergeChunks' cleanupFile destFile (S. fromList chunksss)
85
108
86
109
readChunk :: SortedChunk -> IO [Event ]
87
110
readChunk fp = do
0 commit comments