blob: 62be3225bcbe4d93669865148380879ad3307d7f [file] [log] [blame]
Brian Silvermand169fcd2013-02-27 13:18:47 -08001#include <stdio.h>
2#include <stdlib.h>
3#include <sys/types.h>
4#include <fcntl.h>
5#include <sys/inotify.h>
6#include <sys/stat.h>
7#include <sys/ioctl.h>
8#include <assert.h>
9#include <signal.h>
10#include <stdint.h>
11#include <errno.h>
12#include <string.h>
13#include <sys/wait.h>
14
15#include <map>
16#include <functional>
17#include <deque>
18#include <fstream>
19#include <queue>
20#include <list>
21#include <string>
22#include <vector>
23#include <memory>
24
25#include <event2/event.h>
26
27#include "aos/common/logging/logging.h"
28#include "aos/common/logging/logging_impl.h"
29#include "aos/atom_code/init.h"
30#include "aos/common/unique_malloc_ptr.h"
31#include "aos/common/time.h"
Brian Silverman5cc661b2013-02-27 15:23:36 -080032#include "aos/common/once.h"
Brian Silvermand169fcd2013-02-27 13:18:47 -080033
34// This is the main piece of code that starts all of the rest of the code and
35// restarts it when the binaries are modified.
36//
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -080037// Throughout, the code is not terribly concerned with thread safety because
38// there is only 1 thread. It does some setup and then lets inotify run things
39// when appropriate.
40//
Brian Silverman5cc661b2013-02-27 15:23:36 -080041// NOTE: This program should never exit nicely. It catches all nice attempts to
42// exit, forwards them to all of the children that it has started, waits for
Brian Silvermand169fcd2013-02-27 13:18:47 -080043// them to exit nicely, and then SIGKILLs anybody left (which will always
44// include itself).
45
46using ::std::unique_ptr;
47
48namespace aos {
49namespace starter {
50
Brian Silvermand169fcd2013-02-27 13:18:47 -080051class EventBaseDeleter {
52 public:
53 void operator()(event_base *base) {
Brian Silvermand169fcd2013-02-27 13:18:47 -080054 event_base_free(base);
55 }
56};
57typedef unique_ptr<event_base, EventBaseDeleter> EventBaseUniquePtr;
Brian Silverman5cc661b2013-02-27 15:23:36 -080058EventBaseUniquePtr libevent_base;
Brian Silvermand169fcd2013-02-27 13:18:47 -080059
60class EventDeleter {
61 public:
62 void operator()(event *evt) {
Brian Silvermand169fcd2013-02-27 13:18:47 -080063 if (event_del(evt) != 0) {
64 LOG(WARNING, "event_del(%p) failed\n", evt);
65 }
66 }
67};
68typedef unique_ptr<event, EventDeleter> EventUniquePtr;
69
Brian Silverman5cc661b2013-02-27 15:23:36 -080070// Watches a file path for modifications. Once created, keeps watching until
71// destroyed or RemoveWatch() is called.
Brian Silvermand169fcd2013-02-27 13:18:47 -080072class FileWatch {
73 public:
74 // Will call callback(value) when filename is modified.
75 // If value is NULL, then a pointer to this object will be passed instead.
Brian Silverman5cc661b2013-02-27 15:23:36 -080076 //
77 // Watching for file creations is slightly different. To do that, pass true
78 // for create, the directory where the file will be created for filename, and
79 // the name of the file (without directory name) for check_filename.
Brian Silvermand169fcd2013-02-27 13:18:47 -080080 FileWatch(std::string filename,
81 std::function<void(void *)> callback, void *value,
82 bool create = false, std::string check_filename = "")
83 : filename_(filename), callback_(callback), value_(value),
84 check_filename_(check_filename) {
Brian Silverman5cc661b2013-02-27 15:23:36 -080085 init_once.Get();
86
Brian Silvermand169fcd2013-02-27 13:18:47 -080087 watch_ = inotify_add_watch(notify_fd, filename.c_str(),
88 create ? IN_CREATE : (IN_ATTRIB | IN_MODIFY));
89 if (watch_ == -1) {
Brian Silverman5cc661b2013-02-27 15:23:36 -080090 LOG(FATAL, "inotify_add_watch(%d, %s,"
91 " %s ? IN_CREATE : (IN_ATTRIB | IN_MODIFY)) failed with %d: %s\n",
92 notify_fd, filename.c_str(), create ? "true" : "false",
93 errno, strerror(errno));
Brian Silvermand169fcd2013-02-27 13:18:47 -080094 }
95 watchers[watch_] = this;
96 }
97 // Cleans up everything.
98 ~FileWatch() {
99 if (watch_ != -1) {
100 RemoveWatch();
101 }
102 }
103
104 // After calling this method, this object won't really be doing much of
Brian Silverman5cc661b2013-02-27 15:23:36 -0800105 // anything besides possibly running its callback or something.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800106 void RemoveWatch() {
107 assert(watch_ != -1);
Brian Silverman5cc661b2013-02-27 15:23:36 -0800108
Brian Silvermand169fcd2013-02-27 13:18:47 -0800109 if (inotify_rm_watch(notify_fd, watch_) == -1) {
110 LOG(WARNING, "inotify_rm_watch(%d, %d) failed with %d: %s\n",
111 notify_fd, watch_, errno, strerror(errno));
112 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800113
Brian Silvermand169fcd2013-02-27 13:18:47 -0800114 if (watchers[watch_] != this) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800115 LOG(WARNING, "watcher for %s (%p) didn't find itself in the map\n",
116 filename_.c_str(), this);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800117 } else {
118 watchers.erase(watch_);
119 }
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800120 LOG(DEBUG, "removed watch ID %d\n", watch_);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800121 watch_ = -1;
122 }
123
Brian Silverman5cc661b2013-02-27 15:23:36 -0800124 private:
125 // Performs the static initialization. Called by init_once from the
126 // constructor.
127 static void *Init() {
128 notify_fd = inotify_init1(IN_CLOEXEC);
129 EventUniquePtr notify_event(event_new(libevent_base.get(), notify_fd,
130 EV_READ | EV_PERSIST,
131 FileWatch::INotifyReadable, NULL));
132 event_add(notify_event.release(), NULL);
133 return NULL;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800134 }
135
136 // This gets set up as the callback for EV_READ on the inotify file
Brian Silverman5cc661b2013-02-27 15:23:36 -0800137 // descriptor. It calls FileNotified on the appropriate instance.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800138 static void INotifyReadable(int /*fd*/, short /*events*/, void *) {
139 unsigned int to_read;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800140 // Use FIONREAD to figure out how many bytes there are to read.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800141 if (ioctl(notify_fd, FIONREAD, &to_read) < 0) {
142 LOG(FATAL, "FIONREAD(%d, %p) failed with %d: %s\n",
143 notify_fd, &to_read, errno, strerror(errno));
144 }
145 inotify_event *notifyevt = static_cast<inotify_event *>(malloc(to_read));
146 const char *end = reinterpret_cast<char *>(notifyevt) + to_read;
147 aos::unique_c_ptr<inotify_event> freer(notifyevt);
148
149 ssize_t ret = read(notify_fd, notifyevt, to_read);
150 if (ret < 0) {
151 LOG(FATAL, "read(%d, %p, %u) failed with %d: %s\n",
152 notify_fd, notifyevt, to_read, errno, strerror(errno));
153 }
154 if (static_cast<size_t>(ret) != to_read) {
155 LOG(ERROR, "read(%d, %p, %u) returned %zd instead of %u\n",
156 notify_fd, notifyevt, to_read, ret, to_read);
157 return;
158 }
159
Brian Silverman5cc661b2013-02-27 15:23:36 -0800160 // Keep looping through until we get to the end because inotify does return
161 // multiple events at once.
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800162 while (reinterpret_cast<char *>(notifyevt) < end) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800163 if (watchers.count(notifyevt->wd) != 1) {
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800164 LOG(WARNING, "couldn't find whose watch ID %d is\n", notifyevt->wd);
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800165 } else {
166 watchers[notifyevt->wd]->FileNotified((notifyevt->len > 0) ?
167 notifyevt->name : NULL);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800168 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800169
170 notifyevt = reinterpret_cast<inotify_event *>(
171 reinterpret_cast<char *>(notifyevt) +
172 sizeof(*notifyevt) + notifyevt->len);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800173 }
174 }
175
Brian Silverman5cc661b2013-02-27 15:23:36 -0800176 // INotifyReadable calls this method whenever the watch for our file triggers.
177 void FileNotified(const char *filename) {
178 assert(watch_ != -1);
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800179 LOG(DEBUG, "got a notification for %s\n", filename_.c_str());
Brian Silverman5cc661b2013-02-27 15:23:36 -0800180
181 if (!check_filename_.empty()) {
182 if (filename == NULL) {
183 return;
184 }
185 if (std::string(filename) != check_filename_) {
186 return;
187 }
188 }
189
190 callback_((value_ == NULL) ? this : value_);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800191 }
192
Brian Silverman5cc661b2013-02-27 15:23:36 -0800193 // To make sure that Init gets called exactly once.
194 static ::aos::Once<void> init_once;
195
Brian Silvermand169fcd2013-02-27 13:18:47 -0800196 const std::string filename_;
197 const std::function<void(void *)> callback_;
198 void *const value_;
199 std::string check_filename_;
200
201 // The watch descriptor or -1 if we don't have one any more.
202 int watch_;
203
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -0800204 // Map from watch IDs to instances of this class.
205 // <https://patchwork.kernel.org/patch/73192/> ("inotify: do not reuse watch
206 // descriptors") says they won't get reused, but that shouldn't be counted on
207 // because we might have a modified/different version/whatever kernel.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800208 static std::map<int, FileWatch *> watchers;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800209 // The inotify(7) file descriptor.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800210 static int notify_fd;
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -0800211
212 DISALLOW_COPY_AND_ASSIGN(FileWatch);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800213};
Brian Silverman5cc661b2013-02-27 15:23:36 -0800214::aos::Once<void> FileWatch::init_once(FileWatch::Init);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800215std::map<int, FileWatch *> FileWatch::watchers;
216int FileWatch::notify_fd;
217
Brian Silverman5cc661b2013-02-27 15:23:36 -0800218// Runs the given command and returns its first line of output (not including
219// the \n). LOG(FATAL)s if the command has an exit status other than 0 or does
220// not print out an entire line.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800221std::string RunCommand(std::string command) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800222 // popen(3) might fail and not set it.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800223 errno = 0;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800224 FILE *pipe = popen(command.c_str(), "r");
225 if (pipe == NULL) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800226 LOG(FATAL, "popen(\"%s\", \"r\") failed with %d: %s\n",
227 command.c_str(), errno, strerror(errno));
228 }
229
Brian Silverman5cc661b2013-02-27 15:23:36 -0800230 // result_size is how many bytes result is currently allocated to.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800231 size_t result_size = 128, read = 0;
232 unique_c_ptr<char> result(static_cast<char *>(malloc(result_size)));
233 while (true) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800234 // If we filled up the buffer, then realloc(3) it bigger.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800235 if (read == result_size) {
236 result_size *= 2;
237 void *new_result = realloc(result.get(), result_size);
238 if (new_result == NULL) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800239 LOG(FATAL, "realloc(%p, %zd) failed because of %d: %s\n",
240 result.get(), result_size, errno, strerror(errno));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800241 } else {
242 result.release();
243 result = unique_c_ptr<char>(static_cast<char *>(new_result));
244 }
245 }
246
Brian Silverman5cc661b2013-02-27 15:23:36 -0800247 size_t ret = fread(result.get() + read, 1, result_size - read, pipe);
248 // If the read didn't fill up the whole buffer, check to see if it was
249 // because of an error.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800250 if (ret < result_size - read) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800251 if (ferror(pipe)) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800252 LOG(FATAL, "couldn't finish reading output of \"%s\"\n",
253 command.c_str());
254 }
255 }
256 read += ret;
257 if (read > 0 && result.get()[read - 1] == '\n') {
258 break;
259 }
260
Brian Silverman5cc661b2013-02-27 15:23:36 -0800261 if (feof(pipe)) {
262 LOG(FATAL, "`%s` failed. didn't print a whole line\n", command.c_str());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800263 }
264 }
265
Brian Silverman5cc661b2013-02-27 15:23:36 -0800266 // Get rid of the first \n and anything after it.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800267 *strchrnul(result.get(), '\n') = '\0';
268
Brian Silverman5cc661b2013-02-27 15:23:36 -0800269 int child_status = pclose(pipe);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800270 if (child_status == -1) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800271 LOG(FATAL, "pclose(%p) failed with %d: %s\n", pipe,
Brian Silvermand169fcd2013-02-27 13:18:47 -0800272 errno, strerror(errno));
273 }
274
275 if (child_status != 0) {
276 LOG(FATAL, "`%s` failed. return %d\n", command.c_str(), child_status);
277 }
278
279 return std::string(result.get());
280}
281
282// Will call callback(arg) after time.
283void Timeout(time::Time time, void (*callback)(int, short, void *), void *arg) {
284 EventUniquePtr timeout(evtimer_new(libevent_base.get(), callback, arg));
285 struct timeval time_timeval = time.ToTimeval();
286 evtimer_add(timeout.release(), &time_timeval);
287}
288
289// Represents a child process. It will take care of restarting itself etc.
290class Child {
291 public:
Brian Silverman5cc661b2013-02-27 15:23:36 -0800292 // command is the (space-separated) command to run and its arguments.
293 Child(const std::string &command) : pid_(-1),
Brian Silvermand169fcd2013-02-27 13:18:47 -0800294 restart_timeout_(
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800295 evtimer_new(libevent_base.get(), StaticDoRestart, this)),
296 stat_at_start_valid_(false) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800297 const char *start, *end;
298 start = command.c_str();
299 while (true) {
300 end = strchrnul(start, ' ');
301 args_.push_back(std::string(start, end - start));
302 start = end + 1;
303 if (*end == '\0') {
304 break;
305 }
306 }
307
Brian Silverman5cc661b2013-02-27 15:23:36 -0800308 original_binary_ = RunCommand("which " + args_[0]);
309 binary_ = original_binary_ + ".stm";
Brian Silvermand169fcd2013-02-27 13:18:47 -0800310
311 watcher_ = unique_ptr<FileWatch>(
Brian Silverman5cc661b2013-02-27 15:23:36 -0800312 new FileWatch(original_binary_, StaticFileModified, this));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800313
314 Start();
315 }
316
317 pid_t pid() { return pid_; }
318
319 // This gets called whenever the actual process dies and should (probably) be
320 // restarted.
321 void ProcessDied() {
322 pid_ = -1;
323 restarts_.push(time::Time::Now());
324 if (restarts_.size() > kMaxRestartsNumber) {
325 time::Time oldest = restarts_.front();
326 restarts_.pop();
327 if ((time::Time::Now() - oldest) > kMaxRestartsTime) {
328 LOG(WARNING, "process %s getting restarted too often\n", name());
329 Timeout(kResumeWait, StaticStart, this);
330 return;
331 }
332 }
333 Start();
334 }
335
336 // Returns a name for logging purposes.
337 const char *name() {
338 return args_[0].c_str();
339 }
340
341 private:
342 struct CheckDiedStatus {
343 Child *self;
344 pid_t old_pid;
345 };
346
347 // How long to wait for a child to die nicely.
348 static const time::Time kProcessDieTime;
349
350 // How long to wait after the file is modified to restart it.
351 // This is important because some programs like modifying the binaries by
352 // writing them in little bits, which results in attempting to start partial
353 // binaries without this.
354 static const time::Time kRestartWaitTime;
355
Brian Silverman5cc661b2013-02-27 15:23:36 -0800356 // Only kMaxRestartsNumber restarts will be allowed in kMaxRestartsTime.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800357 static const time::Time kMaxRestartsTime;
358 static const size_t kMaxRestartsNumber = 5;
359 // How long to wait if it gets restarted too many times.
360 static const time::Time kResumeWait;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800361
Brian Silvermand169fcd2013-02-27 13:18:47 -0800362 static void StaticFileModified(void *self) {
363 static_cast<Child *>(self)->FileModified();
364 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800365
Brian Silvermand169fcd2013-02-27 13:18:47 -0800366 void FileModified() {
367 struct timeval restart_time_timeval = kRestartWaitTime.ToTimeval();
368 // This will reset the timeout again if it hasn't run yet.
369 evtimer_add(restart_timeout_.get(), &restart_time_timeval);
370 }
371
372 static void StaticDoRestart(int, short, void *self) {
373 static_cast<Child *>(self)->DoRestart();
374 }
375
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800376 // Called after somebody else has finished modifying the file.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800377 void DoRestart() {
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800378 if (stat_at_start_valid_) {
379 struct stat current_stat;
380 if (stat(original_binary_.c_str(), &current_stat) == -1) {
381 LOG(FATAL, "stat(%s, %p) failed with %d: %s\n",
382 original_binary_.c_str(), &current_stat, errno, strerror(errno));
383 }
384 if (current_stat.st_mtime == stat_at_start_.st_mtime) {
385 LOG(DEBUG, "ignoring trigger for %s because mtime didn't change\n",
386 name());
387 return;
388 }
389 }
390
Brian Silvermand169fcd2013-02-27 13:18:47 -0800391 if (pid_ != -1) {
392 LOG(DEBUG, "sending SIGTERM to child %d to restart it\n", pid_);
393 if (kill(pid_, SIGTERM) == -1) {
394 LOG(WARNING, "kill(%d, SIGTERM) failed with %d: %s\n",
395 pid_, errno, strerror(errno));
396 }
397 CheckDiedStatus *status = new CheckDiedStatus();
398 status->self = this;
399 status->old_pid = pid_;
400 Timeout(kProcessDieTime, StaticCheckDied, status);
401 }
402 }
403
404 static void StaticCheckDied(int, short, void *status_in) {
405 CheckDiedStatus *status = static_cast<CheckDiedStatus *>(status_in);
406 status->self->CheckDied(status->old_pid);
407 delete status;
408 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800409
410 // Checks to see if the child using the PID old_pid is still running.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800411 void CheckDied(pid_t old_pid) {
412 if (pid_ == old_pid) {
413 LOG(WARNING, "child %d refused to die\n", old_pid);
414 if (kill(old_pid, SIGKILL) == -1) {
415 LOG(WARNING, "kill(%d, SIGKILL) failed with %d: %s\n",
416 old_pid, errno, strerror(errno));
417 }
418 }
419 }
420
421 static void StaticStart(int, short, void *self) {
422 static_cast<Child *>(self)->Start();
423 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800424
425 // Actually starts the child.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800426 void Start() {
427 if (pid_ != -1) {
428 LOG(WARNING, "calling Start() but already have child %d running\n",
429 pid_);
Brian Silverman5cc661b2013-02-27 15:23:36 -0800430 if (kill(pid_, SIGKILL) == -1) {
431 LOG(WARNING, "kill(%d, SIGKILL) failed with %d: %s\n",
432 pid_, errno, strerror(errno));
433 return;
434 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800435 pid_ = -1;
436 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800437
438 // Remove the name that we run from (ie from a previous execution) and then
439 // hard link the real filename to it.
440 if (unlink(binary_.c_str()) != 0 && errno != ENOENT) {
441 LOG(FATAL, "removing %s failed because of %d: %s\n",
442 binary_.c_str(), errno, strerror(errno));
443 }
444 if (link(original_binary_.c_str(), binary_.c_str()) != 0) {
445 LOG(FATAL, "link('%s', '%s') failed because of %d: %s\n",
446 original_binary_.c_str(), binary_.c_str(), errno, strerror(errno));
447 }
448
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800449 if (stat(original_binary_.c_str(), &stat_at_start_) == -1) {
450 LOG(FATAL, "stat(%s, %p) failed with %d: %s\n",
451 original_binary_.c_str(), &stat_at_start_, errno, strerror(errno));
452 }
453 stat_at_start_valid_ = true;
454
Brian Silvermand169fcd2013-02-27 13:18:47 -0800455 if ((pid_ = fork()) == 0) {
456 ssize_t args_size = args_.size();
457 const char **argv = new const char *[args_size + 1];
458 for (int i = 0; i < args_size; ++i) {
459 argv[i] = args_[i].c_str();
460 }
461 argv[args_size] = NULL;
462 // The const_cast is safe because no code that might care if it gets
463 // modified can run afterwards.
464 execv(binary_.c_str(), const_cast<char **>(argv));
465 LOG(FATAL, "execv(%s, %p) failed with %d: %s\n",
466 binary_.c_str(), argv, errno, strerror(errno));
467 _exit(EXIT_FAILURE);
468 }
469 if (pid_ == -1) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800470 LOG(FATAL, "forking to run \"%s\" failed with %d: %s\n",
Brian Silvermand169fcd2013-02-27 13:18:47 -0800471 binary_.c_str(), errno, strerror(errno));
472 }
473 }
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -0800474
475 // A history of the times that this process has been restarted.
476 std::queue<time::Time, std::list<time::Time>> restarts_;
477
478 // The currently running child's PID or NULL.
479 pid_t pid_;
480
481 // All of the arguments (including the name of the binary).
482 std::deque<std::string> args_;
483
484 // The name of the real binary that we were told to run.
485 std::string original_binary_;
486 // The name of the file that we're actually running.
487 std::string binary_;
488
489 // Watches original_binary_.
490 unique_ptr<FileWatch> watcher_;
491
492 // An event that restarts after kRestartWaitTime.
493 EventUniquePtr restart_timeout_;
494
495 // Captured from the original file when we most recently started a new child
496 // process. Used to see if it actually changes or not.
497 struct stat stat_at_start_;
498 bool stat_at_start_valid_;
499
500 DISALLOW_COPY_AND_ASSIGN(Child);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800501};
502const time::Time Child::kProcessDieTime = time::Time::InSeconds(0.5);
503const time::Time Child::kMaxRestartsTime = time::Time::InSeconds(2);
504const time::Time Child::kResumeWait = time::Time::InSeconds(1.5);
505const time::Time Child::kRestartWaitTime = time::Time::InSeconds(1.5);
506
507// This is where all of the Child instances except core live.
508std::vector<unique_ptr<Child>> children;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800509// A global place to hold on to which child is core.
510unique_ptr<Child> core;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800511
Brian Silverman5cc661b2013-02-27 15:23:36 -0800512// Kills off the entire process group (including ourself).
513void KillChildren(bool try_nice) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800514 if (try_nice) {
515 static const int kNiceStopSignal = SIGTERM;
516 static const time::Time kNiceWaitTime = time::Time::InSeconds(1);
517
518 // Make sure that we don't just nicely stop ourself...
519 sigset_t mask;
520 sigemptyset(&mask);
521 sigaddset(&mask, kNiceStopSignal);
522 sigprocmask(SIG_BLOCK, &mask, NULL);
523
Brian Silverman5cc661b2013-02-27 15:23:36 -0800524 kill(-getpid(), kNiceStopSignal);
525
526 fflush(NULL);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800527 time::SleepFor(kNiceWaitTime);
528 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800529
Brian Silvermand169fcd2013-02-27 13:18:47 -0800530 // Send SIGKILL to our whole process group, which will forcibly terminate any
531 // of them that are still running (us for sure, maybe more too).
Brian Silverman5cc661b2013-02-27 15:23:36 -0800532 kill(-getpid(), SIGKILL);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800533}
534
Brian Silverman5cc661b2013-02-27 15:23:36 -0800535void ExitHandler() {
536 KillChildren(true);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800537}
Brian Silverman5cc661b2013-02-27 15:23:36 -0800538
539void KillChildrenSignalHandler(int signum) {
540 // If we get SIGSEGV or some other random signal who knows what's happening
541 // and we should just kill everybody immediately.
542 // This is a list of all of the signals that mean some form of "nicely stop".
543 KillChildren(signum == SIGHUP || signum == SIGINT || signum == SIGQUIT ||
Brian Silvermand169fcd2013-02-27 13:18:47 -0800544 signum == SIGABRT || signum == SIGPIPE || signum == SIGTERM ||
545 signum == SIGXCPU);
546}
547
Brian Silverman5cc661b2013-02-27 15:23:36 -0800548// Returns the currently running child with PID pid or an empty unique_ptr.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800549const unique_ptr<Child> &FindChild(pid_t pid) {
550 for (auto it = children.begin(); it != children.end(); ++it) {
551 if (pid == (*it)->pid()) {
552 return *it;
553 }
554 }
555
556 if (pid == core->pid()) {
557 return core;
558 }
559
Brian Silverman5cc661b2013-02-27 15:23:36 -0800560 static const unique_ptr<Child> kNothing;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800561 return kNothing;
562}
563
Brian Silverman5cc661b2013-02-27 15:23:36 -0800564// Gets set up as a libevent handler for SIGCHLD.
565// Handles calling Child::ProcessDied() on the appropriate one.
566void SigCHLDReceived(int /*fd*/, short /*events*/, void *) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800567 // In a while loop in case we miss any SIGCHLDs.
568 while (true) {
569 siginfo_t infop;
570 infop.si_pid = 0;
571 if (waitid(P_ALL, 0, &infop, WEXITED | WSTOPPED | WNOHANG) != 0) {
572 LOG(WARNING, "waitid failed with %d: %s", errno, strerror(errno));
Brian Silverman5cc661b2013-02-27 15:23:36 -0800573 continue;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800574 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800575 // If there are no more child process deaths to process.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800576 if (infop.si_pid == 0) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800577 return;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800578 }
579
580 pid_t pid = infop.si_pid;
581 int status = infop.si_status;
582 const unique_ptr<Child> &child = FindChild(pid);
583 if (child) {
584 switch (infop.si_code) {
585 case CLD_EXITED:
586 LOG(WARNING, "child %d (%s) exited with status %d\n",
587 pid, child->name(), status);
588 break;
589 case CLD_DUMPED:
590 LOG(INFO, "child %d actually dumped core. "
591 "falling through to killed by signal case\n", pid);
592 case CLD_KILLED:
593 // If somebody (possibly us) sent it SIGTERM that means that they just
594 // want it to stop, so it stopping isn't a WARNING.
595 LOG((status == SIGTERM) ? DEBUG : WARNING,
596 "child %d (%s) was killed by signal %d (%s)\n",
597 pid, child->name(), status,
598 strsignal(status));
599 break;
600 case CLD_STOPPED:
601 LOG(WARNING, "child %d (%s) was stopped by signal %d "
602 "(giving it a SIGCONT(%d))\n",
603 pid, child->name(), status, SIGCONT);
604 kill(pid, SIGCONT);
605 continue;
606 default:
607 LOG(WARNING, "something happened to child %d (%s) (killing it)\n",
608 pid, child->name());
609 kill(pid, SIGKILL);
610 continue;
611 }
612 } else {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800613 LOG(WARNING, "couldn't find a Child for pid %d\n", pid);
614 return;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800615 }
616
Brian Silverman5cc661b2013-02-27 15:23:36 -0800617 if (child == core) {
618 LOG(FATAL, "core died\n");
619 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800620 child->ProcessDied();
621 }
622}
623
Brian Silverman5cc661b2013-02-27 15:23:36 -0800624// This is used for communicating the name of the file to read processes to
625// start from main to Run.
626const char *child_list_file;
627
Brian Silvermand169fcd2013-02-27 13:18:47 -0800628// This is the callback for when core creates the file indicating that it has
629// started.
630void Run(void *watch) {
631 // Make it so it doesn't keep on seeing random changes in /tmp.
632 static_cast<FileWatch *>(watch)->RemoveWatch();
633
634 // It's safe now because core is up.
635 aos::InitNRT();
636
637 std::ifstream list_file(child_list_file);
638
Brian Silvermand169fcd2013-02-27 13:18:47 -0800639 while (true) {
640 std::string child_name;
641 getline(list_file, child_name);
642 if ((list_file.rdstate() & std::ios_base::eofbit) != 0) {
643 break;
644 }
645 if (list_file.rdstate() != 0) {
646 LOG(FATAL, "reading input file %s failed\n", child_list_file);
647 }
648 children.push_back(unique_ptr<Child>(new Child(child_name)));
649 }
650
651 EventUniquePtr sigchld(event_new(libevent_base.get(), SIGCHLD,
Brian Silverman5cc661b2013-02-27 15:23:36 -0800652 EV_SIGNAL | EV_PERSIST,
653 SigCHLDReceived, NULL));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800654 event_add(sigchld.release(), NULL);
655}
656
657void Main() {
658 logging::Init();
659 // TODO(brians) tell logging that using the root logger from here until we
660 // bring up shm is ok
661
Brian Silverman5cc661b2013-02-27 15:23:36 -0800662 if (setpgid(0 /*self*/, 0 /*make PGID the same as PID*/) != 0) {
663 LOG(FATAL, "setpgid(0, 0) failed with %d: %s\n", errno, strerror(errno));
664 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800665
666 // Make sure that we kill all children when we exit.
Brian Silverman5cc661b2013-02-27 15:23:36 -0800667 atexit(ExitHandler);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800668 // Do it on some signals too (ones that we otherwise tend to receive and then
669 // leave all of our children going).
Brian Silverman5cc661b2013-02-27 15:23:36 -0800670 signal(SIGHUP, KillChildrenSignalHandler);
671 signal(SIGINT, KillChildrenSignalHandler);
672 signal(SIGQUIT, KillChildrenSignalHandler);
673 signal(SIGILL, KillChildrenSignalHandler);
674 signal(SIGABRT, KillChildrenSignalHandler);
675 signal(SIGFPE, KillChildrenSignalHandler);
676 signal(SIGSEGV, KillChildrenSignalHandler);
677 signal(SIGPIPE, KillChildrenSignalHandler);
678 signal(SIGTERM, KillChildrenSignalHandler);
679 signal(SIGBUS, KillChildrenSignalHandler);
680 signal(SIGXCPU, KillChildrenSignalHandler);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800681
682 libevent_base = EventBaseUniquePtr(event_base_new());
683
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800684 std::string core_touch_file = "/tmp/starter.";
Brian Silvermand169fcd2013-02-27 13:18:47 -0800685 core_touch_file += std::to_string(static_cast<intmax_t>(getpid()));
686 core_touch_file += ".core_touch_file";
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800687 if (system(("touch '" + core_touch_file + "'").c_str()) != 0) {
688 LOG(FATAL, "running `touch '%s'` failed\n", core_touch_file.c_str());
689 }
690 FileWatch core_touch_file_watch(core_touch_file, Run, NULL);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800691 core = unique_ptr<Child>(
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800692 new Child("core " + core_touch_file));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800693
694 FILE *pid_file = fopen("/tmp/starter.pid", "w");
695 if (pid_file == NULL) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800696 LOG(FATAL, "fopen(\"/tmp/starter.pid\", \"w\") failed with %d: %s\n",
Brian Silvermand169fcd2013-02-27 13:18:47 -0800697 errno, strerror(errno));
698 } else {
699 if (fprintf(pid_file, "%d", core->pid()) == -1) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800700 LOG(WARNING, "fprintf(%p, \"%%d\", %d) failed with %d: %s\n",
701 pid_file, core->pid(), errno, strerror(errno));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800702 }
703 fclose(pid_file);
704 }
705
706 LOG(INFO, "waiting for %s to appear\n", core_touch_file.c_str());
707
708 event_base_dispatch(libevent_base.get());
709 LOG(FATAL, "event_base_dispatch(%p) returned\n", libevent_base.get());
710}
711
712} // namespace starter
713} // namespace aos
714
715int main(int argc, char *argv[]) {
716 if (argc < 2) {
717 fputs("starter: error: need an argument specifying what file to use\n",
718 stderr);
719 exit(EXIT_FAILURE);
720 } else if(argc > 2) {
721 fputs("starter: warning: too many arguments\n", stderr);
722 }
723 aos::starter::child_list_file = argv[1];
724
725 aos::starter::Main();
726}