1 /*
2  * Copyright (C) 2018 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 #pragma once
17 
18 #include <memory>
19 #include <mutex>
20 #include <thread>
21 #include <vector>
22 
23 #include <common/libs/utils/subprocess.h>
24 
25 namespace cuttlefish {
26 
27 struct MonitorEntry;
28 using OnSocketReadyCb = std::function<bool(MonitorEntry*)>;
29 
30 struct MonitorEntry {
31   std::unique_ptr<Command> cmd;
32   std::unique_ptr<Subprocess> proc;
33   OnSocketReadyCb on_control_socket_ready_cb;
34 };
35 
36 // Keeps track of launched subprocesses, restarts them if they unexpectedly exit
37 class ProcessMonitor {
38  public:
39   ProcessMonitor();
40   // Starts a managed subprocess with a controlling socket.
41   // The on_control_socket_ready_cb callback will be called when data is ready
42   // to be read from the socket or the subprocess has ended. No member functions
43   // of the process monitor object should be called from the callback as it may
44   // lead to a deadlock. If the callback returns false the subprocess will no
45   // longer be monitored.
46   void StartSubprocess(Command cmd, OnSocketReadyCb on_control_socket_ready_cb);
47   // Monitors an already started subprocess
48   void MonitorExistingSubprocess(Command cmd, Subprocess sub_process,
49                                  OnSocketReadyCb on_control_socket_ready_cb);
50   // Stops all monitored subprocesses.
51   bool StopMonitoredProcesses();
52   static bool RestartOnExitCb(MonitorEntry* entry);
53   static bool DoNotMonitorCb(MonitorEntry* entry);
54 
55  private:
56   void MonitorRoutine();
57 
58   std::vector<MonitorEntry> monitored_processes_;
59   // Used for communication with the restarter thread
60   cuttlefish::SharedFD thread_comm_main_, thread_comm_monitor_;
61   std::thread monitor_thread_;
62   // Protects access to the monitored_processes_
63   std::mutex processes_mutex_;
64 };
65 }  // namespace cuttlefish
66