Home | History | Annotate | Download | only in launch
      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 cvd {
     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. The
     41   // on_control_socket_ready_cb callback will be called when data is ready to be
     42   // read from the socket or the subprocess has ended. No member functions of
     43   // the process monitor object should be called from the callback as it may
     44   // lead to a dealock. 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 alreacy started subprocess
     48   void MonitorExistingSubprocess(Command cmd, Subprocess sub_process,
     49                                  OnSocketReadyCb on_control_socket_ready_cb);
     50   static bool RestartOnExitCb(MonitorEntry* entry);
     51   static bool DoNotMonitorCb(MonitorEntry* entry);
     52 
     53  private:
     54   void MonitorRoutine();
     55 
     56   std::vector<MonitorEntry> monitored_processes_;
     57   // Used for communication with the restarter thread
     58   cvd::SharedFD thread_comm_main_, thread_comm_monitor_;
     59   std::thread monitor_thread_;
     60   // Protects access to the monitored_processes_
     61   std::mutex processes_mutex_;
     62 };
     63 }  // namespace cvd
     64