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_prebuffering_bytes(stream_index, stream_config.prebuffering_bytes);
189 servers->set_encoding(stream_index,
190 Stream::Encoding(stream_config.encoding));
193 servers->set_pacing_rate(stream_index, stream_config.pacing_rate);
195 string src = stream_config.src;
197 multimap<string, InputWithRefcount>::iterator input_it = inputs->find(src);
198 if (input_it != inputs->end()) {
199 input_it->second.input->add_destination(stream_index);
200 ++input_it->second.refcount;
205 // Warn about any streams servers we've lost.
206 for (set<string>::const_iterator stream_it = expecting_urls.begin();
207 stream_it != expecting_urls.end();
209 string url = *stream_it;
210 log(WARNING, "stream '%s' disappeared from the configuration file. "
211 "It will not be deleted, but clients will not get any new inputs. "
212 "If you really meant to delete it, set src=delete and reload.",
217 for (unsigned i = 0; i < config.udpstreams.size(); ++i) {
218 const UDPStreamConfig &udpstream_config = config.udpstreams[i];
219 int stream_index = servers->add_udpstream(
220 udpstream_config.dst,
221 udpstream_config.pacing_rate,
222 udpstream_config.ttl,
223 udpstream_config.multicast_iface_index);
225 string src = udpstream_config.src;
227 multimap<string, InputWithRefcount>::iterator input_it = inputs->find(src);
228 assert(input_it != inputs->end());
229 input_it->second.input->add_destination(stream_index);
230 ++input_it->second.refcount;
235 void open_logs(const vector<LogConfig> &log_destinations)
237 for (size_t i = 0; i < log_destinations.size(); ++i) {
238 if (log_destinations[i].type == LogConfig::LOG_TYPE_FILE) {
239 add_log_destination_file(log_destinations[i].filename);
240 } else if (log_destinations[i].type == LogConfig::LOG_TYPE_CONSOLE) {
241 add_log_destination_console();
242 } else if (log_destinations[i].type == LogConfig::LOG_TYPE_SYSLOG) {
243 add_log_destination_syslog();
251 bool dry_run_config(const std::string &argv0, const std::string &config_filename)
253 char *argv0_copy = strdup(argv0.c_str());
254 char *config_filename_copy = strdup(config_filename.c_str());
259 log_perror("fork()");
261 free(config_filename_copy);
265 execlp(argv0_copy, argv0_copy, "--test-config", config_filename_copy, NULL);
266 log_perror(argv0_copy);
274 free(config_filename_copy);
279 err = waitpid(pid, &status, 0);
280 } while (err == -1 && errno == EINTR);
283 log_perror("waitpid()");
287 return (WIFEXITED(status) && WEXITSTATUS(status) == 0);
290 void find_deleted_streams(const Config &config, set<string> *deleted_urls)
292 for (unsigned i = 0; i < config.streams.size(); ++i) {
293 const StreamConfig &stream_config = config.streams[i];
294 if (stream_config.src == "delete") {
295 log(INFO, "Deleting stream '%s'.", stream_config.url.c_str());
296 deleted_urls->insert(stream_config.url);
301 int main(int argc, char **argv)
305 signal(SIGUSR1, do_nothing); // Used in internal signalling.
306 signal(SIGPIPE, SIG_IGN);
310 bool test_config = false;
312 static const option long_options[] = {
313 { "state", required_argument, 0, 's' },
314 { "test-config", no_argument, 0, 't' },
317 int option_index = 0;
318 int c = getopt_long(argc, argv, "s:t", long_options, &option_index);
325 state_fd = atoi(optarg);
331 fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
336 string config_filename = "cubemap.config";
338 config_filename = argv[optind++];
341 // Canonicalize argv[0] and config_filename.
342 char argv0_canon[PATH_MAX];
343 char config_filename_canon[PATH_MAX];
345 if (realpath("/proc/self/exe", argv0_canon) == NULL) {
349 if (realpath(config_filename.c_str(), config_filename_canon) == NULL) {
350 log_perror(config_filename.c_str());
354 // Now parse the configuration file.
356 if (!parse_config(config_filename_canon, &config)) {
363 // Ideally we'd like to daemonize only when we've started up all threads etc.,
364 // but daemon() forks, which is not good in multithreaded software, so we'll
365 // have to do it here.
366 if (config.daemonize) {
367 if (daemon(0, 0) == -1) {
368 log_perror("daemon");
374 // Open logs as soon as possible.
375 open_logs(config.log_destinations);
377 log(INFO, "Cubemap " SERVER_VERSION " starting.");
378 if (config.access_log_file.empty()) {
379 // Create a dummy logger.
380 access_log = new AccessLogThread();
382 access_log = new AccessLogThread(config.access_log_file);
386 servers = new ServerPool(config.num_servers);
388 // Find all the streams that are to be deleted.
389 set<string> deleted_urls;
390 find_deleted_streams(config, &deleted_urls);
392 CubemapStateProto loaded_state;
393 struct timeval serialize_start;
394 set<string> deserialized_urls;
395 map<sockaddr_in6, Acceptor *, Sockaddr6Compare> deserialized_acceptors;
396 multimap<string, InputWithRefcount> inputs; // multimap due to older versions without deduplication.
397 if (state_fd != -1) {
398 log(INFO, "Deserializing state from previous process...");
400 if (!read_tempfile_and_close(state_fd, &serialized)) {
403 if (!loaded_state.ParseFromString(serialized)) {
404 log(ERROR, "Failed deserialization of state.");
408 serialize_start.tv_sec = loaded_state.serialize_start_sec();
409 serialize_start.tv_usec = loaded_state.serialize_start_usec();
411 // Deserialize the streams.
412 map<string, string> stream_headers_for_url; // See below.
413 for (int i = 0; i < loaded_state.streams_size(); ++i) {
414 const StreamProto &stream = loaded_state.streams(i);
416 if (deleted_urls.count(stream.url()) != 0) {
417 // Delete the stream backlogs.
418 for (int j = 0; j < stream.data_fds_size(); ++j) {
419 safe_close(stream.data_fds(j));
422 vector<int> data_fds;
423 for (int j = 0; j < stream.data_fds_size(); ++j) {
424 data_fds.push_back(stream.data_fds(j));
427 servers->add_stream_from_serialized(stream, data_fds);
428 deserialized_urls.insert(stream.url());
430 stream_headers_for_url.insert(make_pair(stream.url(), stream.stream_header()));
434 // Deserialize the inputs. Note that we don't actually add them to any stream yet.
435 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
436 InputProto serialized_input = loaded_state.inputs(i);
438 InputWithRefcount iwr;
439 iwr.input = create_input(serialized_input);
441 inputs.insert(make_pair(serialized_input.url(), iwr));
444 // Deserialize the acceptors.
445 for (int i = 0; i < loaded_state.acceptors_size(); ++i) {
446 sockaddr_in6 sin6 = extract_address_from_acceptor_proto(loaded_state.acceptors(i));
447 deserialized_acceptors.insert(make_pair(
449 new Acceptor(loaded_state.acceptors(i))));
452 log(INFO, "Deserialization done.");
455 // Add any new inputs coming from the config.
456 create_config_inputs(config, &inputs);
458 // Find all streams in the configuration file, create them, and connect to the inputs.
459 create_streams(config, deserialized_urls, &inputs);
460 vector<Acceptor *> acceptors = create_acceptors(config, &deserialized_acceptors);
462 // Convert old-style timestamps to new-style timestamps for all clients;
463 // this simplifies the sort below.
465 timespec now_monotonic;
466 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &now_monotonic) == -1) {
467 log(ERROR, "clock_gettime(CLOCK_MONOTONIC_COARSE) failed.");
470 long delta_sec = now_monotonic.tv_sec - time(NULL);
472 for (int i = 0; i < loaded_state.clients_size(); ++i) {
473 ClientProto* client = loaded_state.mutable_clients(i);
474 if (client->has_connect_time_old()) {
475 client->set_connect_time_sec(client->connect_time_old() + delta_sec);
476 client->set_connect_time_nsec(now_monotonic.tv_nsec);
477 client->clear_connect_time_old();
482 // Put back the existing clients. It doesn't matter which server we
483 // allocate them to, so just do round-robin. However, we need to sort them
484 // by connection time first, since add_client_serialized() expects that.
485 sort(loaded_state.mutable_clients()->begin(),
486 loaded_state.mutable_clients()->end(),
487 OrderByConnectionTime());
488 for (int i = 0; i < loaded_state.clients_size(); ++i) {
489 if (deleted_urls.count(loaded_state.clients(i).url()) != 0) {
490 safe_close(loaded_state.clients(i).sock());
492 servers->add_client_from_serialized(loaded_state.clients(i));
498 // Now delete all inputs that are longer in use, and start the others.
499 for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
500 input_it != inputs.end(); ) {
501 if (input_it->second.refcount == 0) {
502 log(WARNING, "Input '%s' no longer in use, closing.",
503 input_it->first.c_str());
504 input_it->second.input->close_socket();
505 delete input_it->second.input;
506 inputs.erase(input_it++);
508 input_it->second.input->run();
513 // Start writing statistics.
514 StatsThread *stats_thread = NULL;
515 if (!config.stats_file.empty()) {
516 stats_thread = new StatsThread(config.stats_file, config.stats_interval);
520 InputStatsThread *input_stats_thread = NULL;
521 if (!config.input_stats_file.empty()) {
522 vector<Input*> inputs_no_refcount;
523 for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
524 input_it != inputs.end(); ++input_it) {
525 inputs_no_refcount.push_back(input_it->second.input);
528 input_stats_thread = new InputStatsThread(config.input_stats_file, config.input_stats_interval, inputs_no_refcount);
529 input_stats_thread->run();
532 struct timeval server_start;
533 gettimeofday(&server_start, NULL);
534 if (state_fd != -1) {
535 // Measure time from we started deserializing (below) to now, when basically everything
536 // is up and running. This is, in other words, a conservative estimate of how long our
537 // “glitch” period was, not counting of course reconnects if the configuration changed.
538 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
539 1e-6 * (server_start.tv_usec - serialize_start.tv_usec);
540 log(INFO, "Re-exec happened in approx. %.0f ms.", glitch_time * 1000.0);
547 // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
548 gettimeofday(&serialize_start, NULL);
550 if (input_stats_thread != NULL) {
551 input_stats_thread->stop();
552 delete input_stats_thread;
554 if (stats_thread != NULL) {
555 stats_thread->stop();
558 for (size_t i = 0; i < acceptors.size(); ++i) {
559 acceptors[i]->stop();
561 for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
562 input_it != inputs.end();
564 input_it->second.input->stop();
568 CubemapStateProto state;
570 log(INFO, "Shutting down.");
572 log(INFO, "Serializing state and re-execing...");
573 state = collect_state(
574 serialize_start, acceptors, inputs, servers);
576 state.SerializeToString(&serialized);
577 state_fd = make_tempfile(serialized);
578 if (state_fd == -1) {
592 // OK, so the signal was SIGHUP. Check that the new config is okay, then exec the new binary.
593 if (!dry_run_config(argv0_canon, config_filename_canon)) {
594 open_logs(config.log_destinations);
595 log(ERROR, "%s --test-config failed. Restarting old version instead of new.", argv[0]);
602 sprintf(buf, "%d", state_fd);
605 execlp(argv0_canon, argv0_canon, config_filename_canon, "--state", buf, NULL);
606 open_logs(config.log_destinations);
607 log_perror("execlp");
608 log(ERROR, "re-exec of %s failed. Waiting 0.2 seconds and trying again...", argv0_canon);