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