12 #include <systemd/sd-daemon.h>
22 #include "accesslog.h"
25 #include "input_stats.h"
27 #include "sa_compare.h"
28 #include "serverpool.h"
37 AccessLogThread *access_log = NULL;
38 ServerPool *servers = NULL;
39 volatile bool hupped = false;
40 volatile bool stopped = false;
42 typedef pair<string, Input::Encoding> InputKey;
46 struct OrderByConnectionTime {
47 bool operator() (const ClientProto &a, const ClientProto &b) const {
48 if (a.connect_time_sec() != b.connect_time_sec())
49 return a.connect_time_sec() < b.connect_time_sec();
50 return a.connect_time_nsec() < b.connect_time_nsec();
56 struct InputWithRefcount {
64 if (signum == SIGINT) {
69 void do_nothing(int signum)
73 CubemapStateProto collect_state(const timespec &serialize_start,
74 const vector<Acceptor *> acceptors,
75 const multimap<InputKey, InputWithRefcount> inputs,
78 CubemapStateProto state = servers->serialize(); // Fills streams() and clients().
79 state.set_serialize_start_sec(serialize_start.tv_sec);
80 state.set_serialize_start_usec(serialize_start.tv_nsec / 1000);
82 for (size_t i = 0; i < acceptors.size(); ++i) {
83 state.add_acceptors()->MergeFrom(acceptors[i]->serialize());
86 for (multimap<InputKey, InputWithRefcount>::const_iterator input_it = inputs.begin();
87 input_it != inputs.end();
89 state.add_inputs()->MergeFrom(input_it->second.input->serialize());
95 // Find all port statements in the configuration file, and create acceptors for htem.
96 vector<Acceptor *> create_acceptors(
98 map<sockaddr_in6, Acceptor *, Sockaddr6Compare> *deserialized_acceptors)
100 vector<Acceptor *> acceptors;
101 for (unsigned i = 0; i < config.acceptors.size(); ++i) {
102 const AcceptorConfig &acceptor_config = config.acceptors[i];
103 Acceptor *acceptor = NULL;
104 map<sockaddr_in6, Acceptor *, Sockaddr6Compare>::iterator deserialized_acceptor_it =
105 deserialized_acceptors->find(acceptor_config.addr);
106 if (deserialized_acceptor_it != deserialized_acceptors->end()) {
107 acceptor = deserialized_acceptor_it->second;
108 deserialized_acceptors->erase(deserialized_acceptor_it);
110 int server_sock = create_server_socket(acceptor_config.addr, TCP_SOCKET);
111 acceptor = new Acceptor(server_sock, acceptor_config.addr);
114 acceptors.push_back(acceptor);
117 // Close all acceptors that are no longer in the configuration file.
118 for (map<sockaddr_in6, Acceptor *, Sockaddr6Compare>::iterator
119 acceptor_it = deserialized_acceptors->begin();
120 acceptor_it != deserialized_acceptors->end();
122 acceptor_it->second->close_socket();
123 delete acceptor_it->second;
129 void create_config_input(const string &src, Input::Encoding encoding, multimap<InputKey, InputWithRefcount> *inputs)
134 InputKey key(src, encoding);
135 if (inputs->count(key) != 0) {
139 InputWithRefcount iwr;
140 iwr.input = create_input(src, encoding);
141 if (iwr.input == NULL) {
142 log(ERROR, "did not understand URL '%s' or source encoding was invalid, clients will not get any data.",
147 inputs->insert(make_pair(key, iwr));
150 // Find all streams in the configuration file, and create inputs for them.
151 void create_config_inputs(const Config &config, multimap<InputKey, InputWithRefcount> *inputs)
153 for (unsigned i = 0; i < config.streams.size(); ++i) {
154 const StreamConfig &stream_config = config.streams[i];
155 if (stream_config.src != "delete") {
156 create_config_input(stream_config.src, Input::Encoding(stream_config.src_encoding), inputs);
159 for (unsigned i = 0; i < config.udpstreams.size(); ++i) {
160 const UDPStreamConfig &udpstream_config = config.udpstreams[i];
161 create_config_input(udpstream_config.src, Input::INPUT_ENCODING_RAW, inputs);
165 void create_streams(const Config &config,
166 const set<string> &deserialized_urls,
167 multimap<InputKey, InputWithRefcount> *inputs)
170 set<string> expecting_urls = deserialized_urls;
171 for (unsigned i = 0; i < config.streams.size(); ++i) {
172 const StreamConfig &stream_config = config.streams[i];
175 expecting_urls.erase(stream_config.url);
177 // Special-case deleted streams; they were never deserialized in the first place,
178 // so just ignore them.
179 if (stream_config.src == "delete") {
183 if (deserialized_urls.count(stream_config.url) == 0) {
184 stream_index = servers->add_stream(stream_config.url,
185 stream_config.backlog_size,
186 stream_config.prebuffering_bytes,
187 Stream::Encoding(stream_config.encoding),
188 Stream::Encoding(stream_config.src_encoding));
190 stream_index = servers->lookup_stream_by_url(stream_config.url);
191 assert(stream_index != -1);
192 servers->set_backlog_size(stream_index, stream_config.backlog_size);
193 servers->set_prebuffering_bytes(stream_index, stream_config.prebuffering_bytes);
194 servers->set_encoding(stream_index,
195 Stream::Encoding(stream_config.encoding));
196 servers->set_src_encoding(stream_index,
197 Stream::Encoding(stream_config.src_encoding));
200 servers->set_pacing_rate(stream_index, stream_config.pacing_rate);
202 string src = stream_config.src;
203 Input::Encoding src_encoding = Input::Encoding(stream_config.src_encoding);
205 multimap<InputKey, InputWithRefcount>::iterator input_it = inputs->find(make_pair(src, src_encoding));
206 if (input_it != inputs->end()) {
207 input_it->second.input->add_destination(stream_index);
208 ++input_it->second.refcount;
213 // Warn about any streams servers we've lost.
214 for (set<string>::const_iterator stream_it = expecting_urls.begin();
215 stream_it != expecting_urls.end();
217 string url = *stream_it;
218 log(WARNING, "stream '%s' disappeared from the configuration file. "
219 "It will not be deleted, but clients will not get any new inputs. "
220 "If you really meant to delete it, set src=delete and reload.",
225 for (unsigned i = 0; i < config.udpstreams.size(); ++i) {
226 const UDPStreamConfig &udpstream_config = config.udpstreams[i];
227 int stream_index = servers->add_udpstream(
228 udpstream_config.dst,
229 udpstream_config.pacing_rate,
230 udpstream_config.ttl,
231 udpstream_config.multicast_iface_index);
233 string src = udpstream_config.src;
235 multimap<InputKey, InputWithRefcount>::iterator input_it = inputs->find(make_pair(src, Input::INPUT_ENCODING_RAW));
236 assert(input_it != inputs->end());
237 input_it->second.input->add_destination(stream_index);
238 ++input_it->second.refcount;
242 // HTTP gen204 endpoints.
243 for (unsigned i = 0; i < config.pings.size(); ++i) {
244 const Gen204Config &ping_config = config.pings[i];
245 servers->add_gen204(ping_config.url, ping_config.allow_origin);
249 void open_logs(const vector<LogConfig> &log_destinations)
251 for (size_t i = 0; i < log_destinations.size(); ++i) {
252 if (log_destinations[i].type == LogConfig::LOG_TYPE_FILE) {
253 add_log_destination_file(log_destinations[i].filename);
254 } else if (log_destinations[i].type == LogConfig::LOG_TYPE_CONSOLE) {
255 add_log_destination_console();
256 } else if (log_destinations[i].type == LogConfig::LOG_TYPE_SYSLOG) {
257 add_log_destination_syslog();
265 bool dry_run_config(const string &argv0, const string &config_filename)
267 char *argv0_copy = strdup(argv0.c_str());
268 char *config_filename_copy = strdup(config_filename.c_str());
273 log_perror("fork()");
275 free(config_filename_copy);
279 execlp(argv0_copy, argv0_copy, "--test-config", config_filename_copy, NULL);
280 log_perror(argv0_copy);
288 free(config_filename_copy);
293 err = waitpid(pid, &status, 0);
294 } while (err == -1 && errno == EINTR);
297 log_perror("waitpid()");
301 return (WIFEXITED(status) && WEXITSTATUS(status) == 0);
304 void find_deleted_streams(const Config &config, set<string> *deleted_urls)
306 for (unsigned i = 0; i < config.streams.size(); ++i) {
307 const StreamConfig &stream_config = config.streams[i];
308 if (stream_config.src == "delete") {
309 log(INFO, "Deleting stream '%s'.", stream_config.url.c_str());
310 deleted_urls->insert(stream_config.url);
315 int main(int argc, char **argv)
319 signal(SIGUSR1, do_nothing); // Used in internal signalling.
320 signal(SIGPIPE, SIG_IGN);
324 bool test_config = false;
326 static const option long_options[] = {
327 { "state", required_argument, 0, 's' },
328 { "test-config", no_argument, 0, 't' },
331 int option_index = 0;
332 int c = getopt_long(argc, argv, "s:t", long_options, &option_index);
339 state_fd = atoi(optarg);
345 fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
350 string config_filename = "cubemap.config";
352 config_filename = argv[optind++];
355 // Canonicalize argv[0] and config_filename.
356 char argv0_canon[PATH_MAX];
357 char config_filename_canon[PATH_MAX];
359 if (realpath("/proc/self/exe", argv0_canon) == NULL) {
363 if (realpath(config_filename.c_str(), config_filename_canon) == NULL) {
364 log_perror(config_filename.c_str());
368 // Now parse the configuration file.
370 if (!parse_config(config_filename_canon, &config)) {
377 // Ideally we'd like to daemonize only when we've started up all threads etc.,
378 // but daemon() forks, which is not good in multithreaded software, so we'll
379 // have to do it here.
380 if (config.daemonize) {
381 if (daemon(0, 0) == -1) {
382 log_perror("daemon");
388 // Open logs as soon as possible.
389 open_logs(config.log_destinations);
391 log(INFO, "Cubemap " SERVER_VERSION " starting.");
392 if (config.access_log_file.empty()) {
393 // Create a dummy logger.
394 access_log = new AccessLogThread();
396 access_log = new AccessLogThread(config.access_log_file);
400 servers = new ServerPool(config.num_servers);
402 // Find all the streams that are to be deleted.
403 set<string> deleted_urls;
404 find_deleted_streams(config, &deleted_urls);
406 CubemapStateProto loaded_state;
407 timespec serialize_start;
408 set<string> deserialized_urls;
409 map<sockaddr_in6, Acceptor *, Sockaddr6Compare> deserialized_acceptors;
410 multimap<InputKey, InputWithRefcount> inputs; // multimap due to older versions without deduplication.
411 if (state_fd != -1) {
412 log(INFO, "Deserializing state from previous process...");
414 if (!read_tempfile_and_close(state_fd, &serialized)) {
417 if (!loaded_state.ParseFromString(serialized)) {
418 log(ERROR, "Failed deserialization of state.");
422 serialize_start.tv_sec = loaded_state.serialize_start_sec();
423 serialize_start.tv_nsec = loaded_state.serialize_start_usec() * 1000ull;
425 // Deserialize the streams.
426 map<string, string> stream_headers_for_url; // See below.
427 for (int i = 0; i < loaded_state.streams_size(); ++i) {
428 const StreamProto &stream = loaded_state.streams(i);
430 if (deleted_urls.count(stream.url()) != 0) {
431 // Delete the stream backlogs.
432 for (int j = 0; j < stream.data_fds_size(); ++j) {
433 safe_close(stream.data_fds(j));
436 vector<int> data_fds;
437 for (int j = 0; j < stream.data_fds_size(); ++j) {
438 data_fds.push_back(stream.data_fds(j));
441 servers->add_stream_from_serialized(stream, data_fds);
442 deserialized_urls.insert(stream.url());
444 stream_headers_for_url.insert(make_pair(stream.url(), stream.stream_header()));
448 // Deserialize the inputs. Note that we don't actually add them to any stream yet.
449 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
450 InputProto serialized_input = loaded_state.inputs(i);
452 InputWithRefcount iwr;
453 iwr.input = create_input(serialized_input);
456 Input::Encoding src_encoding = serialized_input.is_metacube_encoded() ?
457 Input::INPUT_ENCODING_METACUBE :
458 Input::INPUT_ENCODING_RAW;
459 InputKey key(serialized_input.url(), src_encoding);
460 inputs.insert(make_pair(key, iwr));
463 // Deserialize the acceptors.
464 for (int i = 0; i < loaded_state.acceptors_size(); ++i) {
465 sockaddr_in6 sin6 = extract_address_from_acceptor_proto(loaded_state.acceptors(i));
466 deserialized_acceptors.insert(make_pair(
468 new Acceptor(loaded_state.acceptors(i))));
471 log(INFO, "Deserialization done.");
474 // Add any new inputs coming from the config.
475 create_config_inputs(config, &inputs);
477 // Find all streams in the configuration file, create them, and connect to the inputs.
478 create_streams(config, deserialized_urls, &inputs);
479 vector<Acceptor *> acceptors = create_acceptors(config, &deserialized_acceptors);
481 // Convert old-style timestamps to new-style timestamps for all clients;
482 // this simplifies the sort below.
484 timespec now_monotonic;
485 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &now_monotonic) == -1) {
486 log(ERROR, "clock_gettime(CLOCK_MONOTONIC_COARSE) failed.");
489 long delta_sec = now_monotonic.tv_sec - time(NULL);
491 for (int i = 0; i < loaded_state.clients_size(); ++i) {
492 ClientProto* client = loaded_state.mutable_clients(i);
493 if (client->has_connect_time_old()) {
494 client->set_connect_time_sec(client->connect_time_old() + delta_sec);
495 client->set_connect_time_nsec(now_monotonic.tv_nsec);
496 client->clear_connect_time_old();
501 // Put back the existing clients. It doesn't matter which server we
502 // allocate them to, so just do round-robin. However, we need to sort them
503 // by connection time first, since add_client_serialized() expects that.
504 sort(loaded_state.mutable_clients()->begin(),
505 loaded_state.mutable_clients()->end(),
506 OrderByConnectionTime());
507 for (int i = 0; i < loaded_state.clients_size(); ++i) {
508 if (deleted_urls.count(loaded_state.clients(i).url()) != 0) {
509 safe_close(loaded_state.clients(i).sock());
511 servers->add_client_from_serialized(loaded_state.clients(i));
517 // Now delete all inputs that are longer in use, and start the others.
518 for (multimap<InputKey, InputWithRefcount>::iterator input_it = inputs.begin();
519 input_it != inputs.end(); ) {
520 if (input_it->second.refcount == 0) {
521 if (input_it->first.second == Input::INPUT_ENCODING_RAW) {
522 log(WARNING, "Raw input '%s' no longer in use, closing.",
523 input_it->first.first.c_str());
525 assert(input_it->first.second == Input::INPUT_ENCODING_METACUBE);
526 log(WARNING, "Metacube input '%s' no longer in use, closing.",
527 input_it->first.first.c_str());
529 input_it->second.input->close_socket();
530 delete input_it->second.input;
531 inputs.erase(input_it++);
533 input_it->second.input->run();
538 // Start writing statistics.
539 StatsThread *stats_thread = NULL;
540 if (!config.stats_file.empty()) {
541 stats_thread = new StatsThread(config.stats_file, config.stats_interval);
545 InputStatsThread *input_stats_thread = NULL;
546 if (!config.input_stats_file.empty()) {
547 vector<Input*> inputs_no_refcount;
548 for (multimap<InputKey, InputWithRefcount>::iterator input_it = inputs.begin();
549 input_it != inputs.end(); ++input_it) {
550 inputs_no_refcount.push_back(input_it->second.input);
553 input_stats_thread = new InputStatsThread(config.input_stats_file, config.input_stats_interval, inputs_no_refcount);
554 input_stats_thread->run();
557 timespec server_start;
558 int err = clock_gettime(CLOCK_MONOTONIC, &server_start);
560 if (state_fd != -1) {
561 // Measure time from we started deserializing (below) to now, when basically everything
562 // is up and running. This is, in other words, a conservative estimate of how long our
563 // “glitch” period was, not counting of course reconnects if the configuration changed.
564 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
565 1e-9 * (server_start.tv_nsec - serialize_start.tv_nsec);
566 log(INFO, "Re-exec happened in approx. %.0f ms.", glitch_time * 1000.0);
569 sd_notify(0, "READY=1");
576 sd_notify(0, "STOPPING=1");
578 sd_notify(0, "RELOADING=1");
581 // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
582 err = clock_gettime(CLOCK_MONOTONIC, &serialize_start);
585 if (input_stats_thread != NULL) {
586 input_stats_thread->stop();
587 delete input_stats_thread;
589 if (stats_thread != NULL) {
590 stats_thread->stop();
593 for (size_t i = 0; i < acceptors.size(); ++i) {
594 acceptors[i]->stop();
596 for (multimap<InputKey, InputWithRefcount>::iterator input_it = inputs.begin();
597 input_it != inputs.end();
599 input_it->second.input->stop();
603 CubemapStateProto state;
605 log(INFO, "Shutting down.");
607 log(INFO, "Serializing state and re-execing...");
608 state = collect_state(
609 serialize_start, acceptors, inputs, servers);
611 state.SerializeToString(&serialized);
612 state_fd = make_tempfile(serialized);
613 if (state_fd == -1) {
627 // OK, so the signal was SIGHUP. Check that the new config is okay, then exec the new binary.
628 if (!dry_run_config(argv0_canon, config_filename_canon)) {
629 open_logs(config.log_destinations);
630 log(ERROR, "%s --test-config failed. Restarting old version instead of new.", argv[0]);
637 sprintf(buf, "%d", state_fd);
640 execlp(argv0_canon, argv0_canon, config_filename_canon, "--state", buf, NULL);
641 open_logs(config.log_destinations);
642 log_perror("execlp");
643 log(ERROR, "re-exec of %s failed. Waiting 0.2 seconds and trying again...", argv0_canon);