• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/result.h"
24 #include "common/libs/utils/subprocess.h"
25 
26 namespace cuttlefish {
27 
28 struct MonitorEntry {
29   std::unique_ptr<Command> cmd;
30   std::unique_ptr<Subprocess> proc;
31 };
32 
33 // Keeps track of launched subprocesses, restarts them if they unexpectedly exit
34 class ProcessMonitor {
35  public:
36   class Properties {
37    public:
38     Properties& RestartSubprocesses(bool) &;
39     Properties RestartSubprocesses(bool) &&;
40 
41     Properties& AddCommand(Command) &;
42     Properties AddCommand(Command) &&;
43 
44     template <typename T>
AddCommands(T commands)45     Properties& AddCommands(T commands) & {
46       for (auto& command : commands) {
47         AddCommand(std::move(command));
48       }
49       return *this;
50     }
51 
52     template <typename T>
AddCommands(T commands)53     Properties AddCommands(T commands) && {
54       for (auto& command : commands) {
55         AddCommand(std::move(command));
56       }
57       return std::move(*this);
58     }
59 
60    private:
61     bool restart_subprocesses_;
62     std::vector<MonitorEntry> entries_;
63 
64     friend class ProcessMonitor;
65   };
66   ProcessMonitor(Properties&&);
67 
68   // Start all processes given by AddCommand.
69   Result<void> StartAndMonitorProcesses();
70   // Stops all monitored subprocesses.
71   Result<void> StopMonitoredProcesses();
72 
73  private:
74   Result<void> MonitorRoutine();
75 
76   Properties properties_;
77   pid_t monitor_;
78   SharedFD monitor_socket_;
79 };
80 
81 }  // namespace cuttlefish
82