aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Common/waitForPid.cpp
blob: 0ec10811354c3184d74a15bb88688696f7f0fdc0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
#include <Common/waitForPid.h>
#include <Common/VersionNumber.h>
#include <Poco/Environment.h>
#include <Common/Stopwatch.h>
/// for abortOnFailedAssertion() via chassert() (dependency chain looks odd)
#include <Common/Exception.h>
#include <base/defines.h>

#include <fcntl.h>
#include <sys/wait.h>
#include <unistd.h>

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu-statement-expression"
#define HANDLE_EINTR(x) ({ \
    decltype(x) eintr_wrapper_result; \
    do { \
        eintr_wrapper_result = (x); \
    } while (eintr_wrapper_result == -1 && errno == EINTR); \
    eintr_wrapper_result; \
})

namespace DB
{

enum PollPidResult
{
    RESTART,
    FAILED
};

}

#if defined(OS_LINUX)

#include <poll.h>
#include <string>

#if !defined(__NR_pidfd_open)
    #if defined(__x86_64__)
        #define SYS_pidfd_open 434
    #elif defined(__aarch64__)
        #define SYS_pidfd_open 434
    #elif defined(__powerpc64__)
        #define SYS_pidfd_open 434
    #elif defined(__riscv)
        #define SYS_pidfd_open 434
    #elif defined(__s390x__)
        #define SYS_pidfd_open 434
    #else
        #error "Unsupported architecture"
    #endif
#else
    #define SYS_pidfd_open __NR_pidfd_open
#endif

namespace DB
{

static int syscall_pidfd_open(pid_t pid)
{
    return static_cast<int>(syscall(SYS_pidfd_open, pid, 0));
}

static bool supportsPidFdOpen()
{
    VersionNumber pidfd_open_minimal_version(5, 3, 0);
    VersionNumber linux_version(Poco::Environment::osVersion());
    return linux_version >= pidfd_open_minimal_version;
}

static PollPidResult pollPid(pid_t pid, int timeout_in_ms)
{
    int pid_fd = 0;

    if (supportsPidFdOpen())
    {
        // pidfd_open cannot be interrupted, no EINTR handling

        pid_fd = syscall_pidfd_open(pid);

        if (pid_fd < 0)
        {
            if (errno == ESRCH)
                return PollPidResult::RESTART;

            return PollPidResult::FAILED;
        }
    }
    else
    {
        std::string path = "/proc/" + std::to_string(pid);
        pid_fd = HANDLE_EINTR(open(path.c_str(), O_DIRECTORY));

        if (pid_fd < 0)
        {
            if (errno == ENOENT)
                return PollPidResult::RESTART;

            return PollPidResult::FAILED;
        }
    }

    struct pollfd pollfd;
    pollfd.fd = pid_fd;
    pollfd.events = POLLIN;

    int ready = HANDLE_EINTR(poll(&pollfd, 1, timeout_in_ms));

    if (ready <= 0)
        return PollPidResult::FAILED;

    int err = close(pid_fd);
    chassert(!err || errno == EINTR);

    return PollPidResult::RESTART;
}

#elif defined(OS_DARWIN) || defined(OS_FREEBSD)

#pragma clang diagnostic ignored "-Wreserved-identifier"

#include <sys/event.h>
#include <err.h>

namespace DB
{

static PollPidResult pollPid(pid_t pid, int timeout_in_ms)
{
    int kq = kqueue();
    if (kq == -1)
        return PollPidResult::FAILED;

    struct kevent change = {.ident = 0};
    EV_SET(&change, pid, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);

    int event_add_result = HANDLE_EINTR(kevent(kq, &change, 1, NULL, 0, NULL));
    if (event_add_result == -1)
    {
        if (errno == ESRCH)
            return PollPidResult::RESTART;

        return PollPidResult::FAILED;
    }

    struct kevent event = {.ident = 0};
    struct timespec remaining_timespec = {.tv_sec = timeout_in_ms / 1000, .tv_nsec = (timeout_in_ms % 1000) * 1000000};
    int ready = HANDLE_EINTR(kevent(kq, nullptr, 0, &event, 1, &remaining_timespec));
    PollPidResult result = ready < 0 ? PollPidResult::FAILED : PollPidResult::RESTART;

    close(kq);

    return result;
}
#else
    #error "Unsupported OS type"
#endif

bool waitForPid(pid_t pid, size_t timeout_in_seconds)
{
    int status = 0;

    Stopwatch watch;

    if (timeout_in_seconds == 0)
    {
        /// If there is no timeout before signal try to waitpid 1 time without block so we can avoid sending
        /// signal if process is already normally terminated.

        int waitpid_res = HANDLE_EINTR(waitpid(pid, &status, WNOHANG));
        bool process_terminated_normally = (waitpid_res == pid);
        return process_terminated_normally;
    }

    /// If timeout is positive try waitpid without block in loop until
    /// process is normally terminated or waitpid return error

    /// NOTE: timeout casted to int, since poll() accept int for timeout
    int timeout_in_ms = static_cast<int>(timeout_in_seconds * 1000);
    while (timeout_in_ms > 0)
    {
        int waitpid_res = HANDLE_EINTR(waitpid(pid, &status, WNOHANG));
        bool process_terminated_normally = (waitpid_res == pid);
        if (process_terminated_normally)
            return true;

        if (waitpid_res != 0)
            return false;

        watch.restart();

        PollPidResult result = pollPid(pid, timeout_in_ms);

        if (result == PollPidResult::FAILED)
            return false;

        timeout_in_ms -= watch.elapsedMilliseconds();
    }

    return false;
}

}
#pragma clang diagnostic pop