blob: a2545c24e390c1fb249d90b8745a9a7fbc60ce44 [file] [log] [blame]
Brian Silvermanaf784862014-05-13 08:14:55 -07001// This has to come before anybody drags in <stdlib.h> or else we end up with
2// the wrong version of WIFEXITED etc (for one thing, they don't const-qualify
3// their casts) (sometimes at least).
4#include <sys/wait.h>
5
Brian Silvermand169fcd2013-02-27 13:18:47 -08006#include <stdio.h>
7#include <stdlib.h>
8#include <sys/types.h>
9#include <fcntl.h>
10#include <sys/inotify.h>
11#include <sys/stat.h>
12#include <sys/ioctl.h>
Brian Silvermand169fcd2013-02-27 13:18:47 -080013#include <signal.h>
14#include <stdint.h>
15#include <errno.h>
16#include <string.h>
Brian Silvermand90b5fe2013-03-10 18:34:42 -070017#include <inttypes.h>
Brian Silvermand169fcd2013-02-27 13:18:47 -080018
19#include <map>
20#include <functional>
21#include <deque>
22#include <fstream>
23#include <queue>
24#include <list>
25#include <string>
26#include <vector>
27#include <memory>
Brian Silvermand94642c2014-03-27 18:21:41 -070028#include <set>
Brian Silvermand169fcd2013-02-27 13:18:47 -080029
Brian Silverman258b9172015-09-19 14:32:57 -040030#include "third_party/libevent/event.h"
Brian Silvermand169fcd2013-02-27 13:18:47 -080031
32#include "aos/common/logging/logging.h"
33#include "aos/common/logging/logging_impl.h"
Brian Silverman14fd0fb2014-01-14 21:42:01 -080034#include "aos/linux_code/init.h"
Brian Silvermand169fcd2013-02-27 13:18:47 -080035#include "aos/common/unique_malloc_ptr.h"
36#include "aos/common/time.h"
Brian Silverman5cc661b2013-02-27 15:23:36 -080037#include "aos/common/once.h"
Brian Silvermanaf784862014-05-13 08:14:55 -070038#include "aos/common/libc/aos_strsignal.h"
39#include "aos/common/util/run_command.h"
Brian Silvermand169fcd2013-02-27 13:18:47 -080040
41// This is the main piece of code that starts all of the rest of the code and
42// restarts it when the binaries are modified.
43//
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -080044// Throughout, the code is not terribly concerned with thread safety because
45// there is only 1 thread. It does some setup and then lets inotify run things
46// when appropriate.
47//
Brian Silverman5cc661b2013-02-27 15:23:36 -080048// NOTE: This program should never exit nicely. It catches all nice attempts to
49// exit, forwards them to all of the children that it has started, waits for
Brian Silvermand169fcd2013-02-27 13:18:47 -080050// them to exit nicely, and then SIGKILLs anybody left (which will always
51// include itself).
52
53using ::std::unique_ptr;
54
55namespace aos {
56namespace starter {
57
Brian Silverman0eec9532013-02-27 20:24:16 -080058// TODO(brians): split out the c++ libevent wrapper stuff into its own file(s)
Brian Silvermand169fcd2013-02-27 13:18:47 -080059class EventBaseDeleter {
60 public:
61 void operator()(event_base *base) {
Brian Silverman8070a222013-02-28 15:01:36 -080062 if (base == NULL) return;
Brian Silvermand169fcd2013-02-27 13:18:47 -080063 event_base_free(base);
64 }
65};
66typedef unique_ptr<event_base, EventBaseDeleter> EventBaseUniquePtr;
Brian Silverman5cc661b2013-02-27 15:23:36 -080067EventBaseUniquePtr libevent_base;
Brian Silvermand169fcd2013-02-27 13:18:47 -080068
69class EventDeleter {
70 public:
71 void operator()(event *evt) {
Brian Silverman8070a222013-02-28 15:01:36 -080072 if (evt == NULL) return;
Brian Silvermand169fcd2013-02-27 13:18:47 -080073 if (event_del(evt) != 0) {
74 LOG(WARNING, "event_del(%p) failed\n", evt);
75 }
76 }
77};
78typedef unique_ptr<event, EventDeleter> EventUniquePtr;
79
Brian Silverman5cc661b2013-02-27 15:23:36 -080080// Watches a file path for modifications. Once created, keeps watching until
81// destroyed or RemoveWatch() is called.
Brian Silverman0eec9532013-02-27 20:24:16 -080082// TODO(brians): split this out into its own file + tests
Brian Silvermand169fcd2013-02-27 13:18:47 -080083class FileWatch {
84 public:
85 // Will call callback(value) when filename is modified.
86 // If value is NULL, then a pointer to this object will be passed instead.
Brian Silverman5cc661b2013-02-27 15:23:36 -080087 //
88 // Watching for file creations is slightly different. To do that, pass true
Brian Silverman8070a222013-02-28 15:01:36 -080089 // as create, the directory where the file will be created for filename, and
Brian Silverman5cc661b2013-02-27 15:23:36 -080090 // the name of the file (without directory name) for check_filename.
Brian Silvermand169fcd2013-02-27 13:18:47 -080091 FileWatch(std::string filename,
Brian Silverman8070a222013-02-28 15:01:36 -080092 std::function<void(void *)> callback,
93 void *value,
94 bool create = false,
95 std::string check_filename = "")
96 : filename_(filename),
97 callback_(callback),
98 value_(value),
Brian Silvermand90b5fe2013-03-10 18:34:42 -070099 create_(create),
100 check_filename_(check_filename),
101 watch_(-1) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800102 init_once.Get();
103
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700104 CreateWatch();
Brian Silvermand169fcd2013-02-27 13:18:47 -0800105 }
106 // Cleans up everything.
107 ~FileWatch() {
108 if (watch_ != -1) {
109 RemoveWatch();
110 }
111 }
112
113 // After calling this method, this object won't really be doing much of
Brian Silverman5cc661b2013-02-27 15:23:36 -0800114 // anything besides possibly running its callback or something.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800115 void RemoveWatch() {
Brian Silvermanfe457de2014-05-26 22:04:08 -0700116 CHECK_NE(watch_, -1);
117 CHECK_EQ(watch_to_remove_, -1);
Brian Silverman5cc661b2013-02-27 15:23:36 -0800118
Brian Silvermand169fcd2013-02-27 13:18:47 -0800119 if (inotify_rm_watch(notify_fd, watch_) == -1) {
Brian Silverman01be0002014-05-10 15:44:38 -0700120 PLOG(WARNING, "inotify_rm_watch(%d, %d) failed", notify_fd, watch_);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800121 }
Brian Silvermand94642c2014-03-27 18:21:41 -0700122 watch_to_remove_ = watch_;
123 watch_ = -1;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800124 }
125
Brian Silverman5cc661b2013-02-27 15:23:36 -0800126 private:
127 // Performs the static initialization. Called by init_once from the
128 // constructor.
129 static void *Init() {
130 notify_fd = inotify_init1(IN_CLOEXEC);
131 EventUniquePtr notify_event(event_new(libevent_base.get(), notify_fd,
132 EV_READ | EV_PERSIST,
133 FileWatch::INotifyReadable, NULL));
134 event_add(notify_event.release(), NULL);
135 return NULL;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800136 }
137
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700138 void RemoveWatchFromMap() {
Brian Silvermand94642c2014-03-27 18:21:41 -0700139 int watch = watch_to_remove_;
140 if (watch == -1) {
Brian Silverman67550242014-07-19 16:58:19 -0700141 CHECK_NE(watch_, -1);
Brian Silvermand94642c2014-03-27 18:21:41 -0700142 watch = watch_;
143 }
144 if (watchers[watch] != this) {
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700145 LOG(WARNING, "watcher for %s (%p) didn't find itself in the map\n",
146 filename_.c_str(), this);
147 } else {
Brian Silvermand94642c2014-03-27 18:21:41 -0700148 watchers.erase(watch);
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700149 }
Brian Silvermand94642c2014-03-27 18:21:41 -0700150 LOG(DEBUG, "removed watch ID %d\n", watch);
151 if (watch_to_remove_ == -1) {
152 watch_ = -1;
153 } else {
154 watch_to_remove_ = -1;
155 }
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700156 }
157
158 void CreateWatch() {
Brian Silvermanfe457de2014-05-26 22:04:08 -0700159 CHECK_EQ(watch_, -1);
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700160 watch_ = inotify_add_watch(notify_fd, filename_.c_str(),
161 create_ ? IN_CREATE : (IN_ATTRIB |
162 IN_MODIFY |
163 IN_DELETE_SELF |
164 IN_MOVE_SELF));
165 if (watch_ == -1) {
Brian Silverman01be0002014-05-10 15:44:38 -0700166 PLOG(FATAL, "inotify_add_watch(%d, %s,"
167 " %s ? IN_CREATE : (IN_ATTRIB | IN_MODIFY)) failed",
168 notify_fd, filename_.c_str(), create_ ? "true" : "false");
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700169 }
170 watchers[watch_] = this;
171 LOG(DEBUG, "watch for %s is %d\n", filename_.c_str(), watch_);
172 }
173
Brian Silvermand169fcd2013-02-27 13:18:47 -0800174 // This gets set up as the callback for EV_READ on the inotify file
Brian Silverman5cc661b2013-02-27 15:23:36 -0800175 // descriptor. It calls FileNotified on the appropriate instance.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800176 static void INotifyReadable(int /*fd*/, short /*events*/, void *) {
177 unsigned int to_read;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800178 // Use FIONREAD to figure out how many bytes there are to read.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800179 if (ioctl(notify_fd, FIONREAD, &to_read) < 0) {
Brian Silverman01be0002014-05-10 15:44:38 -0700180 PLOG(FATAL, "FIONREAD(%d, %p) failed", notify_fd, &to_read);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800181 }
182 inotify_event *notifyevt = static_cast<inotify_event *>(malloc(to_read));
183 const char *end = reinterpret_cast<char *>(notifyevt) + to_read;
184 aos::unique_c_ptr<inotify_event> freer(notifyevt);
185
186 ssize_t ret = read(notify_fd, notifyevt, to_read);
187 if (ret < 0) {
Brian Silverman01be0002014-05-10 15:44:38 -0700188 PLOG(FATAL, "read(%d, %p, %u) failed", notify_fd, notifyevt, to_read);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800189 }
190 if (static_cast<size_t>(ret) != to_read) {
191 LOG(ERROR, "read(%d, %p, %u) returned %zd instead of %u\n",
192 notify_fd, notifyevt, to_read, ret, to_read);
193 return;
194 }
195
Brian Silverman5cc661b2013-02-27 15:23:36 -0800196 // Keep looping through until we get to the end because inotify does return
197 // multiple events at once.
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800198 while (reinterpret_cast<char *>(notifyevt) < end) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800199 if (watchers.count(notifyevt->wd) != 1) {
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800200 LOG(WARNING, "couldn't find whose watch ID %d is\n", notifyevt->wd);
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800201 } else {
Brian Silverman8efe23e2013-07-07 23:31:37 -0700202 LOG(DEBUG, "mask=%" PRIu32 "\n", notifyevt->mask);
Brian Silvermand94642c2014-03-27 18:21:41 -0700203 // If the watch was removed.
204 if (notifyevt->mask & IN_IGNORED) {
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700205 watchers[notifyevt->wd]->WatchDeleted();
206 } else {
Brian Silvermand94642c2014-03-27 18:21:41 -0700207 watchers[notifyevt->wd]
208 ->FileNotified((notifyevt->len > 0) ? notifyevt->name : NULL);
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700209 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800210 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800211
212 notifyevt = reinterpret_cast<inotify_event *>(
Brian Silvermandbdf1d02013-11-17 13:19:41 -0800213 __builtin_assume_aligned(reinterpret_cast<char *>(notifyevt) +
214 sizeof(*notifyevt) + notifyevt->len,
Brian Silvermanafc00a62014-04-21 17:51:23 -0700215 alignof(inotify_event)));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800216 }
217 }
218
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700219 // INotifyReadable calls this method whenever the watch for our file gets
220 // removed somehow.
221 void WatchDeleted() {
222 LOG(DEBUG, "watch for %s deleted\n", filename_.c_str());
223 RemoveWatchFromMap();
224 CreateWatch();
225 }
226
Brian Silverman5cc661b2013-02-27 15:23:36 -0800227 // INotifyReadable calls this method whenever the watch for our file triggers.
228 void FileNotified(const char *filename) {
Brian Silvermanfe457de2014-05-26 22:04:08 -0700229 CHECK_NE(watch_, -1);
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800230 LOG(DEBUG, "got a notification for %s\n", filename_.c_str());
Brian Silverman5cc661b2013-02-27 15:23:36 -0800231
232 if (!check_filename_.empty()) {
233 if (filename == NULL) {
234 return;
235 }
236 if (std::string(filename) != check_filename_) {
237 return;
238 }
239 }
240
241 callback_((value_ == NULL) ? this : value_);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800242 }
243
Brian Silverman5cc661b2013-02-27 15:23:36 -0800244 // To make sure that Init gets called exactly once.
245 static ::aos::Once<void> init_once;
246
Brian Silvermand169fcd2013-02-27 13:18:47 -0800247 const std::string filename_;
248 const std::function<void(void *)> callback_;
249 void *const value_;
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700250 const bool create_;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800251 std::string check_filename_;
252
253 // The watch descriptor or -1 if we don't have one any more.
254 int watch_;
Brian Silvermand94642c2014-03-27 18:21:41 -0700255 // The watch that we still have to take out of the map once we get the
256 // IN_IGNORED or -1.
257 int watch_to_remove_ = -1;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800258
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -0800259 // Map from watch IDs to instances of this class.
260 // <https://patchwork.kernel.org/patch/73192/> ("inotify: do not reuse watch
261 // descriptors") says they won't get reused, but that shouldn't be counted on
262 // because we might have a modified/different version/whatever kernel.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800263 static std::map<int, FileWatch *> watchers;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800264 // The inotify(7) file descriptor.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800265 static int notify_fd;
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -0800266
267 DISALLOW_COPY_AND_ASSIGN(FileWatch);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800268};
Brian Silverman5cc661b2013-02-27 15:23:36 -0800269::aos::Once<void> FileWatch::init_once(FileWatch::Init);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800270std::map<int, FileWatch *> FileWatch::watchers;
271int FileWatch::notify_fd;
272
Brian Silverman5cc661b2013-02-27 15:23:36 -0800273// Runs the given command and returns its first line of output (not including
274// the \n). LOG(FATAL)s if the command has an exit status other than 0 or does
275// not print out an entire line.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800276std::string RunCommand(std::string command) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800277 // popen(3) might fail and not set it.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800278 errno = 0;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800279 FILE *pipe = popen(command.c_str(), "r");
280 if (pipe == NULL) {
Brian Silverman01be0002014-05-10 15:44:38 -0700281 PLOG(FATAL, "popen(\"%s\", \"r\") failed", command.c_str());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800282 }
283
Brian Silverman5cc661b2013-02-27 15:23:36 -0800284 // result_size is how many bytes result is currently allocated to.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800285 size_t result_size = 128, read = 0;
286 unique_c_ptr<char> result(static_cast<char *>(malloc(result_size)));
287 while (true) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800288 // If we filled up the buffer, then realloc(3) it bigger.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800289 if (read == result_size) {
290 result_size *= 2;
291 void *new_result = realloc(result.get(), result_size);
292 if (new_result == NULL) {
Brian Silverman01be0002014-05-10 15:44:38 -0700293 PLOG(FATAL, "realloc(%p, %zd) failed", result.get(), result_size);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800294 } else {
295 result.release();
296 result = unique_c_ptr<char>(static_cast<char *>(new_result));
297 }
298 }
299
Brian Silverman5cc661b2013-02-27 15:23:36 -0800300 size_t ret = fread(result.get() + read, 1, result_size - read, pipe);
301 // If the read didn't fill up the whole buffer, check to see if it was
302 // because of an error.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800303 if (ret < result_size - read) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800304 if (ferror(pipe)) {
Brian Silverman01be0002014-05-10 15:44:38 -0700305 PLOG(FATAL, "couldn't finish reading output of \"%s\"\n",
306 command.c_str());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800307 }
308 }
309 read += ret;
310 if (read > 0 && result.get()[read - 1] == '\n') {
311 break;
312 }
313
Brian Silverman5cc661b2013-02-27 15:23:36 -0800314 if (feof(pipe)) {
315 LOG(FATAL, "`%s` failed. didn't print a whole line\n", command.c_str());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800316 }
317 }
318
Brian Silverman5cc661b2013-02-27 15:23:36 -0800319 // Get rid of the first \n and anything after it.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800320 *strchrnul(result.get(), '\n') = '\0';
321
Brian Silverman5cc661b2013-02-27 15:23:36 -0800322 int child_status = pclose(pipe);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800323 if (child_status == -1) {
Brian Silverman01be0002014-05-10 15:44:38 -0700324 PLOG(FATAL, "pclose(%p) failed", pipe);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800325 }
326
327 if (child_status != 0) {
328 LOG(FATAL, "`%s` failed. return %d\n", command.c_str(), child_status);
329 }
330
331 return std::string(result.get());
332}
333
334// Will call callback(arg) after time.
335void Timeout(time::Time time, void (*callback)(int, short, void *), void *arg) {
336 EventUniquePtr timeout(evtimer_new(libevent_base.get(), callback, arg));
337 struct timeval time_timeval = time.ToTimeval();
Brian Silvermand94642c2014-03-27 18:21:41 -0700338 if (evtimer_add(timeout.release(), &time_timeval) != 0) {
339 LOG(FATAL, "evtimer_add(%p, %p) failed\n",
340 timeout.release(), &time_timeval);
341 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800342}
343
Brian Silvermand94642c2014-03-27 18:21:41 -0700344class Child;
345// This is where all of the Child instances except core live.
346std::vector<unique_ptr<Child>> children;
347// A global place to hold on to which child is core.
348unique_ptr<Child> core;
349
Brian Silvermand169fcd2013-02-27 13:18:47 -0800350// Represents a child process. It will take care of restarting itself etc.
351class Child {
352 public:
Brian Silverman5cc661b2013-02-27 15:23:36 -0800353 // command is the (space-separated) command to run and its arguments.
354 Child(const std::string &command) : pid_(-1),
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800355 stat_at_start_valid_(false) {
Brian Silvermand94642c2014-03-27 18:21:41 -0700356 if (!restart_timeout) {
357 restart_timeout = EventUniquePtr(
358 evtimer_new(libevent_base.get(), StaticDoRestart, nullptr));
359 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800360 const char *start, *end;
361 start = command.c_str();
362 while (true) {
363 end = strchrnul(start, ' ');
364 args_.push_back(std::string(start, end - start));
365 start = end + 1;
366 if (*end == '\0') {
367 break;
368 }
369 }
370
Brian Silverman5cc661b2013-02-27 15:23:36 -0800371 original_binary_ = RunCommand("which " + args_[0]);
372 binary_ = original_binary_ + ".stm";
Brian Silvermand169fcd2013-02-27 13:18:47 -0800373
374 watcher_ = unique_ptr<FileWatch>(
Brian Silverman5cc661b2013-02-27 15:23:36 -0800375 new FileWatch(original_binary_, StaticFileModified, this));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800376
377 Start();
378 }
379
380 pid_t pid() { return pid_; }
381
382 // This gets called whenever the actual process dies and should (probably) be
383 // restarted.
384 void ProcessDied() {
385 pid_ = -1;
386 restarts_.push(time::Time::Now());
387 if (restarts_.size() > kMaxRestartsNumber) {
388 time::Time oldest = restarts_.front();
389 restarts_.pop();
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700390 if ((time::Time::Now() - oldest) <= kMaxRestartsTime) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800391 LOG(WARNING, "process %s getting restarted too often\n", name());
392 Timeout(kResumeWait, StaticStart, this);
393 return;
394 }
395 }
396 Start();
397 }
398
399 // Returns a name for logging purposes.
400 const char *name() {
401 return args_[0].c_str();
402 }
403
404 private:
405 struct CheckDiedStatus {
406 Child *self;
407 pid_t old_pid;
408 };
409
410 // How long to wait for a child to die nicely.
Brian Silvermand94642c2014-03-27 18:21:41 -0700411 static constexpr time::Time kProcessDieTime = time::Time::InSeconds(2);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800412
413 // How long to wait after the file is modified to restart it.
414 // This is important because some programs like modifying the binaries by
415 // writing them in little bits, which results in attempting to start partial
416 // binaries without this.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700417 static constexpr time::Time kRestartWaitTime = time::Time::InSeconds(1.5);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800418
Brian Silverman5cc661b2013-02-27 15:23:36 -0800419 // Only kMaxRestartsNumber restarts will be allowed in kMaxRestartsTime.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700420 static constexpr time::Time kMaxRestartsTime = time::Time::InSeconds(4);
421 static const size_t kMaxRestartsNumber = 3;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800422 // How long to wait if it gets restarted too many times.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700423 static constexpr time::Time kResumeWait = time::Time::InSeconds(5);
Brian Silverman5cc661b2013-02-27 15:23:36 -0800424
Brian Silvermand169fcd2013-02-27 13:18:47 -0800425 static void StaticFileModified(void *self) {
426 static_cast<Child *>(self)->FileModified();
427 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800428
Brian Silvermand169fcd2013-02-27 13:18:47 -0800429 void FileModified() {
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700430 LOG(DEBUG, "file for %s modified\n", name());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800431 struct timeval restart_time_timeval = kRestartWaitTime.ToTimeval();
432 // This will reset the timeout again if it hasn't run yet.
Brian Silvermand94642c2014-03-27 18:21:41 -0700433 if (evtimer_add(restart_timeout.get(), &restart_time_timeval) != 0) {
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700434 LOG(FATAL, "evtimer_add(%p, %p) failed\n",
Brian Silvermand94642c2014-03-27 18:21:41 -0700435 restart_timeout.get(), &restart_time_timeval);
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700436 }
Brian Silvermand94642c2014-03-27 18:21:41 -0700437 waiting_to_restart.insert(this);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800438 }
439
Brian Silvermand94642c2014-03-27 18:21:41 -0700440 static void StaticDoRestart(int, short, void *) {
441 LOG(DEBUG, "restarting everything that needs it\n");
442 if (waiting_to_restart.find(core.get()) != waiting_to_restart.end()) {
443 core->DoRestart();
444 waiting_to_restart.erase(core.get());
445 }
446 for (auto c : waiting_to_restart) {
447 c->DoRestart();
448 }
449 waiting_to_restart.clear();
Brian Silvermand169fcd2013-02-27 13:18:47 -0800450 }
451
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800452 // Called after somebody else has finished modifying the file.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800453 void DoRestart() {
Brian Silvermand94642c2014-03-27 18:21:41 -0700454 fprintf(stderr, "DoRestart(%s)\n", binary_.c_str());
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800455 if (stat_at_start_valid_) {
456 struct stat current_stat;
457 if (stat(original_binary_.c_str(), &current_stat) == -1) {
Brian Silverman01be0002014-05-10 15:44:38 -0700458 PLOG(FATAL, "stat(%s, %p) failed",
459 original_binary_.c_str(), &current_stat);
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800460 }
461 if (current_stat.st_mtime == stat_at_start_.st_mtime) {
462 LOG(DEBUG, "ignoring trigger for %s because mtime didn't change\n",
463 name());
464 return;
465 }
466 }
467
Brian Silvermand94642c2014-03-27 18:21:41 -0700468 if (this == core.get()) {
469 fprintf(stderr, "Restarting core -> exiting now.\n");
470 exit(0);
471 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800472 if (pid_ != -1) {
473 LOG(DEBUG, "sending SIGTERM to child %d to restart it\n", pid_);
474 if (kill(pid_, SIGTERM) == -1) {
Brian Silverman01be0002014-05-10 15:44:38 -0700475 PLOG(WARNING, "kill(%d, SIGTERM) failed", pid_);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800476 }
477 CheckDiedStatus *status = new CheckDiedStatus();
478 status->self = this;
479 status->old_pid = pid_;
480 Timeout(kProcessDieTime, StaticCheckDied, status);
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700481 } else {
482 LOG(WARNING, "%s restart attempted but not running\n", name());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800483 }
484 }
485
486 static void StaticCheckDied(int, short, void *status_in) {
487 CheckDiedStatus *status = static_cast<CheckDiedStatus *>(status_in);
488 status->self->CheckDied(status->old_pid);
489 delete status;
490 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800491
492 // Checks to see if the child using the PID old_pid is still running.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800493 void CheckDied(pid_t old_pid) {
494 if (pid_ == old_pid) {
495 LOG(WARNING, "child %d refused to die\n", old_pid);
496 if (kill(old_pid, SIGKILL) == -1) {
Brian Silverman01be0002014-05-10 15:44:38 -0700497 PLOG(WARNING, "kill(%d, SIGKILL) failed", old_pid);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800498 }
499 }
500 }
501
502 static void StaticStart(int, short, void *self) {
503 static_cast<Child *>(self)->Start();
504 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800505
506 // Actually starts the child.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800507 void Start() {
508 if (pid_ != -1) {
509 LOG(WARNING, "calling Start() but already have child %d running\n",
510 pid_);
Brian Silverman5cc661b2013-02-27 15:23:36 -0800511 if (kill(pid_, SIGKILL) == -1) {
Brian Silverman01be0002014-05-10 15:44:38 -0700512 PLOG(WARNING, "kill(%d, SIGKILL) failed", pid_);
Brian Silverman5cc661b2013-02-27 15:23:36 -0800513 return;
514 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800515 pid_ = -1;
516 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800517
518 // Remove the name that we run from (ie from a previous execution) and then
519 // hard link the real filename to it.
520 if (unlink(binary_.c_str()) != 0 && errno != ENOENT) {
Brian Silverman01be0002014-05-10 15:44:38 -0700521 PLOG(FATAL, "removing %s failed", binary_.c_str());
Brian Silverman5cc661b2013-02-27 15:23:36 -0800522 }
523 if (link(original_binary_.c_str(), binary_.c_str()) != 0) {
Brian Silverman01be0002014-05-10 15:44:38 -0700524 PLOG(FATAL, "link('%s', '%s') failed",
525 original_binary_.c_str(), binary_.c_str());
Brian Silverman5cc661b2013-02-27 15:23:36 -0800526 }
527
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800528 if (stat(original_binary_.c_str(), &stat_at_start_) == -1) {
Brian Silverman01be0002014-05-10 15:44:38 -0700529 PLOG(FATAL, "stat(%s, %p) failed",
530 original_binary_.c_str(), &stat_at_start_);
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800531 }
532 stat_at_start_valid_ = true;
533
Brian Silvermand169fcd2013-02-27 13:18:47 -0800534 if ((pid_ = fork()) == 0) {
535 ssize_t args_size = args_.size();
536 const char **argv = new const char *[args_size + 1];
537 for (int i = 0; i < args_size; ++i) {
538 argv[i] = args_[i].c_str();
539 }
540 argv[args_size] = NULL;
541 // The const_cast is safe because no code that might care if it gets
542 // modified can run afterwards.
543 execv(binary_.c_str(), const_cast<char **>(argv));
Brian Silverman01be0002014-05-10 15:44:38 -0700544 PLOG(FATAL, "execv(%s, %p) failed", binary_.c_str(), argv);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800545 _exit(EXIT_FAILURE);
546 }
547 if (pid_ == -1) {
Brian Silverman01be0002014-05-10 15:44:38 -0700548 PLOG(FATAL, "forking to run \"%s\" failed", binary_.c_str());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800549 }
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700550 LOG(DEBUG, "started \"%s\" successfully\n", binary_.c_str());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800551 }
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -0800552
553 // A history of the times that this process has been restarted.
554 std::queue<time::Time, std::list<time::Time>> restarts_;
555
556 // The currently running child's PID or NULL.
557 pid_t pid_;
558
559 // All of the arguments (including the name of the binary).
560 std::deque<std::string> args_;
561
562 // The name of the real binary that we were told to run.
563 std::string original_binary_;
564 // The name of the file that we're actually running.
565 std::string binary_;
566
567 // Watches original_binary_.
568 unique_ptr<FileWatch> watcher_;
569
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -0800570 // Captured from the original file when we most recently started a new child
571 // process. Used to see if it actually changes or not.
572 struct stat stat_at_start_;
573 bool stat_at_start_valid_;
574
Brian Silvermand94642c2014-03-27 18:21:41 -0700575 // An event that restarts after kRestartWaitTime.
576 static EventUniquePtr restart_timeout;
577
578 // The set of children waiting to be restarted once all modifications stop.
579 static ::std::set<Child *> waiting_to_restart;
580
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -0800581 DISALLOW_COPY_AND_ASSIGN(Child);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800582};
Brian Silverman52aeeac2013-08-28 16:20:53 -0700583
584constexpr time::Time Child::kProcessDieTime;
585constexpr time::Time Child::kRestartWaitTime;
586constexpr time::Time Child::kMaxRestartsTime;
587constexpr time::Time Child::kResumeWait;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800588
Brian Silvermand94642c2014-03-27 18:21:41 -0700589EventUniquePtr Child::restart_timeout;
590::std::set<Child *> Child::waiting_to_restart;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800591
Brian Silverman5cc661b2013-02-27 15:23:36 -0800592// Kills off the entire process group (including ourself).
593void KillChildren(bool try_nice) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800594 if (try_nice) {
595 static const int kNiceStopSignal = SIGTERM;
596 static const time::Time kNiceWaitTime = time::Time::InSeconds(1);
597
598 // Make sure that we don't just nicely stop ourself...
599 sigset_t mask;
600 sigemptyset(&mask);
601 sigaddset(&mask, kNiceStopSignal);
602 sigprocmask(SIG_BLOCK, &mask, NULL);
603
Brian Silverman5cc661b2013-02-27 15:23:36 -0800604 kill(-getpid(), kNiceStopSignal);
605
606 fflush(NULL);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800607 time::SleepFor(kNiceWaitTime);
608 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800609
Brian Silvermand169fcd2013-02-27 13:18:47 -0800610 // Send SIGKILL to our whole process group, which will forcibly terminate any
611 // of them that are still running (us for sure, maybe more too).
Brian Silverman5cc661b2013-02-27 15:23:36 -0800612 kill(-getpid(), SIGKILL);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800613}
614
Brian Silverman5cc661b2013-02-27 15:23:36 -0800615void ExitHandler() {
616 KillChildren(true);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800617}
Brian Silverman5cc661b2013-02-27 15:23:36 -0800618
619void KillChildrenSignalHandler(int signum) {
620 // If we get SIGSEGV or some other random signal who knows what's happening
621 // and we should just kill everybody immediately.
622 // This is a list of all of the signals that mean some form of "nicely stop".
623 KillChildren(signum == SIGHUP || signum == SIGINT || signum == SIGQUIT ||
Brian Silverman0eec9532013-02-27 20:24:16 -0800624 signum == SIGABRT || signum == SIGPIPE || signum == SIGTERM ||
625 signum == SIGXCPU);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800626}
627
Brian Silverman5cc661b2013-02-27 15:23:36 -0800628// Returns the currently running child with PID pid or an empty unique_ptr.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800629const unique_ptr<Child> &FindChild(pid_t pid) {
630 for (auto it = children.begin(); it != children.end(); ++it) {
631 if (pid == (*it)->pid()) {
632 return *it;
633 }
634 }
635
636 if (pid == core->pid()) {
637 return core;
638 }
639
Brian Silverman5cc661b2013-02-27 15:23:36 -0800640 static const unique_ptr<Child> kNothing;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800641 return kNothing;
642}
643
Brian Silverman5cc661b2013-02-27 15:23:36 -0800644// Gets set up as a libevent handler for SIGCHLD.
645// Handles calling Child::ProcessDied() on the appropriate one.
646void SigCHLDReceived(int /*fd*/, short /*events*/, void *) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800647 // In a while loop in case we miss any SIGCHLDs.
648 while (true) {
649 siginfo_t infop;
650 infop.si_pid = 0;
651 if (waitid(P_ALL, 0, &infop, WEXITED | WSTOPPED | WNOHANG) != 0) {
Brian Silverman01be0002014-05-10 15:44:38 -0700652 PLOG(WARNING, "waitid failed");
Brian Silverman5cc661b2013-02-27 15:23:36 -0800653 continue;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800654 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800655 // If there are no more child process deaths to process.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800656 if (infop.si_pid == 0) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800657 return;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800658 }
659
660 pid_t pid = infop.si_pid;
661 int status = infop.si_status;
662 const unique_ptr<Child> &child = FindChild(pid);
663 if (child) {
664 switch (infop.si_code) {
665 case CLD_EXITED:
666 LOG(WARNING, "child %d (%s) exited with status %d\n",
667 pid, child->name(), status);
668 break;
669 case CLD_DUMPED:
670 LOG(INFO, "child %d actually dumped core. "
671 "falling through to killed by signal case\n", pid);
672 case CLD_KILLED:
673 // If somebody (possibly us) sent it SIGTERM that means that they just
674 // want it to stop, so it stopping isn't a WARNING.
675 LOG((status == SIGTERM) ? DEBUG : WARNING,
676 "child %d (%s) was killed by signal %d (%s)\n",
Brian Silvermanaf784862014-05-13 08:14:55 -0700677 pid, child->name(), status, aos_strsignal(status));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800678 break;
679 case CLD_STOPPED:
680 LOG(WARNING, "child %d (%s) was stopped by signal %d "
681 "(giving it a SIGCONT(%d))\n",
682 pid, child->name(), status, SIGCONT);
683 kill(pid, SIGCONT);
684 continue;
685 default:
686 LOG(WARNING, "something happened to child %d (%s) (killing it)\n",
687 pid, child->name());
688 kill(pid, SIGKILL);
689 continue;
690 }
691 } else {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800692 LOG(WARNING, "couldn't find a Child for pid %d\n", pid);
693 return;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800694 }
695
Brian Silverman5cc661b2013-02-27 15:23:36 -0800696 if (child == core) {
697 LOG(FATAL, "core died\n");
698 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800699 child->ProcessDied();
700 }
701}
702
Brian Silverman5cc661b2013-02-27 15:23:36 -0800703// This is used for communicating the name of the file to read processes to
704// start from main to Run.
705const char *child_list_file;
706
Brian Silverman8070a222013-02-28 15:01:36 -0800707void Run(void *watch);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800708void Main() {
709 logging::Init();
Brian Silvermand169fcd2013-02-27 13:18:47 -0800710
Brian Silverman5cc661b2013-02-27 15:23:36 -0800711 if (setpgid(0 /*self*/, 0 /*make PGID the same as PID*/) != 0) {
Brian Silverman01be0002014-05-10 15:44:38 -0700712 PLOG(FATAL, "setpgid(0, 0) failed");
Brian Silverman5cc661b2013-02-27 15:23:36 -0800713 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800714
715 // Make sure that we kill all children when we exit.
Brian Silverman5cc661b2013-02-27 15:23:36 -0800716 atexit(ExitHandler);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800717 // Do it on some signals too (ones that we otherwise tend to receive and then
718 // leave all of our children going).
Brian Silverman5cc661b2013-02-27 15:23:36 -0800719 signal(SIGHUP, KillChildrenSignalHandler);
720 signal(SIGINT, KillChildrenSignalHandler);
721 signal(SIGQUIT, KillChildrenSignalHandler);
722 signal(SIGILL, KillChildrenSignalHandler);
723 signal(SIGABRT, KillChildrenSignalHandler);
724 signal(SIGFPE, KillChildrenSignalHandler);
725 signal(SIGSEGV, KillChildrenSignalHandler);
726 signal(SIGPIPE, KillChildrenSignalHandler);
727 signal(SIGTERM, KillChildrenSignalHandler);
728 signal(SIGBUS, KillChildrenSignalHandler);
729 signal(SIGXCPU, KillChildrenSignalHandler);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800730
731 libevent_base = EventBaseUniquePtr(event_base_new());
732
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800733 std::string core_touch_file = "/tmp/starter.";
Brian Silvermand169fcd2013-02-27 13:18:47 -0800734 core_touch_file += std::to_string(static_cast<intmax_t>(getpid()));
735 core_touch_file += ".core_touch_file";
Brian Silvermanaf784862014-05-13 08:14:55 -0700736 const int result =
737 ::aos::util::RunCommand(("touch '" + core_touch_file + "'").c_str());
738 if (result == -1) {
Brian Silverman01be0002014-05-10 15:44:38 -0700739 PLOG(FATAL, "running `touch '%s'` failed\n", core_touch_file.c_str());
Brian Silvermanaf784862014-05-13 08:14:55 -0700740 } else if (!WIFEXITED(result) || WEXITSTATUS(result) != 0) {
741 LOG(FATAL, "`touch '%s'` gave result %x\n", core_touch_file.c_str(),
742 result);
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800743 }
744 FileWatch core_touch_file_watch(core_touch_file, Run, NULL);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800745 core = unique_ptr<Child>(
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800746 new Child("core " + core_touch_file));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800747
748 FILE *pid_file = fopen("/tmp/starter.pid", "w");
749 if (pid_file == NULL) {
Brian Silverman01be0002014-05-10 15:44:38 -0700750 PLOG(FATAL, "fopen(\"/tmp/starter.pid\", \"w\") failed");
Brian Silvermand169fcd2013-02-27 13:18:47 -0800751 } else {
752 if (fprintf(pid_file, "%d", core->pid()) == -1) {
Brian Silverman01be0002014-05-10 15:44:38 -0700753 PLOG(WARNING, "fprintf(%p, \"%%d\", %d) failed",
754 pid_file, core->pid());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800755 }
756 fclose(pid_file);
757 }
758
759 LOG(INFO, "waiting for %s to appear\n", core_touch_file.c_str());
760
761 event_base_dispatch(libevent_base.get());
762 LOG(FATAL, "event_base_dispatch(%p) returned\n", libevent_base.get());
763}
764
Brian Silverman0eec9532013-02-27 20:24:16 -0800765// This is the callback for when core creates the file indicating that it has
766// started.
767void Run(void *watch) {
768 // Make it so it doesn't keep on seeing random changes in /tmp.
769 static_cast<FileWatch *>(watch)->RemoveWatch();
770
771 // It's safe now because core is up.
772 aos::InitNRT();
773
774 std::ifstream list_file(child_list_file);
775
776 while (true) {
777 std::string child_name;
778 getline(list_file, child_name);
779 if ((list_file.rdstate() & std::ios_base::eofbit) != 0) {
780 break;
781 }
782 if (list_file.rdstate() != 0) {
783 LOG(FATAL, "reading input file %s failed\n", child_list_file);
784 }
785 children.push_back(unique_ptr<Child>(new Child(child_name)));
786 }
787
788 EventUniquePtr sigchld(event_new(libevent_base.get(), SIGCHLD,
789 EV_SIGNAL | EV_PERSIST,
790 SigCHLDReceived, NULL));
791 event_add(sigchld.release(), NULL);
792}
793
Brian Silverman8070a222013-02-28 15:01:36 -0800794const char *kArgsHelp = "[OPTION]... START_LIST\n"
795 "Start all of the robot code binaries in START_LIST.\n"
796 "\n"
797 "START_LIST is the file to read binaries (looked up on PATH) to run.\n"
798 " --help display this help and exit\n";
799void PrintHelp() {
800 fprintf(stderr, "Usage: %s %s", program_invocation_name, kArgsHelp);
801}
802
Brian Silvermand169fcd2013-02-27 13:18:47 -0800803} // namespace starter
804} // namespace aos
805
806int main(int argc, char *argv[]) {
Brian Silverman8070a222013-02-28 15:01:36 -0800807 if (argc != 2) {
808 aos::starter::PrintHelp();
Brian Silvermand169fcd2013-02-27 13:18:47 -0800809 exit(EXIT_FAILURE);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800810 }
Brian Silverman8070a222013-02-28 15:01:36 -0800811 if (strcmp(argv[1], "--help") == 0) {
812 aos::starter::PrintHelp();
813 exit(EXIT_SUCCESS);
814 }
815
Brian Silvermand169fcd2013-02-27 13:18:47 -0800816 aos::starter::child_list_file = argv[1];
817
818 aos::starter::Main();
819}