1 // 2 // Copyright (C) 2011 The Android Open Source Project 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 // 16 17 #ifndef UPDATE_ENGINE_COMMON_SUBPROCESS_H_ 18 #define UPDATE_ENGINE_COMMON_SUBPROCESS_H_ 19 20 #include <unistd.h> 21 22 #include <map> 23 #include <memory> 24 #include <string> 25 #include <vector> 26 27 #include <base/callback.h> 28 #include <base/files/file_descriptor_watcher_posix.h> 29 #include <base/logging.h> 30 #include <base/macros.h> 31 #include <brillo/asynchronous_signal_handler_interface.h> 32 #include <brillo/message_loops/message_loop.h> 33 #include <brillo/process.h> 34 #include <brillo/process_reaper.h> 35 #include <gtest/gtest_prod.h> // for FRIEND_TEST 36 37 // The Subprocess class is a singleton. It's used to spawn off a subprocess 38 // and get notified when the subprocess exits. The result of Exec() can 39 // be saved and used to cancel the callback request and kill your process. If 40 // you know you won't call KillExec(), you may safely lose the return value 41 // from Exec(). 42 43 // To create the Subprocess singleton just instantiate it with and call Init(). 44 // You can't have two Subprocess instances initialized at the same time. 45 46 namespace chromeos_update_engine { 47 48 class Subprocess { 49 public: 50 enum Flags { 51 kSearchPath = 1 << 0, 52 kRedirectStderrToStdout = 1 << 1, 53 }; 54 55 // Callback type used when an async process terminates. It receives the exit 56 // code and the stdout output (and stderr if redirected). 57 using ExecCallback = base::Callback<void(int, const std::string&)>; 58 59 Subprocess() = default; 60 61 // Destroy and unregister the Subprocess singleton. 62 ~Subprocess(); 63 64 // Initialize and register the Subprocess singleton. 65 void Init(brillo::AsynchronousSignalHandlerInterface* async_signal_handler); 66 67 // Launches a process in the background and calls the passed |callback| when 68 // the process exits. The file descriptors specified in |output_pipes| will 69 // be available in the child as the writer end of a pipe. Use GetPipeFd() to 70 // know the reader end in the parent. Only stdin, stdout, stderr and the file 71 // descriptors in |output_pipes| will be open in the child. 72 // Returns the process id of the new launched process or 0 in case of failure. 73 pid_t Exec(const std::vector<std::string>& cmd, const ExecCallback& callback); 74 pid_t ExecFlags(const std::vector<std::string>& cmd, 75 uint32_t flags, 76 const std::vector<int>& output_pipes, 77 const ExecCallback& callback); 78 79 // Kills the running process with SIGTERM and ignores the callback. 80 void KillExec(pid_t pid); 81 82 // Return the parent end of the pipe mapped onto |fd| in the child |pid|. This 83 // file descriptor is available until the callback for the child |pid| 84 // returns. After that the file descriptor will be closed. The passed |fd| 85 // must be one of the file descriptors passed to ExecFlags() in 86 // |output_pipes|, otherwise returns -1. 87 int GetPipeFd(pid_t pid, int fd) const; 88 89 // Executes a command synchronously. Returns true on success. If |stdout| is 90 // non-null, the process output is stored in it, otherwise the output is 91 // logged. 92 static bool SynchronousExec(const std::vector<std::string>& cmd, 93 int* return_code, 94 std::string* stdout, 95 std::string* stderr); 96 static bool SynchronousExecFlags(const std::vector<std::string>& cmd, 97 uint32_t flags, 98 int* return_code, 99 std::string* stdout, 100 std::string* stderr); 101 102 // Gets the one instance. Get()103 static Subprocess& Get() { return *subprocess_singleton_; } 104 105 // Tries to log all in flight processes's output. It is used right before 106 // exiting the update_engine, probably when the subprocess caused a system 107 // shutdown. 108 void FlushBufferedLogsAtExit(); 109 110 private: 111 FRIEND_TEST(SubprocessTest, CancelTest); 112 113 struct SubprocessRecord { SubprocessRecordSubprocessRecord114 explicit SubprocessRecord(const ExecCallback& callback) 115 : callback(callback) {} 116 117 // The callback supplied by the caller. 118 ExecCallback callback; 119 120 // The ProcessImpl instance managing the child process. Destroying this 121 // will close our end of the pipes we have open. 122 brillo::ProcessImpl proc; 123 124 // These are used to monitor the stdout of the running process, including 125 // the stderr if it was redirected. 126 std::unique_ptr<base::FileDescriptorWatcher::Controller> stdout_controller; 127 128 int stdout_fd{-1}; 129 std::string stdout; 130 }; 131 132 // Callback which runs whenever there is input available on the subprocess 133 // stdout pipe. 134 static void OnStdoutReady(SubprocessRecord* record); 135 136 // Callback for when any subprocess terminates. This calls the user 137 // requested callback. 138 void ChildExitedCallback(const siginfo_t& info); 139 140 // The global instance. 141 static Subprocess* subprocess_singleton_; 142 143 // A map from the asynchronous subprocess tag (see Exec) to the subprocess 144 // record structure for all active asynchronous subprocesses. 145 std::map<pid_t, std::unique_ptr<SubprocessRecord>> subprocess_records_; 146 147 // Used to watch for child processes. 148 brillo::ProcessReaper process_reaper_; 149 150 DISALLOW_COPY_AND_ASSIGN(Subprocess); 151 }; 152 153 } // namespace chromeos_update_engine 154 155 #endif // UPDATE_ENGINE_COMMON_SUBPROCESS_H_ 156