diff --git a/simplexmq.cabal b/simplexmq.cabal index b21ce714b..bc5a4a121 100644 --- a/simplexmq.cabal +++ b/simplexmq.cabal @@ -258,6 +258,7 @@ library , time-manager ==0.0.* , tls >=1.7.0 && <1.8 , transformers ==0.6.* + , unix ==2.8.* , unliftio ==0.2.* , unliftio-core ==0.2.* , websockets ==0.12.* diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index aa1b95126..55b7bbec1 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -185,7 +185,9 @@ import Simplex.RemoteControl.Client import Simplex.RemoteControl.Invitation import Simplex.RemoteControl.Types import System.Directory +import System.Exit (exitSuccess) import System.Mem.Weak (deRefWeak) +import System.Posix.Signals (Handler (Catch), installHandler, sigINT, sigTERM) import UnliftIO.Concurrent (forkFinally, forkIO, killThread, mkWeakThreadId, threadDelay) import qualified UnliftIO.Exception as E import UnliftIO.STM @@ -211,6 +213,8 @@ getSMPAgentClient_ clientId cfg initServers store backgroundMode = runAgentThreads c | backgroundMode = run c "subscriber" $ subscriber c | otherwise = do + -- _ <- liftIO $ installHandler sigINT (Catch $ withAgentEnv' c $ handleSignal c) Nothing + -- _ <- liftIO $ installHandler sigTERM (Catch $ withAgentEnv' c $ handleSignal c) Nothing restoreAgentStats c let threads = [ run c "subscriber" $ subscriber c, @@ -227,6 +231,11 @@ getSMPAgentClient_ clientId cfg initServers store backgroundMode = logError $ "Agent thread " <> name <> " crashed: " <> tshow e atomically $ writeTBQueue subQ ("", "", AEvt SAEConn $ ERR $ CRITICAL True $ show e) +handleSignal :: AgentClient -> AM' () +handleSignal c = do + saveAgentStats c `E.catchAny` \e -> liftIO $ print $ "error saving agent stats: " <> tshow e + liftIO exitSuccess + logAgentStats :: AgentClient -> AM' () logAgentStats c = do let interval = 1000000 * 30 -- 30 seconds -- TODO config @@ -244,7 +253,8 @@ saveAgentStats AgentClient {smpServersStats, xftpServersStats} = xss <- readTVarIO xftpServersStats xftpServersStatsData <- mapM (atomically . getAgentXFTPServerStats) xss let stats = AgentPersistedServerStats {smpServersStatsData, xftpServersStatsData} - logInfo $ "saving agent stats to file " <> T.pack f + -- logInfo $ "saving agent stats to file " <> T.pack f + liftIO $ print $ "saving agent stats to file " <> T.pack f B.writeFile f $ LB.toStrict $ J.encode stats logInfo "agent stats saved"