blob: 800acd939f9d394ba636c12bdbe3eb063dfb3199 [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>
Brian Silvermand94642c2014-03-27 18:21:41 -070025#include <set>
Brian Silvermand169fcd2013-02-27 13:18:47 -080026
27#include <event2/event.h>
28
29#include "aos/common/logging/logging.h"
30#include "aos/common/logging/logging_impl.h"
Brian Silverman14fd0fb2014-01-14 21:42:01 -080031#include "aos/linux_code/init.h"
Brian Silvermand169fcd2013-02-27 13:18:47 -080032#include "aos/common/unique_malloc_ptr.h"
33#include "aos/common/time.h"
Brian Silverman5cc661b2013-02-27 15:23:36 -080034#include "aos/common/once.h"
Brian Silvermand169fcd2013-02-27 13:18:47 -080035
36// This is the main piece of code that starts all of the rest of the code and
37// restarts it when the binaries are modified.
38//
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -080039// Throughout, the code is not terribly concerned with thread safety because
40// there is only 1 thread. It does some setup and then lets inotify run things
41// when appropriate.
42//
Brian Silverman5cc661b2013-02-27 15:23:36 -080043// NOTE: This program should never exit nicely. It catches all nice attempts to
44// exit, forwards them to all of the children that it has started, waits for
Brian Silvermand169fcd2013-02-27 13:18:47 -080045// them to exit nicely, and then SIGKILLs anybody left (which will always
46// include itself).
47
48using ::std::unique_ptr;
49
50namespace aos {
51namespace starter {
52
Brian Silverman0eec9532013-02-27 20:24:16 -080053// TODO(brians): split out the c++ libevent wrapper stuff into its own file(s)
Brian Silvermand169fcd2013-02-27 13:18:47 -080054class EventBaseDeleter {
55 public:
56 void operator()(event_base *base) {
Brian Silverman8070a222013-02-28 15:01:36 -080057 if (base == NULL) return;
Brian Silvermand169fcd2013-02-27 13:18:47 -080058 event_base_free(base);
59 }
60};
61typedef unique_ptr<event_base, EventBaseDeleter> EventBaseUniquePtr;
Brian Silverman5cc661b2013-02-27 15:23:36 -080062EventBaseUniquePtr libevent_base;
Brian Silvermand169fcd2013-02-27 13:18:47 -080063
64class EventDeleter {
65 public:
66 void operator()(event *evt) {
Brian Silverman8070a222013-02-28 15:01:36 -080067 if (evt == NULL) return;
Brian Silvermand169fcd2013-02-27 13:18:47 -080068 if (event_del(evt) != 0) {
69 LOG(WARNING, "event_del(%p) failed\n", evt);
70 }
71 }
72};
73typedef unique_ptr<event, EventDeleter> EventUniquePtr;
74
Brian Silverman5cc661b2013-02-27 15:23:36 -080075// Watches a file path for modifications. Once created, keeps watching until
76// destroyed or RemoveWatch() is called.
Brian Silverman0eec9532013-02-27 20:24:16 -080077// TODO(brians): split this out into its own file + tests
Brian Silvermand169fcd2013-02-27 13:18:47 -080078class FileWatch {
79 public:
80 // Will call callback(value) when filename is modified.
81 // If value is NULL, then a pointer to this object will be passed instead.
Brian Silverman5cc661b2013-02-27 15:23:36 -080082 //
83 // Watching for file creations is slightly different. To do that, pass true
Brian Silverman8070a222013-02-28 15:01:36 -080084 // as create, the directory where the file will be created for filename, and
Brian Silverman5cc661b2013-02-27 15:23:36 -080085 // the name of the file (without directory name) for check_filename.
Brian Silvermand169fcd2013-02-27 13:18:47 -080086 FileWatch(std::string filename,
Brian Silverman8070a222013-02-28 15:01:36 -080087 std::function<void(void *)> callback,
88 void *value,
89 bool create = false,
90 std::string check_filename = "")
91 : filename_(filename),
92 callback_(callback),
93 value_(value),
Brian Silvermand90b5fe2013-03-10 18:34:42 -070094 create_(create),
95 check_filename_(check_filename),
96 watch_(-1) {
Brian Silverman5cc661b2013-02-27 15:23:36 -080097 init_once.Get();
98
Brian Silvermand90b5fe2013-03-10 18:34:42 -070099 CreateWatch();
Brian Silvermand169fcd2013-02-27 13:18:47 -0800100 }
101 // Cleans up everything.
102 ~FileWatch() {
103 if (watch_ != -1) {
104 RemoveWatch();
105 }
106 }
107
108 // After calling this method, this object won't really be doing much of
Brian Silverman5cc661b2013-02-27 15:23:36 -0800109 // anything besides possibly running its callback or something.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800110 void RemoveWatch() {
111 assert(watch_ != -1);
Brian Silvermand94642c2014-03-27 18:21:41 -0700112 assert(watch_to_remove_ == -1);
Brian Silverman5cc661b2013-02-27 15:23:36 -0800113
Brian Silvermand169fcd2013-02-27 13:18:47 -0800114 if (inotify_rm_watch(notify_fd, watch_) == -1) {
Brian Silverman01be0002014-05-10 15:44:38 -0700115 PLOG(WARNING, "inotify_rm_watch(%d, %d) failed", notify_fd, watch_);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800116 }
Brian Silvermand94642c2014-03-27 18:21:41 -0700117 watch_to_remove_ = watch_;
118 watch_ = -1;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800119 }
120
Brian Silverman5cc661b2013-02-27 15:23:36 -0800121 private:
122 // Performs the static initialization. Called by init_once from the
123 // constructor.
124 static void *Init() {
125 notify_fd = inotify_init1(IN_CLOEXEC);
126 EventUniquePtr notify_event(event_new(libevent_base.get(), notify_fd,
127 EV_READ | EV_PERSIST,
128 FileWatch::INotifyReadable, NULL));
129 event_add(notify_event.release(), NULL);
130 return NULL;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800131 }
132
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700133 void RemoveWatchFromMap() {
Brian Silvermand94642c2014-03-27 18:21:41 -0700134 int watch = watch_to_remove_;
135 if (watch == -1) {
136 assert(watch_ != -1);
137 watch = watch_;
138 }
139 if (watchers[watch] != this) {
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700140 LOG(WARNING, "watcher for %s (%p) didn't find itself in the map\n",
141 filename_.c_str(), this);
142 } else {
Brian Silvermand94642c2014-03-27 18:21:41 -0700143 watchers.erase(watch);
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700144 }
Brian Silvermand94642c2014-03-27 18:21:41 -0700145 LOG(DEBUG, "removed watch ID %d\n", watch);
146 if (watch_to_remove_ == -1) {
147 watch_ = -1;
148 } else {
149 watch_to_remove_ = -1;
150 }
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700151 }
152
153 void CreateWatch() {
154 assert(watch_ == -1);
155 watch_ = inotify_add_watch(notify_fd, filename_.c_str(),
156 create_ ? IN_CREATE : (IN_ATTRIB |
157 IN_MODIFY |
158 IN_DELETE_SELF |
159 IN_MOVE_SELF));
160 if (watch_ == -1) {
Brian Silverman01be0002014-05-10 15:44:38 -0700161 PLOG(FATAL, "inotify_add_watch(%d, %s,"
162 " %s ? IN_CREATE : (IN_ATTRIB | IN_MODIFY)) failed",
163 notify_fd, filename_.c_str(), create_ ? "true" : "false");
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700164 }
165 watchers[watch_] = this;
166 LOG(DEBUG, "watch for %s is %d\n", filename_.c_str(), watch_);
167 }
168
Brian Silvermand169fcd2013-02-27 13:18:47 -0800169 // This gets set up as the callback for EV_READ on the inotify file
Brian Silverman5cc661b2013-02-27 15:23:36 -0800170 // descriptor. It calls FileNotified on the appropriate instance.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800171 static void INotifyReadable(int /*fd*/, short /*events*/, void *) {
172 unsigned int to_read;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800173 // Use FIONREAD to figure out how many bytes there are to read.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800174 if (ioctl(notify_fd, FIONREAD, &to_read) < 0) {
Brian Silverman01be0002014-05-10 15:44:38 -0700175 PLOG(FATAL, "FIONREAD(%d, %p) failed", notify_fd, &to_read);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800176 }
177 inotify_event *notifyevt = static_cast<inotify_event *>(malloc(to_read));
178 const char *end = reinterpret_cast<char *>(notifyevt) + to_read;
179 aos::unique_c_ptr<inotify_event> freer(notifyevt);
180
181 ssize_t ret = read(notify_fd, notifyevt, to_read);
182 if (ret < 0) {
Brian Silverman01be0002014-05-10 15:44:38 -0700183 PLOG(FATAL, "read(%d, %p, %u) failed", notify_fd, notifyevt, to_read);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800184 }
185 if (static_cast<size_t>(ret) != to_read) {
186 LOG(ERROR, "read(%d, %p, %u) returned %zd instead of %u\n",
187 notify_fd, notifyevt, to_read, ret, to_read);
188 return;
189 }
190
Brian Silverman5cc661b2013-02-27 15:23:36 -0800191 // Keep looping through until we get to the end because inotify does return
192 // multiple events at once.
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800193 while (reinterpret_cast<char *>(notifyevt) < end) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800194 if (watchers.count(notifyevt->wd) != 1) {
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800195 LOG(WARNING, "couldn't find whose watch ID %d is\n", notifyevt->wd);
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800196 } else {
Brian Silverman8efe23e2013-07-07 23:31:37 -0700197 LOG(DEBUG, "mask=%" PRIu32 "\n", notifyevt->mask);
Brian Silvermand94642c2014-03-27 18:21:41 -0700198 // If the watch was removed.
199 if (notifyevt->mask & IN_IGNORED) {
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700200 watchers[notifyevt->wd]->WatchDeleted();
201 } else {
Brian Silvermand94642c2014-03-27 18:21:41 -0700202 watchers[notifyevt->wd]
203 ->FileNotified((notifyevt->len > 0) ? notifyevt->name : NULL);
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700204 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800205 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800206
207 notifyevt = reinterpret_cast<inotify_event *>(
Brian Silvermandbdf1d02013-11-17 13:19:41 -0800208 __builtin_assume_aligned(reinterpret_cast<char *>(notifyevt) +
209 sizeof(*notifyevt) + notifyevt->len,
Brian Silvermanafc00a62014-04-21 17:51:23 -0700210 alignof(inotify_event)));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800211 }
212 }
213
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700214 // INotifyReadable calls this method whenever the watch for our file gets
215 // removed somehow.
216 void WatchDeleted() {
217 LOG(DEBUG, "watch for %s deleted\n", filename_.c_str());
218 RemoveWatchFromMap();
219 CreateWatch();
220 }
221
Brian Silverman5cc661b2013-02-27 15:23:36 -0800222 // INotifyReadable calls this method whenever the watch for our file triggers.
223 void FileNotified(const char *filename) {
224 assert(watch_ != -1);
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800225 LOG(DEBUG, "got a notification for %s\n", filename_.c_str());
Brian Silverman5cc661b2013-02-27 15:23:36 -0800226
227 if (!check_filename_.empty()) {
228 if (filename == NULL) {
229 return;
230 }
231 if (std::string(filename) != check_filename_) {
232 return;
233 }
234 }
235
236 callback_((value_ == NULL) ? this : value_);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800237 }
238
Brian Silverman5cc661b2013-02-27 15:23:36 -0800239 // To make sure that Init gets called exactly once.
240 static ::aos::Once<void> init_once;
241
Brian Silvermand169fcd2013-02-27 13:18:47 -0800242 const std::string filename_;
243 const std::function<void(void *)> callback_;
244 void *const value_;
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700245 const bool create_;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800246 std::string check_filename_;
247
248 // The watch descriptor or -1 if we don't have one any more.
249 int watch_;
Brian Silvermand94642c2014-03-27 18:21:41 -0700250 // The watch that we still have to take out of the map once we get the
251 // IN_IGNORED or -1.
252 int watch_to_remove_ = -1;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800253
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -0800254 // Map from watch IDs to instances of this class.
255 // <https://patchwork.kernel.org/patch/73192/> ("inotify: do not reuse watch
256 // descriptors") says they won't get reused, but that shouldn't be counted on
257 // because we might have a modified/different version/whatever kernel.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800258 static std::map<int, FileWatch *> watchers;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800259 // The inotify(7) file descriptor.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800260 static int notify_fd;
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -0800261
262 DISALLOW_COPY_AND_ASSIGN(FileWatch);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800263};
Brian Silverman5cc661b2013-02-27 15:23:36 -0800264::aos::Once<void> FileWatch::init_once(FileWatch::Init);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800265std::map<int, FileWatch *> FileWatch::watchers;
266int FileWatch::notify_fd;
267
Brian Silverman5cc661b2013-02-27 15:23:36 -0800268// Runs the given command and returns its first line of output (not including
269// the \n). LOG(FATAL)s if the command has an exit status other than 0 or does
270// not print out an entire line.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800271std::string RunCommand(std::string command) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800272 // popen(3) might fail and not set it.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800273 errno = 0;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800274 FILE *pipe = popen(command.c_str(), "r");
275 if (pipe == NULL) {
Brian Silverman01be0002014-05-10 15:44:38 -0700276 PLOG(FATAL, "popen(\"%s\", \"r\") failed", command.c_str());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800277 }
278
Brian Silverman5cc661b2013-02-27 15:23:36 -0800279 // result_size is how many bytes result is currently allocated to.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800280 size_t result_size = 128, read = 0;
281 unique_c_ptr<char> result(static_cast<char *>(malloc(result_size)));
282 while (true) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800283 // If we filled up the buffer, then realloc(3) it bigger.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800284 if (read == result_size) {
285 result_size *= 2;
286 void *new_result = realloc(result.get(), result_size);
287 if (new_result == NULL) {
Brian Silverman01be0002014-05-10 15:44:38 -0700288 PLOG(FATAL, "realloc(%p, %zd) failed", result.get(), result_size);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800289 } else {
290 result.release();
291 result = unique_c_ptr<char>(static_cast<char *>(new_result));
292 }
293 }
294
Brian Silverman5cc661b2013-02-27 15:23:36 -0800295 size_t ret = fread(result.get() + read, 1, result_size - read, pipe);
296 // If the read didn't fill up the whole buffer, check to see if it was
297 // because of an error.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800298 if (ret < result_size - read) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800299 if (ferror(pipe)) {
Brian Silverman01be0002014-05-10 15:44:38 -0700300 PLOG(FATAL, "couldn't finish reading output of \"%s\"\n",
301 command.c_str());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800302 }
303 }
304 read += ret;
305 if (read > 0 && result.get()[read - 1] == '\n') {
306 break;
307 }
308
Brian Silverman5cc661b2013-02-27 15:23:36 -0800309 if (feof(pipe)) {
310 LOG(FATAL, "`%s` failed. didn't print a whole line\n", command.c_str());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800311 }
312 }
313
Brian Silverman5cc661b2013-02-27 15:23:36 -0800314 // Get rid of the first \n and anything after it.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800315 *strchrnul(result.get(), '\n') = '\0';
316
Brian Silverman5cc661b2013-02-27 15:23:36 -0800317 int child_status = pclose(pipe);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800318 if (child_status == -1) {
Brian Silverman01be0002014-05-10 15:44:38 -0700319 PLOG(FATAL, "pclose(%p) failed", pipe);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800320 }
321
322 if (child_status != 0) {
323 LOG(FATAL, "`%s` failed. return %d\n", command.c_str(), child_status);
324 }
325
326 return std::string(result.get());
327}
328
329// Will call callback(arg) after time.
330void Timeout(time::Time time, void (*callback)(int, short, void *), void *arg) {
331 EventUniquePtr timeout(evtimer_new(libevent_base.get(), callback, arg));
332 struct timeval time_timeval = time.ToTimeval();
Brian Silvermand94642c2014-03-27 18:21:41 -0700333 if (evtimer_add(timeout.release(), &time_timeval) != 0) {
334 LOG(FATAL, "evtimer_add(%p, %p) failed\n",
335 timeout.release(), &time_timeval);
336 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800337}
338
Brian Silvermand94642c2014-03-27 18:21:41 -0700339class Child;
340// This is where all of the Child instances except core live.
341std::vector<unique_ptr<Child>> children;
342// A global place to hold on to which child is core.
343unique_ptr<Child> core;
344
Brian Silvermand169fcd2013-02-27 13:18:47 -0800345// Represents a child process. It will take care of restarting itself etc.
346class Child {
347 public:
Brian Silverman5cc661b2013-02-27 15:23:36 -0800348 // command is the (space-separated) command to run and its arguments.
349 Child(const std::string &command) : pid_(-1),
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800350 stat_at_start_valid_(false) {
Brian Silvermand94642c2014-03-27 18:21:41 -0700351 if (!restart_timeout) {
352 restart_timeout = EventUniquePtr(
353 evtimer_new(libevent_base.get(), StaticDoRestart, nullptr));
354 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800355 const char *start, *end;
356 start = command.c_str();
357 while (true) {
358 end = strchrnul(start, ' ');
359 args_.push_back(std::string(start, end - start));
360 start = end + 1;
361 if (*end == '\0') {
362 break;
363 }
364 }
365
Brian Silverman5cc661b2013-02-27 15:23:36 -0800366 original_binary_ = RunCommand("which " + args_[0]);
367 binary_ = original_binary_ + ".stm";
Brian Silvermand169fcd2013-02-27 13:18:47 -0800368
369 watcher_ = unique_ptr<FileWatch>(
Brian Silverman5cc661b2013-02-27 15:23:36 -0800370 new FileWatch(original_binary_, StaticFileModified, this));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800371
372 Start();
373 }
374
375 pid_t pid() { return pid_; }
376
377 // This gets called whenever the actual process dies and should (probably) be
378 // restarted.
379 void ProcessDied() {
380 pid_ = -1;
381 restarts_.push(time::Time::Now());
382 if (restarts_.size() > kMaxRestartsNumber) {
383 time::Time oldest = restarts_.front();
384 restarts_.pop();
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700385 if ((time::Time::Now() - oldest) <= kMaxRestartsTime) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800386 LOG(WARNING, "process %s getting restarted too often\n", name());
387 Timeout(kResumeWait, StaticStart, this);
388 return;
389 }
390 }
391 Start();
392 }
393
394 // Returns a name for logging purposes.
395 const char *name() {
396 return args_[0].c_str();
397 }
398
399 private:
400 struct CheckDiedStatus {
401 Child *self;
402 pid_t old_pid;
403 };
404
405 // How long to wait for a child to die nicely.
Brian Silvermand94642c2014-03-27 18:21:41 -0700406 static constexpr time::Time kProcessDieTime = time::Time::InSeconds(2);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800407
408 // How long to wait after the file is modified to restart it.
409 // This is important because some programs like modifying the binaries by
410 // writing them in little bits, which results in attempting to start partial
411 // binaries without this.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700412 static constexpr time::Time kRestartWaitTime = time::Time::InSeconds(1.5);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800413
Brian Silverman5cc661b2013-02-27 15:23:36 -0800414 // Only kMaxRestartsNumber restarts will be allowed in kMaxRestartsTime.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700415 static constexpr time::Time kMaxRestartsTime = time::Time::InSeconds(4);
416 static const size_t kMaxRestartsNumber = 3;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800417 // How long to wait if it gets restarted too many times.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700418 static constexpr time::Time kResumeWait = time::Time::InSeconds(5);
Brian Silverman5cc661b2013-02-27 15:23:36 -0800419
Brian Silvermand169fcd2013-02-27 13:18:47 -0800420 static void StaticFileModified(void *self) {
421 static_cast<Child *>(self)->FileModified();
422 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800423
Brian Silvermand169fcd2013-02-27 13:18:47 -0800424 void FileModified() {
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700425 LOG(DEBUG, "file for %s modified\n", name());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800426 struct timeval restart_time_timeval = kRestartWaitTime.ToTimeval();
427 // This will reset the timeout again if it hasn't run yet.
Brian Silvermand94642c2014-03-27 18:21:41 -0700428 if (evtimer_add(restart_timeout.get(), &restart_time_timeval) != 0) {
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700429 LOG(FATAL, "evtimer_add(%p, %p) failed\n",
Brian Silvermand94642c2014-03-27 18:21:41 -0700430 restart_timeout.get(), &restart_time_timeval);
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700431 }
Brian Silvermand94642c2014-03-27 18:21:41 -0700432 waiting_to_restart.insert(this);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800433 }
434
Brian Silvermand94642c2014-03-27 18:21:41 -0700435 static void StaticDoRestart(int, short, void *) {
436 LOG(DEBUG, "restarting everything that needs it\n");
437 if (waiting_to_restart.find(core.get()) != waiting_to_restart.end()) {
438 core->DoRestart();
439 waiting_to_restart.erase(core.get());
440 }
441 for (auto c : waiting_to_restart) {
442 c->DoRestart();
443 }
444 waiting_to_restart.clear();
Brian Silvermand169fcd2013-02-27 13:18:47 -0800445 }
446
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800447 // Called after somebody else has finished modifying the file.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800448 void DoRestart() {
Brian Silvermand94642c2014-03-27 18:21:41 -0700449 fprintf(stderr, "DoRestart(%s)\n", binary_.c_str());
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800450 if (stat_at_start_valid_) {
451 struct stat current_stat;
452 if (stat(original_binary_.c_str(), &current_stat) == -1) {
Brian Silverman01be0002014-05-10 15:44:38 -0700453 PLOG(FATAL, "stat(%s, %p) failed",
454 original_binary_.c_str(), &current_stat);
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800455 }
456 if (current_stat.st_mtime == stat_at_start_.st_mtime) {
457 LOG(DEBUG, "ignoring trigger for %s because mtime didn't change\n",
458 name());
459 return;
460 }
461 }
462
Brian Silvermand94642c2014-03-27 18:21:41 -0700463 if (this == core.get()) {
464 fprintf(stderr, "Restarting core -> exiting now.\n");
465 exit(0);
466 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800467 if (pid_ != -1) {
468 LOG(DEBUG, "sending SIGTERM to child %d to restart it\n", pid_);
469 if (kill(pid_, SIGTERM) == -1) {
Brian Silverman01be0002014-05-10 15:44:38 -0700470 PLOG(WARNING, "kill(%d, SIGTERM) failed", pid_);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800471 }
472 CheckDiedStatus *status = new CheckDiedStatus();
473 status->self = this;
474 status->old_pid = pid_;
475 Timeout(kProcessDieTime, StaticCheckDied, status);
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700476 } else {
477 LOG(WARNING, "%s restart attempted but not running\n", name());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800478 }
479 }
480
481 static void StaticCheckDied(int, short, void *status_in) {
482 CheckDiedStatus *status = static_cast<CheckDiedStatus *>(status_in);
483 status->self->CheckDied(status->old_pid);
484 delete status;
485 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800486
487 // Checks to see if the child using the PID old_pid is still running.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800488 void CheckDied(pid_t old_pid) {
489 if (pid_ == old_pid) {
490 LOG(WARNING, "child %d refused to die\n", old_pid);
491 if (kill(old_pid, SIGKILL) == -1) {
Brian Silverman01be0002014-05-10 15:44:38 -0700492 PLOG(WARNING, "kill(%d, SIGKILL) failed", old_pid);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800493 }
494 }
495 }
496
497 static void StaticStart(int, short, void *self) {
498 static_cast<Child *>(self)->Start();
499 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800500
501 // Actually starts the child.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800502 void Start() {
503 if (pid_ != -1) {
504 LOG(WARNING, "calling Start() but already have child %d running\n",
505 pid_);
Brian Silverman5cc661b2013-02-27 15:23:36 -0800506 if (kill(pid_, SIGKILL) == -1) {
Brian Silverman01be0002014-05-10 15:44:38 -0700507 PLOG(WARNING, "kill(%d, SIGKILL) failed", pid_);
Brian Silverman5cc661b2013-02-27 15:23:36 -0800508 return;
509 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800510 pid_ = -1;
511 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800512
513 // Remove the name that we run from (ie from a previous execution) and then
514 // hard link the real filename to it.
515 if (unlink(binary_.c_str()) != 0 && errno != ENOENT) {
Brian Silverman01be0002014-05-10 15:44:38 -0700516 PLOG(FATAL, "removing %s failed", binary_.c_str());
Brian Silverman5cc661b2013-02-27 15:23:36 -0800517 }
518 if (link(original_binary_.c_str(), binary_.c_str()) != 0) {
Brian Silverman01be0002014-05-10 15:44:38 -0700519 PLOG(FATAL, "link('%s', '%s') failed",
520 original_binary_.c_str(), binary_.c_str());
Brian Silverman5cc661b2013-02-27 15:23:36 -0800521 }
522
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800523 if (stat(original_binary_.c_str(), &stat_at_start_) == -1) {
Brian Silverman01be0002014-05-10 15:44:38 -0700524 PLOG(FATAL, "stat(%s, %p) failed",
525 original_binary_.c_str(), &stat_at_start_);
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800526 }
527 stat_at_start_valid_ = true;
528
Brian Silvermand169fcd2013-02-27 13:18:47 -0800529 if ((pid_ = fork()) == 0) {
530 ssize_t args_size = args_.size();
531 const char **argv = new const char *[args_size + 1];
532 for (int i = 0; i < args_size; ++i) {
533 argv[i] = args_[i].c_str();
534 }
535 argv[args_size] = NULL;
536 // The const_cast is safe because no code that might care if it gets
537 // modified can run afterwards.
538 execv(binary_.c_str(), const_cast<char **>(argv));
Brian Silverman01be0002014-05-10 15:44:38 -0700539 PLOG(FATAL, "execv(%s, %p) failed", binary_.c_str(), argv);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800540 _exit(EXIT_FAILURE);
541 }
542 if (pid_ == -1) {
Brian Silverman01be0002014-05-10 15:44:38 -0700543 PLOG(FATAL, "forking to run \"%s\" failed", binary_.c_str());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800544 }
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700545 LOG(DEBUG, "started \"%s\" successfully\n", binary_.c_str());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800546 }
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -0800547
548 // A history of the times that this process has been restarted.
549 std::queue<time::Time, std::list<time::Time>> restarts_;
550
551 // The currently running child's PID or NULL.
552 pid_t pid_;
553
554 // All of the arguments (including the name of the binary).
555 std::deque<std::string> args_;
556
557 // The name of the real binary that we were told to run.
558 std::string original_binary_;
559 // The name of the file that we're actually running.
560 std::string binary_;
561
562 // Watches original_binary_.
563 unique_ptr<FileWatch> watcher_;
564
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -0800565 // Captured from the original file when we most recently started a new child
566 // process. Used to see if it actually changes or not.
567 struct stat stat_at_start_;
568 bool stat_at_start_valid_;
569
Brian Silvermand94642c2014-03-27 18:21:41 -0700570 // An event that restarts after kRestartWaitTime.
571 static EventUniquePtr restart_timeout;
572
573 // The set of children waiting to be restarted once all modifications stop.
574 static ::std::set<Child *> waiting_to_restart;
575
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -0800576 DISALLOW_COPY_AND_ASSIGN(Child);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800577};
Brian Silverman52aeeac2013-08-28 16:20:53 -0700578
579constexpr time::Time Child::kProcessDieTime;
580constexpr time::Time Child::kRestartWaitTime;
581constexpr time::Time Child::kMaxRestartsTime;
582constexpr time::Time Child::kResumeWait;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800583
Brian Silvermand94642c2014-03-27 18:21:41 -0700584EventUniquePtr Child::restart_timeout;
585::std::set<Child *> Child::waiting_to_restart;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800586
Brian Silverman5cc661b2013-02-27 15:23:36 -0800587// Kills off the entire process group (including ourself).
588void KillChildren(bool try_nice) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800589 if (try_nice) {
590 static const int kNiceStopSignal = SIGTERM;
591 static const time::Time kNiceWaitTime = time::Time::InSeconds(1);
592
593 // Make sure that we don't just nicely stop ourself...
594 sigset_t mask;
595 sigemptyset(&mask);
596 sigaddset(&mask, kNiceStopSignal);
597 sigprocmask(SIG_BLOCK, &mask, NULL);
598
Brian Silverman5cc661b2013-02-27 15:23:36 -0800599 kill(-getpid(), kNiceStopSignal);
600
601 fflush(NULL);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800602 time::SleepFor(kNiceWaitTime);
603 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800604
Brian Silvermand169fcd2013-02-27 13:18:47 -0800605 // Send SIGKILL to our whole process group, which will forcibly terminate any
606 // of them that are still running (us for sure, maybe more too).
Brian Silverman5cc661b2013-02-27 15:23:36 -0800607 kill(-getpid(), SIGKILL);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800608}
609
Brian Silverman5cc661b2013-02-27 15:23:36 -0800610void ExitHandler() {
611 KillChildren(true);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800612}
Brian Silverman5cc661b2013-02-27 15:23:36 -0800613
614void KillChildrenSignalHandler(int signum) {
615 // If we get SIGSEGV or some other random signal who knows what's happening
616 // and we should just kill everybody immediately.
617 // This is a list of all of the signals that mean some form of "nicely stop".
618 KillChildren(signum == SIGHUP || signum == SIGINT || signum == SIGQUIT ||
Brian Silverman0eec9532013-02-27 20:24:16 -0800619 signum == SIGABRT || signum == SIGPIPE || signum == SIGTERM ||
620 signum == SIGXCPU);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800621}
622
Brian Silverman5cc661b2013-02-27 15:23:36 -0800623// Returns the currently running child with PID pid or an empty unique_ptr.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800624const unique_ptr<Child> &FindChild(pid_t pid) {
625 for (auto it = children.begin(); it != children.end(); ++it) {
626 if (pid == (*it)->pid()) {
627 return *it;
628 }
629 }
630
631 if (pid == core->pid()) {
632 return core;
633 }
634
Brian Silverman5cc661b2013-02-27 15:23:36 -0800635 static const unique_ptr<Child> kNothing;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800636 return kNothing;
637}
638
Brian Silverman5cc661b2013-02-27 15:23:36 -0800639// Gets set up as a libevent handler for SIGCHLD.
640// Handles calling Child::ProcessDied() on the appropriate one.
641void SigCHLDReceived(int /*fd*/, short /*events*/, void *) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800642 // In a while loop in case we miss any SIGCHLDs.
643 while (true) {
644 siginfo_t infop;
645 infop.si_pid = 0;
646 if (waitid(P_ALL, 0, &infop, WEXITED | WSTOPPED | WNOHANG) != 0) {
Brian Silverman01be0002014-05-10 15:44:38 -0700647 PLOG(WARNING, "waitid failed");
Brian Silverman5cc661b2013-02-27 15:23:36 -0800648 continue;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800649 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800650 // If there are no more child process deaths to process.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800651 if (infop.si_pid == 0) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800652 return;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800653 }
654
655 pid_t pid = infop.si_pid;
656 int status = infop.si_status;
657 const unique_ptr<Child> &child = FindChild(pid);
658 if (child) {
659 switch (infop.si_code) {
660 case CLD_EXITED:
661 LOG(WARNING, "child %d (%s) exited with status %d\n",
662 pid, child->name(), status);
663 break;
664 case CLD_DUMPED:
665 LOG(INFO, "child %d actually dumped core. "
666 "falling through to killed by signal case\n", pid);
667 case CLD_KILLED:
668 // If somebody (possibly us) sent it SIGTERM that means that they just
669 // want it to stop, so it stopping isn't a WARNING.
670 LOG((status == SIGTERM) ? DEBUG : WARNING,
671 "child %d (%s) was killed by signal %d (%s)\n",
672 pid, child->name(), status,
673 strsignal(status));
674 break;
675 case CLD_STOPPED:
676 LOG(WARNING, "child %d (%s) was stopped by signal %d "
677 "(giving it a SIGCONT(%d))\n",
678 pid, child->name(), status, SIGCONT);
679 kill(pid, SIGCONT);
680 continue;
681 default:
682 LOG(WARNING, "something happened to child %d (%s) (killing it)\n",
683 pid, child->name());
684 kill(pid, SIGKILL);
685 continue;
686 }
687 } else {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800688 LOG(WARNING, "couldn't find a Child for pid %d\n", pid);
689 return;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800690 }
691
Brian Silverman5cc661b2013-02-27 15:23:36 -0800692 if (child == core) {
693 LOG(FATAL, "core died\n");
694 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800695 child->ProcessDied();
696 }
697}
698
Brian Silverman5cc661b2013-02-27 15:23:36 -0800699// This is used for communicating the name of the file to read processes to
700// start from main to Run.
701const char *child_list_file;
702
Brian Silverman8070a222013-02-28 15:01:36 -0800703void Run(void *watch);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800704void Main() {
705 logging::Init();
Brian Silverman0eec9532013-02-27 20:24:16 -0800706 // TODO(brians): tell logging that using the root logger from here until we
Brian Silvermand169fcd2013-02-27 13:18:47 -0800707 // bring up shm is ok
708
Brian Silverman5cc661b2013-02-27 15:23:36 -0800709 if (setpgid(0 /*self*/, 0 /*make PGID the same as PID*/) != 0) {
Brian Silverman01be0002014-05-10 15:44:38 -0700710 PLOG(FATAL, "setpgid(0, 0) failed");
Brian Silverman5cc661b2013-02-27 15:23:36 -0800711 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800712
713 // Make sure that we kill all children when we exit.
Brian Silverman5cc661b2013-02-27 15:23:36 -0800714 atexit(ExitHandler);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800715 // Do it on some signals too (ones that we otherwise tend to receive and then
716 // leave all of our children going).
Brian Silverman5cc661b2013-02-27 15:23:36 -0800717 signal(SIGHUP, KillChildrenSignalHandler);
718 signal(SIGINT, KillChildrenSignalHandler);
719 signal(SIGQUIT, KillChildrenSignalHandler);
720 signal(SIGILL, KillChildrenSignalHandler);
721 signal(SIGABRT, KillChildrenSignalHandler);
722 signal(SIGFPE, KillChildrenSignalHandler);
723 signal(SIGSEGV, KillChildrenSignalHandler);
724 signal(SIGPIPE, KillChildrenSignalHandler);
725 signal(SIGTERM, KillChildrenSignalHandler);
726 signal(SIGBUS, KillChildrenSignalHandler);
727 signal(SIGXCPU, KillChildrenSignalHandler);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800728
729 libevent_base = EventBaseUniquePtr(event_base_new());
730
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800731 std::string core_touch_file = "/tmp/starter.";
Brian Silvermand169fcd2013-02-27 13:18:47 -0800732 core_touch_file += std::to_string(static_cast<intmax_t>(getpid()));
733 core_touch_file += ".core_touch_file";
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800734 if (system(("touch '" + core_touch_file + "'").c_str()) != 0) {
Brian Silverman01be0002014-05-10 15:44:38 -0700735 PLOG(FATAL, "running `touch '%s'` failed\n", core_touch_file.c_str());
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800736 }
737 FileWatch core_touch_file_watch(core_touch_file, Run, NULL);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800738 core = unique_ptr<Child>(
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800739 new Child("core " + core_touch_file));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800740
741 FILE *pid_file = fopen("/tmp/starter.pid", "w");
742 if (pid_file == NULL) {
Brian Silverman01be0002014-05-10 15:44:38 -0700743 PLOG(FATAL, "fopen(\"/tmp/starter.pid\", \"w\") failed");
Brian Silvermand169fcd2013-02-27 13:18:47 -0800744 } else {
745 if (fprintf(pid_file, "%d", core->pid()) == -1) {
Brian Silverman01be0002014-05-10 15:44:38 -0700746 PLOG(WARNING, "fprintf(%p, \"%%d\", %d) failed",
747 pid_file, core->pid());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800748 }
749 fclose(pid_file);
750 }
751
752 LOG(INFO, "waiting for %s to appear\n", core_touch_file.c_str());
753
754 event_base_dispatch(libevent_base.get());
755 LOG(FATAL, "event_base_dispatch(%p) returned\n", libevent_base.get());
756}
757
Brian Silverman0eec9532013-02-27 20:24:16 -0800758// This is the callback for when core creates the file indicating that it has
759// started.
760void Run(void *watch) {
761 // Make it so it doesn't keep on seeing random changes in /tmp.
762 static_cast<FileWatch *>(watch)->RemoveWatch();
763
764 // It's safe now because core is up.
765 aos::InitNRT();
766
767 std::ifstream list_file(child_list_file);
768
769 while (true) {
770 std::string child_name;
771 getline(list_file, child_name);
772 if ((list_file.rdstate() & std::ios_base::eofbit) != 0) {
773 break;
774 }
775 if (list_file.rdstate() != 0) {
776 LOG(FATAL, "reading input file %s failed\n", child_list_file);
777 }
778 children.push_back(unique_ptr<Child>(new Child(child_name)));
779 }
780
781 EventUniquePtr sigchld(event_new(libevent_base.get(), SIGCHLD,
782 EV_SIGNAL | EV_PERSIST,
783 SigCHLDReceived, NULL));
784 event_add(sigchld.release(), NULL);
785}
786
Brian Silverman8070a222013-02-28 15:01:36 -0800787const char *kArgsHelp = "[OPTION]... START_LIST\n"
788 "Start all of the robot code binaries in START_LIST.\n"
789 "\n"
790 "START_LIST is the file to read binaries (looked up on PATH) to run.\n"
791 " --help display this help and exit\n";
792void PrintHelp() {
793 fprintf(stderr, "Usage: %s %s", program_invocation_name, kArgsHelp);
794}
795
Brian Silvermand169fcd2013-02-27 13:18:47 -0800796} // namespace starter
797} // namespace aos
798
799int main(int argc, char *argv[]) {
Brian Silverman8070a222013-02-28 15:01:36 -0800800 if (argc != 2) {
801 aos::starter::PrintHelp();
Brian Silvermand169fcd2013-02-27 13:18:47 -0800802 exit(EXIT_FAILURE);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800803 }
Brian Silverman8070a222013-02-28 15:01:36 -0800804 if (strcmp(argv[1], "--help") == 0) {
805 aos::starter::PrintHelp();
806 exit(EXIT_SUCCESS);
807 }
808
Brian Silvermand169fcd2013-02-27 13:18:47 -0800809 aos::starter::child_list_file = argv[1];
810
811 aos::starter::Main();
812}