File: EventsSourceSpawner.cpp

package info (click to toggle)
drbd-utils 9.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 5,388 kB
  • sloc: ansic: 43,698; xml: 15,968; cpp: 7,783; sh: 3,699; makefile: 1,353; perl: 353
file content (329 lines) | stat: -rw-r--r-- 9,473 bytes parent folder | download
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
#include <EventsSourceSpawner.h>
#include <memory>
#include <cstring>

extern "C"
{
    #include <unistd.h>
    #include <signal.h>
    #include <spawn.h>
    #include <fcntl.h>
    #include <sys/wait.h>
    #include <errno.h>
}

const char* EventsSourceSpawner::EVENTS_PROGRAM = "drbdsetup";
const char* EventsSourceSpawner::EVENTS_PROGRAM_ARGS[] =
{
    "drbdsetup",
    "events2",
    "all",
    nullptr
};

const int EventsSourceSpawner::PIPE_READ_SIDE  = 0;
const int EventsSourceSpawner::PIPE_WRITE_SIDE = 1;

EventsSourceSpawner::EventsSourceSpawner(MessageLog& logRef):
    log(logRef)
{
}

EventsSourceSpawner::~EventsSourceSpawner()
{
    try
    {
        cleanup_child_processes_impl();
    }
    catch (EventsSourceException&)
    {
        // Triggered by cleanup_child_processes_impl() if the events source
        // process tracked by this instance exited
    }

    terminate_child_process();
}

pid_t EventsSourceSpawner::get_process_id()
{
    return spawned_pid;
}

int EventsSourceSpawner::get_events_source_fd()
{
    return pipe_fd[PIPE_READ_SIDE];
}

// @throws std::bad_alloc, EventSourceException
int EventsSourceSpawner::spawn_source()
{
    const std::unique_ptr<posix_spawn_file_actions_t> pipe_init_actions_alloc(new posix_spawn_file_actions_t);
    const std::unique_ptr<posix_spawnattr_t> spawn_attr_alloc(new posix_spawnattr_t);

    posix_spawn_file_actions_t* pipe_init_actions {nullptr};
    posix_spawnattr_t* spawn_attr {nullptr};
    char** spawn_args {nullptr};

    // Indicates that posix_spawn_file_actions_init() was executed on pipe_init_actions
    // and requires cleanup by executing posix_spawn_file_actions_destroy()
    bool cleanup_pipe_init_actions {false};
    // Indicates that posix_spawnattr_init() was executed on spawn_attr
    // and requires cleanup by executing posix_spawnattr_destroy()
    bool cleanup_spawn_attr {false};

    try
    {
        // Initialize the pipe
        checked_int_rc(pipe2(pipe_fd, 0));
        // Make the pipe's read end nonblocking
        fcntl(pipe_fd[PIPE_READ_SIDE], F_SETFL, O_NONBLOCK);
        // Make stdin nonblocking
        fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);

        // Initialize the datastructures for posix_spawn())
        {
            // Use direct pointers
            pipe_init_actions = pipe_init_actions_alloc.get();
            spawn_attr = spawn_attr_alloc.get();

            // Initialize a copy of the spawn arguments
            spawn_args = init_spawn_args();

            checked_int_rc(posix_spawn_file_actions_init(pipe_init_actions));
            cleanup_pipe_init_actions = true;

            // Redirect stdout to the pipe's write side
            checked_int_rc(
                posix_spawn_file_actions_adddup2(
                    pipe_init_actions,
                    pipe_fd[PIPE_WRITE_SIDE],
                    STDOUT_FILENO
                )
            );
            // Close the read end of the pipe
            checked_int_rc(
                posix_spawn_file_actions_addclose(
                    pipe_init_actions,
                    pipe_fd[PIPE_READ_SIDE]
                )
            );

            checked_int_rc(posix_spawnattr_init(spawn_attr));
            cleanup_spawn_attr = true;

            // Reset ignored signals to the default action
            sigset_t mask;
            checked_int_rc(sigemptyset(&mask));
            checked_int_rc(sigaddset(&mask, SIGTERM));
            checked_int_rc(sigaddset(&mask, SIGHUP));
            checked_int_rc(sigaddset(&mask, SIGINT));
            checked_int_rc(sigaddset(&mask, SIGWINCH));
            checked_int_rc(sigaddset(&mask, SIGCHLD));
            checked_int_rc(posix_spawnattr_setsigdefault(spawn_attr, &mask));
            checked_int_rc(posix_spawnattr_setflags(spawn_attr, POSIX_SPAWN_SETSIGDEF));

            // Attempt to spawn the events source program
            int spawn_rc = posix_spawnp(&spawned_pid, EVENTS_PROGRAM, pipe_init_actions, spawn_attr,
                                        spawn_args, environ);
            if (spawn_rc != 0)
            {
                spawned_pid = -1;
                log.add_entry(
                    MessageLog::log_level::ALERT,
                    "Spawning the events source process failed"
                );
                throw EventsSourceException();
            }

            destroy_spawn_args(spawn_args);

            // Close the local write side of the pipe
            {
                int close_rc = 0;
                do
                {
                    errno = 0;
                    close_rc = close(pipe_fd[PIPE_WRITE_SIDE]);
                }
                while (close_rc != 0 && errno == EINTR);
            }

            // Cleanup pipe_init_actions
            static_cast<void> (posix_spawn_file_actions_destroy(pipe_init_actions));
            cleanup_pipe_init_actions = false;
            // Cleanup spawn_attr
            static_cast<void> (posix_spawnattr_destroy(spawn_attr));
            cleanup_spawn_attr = false;
        }
    }
    catch (EventsSourceException&)
    {
        // Cleanup calls below may change errno, so the relevant
        // information must be cached
        bool spawn_out_of_memory = (errno == ENOMEM);

        if (cleanup_pipe_init_actions)
        {
            static_cast<void> (posix_spawn_file_actions_destroy(pipe_init_actions));
        }

        if (cleanup_spawn_attr)
        {
            static_cast<void> (posix_spawnattr_destroy(spawn_attr));
        }

        destroy_spawn_args(spawn_args);

        close_pipe();

        if (spawn_out_of_memory)
        {
            throw std::bad_alloc();
        }
        throw;
    }
    catch (std::bad_alloc&)
    {
        if (cleanup_pipe_init_actions)
        {
            static_cast<void> (posix_spawn_file_actions_destroy(pipe_init_actions));
        }

        if (cleanup_spawn_attr)
        {
            static_cast<void> (posix_spawnattr_destroy(spawn_attr));
        }

        destroy_spawn_args(spawn_args);

        close_pipe();

        throw;
    }

    return pipe_fd[PIPE_READ_SIDE];
}

