Source

udon / src / Master.hs

  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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
{-# LANGUAGE GeneralizedNewtypeDeriving, CPP #-}
module Master where

import Control.Applicative ((<$>))
import Control.Concurrent (forkIO, ThreadId, killThread)
import Control.Concurrent.STM (STM, atomically, retry, catchSTM)
import Control.Concurrent.STM.TMVar (TMVar, newTMVarIO, readTMVar, takeTMVar, putTMVar)
import Control.Exception (SomeException(..), block)
import Control.Monad (forM, forM_, when)
import Control.Monad.State (StateT, evalStateT, get, put, gets, modify, liftIO, MonadIO, MonadState)
import Control.Monad.Reader (ReaderT, runReaderT, ask, asks, MonadReader)
import Data.List (isSuffixOf, sortBy)
import Data.Maybe (catMaybes)
import Data.Time (getCurrentTime, ZonedTime, getZonedTime, diffUTCTime)
import Network.Socket (socket, Family(AF_UNIX), SocketType(Stream), defaultProtocol, connect, SockAddr(SockAddrUnix), socketToHandle, Socket, bindSocket, listen, accept, fdSocket, mkSocket, SocketStatus(Listening))
import System.Directory (getDirectoryContents)
import System.Environment (getProgName, getEnvironment)
import System.Exit (exitSuccess, ExitCode(ExitSuccess, ExitFailure))
import System.FilePath (takeBaseName)
import System.IO (Handle, IOMode(AppendMode, ReadWriteMode), openFile, hSetBuffering, BufferMode(LineBuffering), hGetLine, hPutStrLn, hClose, openTempFile, hPrint, hSeek, SeekMode(AbsoluteSeek), stdin)
import System.FilePath ((</>))
import System.Posix.Directory (getWorkingDirectory)
import System.Posix.Files (fileExist, removeLink, rename)
import System.Posix.IO (stdOutput, stdError, closeFd, dupTo, openFd, OpenMode(WriteOnly, ReadOnly), OpenFileFlags(append), defaultFileFlags, createPipe, handleToFd, stdInput, fdToHandle)
import System.Posix.Process (executeFile, exitImmediately)
import System.Posix.Signals (Signal, sigTERM, sigINT, installHandler, Handler(Catch), blockSignals, addSignal, emptySignalSet, unblockSignals)
import System.Posix.Types (Fd)

import qualified System.Posix.Process as P

import Paths_udon (version)

import Common
import Process (runCommandWithFd, forkDaemon, waitChild, killProcess, ProcessStatus, systemWithInput)
import Utils (whenM, withFileLock, readMaybeIO, hPrintM, hGetLineM)

#ifdef DEBUG
import Debug.Trace (trace)
import System.IO (stderr)

p :: MonadIO m => String -> m ()
p = io . hPutStrLn stderr

pp :: Monad m => String -> m ()
pp cs = trace cs $ return ()
#else
p :: MonadIO m => String -> m ()
p = const (return ())
#endif

data DaemonLogger = DaemonLogger
    { dlDaemonManagerIds :: ThreadId
    , dlLoggerManagerIds :: ThreadId
    , dlDaemonState     :: TMVar DaemonState
    , dlLoggerState     :: TMVar LoggerState
    }

newtype Master a = Master { runMaster :: ReaderT Config (StateT [(String, DaemonLogger)] IO) a }
    deriving (Functor, Monad, MonadIO, MonadState [(String, DaemonLogger)], MonadReader Config)

data ResumeState = ResumeState
    { rsMasterSockFd :: Fd
    , rsClientSockFd :: Fd
    , rsDaemonState  :: [(String, (DaemonState, LoggerState))]
    } deriving (Show, Read)

data ManagerState = ManagerState
    { getConfig :: Config
    , getDaemonState :: TMVar DaemonState
    }

newtype DaemonManager a = DaemonManager (StateT Int (ReaderT ManagerState IO) a)
    deriving (Functor, Monad, MonadIO, MonadState Int, MonadReader ManagerState)

runManager :: DaemonManager a -> Config -> TMVar DaemonState -> IO a
runManager (DaemonManager m) cfg tds = runReaderT (evalStateT m 0) $ ManagerState cfg tds

forkMaster :: Config -> IO ()
forkMaster cfg = forkDaemon $ withFileLock (masterLock cfg) (startMaster' cfg (setOutputToLog >> master)) >> return ()

startMaster :: Config -> IO ()
startMaster cfg = withFileLock (masterLock cfg) (startMaster' cfg master) >> return ()

resumeMaster :: Config -> IO ()
resumeMaster cfg = startMaster' cfg (setOutputToLog >> resumeMaster')

startMaster' :: Config -> Master () -> IO ()
startMaster' cfg m = evalStateT (runReaderT (runMaster m) cfg) []

master :: Master ()
master = do
    p "[master] Starting Master ..."

    p "[master] Loading daemons ..."
    blkSigs
    mapM_ (uncurry startDaemonManager) =<< loadDaemons
    updateHandler
    unblkSigs
    p "[master] Done!"

    p "[master] Creating master socket ..."
    s <- mkMasterSock
    p "[master] Done!"

    p "[master] Starting mainLoop ..."
    mainLoop s

setOutputToLog :: Master ()
setOutputToLog = do
    p "[setOutputToLog] start"
    logf <- asks masterLog

    p $ "[setOutputToLog] log file: " ++ logf
    io $ do
        fd <- openFd logf WriteOnly (Just 0o0600) (defaultFileFlags { append = True })
        p "[setOutputToLog] open fd"
        p "[setOutputToLog] dup"
        -- TODO: createPipe して、 logReader/logWriter で記録する
        dupTo fd stdOutput
        dupTo fd stdError
        closeFd fd
    p "[setOutputToLog] done"
    return ()

loadDaemons :: Master [(Daemon, Logger)]
loadDaemons = do
    dd <-  asks daemonsDir
    ld <-  asks loggersDir
    files <- io $ getDirectoryContents dd
    mds <- forM files $ \f -> do
              if ".run" `isSuffixOf` f
                then do
                    md <- io $ readMaybeIO =<< readFile (dd </> f)
                    case md of
                        Nothing -> do
                            p $ "[loadDaemons] cannot readMaybeIO " ++ (dd </> f)
                            return Nothing
                        Just d -> do
                            let lf = ld </> takeBaseName f ++ "-log.run"
                            -- because udon-master < 0.2 has not save loggers
                            -- we should check whether file exists or not
                            fe <- io $ fileExist lf
                            ml <- if fe
                                    then io $ readMaybeIO =<< readFile lf
                                    else return Nothing
                            l <- maybe (mkDefaultLogger d) return ml
                            return $ Just (d, l)
                else return Nothing
    return $ catMaybes mds

saveDaemon :: Daemon -> Master ()
saveDaemon d = ask >>= saveDaemon' d

saveDaemon' :: MonadIO m => Daemon -> Config -> m ()
saveDaemon' d cfg = do
    let df = daemonsDir cfg </> (escapedDName d ++ ".run")
    io $ writeFile df (pprintDaemon d)

deleteDaemon :: Daemon -> Master ()
deleteDaemon d = do
    df <- (</> escapedDName d ++ ".run") <$> asks daemonsDir
    let df' = df ++ ".back"

    p $ "[deleteDaemon] rename: " ++ df ++ " to " ++ df'
    io $ rename df df'

mkDefaultLogger :: Daemon -> Master Logger
mkDefaultLogger Daemon { dName = dn } = do
    Config { loggerCmd = (lcmd, largs) } <- ask
    cwd <- io getWorkingDirectory
    env <- io getEnvironment
    logd <- asks logDir
    let logf = logd </> escapeFName (dn ++ ".log")
        largs' = largs ++ [logf]
        l = Daemon (dn ++ "-log") lcmd largs' cwd env True
    return l

saveLogger :: Logger -> Master ()
saveLogger l = do
    cfg <- ask
    saveDaemon' l cfg { daemonsDir = loggersDir cfg }

mkMasterSock :: Master Socket
mkMasterSock = do
    sp <- asks masterSock
    io $ do
        whenM (fileExist sp) $ removeLink sp
        s <- socket AF_UNIX Stream defaultProtocol
        bindSocket s (SockAddrUnix sp)
        listen s 1
        return s

mainLoop :: Socket -> Master ()
mainLoop s = do
    p "[mainLoop] start"

    p "[mainLoop] accepting ..."
    (c, a) <- io $ accept s

    p "[handleConnection] start"
    h <- io $ socketToHandle c ReadWriteMode
    io $ hSetBuffering h LineBuffering

    inp <- hGetLineM h
    p $ "[handleConnection] Input: " ++ show inp

    mr <- io $ readMaybeIO inp
    blkSigs
    case mr of
        Just (RestartMaster cmd args) -> restartMaster s h cmd args
        Just req -> handleRequest req h
        Nothing  -> hPrintM h $ NG "Unknown Request"
    updateHandler
    unblkSigs

    p "[handleConnection] Closing handle ..."
    io $ hClose h
    p "[handleConnection] Done"

    mainLoop s

handleRequest :: Request -> Handle -> Master ()
handleRequest Ping               h = hPrintM h Pong
handleRequest (RegisterDaemon d) h = do
    p "[handleRequest] RegisterDaemon"
    df <- (</> escapedDName d ++ ".run") <$> asks daemonsDir
    exist <- io $ fileExist df
    if not exist
      then do
        saveDaemon d
        l <- mkDefaultLogger d
        saveLogger l
        startDaemonManager d l
        hPrintM h OK
      else hPrintM h $ NG "Daemon Already Exists"

handleRequest (UnregisterDaemon dn) h = do
    p "[handleRequest] UnregisterDaemon"
    mdl <- gets $ lookup dn
    case mdl of
        Nothing  -> hPrintM h $ NG ("no such daemon: " ++ dn)
        Just (DaemonLogger _ _ tds tls) -> do
            ed <- io $ atomically $ errorToEither $ do
                       ds@(DaemonState d dst _ _) <- takeTMVar tds
                       case dst of
                           Running _ _  -> fail "daemon still running"
                           Initializing -> fail "daemon initializing"
                           Deleting     -> fail "daemon deleting"
                           _            -> do
                               putTMVar tds $ ds { dsStatus = Deleting }
                               return d
            case ed of
                Left e  -> hPrintM h $ NG e
                Right d -> do
                    p "[handleRequest] deleting daemon ..."
                    deleteDaemon d
                    p "[handleRequest] done"

                    p "[handleRequest] setting logger's auto start to \"False\" ..."
                    io $ atomically $ modifyDaemon' tls $ \d -> d { dAutoStart = False }
                    p "[handleRequest] done"

                    p "[handleRequest] close daemon pipes ..."
                    closeDaemonPipes $ dName d
                    p "[handleRequest] done"

                    p "[handleRequest] waiting logger ..."
                    waitDaemon True tls
                    p "[handleRequest] done"

                    p "[handleRequest] setting logger's state to Deleting ..."
                    io $ atomically $ do
                        ls <- takeTMVar tls
                        putTMVar tls $ ls { dsStatus = Deleting}
                    p "[handleRequest] done"

                    p "[handleRequest] modifying state ..."
                    modify $ \tdss -> filter ((/= dn) . fst) tdss
                    p "[handleRequest] done"

                    hPrintM h OK

handleRequest (UpdateDaemon dn d) h = do
    p "[handleRequest] UpdateDaemon"
    -- TODO: deal with the case of dn /= dName d
    mdl <- gets $ lookup dn
    case mdl of
        Nothing  -> hPrintM h $ NG ("no such daemon: " ++ dn)
        Just (DaemonLogger _ _ tds _) -> do
            ed <- io $ atomically $ errorToEither $ do
                       ds@(DaemonState d dst _ _) <- takeTMVar tds
                       case dst of
                           Running _ _  -> fail "daemon still running"
                           Initializing -> fail "daemon initializing"
                           Deleting     -> fail "daemon deleting"
                           _            -> do
                               putTMVar tds $ ds { dsStatus = Updating }
                               return d
            case ed of
                Left e  -> hPrintM h $ NG e
                Right old -> do
                    p "[handleRequest] updating daemon' run file ..."
                    deleteDaemon old
                    saveDaemon d
                    p "[handleRequest] done"

                    p "[handleRequest] updating daemon state ..."
                    io $ atomically $ do
                        ds <- takeTMVar tds
                        putTMVar tds $ ds { dsDaemon = d, dsStatus = NotStarted }
                    p "[handleRequest] done"

                    hPrintM h OK

handleRequest GetListDaemons     h = do
    p "[handleRequest] GetListDaemons"
    dls <- gets (map snd)
    dlss <- io $ atomically $ forM dls $ \(DaemonLogger _ _ tds tls) -> do
        ds <- readTMVar tds
        ls <- readTMVar tls
        return (ds, ls)
    hPrintM h $ ListDaemons dlss

handleRequest (StartDaemon dn)   h = do
    p "[handleRequest] StartDaemon"
    handleRequest (SetAutoStart dn True) h

handleRequest (SetAutoStart dn b) h = do
    p "[handleRequest] SetAutoStart"

    p "[handleRequest] maybe modifying daemon ..."
    ret <- modifyDaemon dn (\d -> d { dAutoStart = b })
    p "[handleRequest] Done"

    case ret of
        Nothing -> hPrintM h $ NG ("no such daemon: " ++ dn)
        Just d  -> do
            p "[handleRequest] saving daemon ..."
            saveDaemon d
            p "[handleRequest] Done"

            hPrintM h OK

handleRequest (KillDaemon dn sig) h = do
    p "[handleRequest] KillDaemon"
    mdl <- gets $ lookup dn
    case mdl of
        Nothing  -> hPrintM h $ NG ("no such daemon: " ++ dn)
        Just (DaemonLogger _ _ tds _) -> do
            b <- killDaemon sig tds
            if b
              then hPrintM h OK
              else hPrintM h $ NG "daemon not running"

handleRequest (GetDaemonStatus dn) h = do
    p "[handleRequest] GetDaemonStatus"
    mdl <- gets $ lookup dn
    case mdl of
        Nothing  -> hPrintM h $ NG ("no such daemon: " ++ dn)
        Just (DaemonLogger _ _ tds tls) -> do
            ds <- io $ atomically $ readTMVar tds
            ls <- io $ atomically $ readTMVar tls
            hPrintM h $ DaemonStatus ds ls

handleRequest ShutdownMaster       h = do
    p "[handleRequest] ShutdownMaster"
    killAllDaemons

    hPrintM h OK

    p "[handleRequest] shutdown master"
    io exitSuccess

handleRequest GetMasterVersion     h = do
    p "[handleRequest] GetMasterVersion"
    self <- io getProgName
    hPrintM h $ MasterVersion self version

--handleRequest _                   h =
--    hPrintM h $ NG "Not impremented"

killAllDaemons :: Master ()
killAllDaemons = do
    dns <- get

    p "[killAllDaemons] modifying all daemons dAutoStart to \"False\" ..."
    forM_ (map fst dns) $ \dn -> modifyDaemon dn (\d -> d { dAutoStart = False })
    p "[killAllDaemons] Done"

    p "[killAllDaemons] sending SIGTERM to all daemons ..."
    forM_ (map (dlDaemonState . snd) dns) $ killDaemon sigTERM
    p "[killAllDaemons] Done"

    p "[killAllDaemons] waiting all daemons to shutdown ..."
    -- TODO: timeout
    forM_ (map (dlDaemonState . snd) dns) $ waitDaemon True
    p "[killAllDaemons] Done"

    p "[killAllDaemons] modifying all logger's dAutoStart to \"False\" ..."
    forM_ (map fst dns) $ \dn -> modifyLogger dn (\d -> d { dAutoStart = False })
    p "[killAllDaemons] Done"

    p "[killAllDaemons] closing all pipes ..."
    forM_ (map fst dns) $ closeDaemonPipes
    p "[killAllDaemons] Done"

    p "[killAllDaemons] waiting all logger to shutdown ..."
    -- TODO: timeout
    forM_ (map (dlLoggerState . snd) dns) $ waitDaemon True
    p "[killAllDaemons] Done"

restartMaster :: Socket -> Handle -> String -> [String] -> Master ()
restartMaster s h cmd args = do
    p "[restartMaster] start"

    dns <- get
    let dls = map snd dns

    p "[restartMaster] wrapping DaemonStatus by \"Resuming\" ..."
    forM_ dls $ \(DaemonLogger _ _ tds tls) ->
        forM_ [tds, tls] $ \ts ->
            io $ atomically $ do
                s@(DaemonState _ dst _ _) <- takeTMVar ts
                case dst of
                    Initializing -> retry
                    _            -> putTMVar ts $ s { dsStatus = Resuming dst }
    p "[restartMaster] done"

    p "[restartMaster] killThreading daemonManagers ..."
    forM_ dls $ \(DaemonLogger tid tid' _ _) -> io $ killThread tid >> killThread tid'
    p "[restartMaster] done"

    p "[restartMaster] creating ResumeState ..."
    rsds <- forM dns $ \(dn, DaemonLogger _ _ tds tls) -> do
        ds <- io $ atomically $ readTMVar tds
        ls <- io $ atomically $ readTMVar tls
        return (dn, (ds, ls))
    cfd <- io $ handleToFd h
    let rs = ResumeState (fromIntegral $ fdSocket s) cfd rsds
    p $ "[restartMaster] done (" ++ show rs ++ ")"

    io $ do
        p "[restartMaster] saving ResumeState ..."
        (rf, rh) <- openTempFile "/tmp" "udon-master.resume"
        removeLink rf

        hPrint rh rs
        hSeek rh AbsoluteSeek 0
        p "[restartMaster] done"

        p $ "[restartMaster] copying " ++ show rh ++ " to stdin ..."
        rfd <- handleToFd rh
        dupTo rfd stdInput
        closeFd rfd
        p "[restartMaster] done"

        p "[restartMaster] executing new master ..."
        executeFile cmd False args Nothing

    hPrintM h $ NG "cannot execute new master"

    fallbackMaster s h

fallbackMaster :: Socket -> Handle -> Master ()
fallbackMaster = undefined

resumeMaster' :: Master ()
resumeMaster' = do
    -- TODO: confirm flock
    p "[resumeMaster'] start"
    mrs <- io $ readMaybeIO =<< getContents
    io $ hClose stdin

    p "[resumeMaster] re-opening stdin with /dev/null ..."
    fd <- io $ openFd "/dev/null" ReadOnly Nothing defaultFileFlags
    when (fd /= 0) $ do
        io $ dupTo fd stdInput
        io $ closeFd fd
    p "[resumeMaster] done"

    case mrs of
        Nothing -> fail "[resumeMaster] cannot read ResumeState"
        Just (ResumeState sfd cfd dns) -> do
            blkSigs
            mapM resumeDaemonManager dns
            updateHandler
            unblkSigs
            p "[resumeMaster] restoring master socket ..."
            s <- io $ mkSocket (fromIntegral sfd) AF_UNIX Stream defaultProtocol Listening
            p "[resumeMaster] done"

            p "[resumeMaster] restoring client handle ..."
            h <- io $ fdToHandle cfd
            p "[resumeMaster] and set buffering mode ..."
            io $ hSetBuffering h LineBuffering
            p "[resumeMaster] done"
            hPrintM h OK

            p "[resumeMaster] start mainloop"
            mainLoop s

resumeDaemonManager :: (String, (DaemonState, LoggerState)) -> Master ()
resumeDaemonManager (dn, (ds, ls)) = do
    cfg <- ask

    tds <- io $ newTMVarIO ds

    p "[resumeDaemonManager] forkIOing daemonManager ..."
    (tds, tid) <- resumeDaemonManager' cfg ds
    p "[resumeDaemonManager] Done"

    p "[resumeDaemonManager] forkIOing daemonManager for logger ..."
    (tls, tid') <- resumeDaemonManager' cfg ls
    p "[resumeDaemonManager] Done"

    modify $ \tdss -> sortByFst $ (dn, DaemonLogger tid tid' tds tls):tdss

resumeDaemonManager' :: Config -> DaemonState -> Master (TMVar DaemonState, ThreadId)
resumeDaemonManager' cfg ds = do
    (mgr, ds') <- case dsStatus ds of
                      Resuming dst@(Running _ _)  -> return (daemonManagerWait, ds { dsStatus = dst })
                      Resuming dst@(Initializing) -> return (daemonManagerRun,  ds { dsStatus = dst })
                      Resuming dst                -> return (daemonManagerInit, ds { dsStatus = dst })
                      dst                         -> fail $ "[resumeDaemonManager'] not a Resuming status: " ++ show dst
    tds <- io $ newTMVarIO ds'
    tid <- io $ forkIO $ runManager mgr cfg tds
    return (tds, tid)

startDaemonManager :: Daemon -> Logger -> Master ()
startDaemonManager d@(Daemon { dName = dn }) l = do
    (pipe_r, pipe_w) <- io createPipe

    p "[startDaemonManager] start"
    let ds = DaemonState d NotStarted Nothing (Just pipe_w)
    tds <- io $ newTMVarIO ds
    cfg <- ask

    p "[startDaemonManager] forkIOing daemonManager ..."
    tid <- io $ forkIO $ runManager daemonManager cfg tds
    p "[startDaemonManager] Done"

    let ls = DaemonState l NotStarted (Just pipe_r) (Just stdError)

    tls <- io $ newTMVarIO ls

    p "[startDaemonManager] forkIOing daemonManager for logger ..."
    -- override daemonsDir for saveDaemon' to save logger's run file under loggersDir
    tid' <- io $ forkIO $ runManager daemonManager (cfg { daemonsDir = loggersDir cfg }) tls
    p "[startDaemonManager] Done"

    p "[startDaemonManager] modifying state ..."
    modify $ \tdss -> sortByFst $ (dn, DaemonLogger tid tid' tds tls):tdss
    p "[startDaemonManager] Done"

daemonManager :: DaemonManager ()
daemonManager = daemonManagerInit

daemonManagerInit :: DaemonManager ()
daemonManagerInit = do
    p "[daemonManagerInit] start"
    tds <- asks getDaemonState

    p "[daemonManagerInit] setting TMVar to \"Initializing\" ..."
    io $ atomically $ do
        ds <- takeTMVar tds
#ifdef DEBUG
        pp $ "[daemonManagerInit] (STM) ds' (" ++ show ds ++ ")"
#endif
        let d' = dsDaemon ds
            auto = dAutoStart d'
            dst = dsStatus ds
        case (dst, auto) of
            (Running _ _, _)  -> fail "daemon already running"
            (Initializing, _) -> fail "daemon now initializing"
            (Deleting, _)     -> fail "daemon now deleting"
            (Updating, _)     -> retry
            (_, False)        -> retry
            _                 -> do
                let ds' = ds { dsStatus = Initializing }
#ifdef DEBUG
                pp $ "[daemonManagerInit] (STM) ds' (" ++ show ds' ++ ")"
                pp "[daemonManagerInit] (STM) puting TMVar ..."
#endif
                putTMVar tds ds'
#ifdef DEBUG
                pp "[daemonManagerInit] (STM) Done"
                pp "[daemonManagerInit] (STM) returning ..."
#endif
                return ()
    p "[daemonManagerInit] Done"

    daemonManagerRun

daemonManagerRun :: DaemonManager ()
daemonManagerRun = do
    tds <- asks getDaemonState
    (d, inp, out) <- io $ atomically $ do
        ds <- readTMVar tds
        case dsStatus ds of
            Initializing -> return (dsDaemon ds, dsFdInput ds, dsFdOutput ds)
            _            -> fail $ "[daemonManagerRun] Error: unexpected DaemonStatus: " ++ show (dsStatus ds)
    p "[daemonManagerRun] forking daemon ..."

    io $ block $ do
        pid <- runCommandWithFd (dCommand d)
                                (dArgs d)
                                (dCwd d)
                                (dEnv d)
                                inp out out

        p $ "[daemonManagerRun] Done (PID: " ++ show pid ++ ")"

        t <- getCurrentTime
        atomically $ do
            ds <- takeTMVar tds
            putTMVar tds $ ds { dsStatus = Running pid t }

    daemonManagerWait

daemonManagerWait :: DaemonManager ()
daemonManagerWait = do
    tds <- asks getDaemonState
    (pid, t) <- io $ atomically $ do
        dst <- dsStatus <$> readTMVar tds
        case dst of
            Running pid t -> return (pid, t)
            _             -> fail $ "[daemonManagerWait] Error: unexpected DaemonStatus: " ++ show dst

    t' <- io $ block $ do
        p "[daemonManagerWait] waiting child ..."
        -- waitChild use threadDelay internaly, so it could be killThreaded
        Just ps <- waitChild pid
        p "[daemonManagerWait] Done"

        t' <- getCurrentTime

        p "[daemonManagerWait] updating status ..."
        atomically $ do
            ds <- takeTMVar tds
            putTMVar tds $ ds { dsStatus = toDaemonStatus ps }
        p "[daemonManagerWait] Done"
        return t'

    fc <- asks (fastspawnCount . getConfig)
    fi <- asks (fastspawnInterval . getConfig)

    p "[daemonManagerWait] checking fast spawn ..."
    if realToFrac (diffUTCTime t' t) < fi
      then modify (+1)
      else put 0

    c <- get

    when (c >= fc) $ do
        p "[daemonManagerWait] over fast spawn count, set auto start to False"
        d' <- io $ atomically $ do
            DaemonState d dst inp out <- takeTMVar tds
            let d' = (d { dAutoStart = False })
            putTMVar tds $ DaemonState d' (FastSpawn dst) inp out
            return d'
        p "[daemonManagerWait] saving Daemon ..."
        saveDaemon' d' =<< asks getConfig
        -- reset fast spawn count
        put 0

    p "[daemonManagerWait] Done"

    daemonManagerNotice
    daemonManager
  where
    toDaemonStatus :: ProcessStatus -> DaemonStatus
    toDaemonStatus (P.Exited c)     = Exited c
    toDaemonStatus (P.Terminated s) = Terminated s
    toDaemonStatus (P.Stopped _)    = error "This pattern should not be executed"

daemonManagerNotice :: DaemonManager ()
daemonManagerNotice = do
    ds <- io . atomically . readTMVar =<< asks getDaemonState
    case dsStatus ds of
        Exited (ExitFailure _) ->
            let t = (dName $ dsDaemon ds) ++ " crashed"
                msg = t ++ "\n" ++ show (dsStatus ds)
            in notice t msg
        FastSpawn _           ->
            let t = (dName $ dsDaemon ds) ++ " spawn too fast"
                msg = t ++ "\n" ++ show (dsStatus ds)
            in notice t msg
        _ -> return ()

notice :: String -- ^ title
       -> String -- ^ message
       -> DaemonManager ()
notice t msg = do
    Config { notificationCmd = (ncmd, nargs)
           , contacts = cs
           } <- asks getConfig
    p $ "[notice] " ++ unwords [show t, show msg, show ncmd, show nargs, show cs]
    forM_ cs $ \c ->
        io . forkIO $ systemWithInput ncmd (nargs ++ [c, ("notice: " ++ t)]) msg >> return ()

modifyDaemonState :: (DaemonState -> DaemonState) -> DaemonManager ()
modifyDaemonState f = do
    tds <- asks getDaemonState
    io $ atomically $ do
        ds <- takeTMVar tds
        putTMVar tds $ f ds

updateStatus :: DaemonStatus -> DaemonManager ()
updateStatus ps = modifyDaemonState $ \ds -> ds { dsStatus = ps }

modifyDaemon :: String -> (Daemon -> Daemon) -> Master (Maybe Daemon)
modifyDaemon dn f = do
    mdl <- gets $ lookup dn
    case mdl of
        Nothing  -> return Nothing
        Just (DaemonLogger _ _ tds _) -> do
            p "[modifyDaemon] modifying TMVar ..."
            d <- io $ atomically $ modifyDaemon' tds f
            p "[modifyDaemon] Done"
            return $ Just d

modifyLogger :: String -> (Daemon -> Daemon) -> Master (Maybe Daemon)
modifyLogger dn f = do
    mdl <- gets $ lookup dn
    case mdl of
        Nothing  -> return Nothing
        Just (DaemonLogger _ _ _ tls) -> do
            p "[modifyLogger] modifying TMVar ..."
            d <- io $ atomically $ modifyDaemon' tls f
            p "[modifyLogger] Done"
            return $ Just d

modifyDaemon' :: TMVar DaemonState -> (Daemon -> Daemon) -> STM Daemon
modifyDaemon' tds f = do
    ds <- takeTMVar tds
    let d = dsDaemon ds
        d' = f d
    putTMVar tds $ ds { dsDaemon = d' }
    return d'

closeDaemonPipes :: String -> Master ()
closeDaemonPipes dn = do
    mdl <- gets $ lookup dn
    case mdl of
        Nothing -> return ()
        Just (DaemonLogger _ _ tds tls) -> do
            fds <- fmap (filter (> 2) . catMaybes . concat) $ io $ atomically $ forM [tds, tls] $ \ts -> do
                s@(DaemonState _ _ inp out) <- takeTMVar ts
                putTMVar ts $ s { dsFdInput = Nothing, dsFdOutput = Nothing }
                return [inp, out]
            p $ "[closeDaemonPipes] close fds " ++ show fds
            io $ mapM_ closeFd fds

killDaemon :: Signal -> TMVar DaemonState -> Master Bool
killDaemon sig tds = do
    ds <- io $ atomically $ readTMVar tds
    case ds of
        (DaemonState _ (Running pid _) _ _) -> do
            p $ "[killDaemon] killing " ++ show pid ++ " ..."
            io $ killProcess sig pid
            p "[killDaemon] Done"

            return True
        _                               ->
            return False

waitDaemon :: Bool              -- ^ Blocking
           -> TMVar DaemonState
           -> Master Bool       -- ^ Whether daemon exited or not
waitDaemon blk tds =
    io $ atomically $ do
        DaemonState _ dst _ _ <- readTMVar tds
        case dst of
            Running _ _  -> retryOrFalse
            Initializing -> retryOrFalse
            _            -> return True
  where
    retryOrFalse = if blk then retry else return False

errorToEither :: STM a -> STM (Either String a)
errorToEither stm = (Right <$> stm) `catchSTM` \e -> return $ Left (show e)

sortByFst :: Ord a => [(a, b)] -> [(a, b)]
sortByFst xs = sortBy compByFst xs

compByFst :: Ord a => (a, b) -> (a, b) -> Ordering
compByFst (a, _) (b, _) = compare a b

updateHandler :: Master ()
updateHandler = do
    cfg <- ask
    dns <- get
    io $ installHandler sigTERM (Catch $ termHandler cfg dns) Nothing
    io $ installHandler sigINT (Catch $ termHandler cfg dns) Nothing
    return ()

termHandler :: Config -> [(String, DaemonLogger)] -> IO ()
termHandler cfg dns = do
    p "[termHandler] stopping all daemons/loggers ..."
    evalStateT (runReaderT (runMaster killAllDaemons) cfg) dns
    p "[termHandler] done"

    p "[termHandler] exitImmediately"
    exitImmediately ExitSuccess

blkSigs :: MonadIO m => m ()
blkSigs = io $ blkSig sigTERM >> blkSig sigINT

blkSig :: Signal -> IO ()
blkSig sig = blockSignals $ addSignal sig emptySignalSet

unblkSigs :: MonadIO m => m ()
unblkSigs = io $ unblkSig sigTERM >> unblkSig sigINT

unblkSig :: Signal -> IO ()
unblkSig sig = unblockSignals $ addSignal sig emptySignalSet