blob: b7060012e7d8ac851bc034e6b4ade7ee383481eb [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
John Park33858a32018-09-28 23:05:48 -070032#include "aos/libc/aos_strsignal.h"
33#include "aos/logging/implementations.h"
34#include "aos/logging/logging.h"
35#include "aos/time/time.h"
36#include "aos/unique_malloc_ptr.h"
37#include "aos/util/run_command.h"
John Park398c74a2018-10-20 21:17:39 -070038#include "aos/init.h"
John Park7bf05bf2019-12-02 21:33:19 -080039#include "absl/base/call_once.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
Austin Schuhf2a50ba2016-12-24 16:16:26 -080058namespace chrono = ::std::chrono;
59
Brian Silverman0eec9532013-02-27 20:24:16 -080060// TODO(brians): split out the c++ libevent wrapper stuff into its own file(s)
Brian Silvermand169fcd2013-02-27 13:18:47 -080061class EventBaseDeleter {
62 public:
63 void operator()(event_base *base) {
Brian Silverman8070a222013-02-28 15:01:36 -080064 if (base == NULL) return;
Brian Silvermand169fcd2013-02-27 13:18:47 -080065 event_base_free(base);
66 }
67};
68typedef unique_ptr<event_base, EventBaseDeleter> EventBaseUniquePtr;
Brian Silverman5cc661b2013-02-27 15:23:36 -080069EventBaseUniquePtr libevent_base;
Brian Silvermand169fcd2013-02-27 13:18:47 -080070
71class EventDeleter {
72 public:
73 void operator()(event *evt) {
Brian Silverman8070a222013-02-28 15:01:36 -080074 if (evt == NULL) return;
Brian Silvermand169fcd2013-02-27 13:18:47 -080075 if (event_del(evt) != 0) {
Austin Schuhf257f3c2019-10-27 21:00:43 -070076 AOS_LOG(WARNING, "event_del(%p) failed\n", evt);
Brian Silvermand169fcd2013-02-27 13:18:47 -080077 }
78 }
79};
80typedef unique_ptr<event, EventDeleter> EventUniquePtr;
81
Brian Silverman5cc661b2013-02-27 15:23:36 -080082// Watches a file path for modifications. Once created, keeps watching until
83// destroyed or RemoveWatch() is called.
Brian Silverman0eec9532013-02-27 20:24:16 -080084// TODO(brians): split this out into its own file + tests
Brian Silvermand169fcd2013-02-27 13:18:47 -080085class FileWatch {
86 public:
87 // Will call callback(value) when filename is modified.
88 // If value is NULL, then a pointer to this object will be passed instead.
Brian Silverman5cc661b2013-02-27 15:23:36 -080089 //
90 // Watching for file creations is slightly different. To do that, pass true
Brian Silverman8070a222013-02-28 15:01:36 -080091 // as create, the directory where the file will be created for filename, and
Brian Silverman5cc661b2013-02-27 15:23:36 -080092 // the name of the file (without directory name) for check_filename.
Brian Silvermand169fcd2013-02-27 13:18:47 -080093 FileWatch(std::string filename,
Brian Silverman8070a222013-02-28 15:01:36 -080094 std::function<void(void *)> callback,
95 void *value,
96 bool create = false,
97 std::string check_filename = "")
98 : filename_(filename),
99 callback_(callback),
100 value_(value),
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700101 create_(create),
102 check_filename_(check_filename),
103 watch_(-1) {
John Park7bf05bf2019-12-02 21:33:19 -0800104 absl::call_once(once_, Init);
Brian Silverman5cc661b2013-02-27 15:23:36 -0800105
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700106 CreateWatch();
Brian Silvermand169fcd2013-02-27 13:18:47 -0800107 }
John Park7bf05bf2019-12-02 21:33:19 -0800108
Brian Silvermand169fcd2013-02-27 13:18:47 -0800109 // Cleans up everything.
110 ~FileWatch() {
111 if (watch_ != -1) {
112 RemoveWatch();
113 }
114 }
115
116 // After calling this method, this object won't really be doing much of
Brian Silverman5cc661b2013-02-27 15:23:36 -0800117 // anything besides possibly running its callback or something.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800118 void RemoveWatch() {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700119 AOS_CHECK_NE(watch_, -1);
120 AOS_CHECK_EQ(watch_to_remove_, -1);
Brian Silverman5cc661b2013-02-27 15:23:36 -0800121
Brian Silvermand169fcd2013-02-27 13:18:47 -0800122 if (inotify_rm_watch(notify_fd, watch_) == -1) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700123 AOS_PLOG(WARNING, "inotify_rm_watch(%d, %d) failed", notify_fd, watch_);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800124 }
Brian Silvermand94642c2014-03-27 18:21:41 -0700125 watch_to_remove_ = watch_;
126 watch_ = -1;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800127 }
128
Brian Silverman5cc661b2013-02-27 15:23:36 -0800129 private:
John Park7bf05bf2019-12-02 21:33:19 -0800130 // Performs the static initialization. Called by from the constructor
131 static void Init() {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800132 notify_fd = inotify_init1(IN_CLOEXEC);
133 EventUniquePtr notify_event(event_new(libevent_base.get(), notify_fd,
134 EV_READ | EV_PERSIST,
135 FileWatch::INotifyReadable, NULL));
136 event_add(notify_event.release(), NULL);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800137 }
138
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700139 void RemoveWatchFromMap() {
Brian Silvermand94642c2014-03-27 18:21:41 -0700140 int watch = watch_to_remove_;
141 if (watch == -1) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700142 AOS_CHECK_NE(watch_, -1);
Brian Silvermand94642c2014-03-27 18:21:41 -0700143 watch = watch_;
144 }
145 if (watchers[watch] != this) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700146 AOS_LOG(WARNING, "watcher for %s (%p) didn't find itself in the map\n",
147 filename_.c_str(), this);
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700148 } else {
Brian Silvermand94642c2014-03-27 18:21:41 -0700149 watchers.erase(watch);
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700150 }
Austin Schuhf257f3c2019-10-27 21:00:43 -0700151 AOS_LOG(DEBUG, "removed watch ID %d\n", watch);
Brian Silvermand94642c2014-03-27 18:21:41 -0700152 if (watch_to_remove_ == -1) {
153 watch_ = -1;
154 } else {
155 watch_to_remove_ = -1;
156 }
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700157 }
158
159 void CreateWatch() {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700160 AOS_CHECK_EQ(watch_, -1);
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700161 watch_ = inotify_add_watch(notify_fd, filename_.c_str(),
162 create_ ? IN_CREATE : (IN_ATTRIB |
163 IN_MODIFY |
164 IN_DELETE_SELF |
165 IN_MOVE_SELF));
166 if (watch_ == -1) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700167 AOS_PLOG(FATAL,
168 "inotify_add_watch(%d, %s,"
169 " %s ? IN_CREATE : (IN_ATTRIB | IN_MODIFY)) failed",
170 notify_fd, filename_.c_str(), create_ ? "true" : "false");
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700171 }
172 watchers[watch_] = this;
Austin Schuhf257f3c2019-10-27 21:00:43 -0700173 AOS_LOG(DEBUG, "watch for %s is %d\n", filename_.c_str(), watch_);
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700174 }
175
Brian Silvermand169fcd2013-02-27 13:18:47 -0800176 // This gets set up as the callback for EV_READ on the inotify file
Brian Silverman5cc661b2013-02-27 15:23:36 -0800177 // descriptor. It calls FileNotified on the appropriate instance.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800178 static void INotifyReadable(int /*fd*/, short /*events*/, void *) {
179 unsigned int to_read;
Brian Silverman5cc661b2013-02-27 15:23:36 -0800180 // Use FIONREAD to figure out how many bytes there are to read.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800181 if (ioctl(notify_fd, FIONREAD, &to_read) < 0) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700182 AOS_PLOG(FATAL, "FIONREAD(%d, %p) failed", notify_fd, &to_read);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800183 }
184 inotify_event *notifyevt = static_cast<inotify_event *>(malloc(to_read));
185 const char *end = reinterpret_cast<char *>(notifyevt) + to_read;
186 aos::unique_c_ptr<inotify_event> freer(notifyevt);
187
188 ssize_t ret = read(notify_fd, notifyevt, to_read);
189 if (ret < 0) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700190 AOS_PLOG(FATAL, "read(%d, %p, %u) failed", notify_fd, notifyevt, to_read);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800191 }
192 if (static_cast<size_t>(ret) != to_read) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700193 AOS_LOG(ERROR, "read(%d, %p, %u) returned %zd instead of %u\n", notify_fd,
194 notifyevt, to_read, ret, to_read);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800195 return;
196 }
197
Brian Silverman5cc661b2013-02-27 15:23:36 -0800198 // Keep looping through until we get to the end because inotify does return
199 // multiple events at once.
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800200 while (reinterpret_cast<char *>(notifyevt) < end) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800201 if (watchers.count(notifyevt->wd) != 1) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700202 AOS_LOG(WARNING, "couldn't find whose watch ID %d is\n", notifyevt->wd);
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800203 } else {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700204 AOS_LOG(DEBUG, "mask=%" PRIu32 "\n", notifyevt->mask);
Brian Silvermand94642c2014-03-27 18:21:41 -0700205 // If the watch was removed.
206 if (notifyevt->mask & IN_IGNORED) {
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700207 watchers[notifyevt->wd]->WatchDeleted();
208 } else {
Brian Silvermand94642c2014-03-27 18:21:41 -0700209 watchers[notifyevt->wd]
210 ->FileNotified((notifyevt->len > 0) ? notifyevt->name : NULL);
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700211 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800212 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800213
214 notifyevt = reinterpret_cast<inotify_event *>(
Brian Silvermandbdf1d02013-11-17 13:19:41 -0800215 __builtin_assume_aligned(reinterpret_cast<char *>(notifyevt) +
216 sizeof(*notifyevt) + notifyevt->len,
Brian Silvermanafc00a62014-04-21 17:51:23 -0700217 alignof(inotify_event)));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800218 }
219 }
220
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700221 // INotifyReadable calls this method whenever the watch for our file gets
222 // removed somehow.
223 void WatchDeleted() {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700224 AOS_LOG(DEBUG, "watch for %s deleted\n", filename_.c_str());
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700225 RemoveWatchFromMap();
226 CreateWatch();
227 }
228
Brian Silverman5cc661b2013-02-27 15:23:36 -0800229 // INotifyReadable calls this method whenever the watch for our file triggers.
230 void FileNotified(const char *filename) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700231 AOS_CHECK_NE(watch_, -1);
232 AOS_LOG(DEBUG, "got a notification for %s\n", filename_.c_str());
Brian Silverman5cc661b2013-02-27 15:23:36 -0800233
234 if (!check_filename_.empty()) {
235 if (filename == NULL) {
236 return;
237 }
238 if (std::string(filename) != check_filename_) {
239 return;
240 }
241 }
242
243 callback_((value_ == NULL) ? this : value_);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800244 }
245
John Park7bf05bf2019-12-02 21:33:19 -0800246 static absl::once_flag once_;
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};
269std::map<int, FileWatch *> FileWatch::watchers;
270int FileWatch::notify_fd;
John Park7bf05bf2019-12-02 21:33:19 -0800271absl::once_flag FileWatch::once_;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800272
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) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700281 AOS_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) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700293 AOS_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)) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700305 AOS_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)) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700315 AOS_LOG(FATAL, "`%s` failed. didn't print a whole line\n",
316 command.c_str());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800317 }
318 }
319
Brian Silverman5cc661b2013-02-27 15:23:36 -0800320 // Get rid of the first \n and anything after it.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800321 *strchrnul(result.get(), '\n') = '\0';
322
Brian Silverman5cc661b2013-02-27 15:23:36 -0800323 int child_status = pclose(pipe);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800324 if (child_status == -1) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700325 AOS_PLOG(FATAL, "pclose(%p) failed", pipe);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800326 }
327
328 if (child_status != 0) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700329 AOS_LOG(FATAL, "`%s` failed. return %d\n", command.c_str(), child_status);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800330 }
331
332 return std::string(result.get());
333}
334
335// Will call callback(arg) after time.
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800336void Timeout(monotonic_clock::duration time,
337 void (*callback)(int, short, void *), void *arg) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800338 EventUniquePtr timeout(evtimer_new(libevent_base.get(), callback, arg));
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800339 struct timeval time_timeval;
340 {
341 ::std::chrono::seconds sec =
342 ::std::chrono::duration_cast<::std::chrono::seconds>(time);
343 ::std::chrono::microseconds usec =
344 ::std::chrono::duration_cast<::std::chrono::microseconds>(time - sec);
345 time_timeval.tv_sec = sec.count();
346 time_timeval.tv_usec = usec.count();
347 }
Brian Silvermand94642c2014-03-27 18:21:41 -0700348 if (evtimer_add(timeout.release(), &time_timeval) != 0) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700349 AOS_LOG(FATAL, "evtimer_add(%p, %p) failed\n", timeout.release(),
350 &time_timeval);
Brian Silvermand94642c2014-03-27 18:21:41 -0700351 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800352}
353
Brian Silvermand94642c2014-03-27 18:21:41 -0700354class Child;
355// This is where all of the Child instances except core live.
356std::vector<unique_ptr<Child>> children;
357// A global place to hold on to which child is core.
358unique_ptr<Child> core;
359
Brian Silvermand169fcd2013-02-27 13:18:47 -0800360// Represents a child process. It will take care of restarting itself etc.
361class Child {
362 public:
Brian Silverman5cc661b2013-02-27 15:23:36 -0800363 // command is the (space-separated) command to run and its arguments.
364 Child(const std::string &command) : pid_(-1),
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800365 stat_at_start_valid_(false) {
Brian Silvermand94642c2014-03-27 18:21:41 -0700366 if (!restart_timeout) {
367 restart_timeout = EventUniquePtr(
368 evtimer_new(libevent_base.get(), StaticDoRestart, nullptr));
369 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800370 const char *start, *end;
371 start = command.c_str();
372 while (true) {
373 end = strchrnul(start, ' ');
374 args_.push_back(std::string(start, end - start));
375 start = end + 1;
376 if (*end == '\0') {
377 break;
378 }
379 }
380
Brian Silverman5cc661b2013-02-27 15:23:36 -0800381 original_binary_ = RunCommand("which " + args_[0]);
382 binary_ = original_binary_ + ".stm";
Brian Silvermand169fcd2013-02-27 13:18:47 -0800383
384 watcher_ = unique_ptr<FileWatch>(
Brian Silverman5cc661b2013-02-27 15:23:36 -0800385 new FileWatch(original_binary_, StaticFileModified, this));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800386
387 Start();
388 }
389
390 pid_t pid() { return pid_; }
391
392 // This gets called whenever the actual process dies and should (probably) be
393 // restarted.
394 void ProcessDied() {
395 pid_ = -1;
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800396 restarts_.push(monotonic_clock::now());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800397 if (restarts_.size() > kMaxRestartsNumber) {
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800398 monotonic_clock::time_point oldest = restarts_.front();
Brian Silvermand169fcd2013-02-27 13:18:47 -0800399 restarts_.pop();
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800400 if (monotonic_clock::now() <= kMaxRestartsTime + oldest) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700401 AOS_LOG(WARNING, "process %s getting restarted too often\n", name());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800402 Timeout(kResumeWait, StaticStart, this);
403 return;
404 }
405 }
406 Start();
407 }
408
409 // Returns a name for logging purposes.
410 const char *name() {
411 return args_[0].c_str();
412 }
413
414 private:
415 struct CheckDiedStatus {
416 Child *self;
417 pid_t old_pid;
418 };
419
420 // How long to wait for a child to die nicely.
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800421 static constexpr chrono::nanoseconds kProcessDieTime = chrono::seconds(2);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800422
423 // How long to wait after the file is modified to restart it.
424 // This is important because some programs like modifying the binaries by
425 // writing them in little bits, which results in attempting to start partial
426 // binaries without this.
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800427 static constexpr chrono::nanoseconds kRestartWaitTime =
428 chrono::milliseconds(1500);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800429
Brian Silverman5cc661b2013-02-27 15:23:36 -0800430 // Only kMaxRestartsNumber restarts will be allowed in kMaxRestartsTime.
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800431 static constexpr chrono::nanoseconds kMaxRestartsTime = chrono::seconds(4);
Brian Silverman52aeeac2013-08-28 16:20:53 -0700432 static const size_t kMaxRestartsNumber = 3;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800433 // How long to wait if it gets restarted too many times.
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800434 static constexpr chrono::nanoseconds kResumeWait = chrono::seconds(5);
Brian Silverman5cc661b2013-02-27 15:23:36 -0800435
Brian Silvermand169fcd2013-02-27 13:18:47 -0800436 static void StaticFileModified(void *self) {
437 static_cast<Child *>(self)->FileModified();
438 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800439
Brian Silvermand169fcd2013-02-27 13:18:47 -0800440 void FileModified() {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700441 AOS_LOG(DEBUG, "file for %s modified\n", name());
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800442 struct timeval restart_time_timeval;
443 {
444 ::std::chrono::seconds sec =
445 ::std::chrono::duration_cast<::std::chrono::seconds>(
446 kRestartWaitTime);
447 ::std::chrono::microseconds usec =
448 ::std::chrono::duration_cast<::std::chrono::microseconds>(
449 kRestartWaitTime - sec);
450 restart_time_timeval.tv_sec = sec.count();
451 restart_time_timeval.tv_usec = usec.count();
452 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800453 // This will reset the timeout again if it hasn't run yet.
Brian Silvermand94642c2014-03-27 18:21:41 -0700454 if (evtimer_add(restart_timeout.get(), &restart_time_timeval) != 0) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700455 AOS_LOG(FATAL, "evtimer_add(%p, %p) failed\n", restart_timeout.get(),
456 &restart_time_timeval);
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700457 }
Brian Silvermand94642c2014-03-27 18:21:41 -0700458 waiting_to_restart.insert(this);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800459 }
460
Brian Silvermand94642c2014-03-27 18:21:41 -0700461 static void StaticDoRestart(int, short, void *) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700462 AOS_LOG(DEBUG, "restarting everything that needs it\n");
Brian Silvermand94642c2014-03-27 18:21:41 -0700463 if (waiting_to_restart.find(core.get()) != waiting_to_restart.end()) {
464 core->DoRestart();
465 waiting_to_restart.erase(core.get());
466 }
467 for (auto c : waiting_to_restart) {
468 c->DoRestart();
469 }
470 waiting_to_restart.clear();
Brian Silvermand169fcd2013-02-27 13:18:47 -0800471 }
472
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800473 // Called after somebody else has finished modifying the file.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800474 void DoRestart() {
Brian Silvermand94642c2014-03-27 18:21:41 -0700475 fprintf(stderr, "DoRestart(%s)\n", binary_.c_str());
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800476 if (stat_at_start_valid_) {
477 struct stat current_stat;
478 if (stat(original_binary_.c_str(), &current_stat) == -1) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700479 AOS_PLOG(FATAL, "stat(%s, %p) failed", original_binary_.c_str(),
480 &current_stat);
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800481 }
482 if (current_stat.st_mtime == stat_at_start_.st_mtime) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700483 AOS_LOG(DEBUG, "ignoring trigger for %s because mtime didn't change\n",
484 name());
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800485 return;
486 }
487 }
488
Brian Silvermand94642c2014-03-27 18:21:41 -0700489 if (this == core.get()) {
490 fprintf(stderr, "Restarting core -> exiting now.\n");
491 exit(0);
492 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800493 if (pid_ != -1) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700494 AOS_LOG(DEBUG, "sending SIGTERM to child %d to restart it\n", pid_);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800495 if (kill(pid_, SIGTERM) == -1) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700496 AOS_PLOG(WARNING, "kill(%d, SIGTERM) failed", pid_);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800497 }
498 CheckDiedStatus *status = new CheckDiedStatus();
499 status->self = this;
500 status->old_pid = pid_;
501 Timeout(kProcessDieTime, StaticCheckDied, status);
Brian Silvermand90b5fe2013-03-10 18:34:42 -0700502 } else {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700503 AOS_LOG(WARNING, "%s restart attempted but not running\n", name());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800504 }
505 }
506
507 static void StaticCheckDied(int, short, void *status_in) {
508 CheckDiedStatus *status = static_cast<CheckDiedStatus *>(status_in);
509 status->self->CheckDied(status->old_pid);
510 delete status;
511 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800512
513 // Checks to see if the child using the PID old_pid is still running.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800514 void CheckDied(pid_t old_pid) {
515 if (pid_ == old_pid) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700516 AOS_LOG(WARNING, "child %d refused to die\n", old_pid);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800517 if (kill(old_pid, SIGKILL) == -1) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700518 AOS_PLOG(WARNING, "kill(%d, SIGKILL) failed", old_pid);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800519 }
520 }
521 }
522
523 static void StaticStart(int, short, void *self) {
524 static_cast<Child *>(self)->Start();
525 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800526
527 // Actually starts the child.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800528 void Start() {
529 if (pid_ != -1) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700530 AOS_LOG(WARNING, "calling Start() but already have child %d running\n",
531 pid_);
Brian Silverman5cc661b2013-02-27 15:23:36 -0800532 if (kill(pid_, SIGKILL) == -1) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700533 AOS_PLOG(WARNING, "kill(%d, SIGKILL) failed", pid_);
Brian Silverman5cc661b2013-02-27 15:23:36 -0800534 return;
535 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800536 pid_ = -1;
537 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800538
539 // Remove the name that we run from (ie from a previous execution) and then
540 // hard link the real filename to it.
541 if (unlink(binary_.c_str()) != 0 && errno != ENOENT) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700542 AOS_PLOG(FATAL, "removing %s failed", binary_.c_str());
Brian Silverman5cc661b2013-02-27 15:23:36 -0800543 }
544 if (link(original_binary_.c_str(), binary_.c_str()) != 0) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700545 AOS_PLOG(FATAL, "link('%s', '%s') failed", original_binary_.c_str(),
546 binary_.c_str());
Brian Silverman5cc661b2013-02-27 15:23:36 -0800547 }
548
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800549 if (stat(original_binary_.c_str(), &stat_at_start_) == -1) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700550 AOS_PLOG(FATAL, "stat(%s, %p) failed", original_binary_.c_str(),
551 &stat_at_start_);
Brian Silvermanfe06fe12013-02-27 18:54:58 -0800552 }
553 stat_at_start_valid_ = true;
554
Brian Silvermand169fcd2013-02-27 13:18:47 -0800555 if ((pid_ = fork()) == 0) {
556 ssize_t args_size = args_.size();
557 const char **argv = new const char *[args_size + 1];
558 for (int i = 0; i < args_size; ++i) {
559 argv[i] = args_[i].c_str();
560 }
561 argv[args_size] = NULL;
562 // The const_cast is safe because no code that might care if it gets
563 // modified can run afterwards.
564 execv(binary_.c_str(), const_cast<char **>(argv));
Austin Schuhf257f3c2019-10-27 21:00:43 -0700565 AOS_PLOG(FATAL, "execv(%s, %p) failed", binary_.c_str(), argv);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800566 _exit(EXIT_FAILURE);
567 }
568 if (pid_ == -1) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700569 AOS_PLOG(FATAL, "forking to run \"%s\" failed", binary_.c_str());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800570 }
Austin Schuhf257f3c2019-10-27 21:00:43 -0700571 AOS_LOG(DEBUG, "started \"%s\" successfully\n", binary_.c_str());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800572 }
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -0800573
574 // A history of the times that this process has been restarted.
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800575 std::queue<monotonic_clock::time_point,
576 std::list<monotonic_clock::time_point>> restarts_;
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -0800577
578 // The currently running child's PID or NULL.
579 pid_t pid_;
580
581 // All of the arguments (including the name of the binary).
582 std::deque<std::string> args_;
583
584 // The name of the real binary that we were told to run.
585 std::string original_binary_;
586 // The name of the file that we're actually running.
587 std::string binary_;
588
589 // Watches original_binary_.
590 unique_ptr<FileWatch> watcher_;
591
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -0800592 // Captured from the original file when we most recently started a new child
593 // process. Used to see if it actually changes or not.
594 struct stat stat_at_start_;
595 bool stat_at_start_valid_;
596
Brian Silvermand94642c2014-03-27 18:21:41 -0700597 // An event that restarts after kRestartWaitTime.
598 static EventUniquePtr restart_timeout;
599
600 // The set of children waiting to be restarted once all modifications stop.
601 static ::std::set<Child *> waiting_to_restart;
602
Brian Silvermanbc4fc2f2013-02-27 19:33:42 -0800603 DISALLOW_COPY_AND_ASSIGN(Child);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800604};
Brian Silverman52aeeac2013-08-28 16:20:53 -0700605
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800606constexpr chrono::nanoseconds Child::kProcessDieTime;
607constexpr chrono::nanoseconds Child::kRestartWaitTime;
608constexpr chrono::nanoseconds Child::kMaxRestartsTime;
609constexpr chrono::nanoseconds Child::kResumeWait;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800610
Brian Silvermand94642c2014-03-27 18:21:41 -0700611EventUniquePtr Child::restart_timeout;
612::std::set<Child *> Child::waiting_to_restart;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800613
Brian Silverman5cc661b2013-02-27 15:23:36 -0800614// Kills off the entire process group (including ourself).
615void KillChildren(bool try_nice) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800616 if (try_nice) {
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800617 static constexpr int kNiceStopSignal = SIGTERM;
618 static constexpr auto kNiceWaitTime = chrono::seconds(1);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800619
620 // Make sure that we don't just nicely stop ourself...
621 sigset_t mask;
622 sigemptyset(&mask);
623 sigaddset(&mask, kNiceStopSignal);
624 sigprocmask(SIG_BLOCK, &mask, NULL);
625
Brian Silverman5cc661b2013-02-27 15:23:36 -0800626 kill(-getpid(), kNiceStopSignal);
627
628 fflush(NULL);
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800629 ::std::this_thread::sleep_for(kNiceWaitTime);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800630 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800631
Brian Silvermand169fcd2013-02-27 13:18:47 -0800632 // Send SIGKILL to our whole process group, which will forcibly terminate any
633 // of them that are still running (us for sure, maybe more too).
Brian Silverman5cc661b2013-02-27 15:23:36 -0800634 kill(-getpid(), SIGKILL);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800635}
636
Brian Silverman5cc661b2013-02-27 15:23:36 -0800637void ExitHandler() {
638 KillChildren(true);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800639}
Brian Silverman5cc661b2013-02-27 15:23:36 -0800640
641void KillChildrenSignalHandler(int signum) {
642 // If we get SIGSEGV or some other random signal who knows what's happening
643 // and we should just kill everybody immediately.
644 // This is a list of all of the signals that mean some form of "nicely stop".
645 KillChildren(signum == SIGHUP || signum == SIGINT || signum == SIGQUIT ||
Brian Silverman0eec9532013-02-27 20:24:16 -0800646 signum == SIGABRT || signum == SIGPIPE || signum == SIGTERM ||
647 signum == SIGXCPU);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800648}
649
Brian Silverman5cc661b2013-02-27 15:23:36 -0800650// Returns the currently running child with PID pid or an empty unique_ptr.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800651const unique_ptr<Child> &FindChild(pid_t pid) {
652 for (auto it = children.begin(); it != children.end(); ++it) {
653 if (pid == (*it)->pid()) {
654 return *it;
655 }
656 }
657
658 if (pid == core->pid()) {
659 return core;
660 }
661
Brian Silverman5cc661b2013-02-27 15:23:36 -0800662 static const unique_ptr<Child> kNothing;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800663 return kNothing;
664}
665
Brian Silverman5cc661b2013-02-27 15:23:36 -0800666// Gets set up as a libevent handler for SIGCHLD.
667// Handles calling Child::ProcessDied() on the appropriate one.
668void SigCHLDReceived(int /*fd*/, short /*events*/, void *) {
Brian Silvermand169fcd2013-02-27 13:18:47 -0800669 // In a while loop in case we miss any SIGCHLDs.
670 while (true) {
671 siginfo_t infop;
672 infop.si_pid = 0;
673 if (waitid(P_ALL, 0, &infop, WEXITED | WSTOPPED | WNOHANG) != 0) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700674 AOS_PLOG(WARNING, "waitid failed");
Brian Silverman5cc661b2013-02-27 15:23:36 -0800675 continue;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800676 }
Brian Silverman5cc661b2013-02-27 15:23:36 -0800677 // If there are no more child process deaths to process.
Brian Silvermand169fcd2013-02-27 13:18:47 -0800678 if (infop.si_pid == 0) {
Brian Silverman5cc661b2013-02-27 15:23:36 -0800679 return;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800680 }
681
682 pid_t pid = infop.si_pid;
683 int status = infop.si_status;
684 const unique_ptr<Child> &child = FindChild(pid);
685 if (child) {
686 switch (infop.si_code) {
687 case CLD_EXITED:
Austin Schuhf257f3c2019-10-27 21:00:43 -0700688 AOS_LOG(WARNING, "child %d (%s) exited with status %d\n", pid,
689 child->name(), status);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800690 break;
691 case CLD_DUMPED:
Austin Schuhf257f3c2019-10-27 21:00:43 -0700692 AOS_LOG(INFO,
693 "child %d actually dumped core. "
694 "falling through to killed by signal case\n",
695 pid);
James Kuszmaul3ae42262019-11-08 12:33:41 -0800696 [[fallthrough]];
697 /* FALLTHRU */
Brian Silvermand169fcd2013-02-27 13:18:47 -0800698 case CLD_KILLED:
699 // If somebody (possibly us) sent it SIGTERM that means that they just
700 // want it to stop, so it stopping isn't a WARNING.
Austin Schuhf257f3c2019-10-27 21:00:43 -0700701 AOS_LOG((status == SIGTERM) ? DEBUG : WARNING,
702 "child %d (%s) was killed by signal %d (%s)\n", pid,
703 child->name(), status, aos_strsignal(status));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800704 break;
705 case CLD_STOPPED:
Austin Schuhf257f3c2019-10-27 21:00:43 -0700706 AOS_LOG(WARNING,
707 "child %d (%s) was stopped by signal %d "
708 "(giving it a SIGCONT(%d))\n",
709 pid, child->name(), status, SIGCONT);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800710 kill(pid, SIGCONT);
711 continue;
712 default:
Austin Schuhf257f3c2019-10-27 21:00:43 -0700713 AOS_LOG(WARNING, "something happened to child %d (%s) (killing it)\n",
714 pid, child->name());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800715 kill(pid, SIGKILL);
716 continue;
717 }
718 } else {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700719 AOS_LOG(WARNING, "couldn't find a Child for pid %d\n", pid);
Brian Silverman5cc661b2013-02-27 15:23:36 -0800720 return;
Brian Silvermand169fcd2013-02-27 13:18:47 -0800721 }
722
Brian Silverman5cc661b2013-02-27 15:23:36 -0800723 if (child == core) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700724 AOS_LOG(FATAL, "core died\n");
Brian Silverman5cc661b2013-02-27 15:23:36 -0800725 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800726 child->ProcessDied();
727 }
728}
729
Brian Silverman5cc661b2013-02-27 15:23:36 -0800730// This is used for communicating the name of the file to read processes to
731// start from main to Run.
732const char *child_list_file;
733
Brian Silverman8070a222013-02-28 15:01:36 -0800734void Run(void *watch);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800735void Main() {
736 logging::Init();
Brian Silvermand169fcd2013-02-27 13:18:47 -0800737
Comran Morshed7f6ba792016-02-21 16:54:05 +0000738 // Set UID to 0 so we can run things as root down below. Since the starter
739 // program on the roborio runs starter.sh under "lvuser", it will continuously
740 // fail due to lack of permissions if we do not manually set the UID to admin.
741#ifdef AOS_ARCHITECTURE_arm_frc
742 if (setuid(0) != 0) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700743 AOS_PLOG(FATAL, "setuid(0) failed");
Comran Morshed7f6ba792016-02-21 16:54:05 +0000744 }
745#endif
746
Brian Silverman5cc661b2013-02-27 15:23:36 -0800747 if (setpgid(0 /*self*/, 0 /*make PGID the same as PID*/) != 0) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700748 AOS_PLOG(FATAL, "setpgid(0, 0) failed");
Brian Silverman5cc661b2013-02-27 15:23:36 -0800749 }
Brian Silvermand169fcd2013-02-27 13:18:47 -0800750
751 // Make sure that we kill all children when we exit.
Brian Silverman5cc661b2013-02-27 15:23:36 -0800752 atexit(ExitHandler);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800753 // Do it on some signals too (ones that we otherwise tend to receive and then
754 // leave all of our children going).
Brian Silverman5cc661b2013-02-27 15:23:36 -0800755 signal(SIGHUP, KillChildrenSignalHandler);
756 signal(SIGINT, KillChildrenSignalHandler);
757 signal(SIGQUIT, KillChildrenSignalHandler);
758 signal(SIGILL, KillChildrenSignalHandler);
759 signal(SIGABRT, KillChildrenSignalHandler);
760 signal(SIGFPE, KillChildrenSignalHandler);
761 signal(SIGSEGV, KillChildrenSignalHandler);
762 signal(SIGPIPE, KillChildrenSignalHandler);
763 signal(SIGTERM, KillChildrenSignalHandler);
764 signal(SIGBUS, KillChildrenSignalHandler);
765 signal(SIGXCPU, KillChildrenSignalHandler);
Brian Silverman35df22f2015-12-27 17:57:10 -0800766
767#ifdef AOS_ARCHITECTURE_arm_frc
768 // Just allow overcommit memory like usual. Various processes map memory they
769 // will never use, and the roboRIO doesn't have enough RAM to handle it.
770 // This is in here instead of starter.sh because starter.sh doesn't run with
771 // permissions on a roboRIO.
Austin Schuhf257f3c2019-10-27 21:00:43 -0700772 AOS_CHECK(system("echo 0 > /proc/sys/vm/overcommit_memory") == 0);
Brian Silverman35df22f2015-12-27 17:57:10 -0800773#endif
James Kuszmaul3ae42262019-11-08 12:33:41 -0800774
Brian Silvermand169fcd2013-02-27 13:18:47 -0800775 libevent_base = EventBaseUniquePtr(event_base_new());
776
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800777 std::string core_touch_file = "/tmp/starter.";
Brian Silvermand169fcd2013-02-27 13:18:47 -0800778 core_touch_file += std::to_string(static_cast<intmax_t>(getpid()));
779 core_touch_file += ".core_touch_file";
Brian Silvermanaf784862014-05-13 08:14:55 -0700780 const int result =
781 ::aos::util::RunCommand(("touch '" + core_touch_file + "'").c_str());
782 if (result == -1) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700783 AOS_PLOG(FATAL, "running `touch '%s'` failed\n", core_touch_file.c_str());
Brian Silvermanaf784862014-05-13 08:14:55 -0700784 } else if (!WIFEXITED(result) || WEXITSTATUS(result) != 0) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700785 AOS_LOG(FATAL, "`touch '%s'` gave result %x\n", core_touch_file.c_str(),
786 result);
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800787 }
788 FileWatch core_touch_file_watch(core_touch_file, Run, NULL);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800789 core = unique_ptr<Child>(
Brian Silvermanb1e4f6c2013-02-27 15:42:02 -0800790 new Child("core " + core_touch_file));
Brian Silvermand169fcd2013-02-27 13:18:47 -0800791
792 FILE *pid_file = fopen("/tmp/starter.pid", "w");
793 if (pid_file == NULL) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700794 AOS_PLOG(FATAL, "fopen(\"/tmp/starter.pid\", \"w\") failed");
Brian Silvermand169fcd2013-02-27 13:18:47 -0800795 } else {
796 if (fprintf(pid_file, "%d", core->pid()) == -1) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700797 AOS_PLOG(WARNING, "fprintf(%p, \"%%d\", %d) failed", pid_file,
798 core->pid());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800799 }
800 fclose(pid_file);
801 }
802
Austin Schuhf257f3c2019-10-27 21:00:43 -0700803 AOS_LOG(INFO, "waiting for %s to appear\n", core_touch_file.c_str());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800804
805 event_base_dispatch(libevent_base.get());
Austin Schuhf257f3c2019-10-27 21:00:43 -0700806 AOS_LOG(FATAL, "event_base_dispatch(%p) returned\n", libevent_base.get());
Brian Silvermand169fcd2013-02-27 13:18:47 -0800807}
808
Brian Silverman0eec9532013-02-27 20:24:16 -0800809// This is the callback for when core creates the file indicating that it has
810// started.
811void Run(void *watch) {
812 // Make it so it doesn't keep on seeing random changes in /tmp.
813 static_cast<FileWatch *>(watch)->RemoveWatch();
814
815 // It's safe now because core is up.
816 aos::InitNRT();
817
818 std::ifstream list_file(child_list_file);
James Kuszmaul3ae42262019-11-08 12:33:41 -0800819
Brian Silverman0eec9532013-02-27 20:24:16 -0800820 while (true) {
821 std::string child_name;
822 getline(list_file, child_name);
823 if ((list_file.rdstate() & std::ios_base::eofbit) != 0) {
824 break;
825 }
826 if (list_file.rdstate() != 0) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700827 AOS_LOG(FATAL, "reading input file %s failed\n", child_list_file);
Brian Silverman0eec9532013-02-27 20:24:16 -0800828 }
829 children.push_back(unique_ptr<Child>(new Child(child_name)));
830 }
831
832 EventUniquePtr sigchld(event_new(libevent_base.get(), SIGCHLD,
833 EV_SIGNAL | EV_PERSIST,
834 SigCHLDReceived, NULL));
835 event_add(sigchld.release(), NULL);
836}
837
Brian Silverman8070a222013-02-28 15:01:36 -0800838const char *kArgsHelp = "[OPTION]... START_LIST\n"
839 "Start all of the robot code binaries in START_LIST.\n"
840 "\n"
841 "START_LIST is the file to read binaries (looked up on PATH) to run.\n"
842 " --help display this help and exit\n";
843void PrintHelp() {
844 fprintf(stderr, "Usage: %s %s", program_invocation_name, kArgsHelp);
845}
846
Brian Silvermand169fcd2013-02-27 13:18:47 -0800847} // namespace starter
848} // namespace aos
849
850int main(int argc, char *argv[]) {
Brian Silverman8070a222013-02-28 15:01:36 -0800851 if (argc != 2) {
852 aos::starter::PrintHelp();
Brian Silvermand169fcd2013-02-27 13:18:47 -0800853 exit(EXIT_FAILURE);
Brian Silvermand169fcd2013-02-27 13:18:47 -0800854 }
Brian Silverman8070a222013-02-28 15:01:36 -0800855 if (strcmp(argv[1], "--help") == 0) {
856 aos::starter::PrintHelp();
857 exit(EXIT_SUCCESS);
858 }
859
Brian Silvermand169fcd2013-02-27 13:18:47 -0800860 aos::starter::child_list_file = argv[1];
861
862 aos::starter::Main();
863}