]> granicus.if.org Git - icinga2/blob - lib/base/process.hpp
Merge pull request #7002 from Icinga/bugfix/check_network-percent-6155
[icinga2] / lib / base / process.hpp
1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
2
3 #ifndef PROCESS_H
4 #define PROCESS_H
5
6 #include "base/i2-base.hpp"
7 #include "base/dictionary.hpp"
8 #include <iosfwd>
9 #include <deque>
10 #include <vector>
11 #include <sstream>
12
13 namespace icinga
14 {
15
16 /**
17  * The result of a Process task.
18  *
19  * @ingroup base
20  */
21 struct ProcessResult
22 {
23         pid_t PID;
24         double ExecutionStart;
25         double ExecutionEnd;
26         long ExitStatus;
27         String Output;
28 };
29
30 /**
31  * A process task. Executes an external application and returns the exit
32  * code and console output.
33  *
34  * @ingroup base
35  */
36 class Process final : public Object
37 {
38 public:
39         DECLARE_PTR_TYPEDEFS(Process);
40
41 #ifdef _WIN32
42         typedef String Arguments;
43         typedef HANDLE ProcessHandle;
44         typedef HANDLE ConsoleHandle;
45 #else /* _WIN32 */
46         typedef std::vector<String> Arguments;
47         typedef pid_t ProcessHandle;
48         typedef int ConsoleHandle;
49 #endif /* _WIN32 */
50
51         static const std::deque<Process::Ptr>::size_type MaxTasksPerThread = 512;
52
53         Process(Arguments arguments, Dictionary::Ptr extraEnvironment = nullptr);
54         ~Process() override;
55
56         void SetTimeout(double timeout);
57         double GetTimeout() const;
58
59         void SetAdjustPriority(bool adjust);
60         bool GetAdjustPriority() const;
61
62         void Run(const std::function<void (const ProcessResult&)>& callback = std::function<void (const ProcessResult&)>());
63
64         pid_t GetPID() const;
65
66         static Arguments PrepareCommand(const Value& command);
67
68         static void ThreadInitialize();
69
70         static String PrettyPrintArguments(const Arguments& arguments);
71
72 #ifndef _WIN32
73         static void InitializeSpawnHelper();
74 #endif /* _WIN32 */
75
76 private:
77         Arguments m_Arguments;
78         Dictionary::Ptr m_ExtraEnvironment;
79
80         double m_Timeout;
81         bool m_AdjustPriority;
82
83         ProcessHandle m_Process;
84         pid_t m_PID;
85         ConsoleHandle m_FD;
86
87 #ifdef _WIN32
88         bool m_ReadPending;
89         bool m_ReadFailed;
90         OVERLAPPED m_Overlapped;
91         char m_ReadBuffer[1024];
92 #endif /* _WIN32 */
93
94         std::ostringstream m_OutputStream;
95         std::function<void (const ProcessResult&)> m_Callback;
96         ProcessResult m_Result;
97
98         static void IOThreadProc(int tid);
99         bool DoEvents();
100         int GetTID() const;
101 };
102
103 }
104
105 #endif /* PROCESS_H */