blob: c9d4c579622fa3f2a1fdd01af78d937f8571d537 [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 Silverman5cc661b2013-02-27 15:23:36 -080037// NOTE: This program should never exit nicely. It catches all nice attempts to
38// exit, forwards them to all of the children that it has started, waits for
Brian Silvermand169fcd2013-02-27 13:18:47 -080039// them to exit nicely, and then SIGKILLs anybody left (which will always
40// include itself).
41
42using ::std::unique_ptr;
43
44namespace aos {
45namespace starter {
46
Brian Silvermand169fcd2013-02-27 13:18:47 -080047class EventBaseDeleter {
48 public:
49 void operator()(event_base *base) {
Brian Silvermand169fcd2013-02-27 13:18:47 -080050 event_base_free(base);
51 }
52};
53typedef unique_ptr<event_base, EventBaseDeleter> EventBaseUniquePtr;
Brian Silverman5cc661b2013-02-27 15:23:36 -080054EventBaseUniquePtr libevent_base;
Brian Silvermand169fcd2013-02-27 13:18:47 -080055
56class EventDeleter {
57 public:
58 void operator()(event *evt) {
Brian Silvermand169fcd2013-02-27 13:18:47 -080059 if (event_del(evt) != 0) {
60 LOG(WARNING, "event_del(%p) failed\n", evt);
61 }
62 }
63};
64typedef unique_ptr<event, EventDeleter> EventUniquePtr;
65
Brian Silverman5cc661b2013-02-27 15:23:36 -080066// Watches a file path for modifications. Once created, keeps watching until
67// destroyed or RemoveWatch() is called.
Brian Silvermand169fcd2013-02-27 13:18:47 -080068class FileWatch {
69 public:
70 // Will call callback(value) when filename is modified.
71 // If value is NULL, then a pointer to this object will be passed instead.
Brian Silverman5cc661b2013-02-27 15:23:36 -080072 //
73 // Watching for file creations is slightly different. To do that, pass true
74 // for create, the directory where the file will be created for filename, and
75 // the name of the file (without directory name) for check_filename.
Brian Silvermand169fcd2013-02-27 13:18:47 -080076 FileWatch(std::string filename,
77 std::function<void(void *)> callback, void *value,
78 bool create = false, std::string check_filename = "")
79 : filename_(filename), callback_(callback), value_(value),
80 check_filename_(check_filename) {
Brian Silverman5cc661b2013-02-27 15:23:36 -080081 init_once.Get();
82
Brian Silvermand169fcd2013-02-27 13:18:47 -080083 watch_ = inotify_add_watch(notify_fd, filename.c_str(),
84 create ? IN_CREATE : (IN_ATTRIB | IN_MODIFY));
85 if (watch_ == -1) {
Brian Silverman5cc661b2013-02-27 15:23:36 -080086 LOG(FATAL, "inotify_add_watch(%d, %s,"
87 " %s ? IN_CREATE : (IN_ATTRIB | IN_MODIFY)) failed with %d: %s\n",
88 notify_fd, filename.c_str(), create ? "true" : "false",
89 errno, strerror(errno));
Brian Silvermand169fcd2013-02-27 13:18:47 -080090 }
91 watchers[watch_] = this;
92 }
93 // Cleans up everything.
94 ~FileWatch() {
95 if (watch_ != -1) {
96 RemoveWatch();
97 }
98 }
99
100 // After calling this method, this object won't really be doing much of
Brian Silverman5cc661b2013-02-27 15:23:36 -0800101 // anything besides possibly running its callback or something.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800102 void RemoveWatch() {
103 assert(watch_ != -1);
Brian Silverman5cc661b2013-02-27 15:23:36 -0800104
Brian Silvermand169fcd2013-02-27 13:18:47 -0800105 if (inotify_rm_watch(notify_fd, watch_) == -1) {
106 LOG(WARNING, "inotify_rm_watch(%d, %d) failed with %d: %s\n",
107 notify_fd, watch_, errno, strerror(errno));
108 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800109
Brian Silvermand169fcd2013-02-27 13:18:47 -0800110 if (watchers[watch_] != this) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800111 LOG(WARNING, "watcher for %s (%p) didn't find itself in the map\n",
112 filename_.c_str(), this);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800113 } else {
114 watchers.erase(watch_);
115 }
116 watch_ = -1;
117 }
118
Brian Silverman5cc661b2013-02-27 15:23:36 -0800119 private:
120 // Performs the static initialization. Called by init_once from the
121 // constructor.
122 static void *Init() {
123 notify_fd = inotify_init1(IN_CLOEXEC);
124 EventUniquePtr notify_event(event_new(libevent_base.get(), notify_fd,
125 EV_READ | EV_PERSIST,
126 FileWatch::INotifyReadable, NULL));
127 event_add(notify_event.release(), NULL);
128 return NULL;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800129 }
130
131 // This gets set up as the callback for EV_READ on the inotify file
Brian Silverman5cc661b2013-02-27 15:23:36 -0800132 // descriptor. It calls FileNotified on the appropriate instance.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800133 static void INotifyReadable(int /*fd*/, short /*events*/, void *) {
134 unsigned int to_read;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800135 // Use FIONREAD to figure out how many bytes there are to read.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800136 if (ioctl(notify_fd, FIONREAD, &to_read) < 0) {
137 LOG(FATAL, "FIONREAD(%d, %p) failed with %d: %s\n",
138 notify_fd, &to_read, errno, strerror(errno));
139 }
140 inotify_event *notifyevt = static_cast<inotify_event *>(malloc(to_read));
141 const char *end = reinterpret_cast<char *>(notifyevt) + to_read;
142 aos::unique_c_ptr<inotify_event> freer(notifyevt);
143
144 ssize_t ret = read(notify_fd, notifyevt, to_read);
145 if (ret < 0) {
146 LOG(FATAL, "read(%d, %p, %u) failed with %d: %s\n",
147 notify_fd, notifyevt, to_read, errno, strerror(errno));
148 }
149 if (static_cast<size_t>(ret) != to_read) {
150 LOG(ERROR, "read(%d, %p, %u) returned %zd instead of %u\n",
151 notify_fd, notifyevt, to_read, ret, to_read);
152 return;
153 }
154
Brian Silverman5cc661b2013-02-27 15:23:36 -0800155 // Keep looping through until we get to the end because inotify does return
156 // multiple events at once.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800157 while (true) {
158 if (watchers.count(notifyevt->wd) != 1) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800159 LOG(DEBUG, "couldn't find whose watch ID %d is\n", notifyevt->wd);
160 continue;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800161 }
162 watchers[notifyevt->wd]->FileNotified((notifyevt->len > 0) ?
163 notifyevt->name : NULL);
164
165 notifyevt = reinterpret_cast<inotify_event *>(
166 reinterpret_cast<char *>(notifyevt) +
167 sizeof(*notifyevt) + notifyevt->len);
168 if (reinterpret_cast<char *>(notifyevt) >= end) break;
169 }
170 }
171
Brian Silverman5cc661b2013-02-27 15:23:36 -0800172 // INotifyReadable calls this method whenever the watch for our file triggers.
173 void FileNotified(const char *filename) {
174 assert(watch_ != -1);
175
176 if (!check_filename_.empty()) {
177 if (filename == NULL) {
178 return;
179 }
180 if (std::string(filename) != check_filename_) {
181 return;
182 }
183 }
184
185 callback_((value_ == NULL) ? this : value_);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800186 }
187
Brian Silverman5cc661b2013-02-27 15:23:36 -0800188 // To make sure that Init gets called exactly once.
189 static ::aos::Once<void> init_once;
190
Brian Silvermand169fcd2013-02-27 13:18:47 -0800191 const std::string filename_;
192 const std::function<void(void *)> callback_;
193 void *const value_;
194 std::string check_filename_;
195
196 // The watch descriptor or -1 if we don't have one any more.
197 int watch_;
198
Brian Silverman5cc661b2013-02-27 15:23:36 -0800199 // Map from watch IDs to instances.
200 // <https://patchwork.kernel.org/patch/73192/> says they won't get reused, but
201 // that shouldn't be counted on because we might have a
202 // modified/different version/whatever kernel.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800203 static std::map<int, FileWatch *> watchers;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800204 // The inotify(7) file descriptor.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800205 static int notify_fd;
206};
Brian Silverman5cc661b2013-02-27 15:23:36 -0800207::aos::Once<void> FileWatch::init_once(FileWatch::Init);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800208std::map<int, FileWatch *> FileWatch::watchers;
209int FileWatch::notify_fd;
210
Brian Silverman5cc661b2013-02-27 15:23:36 -0800211// Runs the given command and returns its first line of output (not including
212// the \n). LOG(FATAL)s if the command has an exit status other than 0 or does
213// not print out an entire line.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800214std::string RunCommand(std::string command) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800215 // popen(3) might fail and not set it.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800216 errno = 0;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800217 FILE *pipe = popen(command.c_str(), "r");
218 if (pipe == NULL) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800219 LOG(FATAL, "popen(\"%s\", \"r\") failed with %d: %s\n",
220 command.c_str(), errno, strerror(errno));
221 }
222
Brian Silverman5cc661b2013-02-27 15:23:36 -0800223 // result_size is how many bytes result is currently allocated to.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800224 size_t result_size = 128, read = 0;
225 unique_c_ptr<char> result(static_cast<char *>(malloc(result_size)));
226 while (true) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800227 // If we filled up the buffer, then realloc(3) it bigger.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800228 if (read == result_size) {
229 result_size *= 2;
230 void *new_result = realloc(result.get(), result_size);
231 if (new_result == NULL) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800232 LOG(FATAL, "realloc(%p, %zd) failed because of %d: %s\n",
233 result.get(), result_size, errno, strerror(errno));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800234 } else {
235 result.release();
236 result = unique_c_ptr<char>(static_cast<char *>(new_result));
237 }
238 }
239
Brian Silverman5cc661b2013-02-27 15:23:36 -0800240 size_t ret = fread(result.get() + read, 1, result_size - read, pipe);
241 // If the read didn't fill up the whole buffer, check to see if it was
242 // because of an error.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800243 if (ret < result_size - read) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800244 if (ferror(pipe)) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800245 LOG(FATAL, "couldn't finish reading output of \"%s\"\n",
246 command.c_str());
247 }
248 }
249 read += ret;
250 if (read > 0 && result.get()[read - 1] == '\n') {
251 break;
252 }
253
Brian Silverman5cc661b2013-02-27 15:23:36 -0800254 if (feof(pipe)) {
255 LOG(FATAL, "`%s` failed. didn't print a whole line\n", command.c_str());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800256 }
257 }
258
Brian Silverman5cc661b2013-02-27 15:23:36 -0800259 // Get rid of the first \n and anything after it.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800260 *strchrnul(result.get(), '\n') = '\0';
261
Brian Silverman5cc661b2013-02-27 15:23:36 -0800262 int child_status = pclose(pipe);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800263 if (child_status == -1) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800264 LOG(FATAL, "pclose(%p) failed with %d: %s\n", pipe,
Brian Silvermand169fcd2013-02-27 13:18:47 -0800265 errno, strerror(errno));
266 }
267
268 if (child_status != 0) {
269 LOG(FATAL, "`%s` failed. return %d\n", command.c_str(), child_status);
270 }
271
272 return std::string(result.get());
273}
274
275// Will call callback(arg) after time.
276void Timeout(time::Time time, void (*callback)(int, short, void *), void *arg) {
277 EventUniquePtr timeout(evtimer_new(libevent_base.get(), callback, arg));
278 struct timeval time_timeval = time.ToTimeval();
279 evtimer_add(timeout.release(), &time_timeval);
280}
281
282// Represents a child process. It will take care of restarting itself etc.
283class Child {
284 public:
Brian Silverman5cc661b2013-02-27 15:23:36 -0800285 // command is the (space-separated) command to run and its arguments.
286 Child(const std::string &command) : pid_(-1),
Brian Silvermand169fcd2013-02-27 13:18:47 -0800287 restart_timeout_(
288 evtimer_new(libevent_base.get(), StaticDoRestart, this)) {
289 const char *start, *end;
290 start = command.c_str();
291 while (true) {
292 end = strchrnul(start, ' ');
293 args_.push_back(std::string(start, end - start));
294 start = end + 1;
295 if (*end == '\0') {
296 break;
297 }
298 }
299
Brian Silverman5cc661b2013-02-27 15:23:36 -0800300 original_binary_ = RunCommand("which " + args_[0]);
301 binary_ = original_binary_ + ".stm";
Brian Silvermand169fcd2013-02-27 13:18:47 -0800302
303 watcher_ = unique_ptr<FileWatch>(
Brian Silverman5cc661b2013-02-27 15:23:36 -0800304 new FileWatch(original_binary_, StaticFileModified, this));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800305
306 Start();
307 }
308
309 pid_t pid() { return pid_; }
310
311 // This gets called whenever the actual process dies and should (probably) be
312 // restarted.
313 void ProcessDied() {
314 pid_ = -1;
315 restarts_.push(time::Time::Now());
316 if (restarts_.size() > kMaxRestartsNumber) {
317 time::Time oldest = restarts_.front();
318 restarts_.pop();
319 if ((time::Time::Now() - oldest) > kMaxRestartsTime) {
320 LOG(WARNING, "process %s getting restarted too often\n", name());
321 Timeout(kResumeWait, StaticStart, this);
322 return;
323 }
324 }
325 Start();
326 }
327
328 // Returns a name for logging purposes.
329 const char *name() {
330 return args_[0].c_str();
331 }
332
333 private:
334 struct CheckDiedStatus {
335 Child *self;
336 pid_t old_pid;
337 };
338
339 // How long to wait for a child to die nicely.
340 static const time::Time kProcessDieTime;
341
342 // How long to wait after the file is modified to restart it.
343 // This is important because some programs like modifying the binaries by
344 // writing them in little bits, which results in attempting to start partial
345 // binaries without this.
346 static const time::Time kRestartWaitTime;
347
Brian Silverman5cc661b2013-02-27 15:23:36 -0800348 // Only kMaxRestartsNumber restarts will be allowed in kMaxRestartsTime.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800349 static const time::Time kMaxRestartsTime;
350 static const size_t kMaxRestartsNumber = 5;
351 // How long to wait if it gets restarted too many times.
352 static const time::Time kResumeWait;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800353
Brian Silvermand169fcd2013-02-27 13:18:47 -0800354 // A history of the times that this process has been restarted.
355 std::queue<time::Time, std::list<time::Time>> restarts_;
356
Brian Silverman5cc661b2013-02-27 15:23:36 -0800357 // The currently running child's PID or NULL.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800358 pid_t pid_;
359
Brian Silverman5cc661b2013-02-27 15:23:36 -0800360 // All of the arguments (including the name of the binary).
Brian Silvermand169fcd2013-02-27 13:18:47 -0800361 std::deque<std::string> args_;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800362
363 // The name of the real binary that we were told to run.
364 std::string original_binary_;
365 // The name of the file that we're actually running.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800366 std::string binary_;
367
Brian Silverman5cc661b2013-02-27 15:23:36 -0800368 // Watches original_binary_.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800369 unique_ptr<FileWatch> watcher_;
370
371 // An event that restarts after kRestartWaitTime.
372 EventUniquePtr restart_timeout_;
373
374 static void StaticFileModified(void *self) {
375 static_cast<Child *>(self)->FileModified();
376 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800377
Brian Silvermand169fcd2013-02-27 13:18:47 -0800378 void FileModified() {
379 struct timeval restart_time_timeval = kRestartWaitTime.ToTimeval();
380 // This will reset the timeout again if it hasn't run yet.
381 evtimer_add(restart_timeout_.get(), &restart_time_timeval);
382 }
383
384 static void StaticDoRestart(int, short, void *self) {
385 static_cast<Child *>(self)->DoRestart();
386 }
387
Brian Silverman5cc661b2013-02-27 15:23:36 -0800388 // Actually kills the current child to start the process of starting up a new
389 // one.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800390 void DoRestart() {
391 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 Silvermand169fcd2013-02-27 13:18:47 -0800449 if ((pid_ = fork()) == 0) {
450 ssize_t args_size = args_.size();
451 const char **argv = new const char *[args_size + 1];
452 for (int i = 0; i < args_size; ++i) {
453 argv[i] = args_[i].c_str();
454 }
455 argv[args_size] = NULL;
456 // The const_cast is safe because no code that might care if it gets
457 // modified can run afterwards.
458 execv(binary_.c_str(), const_cast<char **>(argv));
459 LOG(FATAL, "execv(%s, %p) failed with %d: %s\n",
460 binary_.c_str(), argv, errno, strerror(errno));
461 _exit(EXIT_FAILURE);
462 }
463 if (pid_ == -1) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800464 LOG(FATAL, "forking to run \"%s\" failed with %d: %s\n",
Brian Silvermand169fcd2013-02-27 13:18:47 -0800465 binary_.c_str(), errno, strerror(errno));
466 }
467 }
468};
469const time::Time Child::kProcessDieTime = time::Time::InSeconds(0.5);
470const time::Time Child::kMaxRestartsTime = time::Time::InSeconds(2);
471const time::Time Child::kResumeWait = time::Time::InSeconds(1.5);
472const time::Time Child::kRestartWaitTime = time::Time::InSeconds(1.5);
473
474// This is where all of the Child instances except core live.
475std::vector<unique_ptr<Child>> children;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800476// A global place to hold on to which child is core.
477unique_ptr<Child> core;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800478
Brian Silverman5cc661b2013-02-27 15:23:36 -0800479// Kills off the entire process group (including ourself).
480void KillChildren(bool try_nice) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800481 if (try_nice) {
482 static const int kNiceStopSignal = SIGTERM;
483 static const time::Time kNiceWaitTime = time::Time::InSeconds(1);
484
485 // Make sure that we don't just nicely stop ourself...
486 sigset_t mask;
487 sigemptyset(&mask);
488 sigaddset(&mask, kNiceStopSignal);
489 sigprocmask(SIG_BLOCK, &mask, NULL);
490
Brian Silverman5cc661b2013-02-27 15:23:36 -0800491 kill(-getpid(), kNiceStopSignal);
492
493 fflush(NULL);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800494 time::SleepFor(kNiceWaitTime);
495 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800496
Brian Silvermand169fcd2013-02-27 13:18:47 -0800497 // Send SIGKILL to our whole process group, which will forcibly terminate any
498 // of them that are still running (us for sure, maybe more too).
Brian Silverman5cc661b2013-02-27 15:23:36 -0800499 kill(-getpid(), SIGKILL);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800500}
501
Brian Silverman5cc661b2013-02-27 15:23:36 -0800502void ExitHandler() {
503 KillChildren(true);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800504}
Brian Silverman5cc661b2013-02-27 15:23:36 -0800505
506void KillChildrenSignalHandler(int signum) {
507 // If we get SIGSEGV or some other random signal who knows what's happening
508 // and we should just kill everybody immediately.
509 // This is a list of all of the signals that mean some form of "nicely stop".
510 KillChildren(signum == SIGHUP || signum == SIGINT || signum == SIGQUIT ||
Brian Silvermand169fcd2013-02-27 13:18:47 -0800511 signum == SIGABRT || signum == SIGPIPE || signum == SIGTERM ||
512 signum == SIGXCPU);
513}
514
Brian Silverman5cc661b2013-02-27 15:23:36 -0800515// Returns the currently running child with PID pid or an empty unique_ptr.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800516const unique_ptr<Child> &FindChild(pid_t pid) {
517 for (auto it = children.begin(); it != children.end(); ++it) {
518 if (pid == (*it)->pid()) {
519 return *it;
520 }
521 }
522
523 if (pid == core->pid()) {
524 return core;
525 }
526
Brian Silverman5cc661b2013-02-27 15:23:36 -0800527 static const unique_ptr<Child> kNothing;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800528 return kNothing;
529}
530
Brian Silverman5cc661b2013-02-27 15:23:36 -0800531// Gets set up as a libevent handler for SIGCHLD.
532// Handles calling Child::ProcessDied() on the appropriate one.
533void SigCHLDReceived(int /*fd*/, short /*events*/, void *) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800534 // In a while loop in case we miss any SIGCHLDs.
535 while (true) {
536 siginfo_t infop;
537 infop.si_pid = 0;
538 if (waitid(P_ALL, 0, &infop, WEXITED | WSTOPPED | WNOHANG) != 0) {
539 LOG(WARNING, "waitid failed with %d: %s", errno, strerror(errno));
Brian Silverman5cc661b2013-02-27 15:23:36 -0800540 continue;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800541 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800542 // If there are no more child process deaths to process.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800543 if (infop.si_pid == 0) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800544 return;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800545 }
546
547 pid_t pid = infop.si_pid;
548 int status = infop.si_status;
549 const unique_ptr<Child> &child = FindChild(pid);
550 if (child) {
551 switch (infop.si_code) {
552 case CLD_EXITED:
553 LOG(WARNING, "child %d (%s) exited with status %d\n",
554 pid, child->name(), status);
555 break;
556 case CLD_DUMPED:
557 LOG(INFO, "child %d actually dumped core. "
558 "falling through to killed by signal case\n", pid);
559 case CLD_KILLED:
560 // If somebody (possibly us) sent it SIGTERM that means that they just
561 // want it to stop, so it stopping isn't a WARNING.
562 LOG((status == SIGTERM) ? DEBUG : WARNING,
563 "child %d (%s) was killed by signal %d (%s)\n",
564 pid, child->name(), status,
565 strsignal(status));
566 break;
567 case CLD_STOPPED:
568 LOG(WARNING, "child %d (%s) was stopped by signal %d "
569 "(giving it a SIGCONT(%d))\n",
570 pid, child->name(), status, SIGCONT);
571 kill(pid, SIGCONT);
572 continue;
573 default:
574 LOG(WARNING, "something happened to child %d (%s) (killing it)\n",
575 pid, child->name());
576 kill(pid, SIGKILL);
577 continue;
578 }
579 } else {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800580 LOG(WARNING, "couldn't find a Child for pid %d\n", pid);
581 return;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800582 }
583
Brian Silverman5cc661b2013-02-27 15:23:36 -0800584 if (child == core) {
585 LOG(FATAL, "core died\n");
586 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800587 child->ProcessDied();
588 }
589}
590
Brian Silverman5cc661b2013-02-27 15:23:36 -0800591// This is used for communicating the name of the file to read processes to
592// start from main to Run.
593const char *child_list_file;
594
Brian Silvermand169fcd2013-02-27 13:18:47 -0800595// This is the callback for when core creates the file indicating that it has
596// started.
597void Run(void *watch) {
598 // Make it so it doesn't keep on seeing random changes in /tmp.
599 static_cast<FileWatch *>(watch)->RemoveWatch();
600
601 // It's safe now because core is up.
602 aos::InitNRT();
603
604 std::ifstream list_file(child_list_file);
605
Brian Silvermand169fcd2013-02-27 13:18:47 -0800606 while (true) {
607 std::string child_name;
608 getline(list_file, child_name);
609 if ((list_file.rdstate() & std::ios_base::eofbit) != 0) {
610 break;
611 }
612 if (list_file.rdstate() != 0) {
613 LOG(FATAL, "reading input file %s failed\n", child_list_file);
614 }
615 children.push_back(unique_ptr<Child>(new Child(child_name)));
616 }
617
618 EventUniquePtr sigchld(event_new(libevent_base.get(), SIGCHLD,
Brian Silverman5cc661b2013-02-27 15:23:36 -0800619 EV_SIGNAL | EV_PERSIST,
620 SigCHLDReceived, NULL));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800621 event_add(sigchld.release(), NULL);
622}
623
624void Main() {
625 logging::Init();
626 // TODO(brians) tell logging that using the root logger from here until we
627 // bring up shm is ok
628
Brian Silverman5cc661b2013-02-27 15:23:36 -0800629 if (setpgid(0 /*self*/, 0 /*make PGID the same as PID*/) != 0) {
630 LOG(FATAL, "setpgid(0, 0) failed with %d: %s\n", errno, strerror(errno));
631 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800632
633 // Make sure that we kill all children when we exit.
Brian Silverman5cc661b2013-02-27 15:23:36 -0800634 atexit(ExitHandler);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800635 // Do it on some signals too (ones that we otherwise tend to receive and then
636 // leave all of our children going).
Brian Silverman5cc661b2013-02-27 15:23:36 -0800637 signal(SIGHUP, KillChildrenSignalHandler);
638 signal(SIGINT, KillChildrenSignalHandler);
639 signal(SIGQUIT, KillChildrenSignalHandler);
640 signal(SIGILL, KillChildrenSignalHandler);
641 signal(SIGABRT, KillChildrenSignalHandler);
642 signal(SIGFPE, KillChildrenSignalHandler);
643 signal(SIGSEGV, KillChildrenSignalHandler);
644 signal(SIGPIPE, KillChildrenSignalHandler);
645 signal(SIGTERM, KillChildrenSignalHandler);
646 signal(SIGBUS, KillChildrenSignalHandler);
647 signal(SIGXCPU, KillChildrenSignalHandler);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800648
649 libevent_base = EventBaseUniquePtr(event_base_new());
650
Brian Silvermand169fcd2013-02-27 13:18:47 -0800651 static const std::string kCoreTouchFileDir = "/tmp/";
652 std::string core_touch_file = "starter.";
653 core_touch_file += std::to_string(static_cast<intmax_t>(getpid()));
654 core_touch_file += ".core_touch_file";
655 FileWatch core_touch_file_watch(kCoreTouchFileDir, Run, NULL, true,
656 core_touch_file);
657 core = unique_ptr<Child>(
658 new Child("core " + kCoreTouchFileDir + core_touch_file));
659
660 FILE *pid_file = fopen("/tmp/starter.pid", "w");
661 if (pid_file == NULL) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800662 LOG(FATAL, "fopen(\"/tmp/starter.pid\", \"w\") failed with %d: %s\n",
Brian Silvermand169fcd2013-02-27 13:18:47 -0800663 errno, strerror(errno));
664 } else {
665 if (fprintf(pid_file, "%d", core->pid()) == -1) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800666 LOG(WARNING, "fprintf(%p, \"%%d\", %d) failed with %d: %s\n",
667 pid_file, core->pid(), errno, strerror(errno));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800668 }
669 fclose(pid_file);
670 }
671
672 LOG(INFO, "waiting for %s to appear\n", core_touch_file.c_str());
673
674 event_base_dispatch(libevent_base.get());
675 LOG(FATAL, "event_base_dispatch(%p) returned\n", libevent_base.get());
676}
677
678} // namespace starter
679} // namespace aos
680
681int main(int argc, char *argv[]) {
682 if (argc < 2) {
683 fputs("starter: error: need an argument specifying what file to use\n",
684 stderr);
685 exit(EXIT_FAILURE);
686 } else if(argc > 2) {
687 fputs("starter: warning: too many arguments\n", stderr);
688 }
689 aos::starter::child_list_file = argv[1];
690
691 aos::starter::Main();
692}