// @throws EventsSourceException
void EventsSourceSpawner::cleanup_child_processes()
{
    cleanup_child_processes_impl();
}

// @throws EventsSourceException
void EventsSourceSpawner::cleanup_child_processes_impl()
{
    // Cleanup any child processes that have exited (zombie processes))
    pid_t child_pid {0};
    do
    {
        int exit_status;
        child_pid = waitpid(-1, &exit_status, WNOHANG);
        if (spawned_pid != -1 && child_pid == spawned_pid &&
            (WIFEXITED(exit_status) || WIFSIGNALED(exit_status)))
        {
            // Events source process exited, throw an EventsSourceException
            // to trigger reinitialization of the application and
            // thereby a respawn of the events source process
            spawned_pid = -1;
            throw EventsSourceException();
        }
    }
    while (child_pid > 0);
}

void EventsSourceSpawner::terminate_child_process() noexcept
{
    // Unless the child process exited already or was not ever spawned,
    // tell the child process to terminate
    if (spawned_pid != -1)
    {
        static_cast<void> (kill(spawned_pid, SIGTERM));
    }
}

void EventsSourceSpawner::close_pipe()
{
    // Close the pipe file descriptors
    if (pipe_fd[PIPE_READ_SIDE] != -1)
    {
        int rc = 0;
        do
        {
            errno = 0;
            rc = close(pipe_fd[PIPE_READ_SIDE]);
        }
        while (rc != 0 && errno == EINTR);
        pipe_fd[PIPE_READ_SIDE] = -1;
    }
    if (pipe_fd[PIPE_WRITE_SIDE] != -1)
    {
        int rc = 0;
        do
        {
            errno = 0;
            rc = close(pipe_fd[PIPE_WRITE_SIDE]);
        }
        while (rc != 0 && errno == EINTR);
        pipe_fd[PIPE_WRITE_SIDE] = -1;
    }
}

// Throws EventsSourceException if rc is not equal to 0
// @throws EventsSourceException
void EventsSourceSpawner::checked_int_rc(int rc) const
{
    if (rc != 0)
    {
        throw EventsSourceException();
    }
}

// @throws std::bad_alloc
char** EventsSourceSpawner::init_spawn_args() const
{
    char** spawn_args = nullptr;

    try
    {
        // Number of arguments, excluding the trailing null pointer
        size_t args_count = 0;
        while (EVENTS_PROGRAM_ARGS[args_count] != nullptr)
        {
            ++args_count;
        }

        // Allocate slots for the arguments and an additional one for
        // the trailing null pointer
        spawn_args = new char*[args_count + 1];
        for (size_t index = 0; index < args_count; ++index)
        {
            size_t arg_length = std::strlen(EVENTS_PROGRAM_ARGS[index]) + 1;
            // If the allocation fails, make sure there is a null pointer in this slot
            // Required for clean deallocation
            spawn_args[index] = nullptr;
            spawn_args[index] = new char[arg_length];
            std::strcpy(spawn_args[index], EVENTS_PROGRAM_ARGS[index]);
        }
        spawn_args[args_count] = nullptr;
    }
    catch (std::bad_alloc&)
    {
        destroy_spawn_args(spawn_args);
        throw;
    }

    return spawn_args;
}

void EventsSourceSpawner::destroy_spawn_args(char** spawn_args) const noexcept
{
    if (spawn_args != nullptr)
    {
        for (size_t index = 0; spawn_args[index] != nullptr; ++index)
        {
            delete[] spawn_args[index];
        }
        delete[] spawn_args;
    }
}