21 #include "accesslog.h"
24 #include "input_stats.h"
26 #include "sa_compare.h"
27 #include "serverpool.h"
36 AccessLogThread *access_log = NULL;
37 ServerPool *servers = NULL;
38 volatile bool hupped = false;
39 volatile bool stopped = false;
43 struct OrderByConnectionTime {
44 bool operator() (const ClientProto &a, const ClientProto &b) const {
45 if (a.connect_time_sec() != b.connect_time_sec())
46 return a.connect_time_sec() < b.connect_time_sec();
47 return a.connect_time_nsec() < b.connect_time_nsec();
53 struct InputWithRefcount {
61 if (signum == SIGINT) {
66 void do_nothing(int signum)
70 CubemapStateProto collect_state(const timeval &serialize_start,
71 const vector<Acceptor *> acceptors,
72 const multimap<string, InputWithRefcount> inputs,
75 CubemapStateProto state = servers->serialize(); // Fills streams() and clients().
76 state.set_serialize_start_sec(serialize_start.tv_sec);
77 state.set_serialize_start_usec(serialize_start.tv_usec);
79 for (size_t i = 0; i < acceptors.size(); ++i) {
80 state.add_acceptors()->MergeFrom(acceptors[i]->serialize());
83 for (multimap<string, InputWithRefcount>::const_iterator input_it = inputs.begin();
84 input_it != inputs.end();
86 state.add_inputs()->MergeFrom(input_it->second.input->serialize());
92 // Find all port statements in the configuration file, and create acceptors for htem.
93 vector<Acceptor *> create_acceptors(
95 map<sockaddr_in6, Acceptor *, Sockaddr6Compare> *deserialized_acceptors)
97 vector<Acceptor *> acceptors;
98 for (unsigned i = 0; i < config.acceptors.size(); ++i) {
99 const AcceptorConfig &acceptor_config = config.acceptors[i];
100 Acceptor *acceptor = NULL;
101 map<sockaddr_in6, Acceptor *, Sockaddr6Compare>::iterator deserialized_acceptor_it =
102 deserialized_acceptors->find(acceptor_config.addr);
103 if (deserialized_acceptor_it != deserialized_acceptors->end()) {
104 acceptor = deserialized_acceptor_it->second;
105 deserialized_acceptors->erase(deserialized_acceptor_it);
107 int server_sock = create_server_socket(acceptor_config.addr, TCP_SOCKET);
108 acceptor = new Acceptor(server_sock, acceptor_config.addr);
111 acceptors.push_back(acceptor);
114 // Close all acceptors that are no longer in the configuration file.
115 for (map<sockaddr_in6, Acceptor *, Sockaddr6Compare>::iterator
116 acceptor_it = deserialized_acceptors->begin();
117 acceptor_it != deserialized_acceptors->end();
119 acceptor_it->second->close_socket();
120 delete acceptor_it->second;
126 void create_config_input(const string &src, multimap<string, InputWithRefcount> *inputs)
131 if (inputs->count(src) != 0) {
135 InputWithRefcount iwr;
136 iwr.input = create_input(src);
137 if (iwr.input == NULL) {
138 log(ERROR, "did not understand URL '%s', clients will not get any data.",
143 inputs->insert(make_pair(src, iwr));
146 // Find all streams in the configuration file, and create inputs for them.
147 void create_config_inputs(const Config &config, multimap<string, InputWithRefcount> *inputs)
149 for (unsigned i = 0; i < config.streams.size(); ++i) {
150 const StreamConfig &stream_config = config.streams[i];
151 if (stream_config.src != "delete") {
152 create_config_input(stream_config.src, inputs);
155 for (unsigned i = 0; i < config.udpstreams.size(); ++i) {
156 const UDPStreamConfig &udpstream_config = config.udpstreams[i];
157 create_config_input(udpstream_config.src, inputs);
161 void create_streams(const Config &config,
162 const set<string> &deserialized_urls,
163 multimap<string, InputWithRefcount> *inputs)
166 set<string> expecting_urls = deserialized_urls;
167 for (unsigned i = 0; i < config.streams.size(); ++i) {
168 const StreamConfig &stream_config = config.streams[i];
171 expecting_urls.erase(stream_config.url);
173 // Special-case deleted streams; they were never deserialized in the first place,
174 // so just ignore them.
175 if (stream_config.src == "delete") {
179 if (deserialized_urls.count(stream_config.url) == 0) {
180 stream_index = servers->add_stream(stream_config.url,
181 stream_config.backlog_size,
182 stream_config.prebuffering_bytes,
183 Stream::Encoding(stream_config.encoding));
185 stream_index = servers->lookup_stream_by_url(stream_config.url);
186 assert(stream_index != -1);
187 servers->set_backlog_size(stream_index, stream_config.backlog_size);
188 servers->set_encoding(stream_index,
189 Stream::Encoding(stream_config.encoding));
192 servers->set_pacing_rate(stream_index, stream_config.pacing_rate);
194 string src = stream_config.src;
196 multimap<string, InputWithRefcount>::iterator input_it = inputs->find(src);
197 if (input_it != inputs->end()) {
198 input_it->second.input->add_destination(stream_index);
199 ++input_it->second.refcount;
204 // Warn about any streams servers we've lost.
205 for (set<string>::const_iterator stream_it = expecting_urls.begin();
206 stream_it != expecting_urls.end();
208 string url = *stream_it;
209 log(WARNING, "stream '%s' disappeared from the configuration file. "
210 "It will not be deleted, but clients will not get any new inputs. "
211 "If you really meant to delete it, set src=delete and reload.",
216 for (unsigned i = 0; i < config.udpstreams.size(); ++i) {
217 const UDPStreamConfig &udpstream_config = config.udpstreams[i];
218 int stream_index = servers->add_udpstream(
219 udpstream_config.dst,
220 udpstream_config.pacing_rate,
221 udpstream_config.ttl,
222 udpstream_config.multicast_iface_index);
224 string src = udpstream_config.src;
226 multimap<string, InputWithRefcount>::iterator input_it = inputs->find(src);
227 assert(input_it != inputs->end());
228 input_it->second.input->add_destination(stream_index);
229 ++input_it->second.refcount;
234 void open_logs(const vector<LogConfig> &log_destinations)
236 for (size_t i = 0; i < log_destinations.size(); ++i) {
237 if (log_destinations[i].type == LogConfig::LOG_TYPE_FILE) {
238 add_log_destination_file(log_destinations[i].filename);
239 } else if (log_destinations[i].type == LogConfig::LOG_TYPE_CONSOLE) {
240 add_log_destination_console();
241 } else if (log_destinations[i].type == LogConfig::LOG_TYPE_SYSLOG) {
242 add_log_destination_syslog();
250 bool dry_run_config(const std::string &argv0, const std::string &config_filename)
252 char *argv0_copy = strdup(argv0.c_str());
253 char *config_filename_copy = strdup(config_filename.c_str());
258 log_perror("fork()");
260 free(config_filename_copy);
264 execlp(argv0_copy, argv0_copy, "--test-config", config_filename_copy, NULL);
265 log_perror(argv0_copy);
273 free(config_filename_copy);
278 err = waitpid(pid, &status, 0);
279 } while (err == -1 && errno == EINTR);
282 log_perror("waitpid()");
286 return (WIFEXITED(status) && WEXITSTATUS(status) == 0);
289 void find_deleted_streams(const Config &config, set<string> *deleted_urls)
291 for (unsigned i = 0; i < config.streams.size(); ++i) {
292 const StreamConfig &stream_config = config.streams[i];
293 if (stream_config.src == "delete") {
294 log(INFO, "Deleting stream '%s'.", stream_config.url.c_str());
295 deleted_urls->insert(stream_config.url);
300 int main(int argc, char **argv)
304 signal(SIGUSR1, do_nothing); // Used in internal signalling.
305 signal(SIGPIPE, SIG_IGN);
309 bool test_config = false;
311 static const option long_options[] = {
312 { "state", required_argument, 0, 's' },
313 { "test-config", no_argument, 0, 't' },
316 int option_index = 0;
317 int c = getopt_long(argc, argv, "s:t", long_options, &option_index);
324 state_fd = atoi(optarg);
330 fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
335 string config_filename = "cubemap.config";
337 config_filename = argv[optind++];
340 // Canonicalize argv[0] and config_filename.
341 char argv0_canon[PATH_MAX];
342 char config_filename_canon[PATH_MAX];
344 if (realpath("/proc/self/exe", argv0_canon) == NULL) {
348 if (realpath(config_filename.c_str(), config_filename_canon) == NULL) {
349 log_perror(config_filename.c_str());
353 // Now parse the configuration file.
355 if (!parse_config(config_filename_canon, &config)) {
362 // Ideally we'd like to daemonize only when we've started up all threads etc.,
363 // but daemon() forks, which is not good in multithreaded software, so we'll
364 // have to do it here.
365 if (config.daemonize) {
366 if (daemon(0, 0) == -1) {
367 log_perror("daemon");
373 // Open logs as soon as possible.
374 open_logs(config.log_destinations);
376 log(INFO, "Cubemap " SERVER_VERSION " starting.");
377 if (config.access_log_file.empty()) {
378 // Create a dummy logger.
379 access_log = new AccessLogThread();
381 access_log = new AccessLogThread(config.access_log_file);
385 servers = new ServerPool(config.num_servers);
387 // Find all the streams that are to be deleted.
388 set<string> deleted_urls;
389 find_deleted_streams(config, &deleted_urls);
391 CubemapStateProto loaded_state;
392 struct timeval serialize_start;
393 set<string> deserialized_urls;
394 map<sockaddr_in6, Acceptor *, Sockaddr6Compare> deserialized_acceptors;
395 multimap<string, InputWithRefcount> inputs; // multimap due to older versions without deduplication.
396 if (state_fd != -1) {
397 log(INFO, "Deserializing state from previous process...");
399 if (!read_tempfile_and_close(state_fd, &serialized)) {
402 if (!loaded_state.ParseFromString(serialized)) {
403 log(ERROR, "Failed deserialization of state.");
407 serialize_start.tv_sec = loaded_state.serialize_start_sec();
408 serialize_start.tv_usec = loaded_state.serialize_start_usec();
410 // Deserialize the streams.
411 map<string, string> stream_headers_for_url; // See below.
412 for (int i = 0; i < loaded_state.streams_size(); ++i) {
413 const StreamProto &stream = loaded_state.streams(i);
415 if (deleted_urls.count(stream.url()) != 0) {
416 // Delete the stream backlogs.
417 for (int j = 0; j < stream.data_fds_size(); ++j) {
418 safe_close(stream.data_fds(j));
421 vector<int> data_fds;
422 for (int j = 0; j < stream.data_fds_size(); ++j) {
423 data_fds.push_back(stream.data_fds(j));
426 servers->add_stream_from_serialized(stream, data_fds);
427 deserialized_urls.insert(stream.url());
429 stream_headers_for_url.insert(make_pair(stream.url(), stream.stream_header()));
433 // Deserialize the inputs. Note that we don't actually add them to any stream yet.
434 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
435 InputProto serialized_input = loaded_state.inputs(i);
437 InputWithRefcount iwr;
438 iwr.input = create_input(serialized_input);
440 inputs.insert(make_pair(serialized_input.url(), iwr));
443 // Deserialize the acceptors.
444 for (int i = 0; i < loaded_state.acceptors_size(); ++i) {
445 sockaddr_in6 sin6 = extract_address_from_acceptor_proto(loaded_state.acceptors(i));
446 deserialized_acceptors.insert(make_pair(
448 new Acceptor(loaded_state.acceptors(i))));
451 log(INFO, "Deserialization done.");
454 // Add any new inputs coming from the config.
455 create_config_inputs(config, &inputs);
457 // Find all streams in the configuration file, create them, and connect to the inputs.
458 create_streams(config, deserialized_urls, &inputs);
459 vector<Acceptor *> acceptors = create_acceptors(config, &deserialized_acceptors);
461 // Convert old-style timestamps to new-style timestamps for all clients;
462 // this simplifies the sort below.
464 timespec now_monotonic;
465 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &now_monotonic) == -1) {
466 log(ERROR, "clock_gettime(CLOCK_MONOTONIC_COARSE) failed.");
469 long delta_sec = now_monotonic.tv_sec - time(NULL);
471 for (int i = 0; i < loaded_state.clients_size(); ++i) {
472 ClientProto* client = loaded_state.mutable_clients(i);
473 if (client->has_connect_time_old()) {
474 client->set_connect_time_sec(client->connect_time_old() + delta_sec);
475 client->set_connect_time_nsec(now_monotonic.tv_nsec);
476 client->clear_connect_time_old();
481 // Put back the existing clients. It doesn't matter which server we
482 // allocate them to, so just do round-robin. However, we need to sort them
483 // by connection time first, since add_client_serialized() expects that.
484 sort(loaded_state.mutable_clients()->begin(),
485 loaded_state.mutable_clients()->end(),
486 OrderByConnectionTime());
487 for (int i = 0; i < loaded_state.clients_size(); ++i) {
488 if (deleted_urls.count(loaded_state.clients(i).url()) != 0) {
489 safe_close(loaded_state.clients(i).sock());
491 servers->add_client_from_serialized(loaded_state.clients(i));
497 // Now delete all inputs that are longer in use, and start the others.
498 for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
499 input_it != inputs.end(); ) {
500 if (input_it->second.refcount == 0) {
501 log(WARNING, "Input '%s' no longer in use, closing.",
502 input_it->first.c_str());
503 input_it->second.input->close_socket();
504 delete input_it->second.input;
505 inputs.erase(input_it++);
507 input_it->second.input->run();
512 // Start writing statistics.
513 StatsThread *stats_thread = NULL;
514 if (!config.stats_file.empty()) {
515 stats_thread = new StatsThread(config.stats_file, config.stats_interval);
519 InputStatsThread *input_stats_thread = NULL;
520 if (!config.input_stats_file.empty()) {
521 vector<Input*> inputs_no_refcount;
522 for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
523 input_it != inputs.end(); ++input_it) {
524 inputs_no_refcount.push_back(input_it->second.input);
527 input_stats_thread = new InputStatsThread(config.input_stats_file, config.input_stats_interval, inputs_no_refcount);
528 input_stats_thread->run();
531 struct timeval server_start;
532 gettimeofday(&server_start, NULL);
533 if (state_fd != -1) {
534 // Measure time from we started deserializing (below) to now, when basically everything
535 // is up and running. This is, in other words, a conservative estimate of how long our
536 // “glitch” period was, not counting of course reconnects if the configuration changed.
537 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
538 1e-6 * (server_start.tv_usec - serialize_start.tv_usec);
539 log(INFO, "Re-exec happened in approx. %.0f ms.", glitch_time * 1000.0);
546 // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
547 gettimeofday(&serialize_start, NULL);
549 if (input_stats_thread != NULL) {
550 input_stats_thread->stop();
551 delete input_stats_thread;
553 if (stats_thread != NULL) {
554 stats_thread->stop();
557 for (size_t i = 0; i < acceptors.size(); ++i) {
558 acceptors[i]->stop();
560 for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
561 input_it != inputs.end();
563 input_it->second.input->stop();
567 CubemapStateProto state;
569 log(INFO, "Shutting down.");
571 log(INFO, "Serializing state and re-execing...");
572 state = collect_state(
573 serialize_start, acceptors, inputs, servers);
575 state.SerializeToString(&serialized);
576 state_fd = make_tempfile(serialized);
577 if (state_fd == -1) {
591 // OK, so the signal was SIGHUP. Check that the new config is okay, then exec the new binary.
592 if (!dry_run_config(argv0_canon, config_filename_canon)) {
593 open_logs(config.log_destinations);
594 log(ERROR, "%s --test-config failed. Restarting old version instead of new.", argv[0]);
601 sprintf(buf, "%d", state_fd);
604 execlp(argv0_canon, argv0_canon, config_filename_canon, "--state", buf, NULL);
605 open_logs(config.log_destinations);
606 log_perror("execlp");
607 log(ERROR, "re-exec of %s failed. Waiting 0.2 seconds and trying again...", argv0_canon);