1 // Copyright 2014 The Chromium OS Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef LIBBRILLO_BRILLO_DAEMONS_DAEMON_H_
6 #define LIBBRILLO_BRILLO_DAEMONS_DAEMON_H_
7 
8 #include <string>
9 
10 #include <base/at_exit.h>
11 #include <base/files/file_path.h>
12 #include <base/macros.h>
13 #include <base/message_loop/message_loop.h>
14 #include <base/time/time.h>
15 #include <brillo/asynchronous_signal_handler.h>
16 #include <brillo/brillo_export.h>
17 #include <brillo/message_loops/base_message_loop.h>
18 
19 struct signalfd_siginfo;
20 
21 namespace brillo {
22 
23 // Daemon is a simple base class for system daemons. It provides a lot
24 // of useful facilities such as a message loop, handling of SIGTERM, SIGINT, and
25 // SIGHUP system signals.
26 // You can use this class directly to implement your daemon or you can
27 // specialize it by creating your own class and deriving it from
28 // brillo::Daemon. Override some of the virtual methods provide to fine-tune
29 // its behavior to suit your daemon's needs.
30 class BRILLO_EXPORT Daemon : public AsynchronousSignalHandlerInterface {
31  public:
32   Daemon();
33   virtual ~Daemon();
34 
35   // Performs proper initialization of the daemon and runs the message loop.
36   // Blocks until the daemon is finished. The return value is the error
37   // code that should be returned from daemon's main(). Returns EX_OK (0) on
38   // success.
39   virtual int Run();
40 
41   // Can be used by call-backs to trigger shut-down of a running message loop.
42   // Calls QuiteWithExitCode(EX_OK);
43   // WARNING: This method (as well as QuitWithExitCode) can only be called when
44   // the message loop is running (that is, during Daemon::Run() call). Calling
45   // these methods before (e.g. during OnInit()) or after (e.g in OnShutdown())
46   // will lead to abnormal process termination.
47   void Quit();
48 
49   // |exit_code| is the status code to be returned when the daemon process
50   // quits. See the warning for Quit() above regarding the allowed scope for
51   // this method.
52   void QuitWithExitCode(int exit_code);
53 
54   // AsynchronousSignalHandlerInterface overrides.
55   // Register/unregister custom signal handlers for the daemon. The semantics
56   // are identical to AsynchronousSignalHandler::RegisterHandler and
57   // AsynchronousSignalHandler::UnregisterHandler, except that handlers for
58   // SIGTERM, SIGINT, and SIGHUP cannot be modified.
59   void RegisterHandler(
60       int signal, const
61       AsynchronousSignalHandlerInterface::SignalHandler& callback) override;
62   void UnregisterHandler(int signal) override;
63 
64  protected:
65   // Overload to provide your own initialization code that should happen just
66   // before running the message loop. Return EX_OK (0) on success or any other
67   // non-zero error codes. If an error is returned, the message loop execution
68   // is aborted and Daemon::Run() exits early.
69   // When overloading, make sure you call the base implementation of OnInit().
70   virtual int OnInit();
71   // Overload to provide initialization code that should be the first code to
72   // run on the message loop. Returning something other than EX_OK will cause
73   // the daemon to exit with that error code.
74   virtual int OnEventLoopStarted();
75   // Called when the message loops exits and before Daemon::Run() returns.
76   // Overload to clean up the data that was set up during OnInit().
77   // |return_code| contains the current error code that will be returned from
78   // Run(). You can override this value with your own error code if needed.
79   // When overloading, make sure you call the base implementation of
80   // OnShutdown().
81   virtual void OnShutdown(int* exit_code);
82   // Called when the SIGHUP signal is received. In response to this call, your
83   // daemon could reset/reload the configuration and re-initialize its state
84   // as if the process has been reloaded.
85   // Return true if the signal was processed successfully and the daemon
86   // reset its configuration. Returning false will force the daemon to
87   // quit (and subsequently relaunched by an upstart job, if one is configured).
88   // The default implementation just returns false (unhandled), which terminates
89   // the daemon, so do not call the base implementation of OnRestart() from
90   // your overload.
91   virtual bool OnRestart();
92 
93   // Returns a delegate to Quit() method in the base::RunLoop instance.
QuitClosure()94   base::Closure QuitClosure() const {
95     return message_loop_.QuitClosure();
96   }
97 
98  private:
99   // Called when SIGTERM/SIGINT signals are received.
100   bool Shutdown(const signalfd_siginfo& info);
101   // Called when SIGHUP signal is received.
102   bool Restart(const signalfd_siginfo& info);
103 
104   // Actual task posted first to the message loop.
105   void OnEventLoopStartedTask();
106 
107   // |at_exit_manager_| must be first to make sure it is initialized before
108   // other members, especially the |message_loop_|.
109   base::AtExitManager at_exit_manager_;
110   // The brillo wrapper for the base message loop.
111   BaseMessageLoop message_loop_;
112   // A helper to dispatch signal handlers asynchronously, so that the main
113   // system signal handler returns as soon as possible.
114   AsynchronousSignalHandler async_signal_handler_;
115   // Process exit code specified in QuitWithExitCode() method call.
116   int exit_code_;
117 
118   DISALLOW_COPY_AND_ASSIGN(Daemon);
119 };
120 
121 // Moves |latest_log_symlink| to |previous_log_symlink| and creates a relative
122 // symlink at |latest_log_symlink| pointing to |log_file|.
123 // |latest_log_symlink| does not need to exist.
124 BRILLO_EXPORT void UpdateLogSymlinks(const base::FilePath& latest_log_symlink,
125                                      const base::FilePath& previous_log_symlink,
126                                      const base::FilePath& log_file);
127 
128 // Formats the current time with "%Y%m%d-%H%M%S".
129 // Commonly used for naming log files.
130 BRILLO_EXPORT std::string GetTimeAsLogString(const base::Time& time);
131 
132 }  // namespace brillo
133 
134 #endif  // LIBBRILLO_BRILLO_DAEMONS_DAEMON_H_
135