blob: 8f8a65dbe60f4ce4605f74f25e1c2f7f1993ccdf [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>
Brian Silvermand90b5fe2013-03-10 18:34:42 -070014#include <inttypes.h>
Brian Silvermand169fcd2013-02-27 13:18:47 -080015
16#include <map>
17#include <functional>
18#include <deque>
19#include <fstream>
20#include <queue>
21#include <list>
22#include <string>
23#include <vector>
24#include <memory>
25
26#include <event2/event.h>
27
28#include "aos/common/logging/logging.h"
29#include "aos/common/logging/logging_impl.h"
30#include "aos/atom_code/init.h"
31#include "aos/common/unique_malloc_ptr.h"
32#include "aos/common/time.h"
Brian Silverman5cc661b2013-02-27 15:23:36 -080033#include "aos/common/once.h"
Brian Silvermand169fcd2013-02-27 13:18:47 -080034
35// This is the main piece of code that starts all of the rest of the code and
36// restarts it when the binaries are modified.
37//
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -080038// Throughout, the code is not terribly concerned with thread safety because
39// there is only 1 thread. It does some setup and then lets inotify run things
40// when appropriate.
41//
Brian Silverman5cc661b2013-02-27 15:23:36 -080042// NOTE: This program should never exit nicely. It catches all nice attempts to
43// exit, forwards them to all of the children that it has started, waits for
Brian Silvermand169fcd2013-02-27 13:18:47 -080044// them to exit nicely, and then SIGKILLs anybody left (which will always
45// include itself).
46
47using ::std::unique_ptr;
48
49namespace aos {
50namespace starter {
51
Brian Silverman0eec9532013-02-27 20:24:16 -080052// TODO(brians): split out the c++ libevent wrapper stuff into its own file(s)
Brian Silvermand169fcd2013-02-27 13:18:47 -080053class EventBaseDeleter {
54 public:
55 void operator()(event_base *base) {
Brian Silverman8070a222013-02-28 15:01:36 -080056 if (base == NULL) return;
Brian Silvermand169fcd2013-02-27 13:18:47 -080057 event_base_free(base);
58 }
59};
60typedef unique_ptr<event_base, EventBaseDeleter> EventBaseUniquePtr;
Brian Silverman5cc661b2013-02-27 15:23:36 -080061EventBaseUniquePtr libevent_base;
Brian Silvermand169fcd2013-02-27 13:18:47 -080062
63class EventDeleter {
64 public:
65 void operator()(event *evt) {
Brian Silverman8070a222013-02-28 15:01:36 -080066 if (evt == NULL) return;
Brian Silvermand169fcd2013-02-27 13:18:47 -080067 if (event_del(evt) != 0) {
68 LOG(WARNING, "event_del(%p) failed\n", evt);
69 }
70 }
71};
72typedef unique_ptr<event, EventDeleter> EventUniquePtr;
73
Brian Silverman5cc661b2013-02-27 15:23:36 -080074// Watches a file path for modifications. Once created, keeps watching until
75// destroyed or RemoveWatch() is called.
Brian Silverman0eec9532013-02-27 20:24:16 -080076// TODO(brians): split this out into its own file + tests
Brian Silvermand169fcd2013-02-27 13:18:47 -080077class FileWatch {
78 public:
79 // Will call callback(value) when filename is modified.
80 // If value is NULL, then a pointer to this object will be passed instead.
Brian Silverman5cc661b2013-02-27 15:23:36 -080081 //
82 // Watching for file creations is slightly different. To do that, pass true
Brian Silverman8070a222013-02-28 15:01:36 -080083 // as create, the directory where the file will be created for filename, and
Brian Silverman5cc661b2013-02-27 15:23:36 -080084 // the name of the file (without directory name) for check_filename.
Brian Silvermand169fcd2013-02-27 13:18:47 -080085 FileWatch(std::string filename,
Brian Silverman8070a222013-02-28 15:01:36 -080086 std::function<void(void *)> callback,
87 void *value,
88 bool create = false,
89 std::string check_filename = "")
90 : filename_(filename),
91 callback_(callback),
92 value_(value),
Brian Silvermand90b5fe2013-03-10 18:34:42 -070093 create_(create),
94 check_filename_(check_filename),
95 watch_(-1) {
Brian Silverman5cc661b2013-02-27 15:23:36 -080096 init_once.Get();
97
Brian Silvermand90b5fe2013-03-10 18:34:42 -070098 CreateWatch();
Brian Silvermand169fcd2013-02-27 13:18:47 -080099 }
100 // Cleans up everything.
101 ~FileWatch() {
102 if (watch_ != -1) {
103 RemoveWatch();
104 }
105 }
106
107 // After calling this method, this object won't really be doing much of
Brian Silverman5cc661b2013-02-27 15:23:36 -0800108 // anything besides possibly running its callback or something.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800109 void RemoveWatch() {
110 assert(watch_ != -1);
Brian Silverman5cc661b2013-02-27 15:23:36 -0800111
Brian Silvermand169fcd2013-02-27 13:18:47 -0800112 if (inotify_rm_watch(notify_fd, watch_) == -1) {
113 LOG(WARNING, "inotify_rm_watch(%d, %d) failed with %d: %s\n",
114 notify_fd, watch_, errno, strerror(errno));
115 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800116
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700117 RemoveWatchFromMap();
Brian Silvermand169fcd2013-02-27 13:18:47 -0800118 }
119
Brian Silverman5cc661b2013-02-27 15:23:36 -0800120 private:
121 // Performs the static initialization. Called by init_once from the
122 // constructor.
123 static void *Init() {
124 notify_fd = inotify_init1(IN_CLOEXEC);
125 EventUniquePtr notify_event(event_new(libevent_base.get(), notify_fd,
126 EV_READ | EV_PERSIST,
127 FileWatch::INotifyReadable, NULL));
128 event_add(notify_event.release(), NULL);
129 return NULL;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800130 }
131
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700132 void RemoveWatchFromMap() {
133 if (watchers[watch_] != this) {
134 LOG(WARNING, "watcher for %s (%p) didn't find itself in the map\n",
135 filename_.c_str(), this);
136 } else {
137 watchers.erase(watch_);
138 }
139 LOG(DEBUG, "removed watch ID %d\n", watch_);
140 watch_ = -1;
141 }
142
143 void CreateWatch() {
144 assert(watch_ == -1);
145 watch_ = inotify_add_watch(notify_fd, filename_.c_str(),
146 create_ ? IN_CREATE : (IN_ATTRIB |
147 IN_MODIFY |
148 IN_DELETE_SELF |
149 IN_MOVE_SELF));
150 if (watch_ == -1) {
151 LOG(FATAL, "inotify_add_watch(%d, %s,"
152 " %s ? IN_CREATE : (IN_ATTRIB | IN_MODIFY)) failed with %d: %s\n",
153 notify_fd, filename_.c_str(), create_ ? "true" : "false",
154 errno, strerror(errno));
155 }
156 watchers[watch_] = this;
157 LOG(DEBUG, "watch for %s is %d\n", filename_.c_str(), watch_);
158 }
159
Brian Silvermand169fcd2013-02-27 13:18:47 -0800160 // This gets set up as the callback for EV_READ on the inotify file
Brian Silverman5cc661b2013-02-27 15:23:36 -0800161 // descriptor. It calls FileNotified on the appropriate instance.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800162 static void INotifyReadable(int /*fd*/, short /*events*/, void *) {
163 unsigned int to_read;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800164 // Use FIONREAD to figure out how many bytes there are to read.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800165 if (ioctl(notify_fd, FIONREAD, &to_read) < 0) {
166 LOG(FATAL, "FIONREAD(%d, %p) failed with %d: %s\n",
167 notify_fd, &to_read, errno, strerror(errno));
168 }
169 inotify_event *notifyevt = static_cast<inotify_event *>(malloc(to_read));
170 const char *end = reinterpret_cast<char *>(notifyevt) + to_read;
171 aos::unique_c_ptr<inotify_event> freer(notifyevt);
172
173 ssize_t ret = read(notify_fd, notifyevt, to_read);
174 if (ret < 0) {
175 LOG(FATAL, "read(%d, %p, %u) failed with %d: %s\n",
176 notify_fd, notifyevt, to_read, errno, strerror(errno));
177 }
178 if (static_cast<size_t>(ret) != to_read) {
179 LOG(ERROR, "read(%d, %p, %u) returned %zd instead of %u\n",
180 notify_fd, notifyevt, to_read, ret, to_read);
181 return;
182 }
183
Brian Silverman5cc661b2013-02-27 15:23:36 -0800184 // Keep looping through until we get to the end because inotify does return
185 // multiple events at once.
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800186 while (reinterpret_cast<char *>(notifyevt) < end) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800187 if (watchers.count(notifyevt->wd) != 1) {
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800188 LOG(WARNING, "couldn't find whose watch ID %d is\n", notifyevt->wd);
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800189 } else {
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700190 LOG(DEBUG, "mask=%"PRIu32"\n", notifyevt->mask);
191 // If it was something that means the file got deleted.
192 if (notifyevt->mask & (IN_MOVE_SELF | IN_DELETE_SELF | IN_IGNORED)) {
193 watchers[notifyevt->wd]->WatchDeleted();
194 } else {
195 watchers[notifyevt->wd]->FileNotified((notifyevt->len > 0) ?
196 notifyevt->name : NULL);
197 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800198 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800199
200 notifyevt = reinterpret_cast<inotify_event *>(
201 reinterpret_cast<char *>(notifyevt) +
202 sizeof(*notifyevt) + notifyevt->len);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800203 }
204 }
205
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700206 // INotifyReadable calls this method whenever the watch for our file gets
207 // removed somehow.
208 void WatchDeleted() {
209 LOG(DEBUG, "watch for %s deleted\n", filename_.c_str());
210 RemoveWatchFromMap();
211 CreateWatch();
212 }
213
Brian Silverman5cc661b2013-02-27 15:23:36 -0800214 // INotifyReadable calls this method whenever the watch for our file triggers.
215 void FileNotified(const char *filename) {
216 assert(watch_ != -1);
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800217 LOG(DEBUG, "got a notification for %s\n", filename_.c_str());
Brian Silverman5cc661b2013-02-27 15:23:36 -0800218
219 if (!check_filename_.empty()) {
220 if (filename == NULL) {
221 return;
222 }
223 if (std::string(filename) != check_filename_) {
224 return;
225 }
226 }
227
228 callback_((value_ == NULL) ? this : value_);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800229 }
230
Brian Silverman5cc661b2013-02-27 15:23:36 -0800231 // To make sure that Init gets called exactly once.
232 static ::aos::Once<void> init_once;
233
Brian Silvermand169fcd2013-02-27 13:18:47 -0800234 const std::string filename_;
235 const std::function<void(void *)> callback_;
236 void *const value_;
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700237 const bool create_;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800238 std::string check_filename_;
239
240 // The watch descriptor or -1 if we don't have one any more.
241 int watch_;
242
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -0800243 // Map from watch IDs to instances of this class.
244 // <https://patchwork.kernel.org/patch/73192/> ("inotify: do not reuse watch
245 // descriptors") says they won't get reused, but that shouldn't be counted on
246 // because we might have a modified/different version/whatever kernel.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800247 static std::map<int, FileWatch *> watchers;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800248 // The inotify(7) file descriptor.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800249 static int notify_fd;
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -0800250
251 DISALLOW_COPY_AND_ASSIGN(FileWatch);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800252};
Brian Silverman5cc661b2013-02-27 15:23:36 -0800253::aos::Once<void> FileWatch::init_once(FileWatch::Init);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800254std::map<int, FileWatch *> FileWatch::watchers;
255int FileWatch::notify_fd;
256
Brian Silverman5cc661b2013-02-27 15:23:36 -0800257// Runs the given command and returns its first line of output (not including
258// the \n). LOG(FATAL)s if the command has an exit status other than 0 or does
259// not print out an entire line.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800260std::string RunCommand(std::string command) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800261 // popen(3) might fail and not set it.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800262 errno = 0;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800263 FILE *pipe = popen(command.c_str(), "r");
264 if (pipe == NULL) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800265 LOG(FATAL, "popen(\"%s\", \"r\") failed with %d: %s\n",
266 command.c_str(), errno, strerror(errno));
267 }
268
Brian Silverman5cc661b2013-02-27 15:23:36 -0800269 // result_size is how many bytes result is currently allocated to.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800270 size_t result_size = 128, read = 0;
271 unique_c_ptr<char> result(static_cast<char *>(malloc(result_size)));
272 while (true) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800273 // If we filled up the buffer, then realloc(3) it bigger.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800274 if (read == result_size) {
275 result_size *= 2;
276 void *new_result = realloc(result.get(), result_size);
277 if (new_result == NULL) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800278 LOG(FATAL, "realloc(%p, %zd) failed because of %d: %s\n",
279 result.get(), result_size, errno, strerror(errno));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800280 } else {
281 result.release();
282 result = unique_c_ptr<char>(static_cast<char *>(new_result));
283 }
284 }
285
Brian Silverman5cc661b2013-02-27 15:23:36 -0800286 size_t ret = fread(result.get() + read, 1, result_size - read, pipe);
287 // If the read didn't fill up the whole buffer, check to see if it was
288 // because of an error.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800289 if (ret < result_size - read) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800290 if (ferror(pipe)) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800291 LOG(FATAL, "couldn't finish reading output of \"%s\"\n",
292 command.c_str());
293 }
294 }
295 read += ret;
296 if (read > 0 && result.get()[read - 1] == '\n') {
297 break;
298 }
299
Brian Silverman5cc661b2013-02-27 15:23:36 -0800300 if (feof(pipe)) {
301 LOG(FATAL, "`%s` failed. didn't print a whole line\n", command.c_str());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800302 }
303 }
304
Brian Silverman5cc661b2013-02-27 15:23:36 -0800305 // Get rid of the first \n and anything after it.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800306 *strchrnul(result.get(), '\n') = '\0';
307
Brian Silverman5cc661b2013-02-27 15:23:36 -0800308 int child_status = pclose(pipe);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800309 if (child_status == -1) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800310 LOG(FATAL, "pclose(%p) failed with %d: %s\n", pipe,
Brian Silvermand169fcd2013-02-27 13:18:47 -0800311 errno, strerror(errno));
312 }
313
314 if (child_status != 0) {
315 LOG(FATAL, "`%s` failed. return %d\n", command.c_str(), child_status);
316 }
317
318 return std::string(result.get());
319}
320
321// Will call callback(arg) after time.
322void Timeout(time::Time time, void (*callback)(int, short, void *), void *arg) {
323 EventUniquePtr timeout(evtimer_new(libevent_base.get(), callback, arg));
324 struct timeval time_timeval = time.ToTimeval();
325 evtimer_add(timeout.release(), &time_timeval);
326}
327
328// Represents a child process. It will take care of restarting itself etc.
329class Child {
330 public:
Brian Silverman5cc661b2013-02-27 15:23:36 -0800331 // command is the (space-separated) command to run and its arguments.
332 Child(const std::string &command) : pid_(-1),
Brian Silvermand169fcd2013-02-27 13:18:47 -0800333 restart_timeout_(
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800334 evtimer_new(libevent_base.get(), StaticDoRestart, this)),
335 stat_at_start_valid_(false) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800336 const char *start, *end;
337 start = command.c_str();
338 while (true) {
339 end = strchrnul(start, ' ');
340 args_.push_back(std::string(start, end - start));
341 start = end + 1;
342 if (*end == '\0') {
343 break;
344 }
345 }
346
Brian Silverman5cc661b2013-02-27 15:23:36 -0800347 original_binary_ = RunCommand("which " + args_[0]);
348 binary_ = original_binary_ + ".stm";
Brian Silvermand169fcd2013-02-27 13:18:47 -0800349
350 watcher_ = unique_ptr<FileWatch>(
Brian Silverman5cc661b2013-02-27 15:23:36 -0800351 new FileWatch(original_binary_, StaticFileModified, this));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800352
353 Start();
354 }
355
356 pid_t pid() { return pid_; }
357
358 // This gets called whenever the actual process dies and should (probably) be
359 // restarted.
360 void ProcessDied() {
361 pid_ = -1;
362 restarts_.push(time::Time::Now());
363 if (restarts_.size() > kMaxRestartsNumber) {
364 time::Time oldest = restarts_.front();
365 restarts_.pop();
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700366 if ((time::Time::Now() - oldest) <= kMaxRestartsTime) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800367 LOG(WARNING, "process %s getting restarted too often\n", name());
368 Timeout(kResumeWait, StaticStart, this);
369 return;
370 }
371 }
372 Start();
373 }
374
375 // Returns a name for logging purposes.
376 const char *name() {
377 return args_[0].c_str();
378 }
379
380 private:
381 struct CheckDiedStatus {
382 Child *self;
383 pid_t old_pid;
384 };
385
386 // How long to wait for a child to die nicely.
387 static const time::Time kProcessDieTime;
388
389 // How long to wait after the file is modified to restart it.
390 // This is important because some programs like modifying the binaries by
391 // writing them in little bits, which results in attempting to start partial
392 // binaries without this.
393 static const time::Time kRestartWaitTime;
394
Brian Silverman5cc661b2013-02-27 15:23:36 -0800395 // Only kMaxRestartsNumber restarts will be allowed in kMaxRestartsTime.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800396 static const time::Time kMaxRestartsTime;
Brian Silverman8070a222013-02-28 15:01:36 -0800397 static const size_t kMaxRestartsNumber = 4;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800398 // How long to wait if it gets restarted too many times.
399 static const time::Time kResumeWait;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800400
Brian Silvermand169fcd2013-02-27 13:18:47 -0800401 static void StaticFileModified(void *self) {
402 static_cast<Child *>(self)->FileModified();
403 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800404
Brian Silvermand169fcd2013-02-27 13:18:47 -0800405 void FileModified() {
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700406 LOG(DEBUG, "file for %s modified\n", name());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800407 struct timeval restart_time_timeval = kRestartWaitTime.ToTimeval();
408 // This will reset the timeout again if it hasn't run yet.
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700409 if (evtimer_add(restart_timeout_.get(), &restart_time_timeval) != 0) {
410 LOG(FATAL, "evtimer_add(%p, %p) failed\n",
411 restart_timeout_.get(), &restart_time_timeval);
412 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800413 }
414
415 static void StaticDoRestart(int, short, void *self) {
416 static_cast<Child *>(self)->DoRestart();
417 }
418
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800419 // Called after somebody else has finished modifying the file.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800420 void DoRestart() {
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800421 if (stat_at_start_valid_) {
422 struct stat current_stat;
423 if (stat(original_binary_.c_str(), &current_stat) == -1) {
424 LOG(FATAL, "stat(%s, %p) failed with %d: %s\n",
425 original_binary_.c_str(), &current_stat, errno, strerror(errno));
426 }
427 if (current_stat.st_mtime == stat_at_start_.st_mtime) {
428 LOG(DEBUG, "ignoring trigger for %s because mtime didn't change\n",
429 name());
430 return;
431 }
432 }
433
Brian Silvermand169fcd2013-02-27 13:18:47 -0800434 if (pid_ != -1) {
435 LOG(DEBUG, "sending SIGTERM to child %d to restart it\n", pid_);
436 if (kill(pid_, SIGTERM) == -1) {
437 LOG(WARNING, "kill(%d, SIGTERM) failed with %d: %s\n",
438 pid_, errno, strerror(errno));
439 }
440 CheckDiedStatus *status = new CheckDiedStatus();
441 status->self = this;
442 status->old_pid = pid_;
443 Timeout(kProcessDieTime, StaticCheckDied, status);
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700444 } else {
445 LOG(WARNING, "%s restart attempted but not running\n", name());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800446 }
447 }
448
449 static void StaticCheckDied(int, short, void *status_in) {
450 CheckDiedStatus *status = static_cast<CheckDiedStatus *>(status_in);
451 status->self->CheckDied(status->old_pid);
452 delete status;
453 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800454
455 // Checks to see if the child using the PID old_pid is still running.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800456 void CheckDied(pid_t old_pid) {
457 if (pid_ == old_pid) {
458 LOG(WARNING, "child %d refused to die\n", old_pid);
459 if (kill(old_pid, SIGKILL) == -1) {
460 LOG(WARNING, "kill(%d, SIGKILL) failed with %d: %s\n",
461 old_pid, errno, strerror(errno));
462 }
463 }
464 }
465
466 static void StaticStart(int, short, void *self) {
467 static_cast<Child *>(self)->Start();
468 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800469
470 // Actually starts the child.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800471 void Start() {
472 if (pid_ != -1) {
473 LOG(WARNING, "calling Start() but already have child %d running\n",
474 pid_);
Brian Silverman5cc661b2013-02-27 15:23:36 -0800475 if (kill(pid_, SIGKILL) == -1) {
476 LOG(WARNING, "kill(%d, SIGKILL) failed with %d: %s\n",
477 pid_, errno, strerror(errno));
478 return;
479 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800480 pid_ = -1;
481 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800482
483 // Remove the name that we run from (ie from a previous execution) and then
484 // hard link the real filename to it.
485 if (unlink(binary_.c_str()) != 0 && errno != ENOENT) {
486 LOG(FATAL, "removing %s failed because of %d: %s\n",
487 binary_.c_str(), errno, strerror(errno));
488 }
489 if (link(original_binary_.c_str(), binary_.c_str()) != 0) {
490 LOG(FATAL, "link('%s', '%s') failed because of %d: %s\n",
491 original_binary_.c_str(), binary_.c_str(), errno, strerror(errno));
492 }
493
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800494 if (stat(original_binary_.c_str(), &stat_at_start_) == -1) {
495 LOG(FATAL, "stat(%s, %p) failed with %d: %s\n",
496 original_binary_.c_str(), &stat_at_start_, errno, strerror(errno));
497 }
498 stat_at_start_valid_ = true;
499
Brian Silvermand169fcd2013-02-27 13:18:47 -0800500 if ((pid_ = fork()) == 0) {
501 ssize_t args_size = args_.size();
502 const char **argv = new const char *[args_size + 1];
503 for (int i = 0; i < args_size; ++i) {
504 argv[i] = args_[i].c_str();
505 }
506 argv[args_size] = NULL;
507 // The const_cast is safe because no code that might care if it gets
508 // modified can run afterwards.
509 execv(binary_.c_str(), const_cast<char **>(argv));
510 LOG(FATAL, "execv(%s, %p) failed with %d: %s\n",
511 binary_.c_str(), argv, errno, strerror(errno));
512 _exit(EXIT_FAILURE);
513 }
514 if (pid_ == -1) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800515 LOG(FATAL, "forking to run \"%s\" failed with %d: %s\n",
Brian Silvermand169fcd2013-02-27 13:18:47 -0800516 binary_.c_str(), errno, strerror(errno));
517 }
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700518 LOG(DEBUG, "started \"%s\" successfully\n", binary_.c_str());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800519 }
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -0800520
521 // A history of the times that this process has been restarted.
522 std::queue<time::Time, std::list<time::Time>> restarts_;
523
524 // The currently running child's PID or NULL.
525 pid_t pid_;
526
527 // All of the arguments (including the name of the binary).
528 std::deque<std::string> args_;
529
530 // The name of the real binary that we were told to run.
531 std::string original_binary_;
532 // The name of the file that we're actually running.
533 std::string binary_;
534
535 // Watches original_binary_.
536 unique_ptr<FileWatch> watcher_;
537
538 // An event that restarts after kRestartWaitTime.
539 EventUniquePtr restart_timeout_;
540
541 // Captured from the original file when we most recently started a new child
542 // process. Used to see if it actually changes or not.
543 struct stat stat_at_start_;
544 bool stat_at_start_valid_;
545
546 DISALLOW_COPY_AND_ASSIGN(Child);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800547};
548const time::Time Child::kProcessDieTime = time::Time::InSeconds(0.5);
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700549const time::Time Child::kMaxRestartsTime = time::Time::InSeconds(4);
Brian Silverman8070a222013-02-28 15:01:36 -0800550const time::Time Child::kResumeWait = time::Time::InSeconds(2);
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700551const time::Time Child::kRestartWaitTime = time::Time::InSeconds(1.5);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800552
553// This is where all of the Child instances except core live.
554std::vector<unique_ptr<Child>> children;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800555// A global place to hold on to which child is core.
556unique_ptr<Child> core;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800557
Brian Silverman5cc661b2013-02-27 15:23:36 -0800558// Kills off the entire process group (including ourself).
559void KillChildren(bool try_nice) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800560 if (try_nice) {
561 static const int kNiceStopSignal = SIGTERM;
562 static const time::Time kNiceWaitTime = time::Time::InSeconds(1);
563
564 // Make sure that we don't just nicely stop ourself...
565 sigset_t mask;
566 sigemptyset(&mask);
567 sigaddset(&mask, kNiceStopSignal);
568 sigprocmask(SIG_BLOCK, &mask, NULL);
569
Brian Silverman5cc661b2013-02-27 15:23:36 -0800570 kill(-getpid(), kNiceStopSignal);
571
572 fflush(NULL);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800573 time::SleepFor(kNiceWaitTime);
574 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800575
Brian Silvermand169fcd2013-02-27 13:18:47 -0800576 // Send SIGKILL to our whole process group, which will forcibly terminate any
577 // of them that are still running (us for sure, maybe more too).
Brian Silverman5cc661b2013-02-27 15:23:36 -0800578 kill(-getpid(), SIGKILL);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800579}
580
Brian Silverman5cc661b2013-02-27 15:23:36 -0800581void ExitHandler() {
582 KillChildren(true);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800583}
Brian Silverman5cc661b2013-02-27 15:23:36 -0800584
585void KillChildrenSignalHandler(int signum) {
586 // If we get SIGSEGV or some other random signal who knows what's happening
587 // and we should just kill everybody immediately.
588 // This is a list of all of the signals that mean some form of "nicely stop".
589 KillChildren(signum == SIGHUP || signum == SIGINT || signum == SIGQUIT ||
Brian Silverman0eec9532013-02-27 20:24:16 -0800590 signum == SIGABRT || signum == SIGPIPE || signum == SIGTERM ||
591 signum == SIGXCPU);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800592}
593
Brian Silverman5cc661b2013-02-27 15:23:36 -0800594// Returns the currently running child with PID pid or an empty unique_ptr.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800595const unique_ptr<Child> &FindChild(pid_t pid) {
596 for (auto it = children.begin(); it != children.end(); ++it) {
597 if (pid == (*it)->pid()) {
598 return *it;
599 }
600 }
601
602 if (pid == core->pid()) {
603 return core;
604 }
605
Brian Silverman5cc661b2013-02-27 15:23:36 -0800606 static const unique_ptr<Child> kNothing;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800607 return kNothing;
608}
609
Brian Silverman5cc661b2013-02-27 15:23:36 -0800610// Gets set up as a libevent handler for SIGCHLD.
611// Handles calling Child::ProcessDied() on the appropriate one.
612void SigCHLDReceived(int /*fd*/, short /*events*/, void *) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800613 // In a while loop in case we miss any SIGCHLDs.
614 while (true) {
615 siginfo_t infop;
616 infop.si_pid = 0;
617 if (waitid(P_ALL, 0, &infop, WEXITED | WSTOPPED | WNOHANG) != 0) {
618 LOG(WARNING, "waitid failed with %d: %s", errno, strerror(errno));
Brian Silverman5cc661b2013-02-27 15:23:36 -0800619 continue;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800620 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800621 // If there are no more child process deaths to process.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800622 if (infop.si_pid == 0) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800623 return;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800624 }
625
626 pid_t pid = infop.si_pid;
627 int status = infop.si_status;
628 const unique_ptr<Child> &child = FindChild(pid);
629 if (child) {
630 switch (infop.si_code) {
631 case CLD_EXITED:
632 LOG(WARNING, "child %d (%s) exited with status %d\n",
633 pid, child->name(), status);
634 break;
635 case CLD_DUMPED:
636 LOG(INFO, "child %d actually dumped core. "
637 "falling through to killed by signal case\n", pid);
638 case CLD_KILLED:
639 // If somebody (possibly us) sent it SIGTERM that means that they just
640 // want it to stop, so it stopping isn't a WARNING.
641 LOG((status == SIGTERM) ? DEBUG : WARNING,
642 "child %d (%s) was killed by signal %d (%s)\n",
643 pid, child->name(), status,
644 strsignal(status));
645 break;
646 case CLD_STOPPED:
647 LOG(WARNING, "child %d (%s) was stopped by signal %d "
648 "(giving it a SIGCONT(%d))\n",
649 pid, child->name(), status, SIGCONT);
650 kill(pid, SIGCONT);
651 continue;
652 default:
653 LOG(WARNING, "something happened to child %d (%s) (killing it)\n",
654 pid, child->name());
655 kill(pid, SIGKILL);
656 continue;
657 }
658 } else {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800659 LOG(WARNING, "couldn't find a Child for pid %d\n", pid);
660 return;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800661 }
662
Brian Silverman5cc661b2013-02-27 15:23:36 -0800663 if (child == core) {
664 LOG(FATAL, "core died\n");
665 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800666 child->ProcessDied();
667 }
668}
669
Brian Silverman5cc661b2013-02-27 15:23:36 -0800670// This is used for communicating the name of the file to read processes to
671// start from main to Run.
672const char *child_list_file;
673
Brian Silverman8070a222013-02-28 15:01:36 -0800674void Run(void *watch);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800675void Main() {
676 logging::Init();
Brian Silverman0eec9532013-02-27 20:24:16 -0800677 // TODO(brians): tell logging that using the root logger from here until we
Brian Silvermand169fcd2013-02-27 13:18:47 -0800678 // bring up shm is ok
679
Brian Silverman5cc661b2013-02-27 15:23:36 -0800680 if (setpgid(0 /*self*/, 0 /*make PGID the same as PID*/) != 0) {
681 LOG(FATAL, "setpgid(0, 0) failed with %d: %s\n", errno, strerror(errno));
682 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800683
684 // Make sure that we kill all children when we exit.
Brian Silverman5cc661b2013-02-27 15:23:36 -0800685 atexit(ExitHandler);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800686 // Do it on some signals too (ones that we otherwise tend to receive and then
687 // leave all of our children going).
Brian Silverman5cc661b2013-02-27 15:23:36 -0800688 signal(SIGHUP, KillChildrenSignalHandler);
689 signal(SIGINT, KillChildrenSignalHandler);
690 signal(SIGQUIT, KillChildrenSignalHandler);
691 signal(SIGILL, KillChildrenSignalHandler);
692 signal(SIGABRT, KillChildrenSignalHandler);
693 signal(SIGFPE, KillChildrenSignalHandler);
694 signal(SIGSEGV, KillChildrenSignalHandler);
695 signal(SIGPIPE, KillChildrenSignalHandler);
696 signal(SIGTERM, KillChildrenSignalHandler);
697 signal(SIGBUS, KillChildrenSignalHandler);
698 signal(SIGXCPU, KillChildrenSignalHandler);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800699
700 libevent_base = EventBaseUniquePtr(event_base_new());
701
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800702 std::string core_touch_file = "/tmp/starter.";
Brian Silvermand169fcd2013-02-27 13:18:47 -0800703 core_touch_file += std::to_string(static_cast<intmax_t>(getpid()));
704 core_touch_file += ".core_touch_file";
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800705 if (system(("touch '" + core_touch_file + "'").c_str()) != 0) {
706 LOG(FATAL, "running `touch '%s'` failed\n", core_touch_file.c_str());
707 }
708 FileWatch core_touch_file_watch(core_touch_file, Run, NULL);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800709 core = unique_ptr<Child>(
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800710 new Child("core " + core_touch_file));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800711
712 FILE *pid_file = fopen("/tmp/starter.pid", "w");
713 if (pid_file == NULL) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800714 LOG(FATAL, "fopen(\"/tmp/starter.pid\", \"w\") failed with %d: %s\n",
Brian Silvermand169fcd2013-02-27 13:18:47 -0800715 errno, strerror(errno));
716 } else {
717 if (fprintf(pid_file, "%d", core->pid()) == -1) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800718 LOG(WARNING, "fprintf(%p, \"%%d\", %d) failed with %d: %s\n",
719 pid_file, core->pid(), errno, strerror(errno));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800720 }
721 fclose(pid_file);
722 }
723
724 LOG(INFO, "waiting for %s to appear\n", core_touch_file.c_str());
725
726 event_base_dispatch(libevent_base.get());
727 LOG(FATAL, "event_base_dispatch(%p) returned\n", libevent_base.get());
728}
729
Brian Silverman0eec9532013-02-27 20:24:16 -0800730// This is the callback for when core creates the file indicating that it has
731// started.
732void Run(void *watch) {
733 // Make it so it doesn't keep on seeing random changes in /tmp.
734 static_cast<FileWatch *>(watch)->RemoveWatch();
735
736 // It's safe now because core is up.
737 aos::InitNRT();
738
739 std::ifstream list_file(child_list_file);
740
741 while (true) {
742 std::string child_name;
743 getline(list_file, child_name);
744 if ((list_file.rdstate() & std::ios_base::eofbit) != 0) {
745 break;
746 }
747 if (list_file.rdstate() != 0) {
748 LOG(FATAL, "reading input file %s failed\n", child_list_file);
749 }
750 children.push_back(unique_ptr<Child>(new Child(child_name)));
751 }
752
753 EventUniquePtr sigchld(event_new(libevent_base.get(), SIGCHLD,
754 EV_SIGNAL | EV_PERSIST,
755 SigCHLDReceived, NULL));
756 event_add(sigchld.release(), NULL);
757}
758
Brian Silverman8070a222013-02-28 15:01:36 -0800759const char *kArgsHelp = "[OPTION]... START_LIST\n"
760 "Start all of the robot code binaries in START_LIST.\n"
761 "\n"
762 "START_LIST is the file to read binaries (looked up on PATH) to run.\n"
763 " --help display this help and exit\n";
764void PrintHelp() {
765 fprintf(stderr, "Usage: %s %s", program_invocation_name, kArgsHelp);
766}
767
Brian Silvermand169fcd2013-02-27 13:18:47 -0800768} // namespace starter
769} // namespace aos
770
771int main(int argc, char *argv[]) {
Brian Silverman8070a222013-02-28 15:01:36 -0800772 if (argc != 2) {
773 aos::starter::PrintHelp();
Brian Silvermand169fcd2013-02-27 13:18:47 -0800774 exit(EXIT_FAILURE);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800775 }
Brian Silverman8070a222013-02-28 15:01:36 -0800776 if (strcmp(argv[1], "--help") == 0) {
777 aos::starter::PrintHelp();
778 exit(EXIT_SUCCESS);
779 }
780
Brian Silvermand169fcd2013-02-27 13:18:47 -0800781 aos::starter::child_list_file = argv[1];
782
783 aos::starter::Main();
784}