20 #include "accesslog.h"
23 #include "input_stats.h"
25 #include "sa_compare.h"
26 #include "serverpool.h"
35 AccessLogThread *access_log = NULL;
36 ServerPool *servers = NULL;
37 volatile bool hupped = false;
38 volatile bool stopped = false;
40 struct InputWithRefcount {
48 if (signum == SIGINT) {
53 void do_nothing(int signum)
57 CubemapStateProto collect_state(const timeval &serialize_start,
58 const vector<Acceptor *> acceptors,
59 const multimap<string, InputWithRefcount> inputs,
62 CubemapStateProto state = servers->serialize(); // Fills streams() and clients().
63 state.set_serialize_start_sec(serialize_start.tv_sec);
64 state.set_serialize_start_usec(serialize_start.tv_usec);
66 for (size_t i = 0; i < acceptors.size(); ++i) {
67 state.add_acceptors()->MergeFrom(acceptors[i]->serialize());
70 for (multimap<string, InputWithRefcount>::const_iterator input_it = inputs.begin();
71 input_it != inputs.end();
73 state.add_inputs()->MergeFrom(input_it->second.input->serialize());
79 // Find all port statements in the configuration file, and create acceptors for htem.
80 vector<Acceptor *> create_acceptors(
82 map<sockaddr_in6, Acceptor *, Sockaddr6Compare> *deserialized_acceptors)
84 vector<Acceptor *> acceptors;
85 for (unsigned i = 0; i < config.acceptors.size(); ++i) {
86 const AcceptorConfig &acceptor_config = config.acceptors[i];
87 Acceptor *acceptor = NULL;
88 map<sockaddr_in6, Acceptor *, Sockaddr6Compare>::iterator deserialized_acceptor_it =
89 deserialized_acceptors->find(acceptor_config.addr);
90 if (deserialized_acceptor_it != deserialized_acceptors->end()) {
91 acceptor = deserialized_acceptor_it->second;
92 deserialized_acceptors->erase(deserialized_acceptor_it);
94 int server_sock = create_server_socket(acceptor_config.addr, TCP_SOCKET);
95 acceptor = new Acceptor(server_sock, acceptor_config.addr);
98 acceptors.push_back(acceptor);
101 // Close all acceptors that are no longer in the configuration file.
102 for (map<sockaddr_in6, Acceptor *, Sockaddr6Compare>::iterator
103 acceptor_it = deserialized_acceptors->begin();
104 acceptor_it != deserialized_acceptors->end();
106 acceptor_it->second->close_socket();
107 delete acceptor_it->second;
113 void create_config_input(const string &src, multimap<string, InputWithRefcount> *inputs)
118 if (inputs->count(src) != 0) {
122 InputWithRefcount iwr;
123 iwr.input = create_input(src);
124 if (iwr.input == NULL) {
125 log(ERROR, "did not understand URL '%s', clients will not get any data.",
130 inputs->insert(make_pair(src, iwr));
133 // Find all streams in the configuration file, and create inputs for them.
134 void create_config_inputs(const Config &config, multimap<string, InputWithRefcount> *inputs)
136 for (unsigned i = 0; i < config.streams.size(); ++i) {
137 const StreamConfig &stream_config = config.streams[i];
138 if (stream_config.src != "delete") {
139 create_config_input(stream_config.src, inputs);
142 for (unsigned i = 0; i < config.udpstreams.size(); ++i) {
143 const UDPStreamConfig &udpstream_config = config.udpstreams[i];
144 create_config_input(udpstream_config.src, inputs);
148 void create_streams(const Config &config,
149 const set<string> &deserialized_urls,
150 multimap<string, InputWithRefcount> *inputs)
153 set<string> expecting_urls = deserialized_urls;
154 for (unsigned i = 0; i < config.streams.size(); ++i) {
155 const StreamConfig &stream_config = config.streams[i];
158 expecting_urls.erase(stream_config.url);
160 // Special-case deleted streams; they were never deserialized in the first place,
161 // so just ignore them.
162 if (stream_config.src == "delete") {
166 if (deserialized_urls.count(stream_config.url) == 0) {
167 stream_index = servers->add_stream(stream_config.url,
168 stream_config.backlog_size,
169 stream_config.prebuffering_bytes,
170 Stream::Encoding(stream_config.encoding));
172 stream_index = servers->lookup_stream_by_url(stream_config.url);
173 assert(stream_index != -1);
174 servers->set_backlog_size(stream_index, stream_config.backlog_size);
175 servers->set_encoding(stream_index,
176 Stream::Encoding(stream_config.encoding));
179 servers->set_pacing_rate(stream_index, stream_config.pacing_rate);
181 string src = stream_config.src;
183 multimap<string, InputWithRefcount>::iterator input_it = inputs->find(src);
184 if (input_it != inputs->end()) {
185 input_it->second.input->add_destination(stream_index);
186 ++input_it->second.refcount;
191 // Warn about any streams servers we've lost.
192 for (set<string>::const_iterator stream_it = expecting_urls.begin();
193 stream_it != expecting_urls.end();
195 string url = *stream_it;
196 log(WARNING, "stream '%s' disappeared from the configuration file. "
197 "It will not be deleted, but clients will not get any new inputs. "
198 "If you really meant to delete it, set src=delete and reload.",
203 for (unsigned i = 0; i < config.udpstreams.size(); ++i) {
204 const UDPStreamConfig &udpstream_config = config.udpstreams[i];
205 int stream_index = servers->add_udpstream(
206 udpstream_config.dst,
207 udpstream_config.pacing_rate,
208 udpstream_config.ttl,
209 udpstream_config.multicast_iface_index);
211 string src = udpstream_config.src;
213 multimap<string, InputWithRefcount>::iterator input_it = inputs->find(src);
214 assert(input_it != inputs->end());
215 input_it->second.input->add_destination(stream_index);
216 ++input_it->second.refcount;
221 void open_logs(const vector<LogConfig> &log_destinations)
223 for (size_t i = 0; i < log_destinations.size(); ++i) {
224 if (log_destinations[i].type == LogConfig::LOG_TYPE_FILE) {
225 add_log_destination_file(log_destinations[i].filename);
226 } else if (log_destinations[i].type == LogConfig::LOG_TYPE_CONSOLE) {
227 add_log_destination_console();
228 } else if (log_destinations[i].type == LogConfig::LOG_TYPE_SYSLOG) {
229 add_log_destination_syslog();
237 bool dry_run_config(const std::string &argv0, const std::string &config_filename)
239 char *argv0_copy = strdup(argv0.c_str());
240 char *config_filename_copy = strdup(config_filename.c_str());
245 log_perror("fork()");
247 free(config_filename_copy);
251 execlp(argv0_copy, argv0_copy, "--test-config", config_filename_copy, NULL);
252 log_perror(argv0_copy);
260 free(config_filename_copy);
265 err = waitpid(pid, &status, 0);
266 } while (err == -1 && errno == EINTR);
269 log_perror("waitpid()");
273 return (WIFEXITED(status) && WEXITSTATUS(status) == 0);
276 void find_deleted_streams(const Config &config, set<string> *deleted_urls)
278 for (unsigned i = 0; i < config.streams.size(); ++i) {
279 const StreamConfig &stream_config = config.streams[i];
280 if (stream_config.src == "delete") {
281 log(INFO, "Deleting stream '%s'.", stream_config.url.c_str());
282 deleted_urls->insert(stream_config.url);
287 int main(int argc, char **argv)
291 signal(SIGUSR1, do_nothing); // Used in internal signalling.
292 signal(SIGPIPE, SIG_IGN);
296 bool test_config = false;
298 static const option long_options[] = {
299 { "state", required_argument, 0, 's' },
300 { "test-config", no_argument, 0, 't' },
303 int option_index = 0;
304 int c = getopt_long(argc, argv, "s:t", long_options, &option_index);
311 state_fd = atoi(optarg);
317 fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
322 string config_filename = "cubemap.config";
324 config_filename = argv[optind++];
327 // Canonicalize argv[0] and config_filename.
328 char argv0_canon[PATH_MAX];
329 char config_filename_canon[PATH_MAX];
331 if (realpath("/proc/self/exe", argv0_canon) == NULL) {
335 if (realpath(config_filename.c_str(), config_filename_canon) == NULL) {
336 log_perror(config_filename.c_str());
340 // Now parse the configuration file.
342 if (!parse_config(config_filename_canon, &config)) {
349 // Ideally we'd like to daemonize only when we've started up all threads etc.,
350 // but daemon() forks, which is not good in multithreaded software, so we'll
351 // have to do it here.
352 if (config.daemonize) {
353 if (daemon(0, 0) == -1) {
354 log_perror("daemon");
360 // Open logs as soon as possible.
361 open_logs(config.log_destinations);
363 log(INFO, "Cubemap " SERVER_VERSION " starting.");
364 if (config.access_log_file.empty()) {
365 // Create a dummy logger.
366 access_log = new AccessLogThread();
368 access_log = new AccessLogThread(config.access_log_file);
372 servers = new ServerPool(config.num_servers);
374 // Find all the streams that are to be deleted.
375 set<string> deleted_urls;
376 find_deleted_streams(config, &deleted_urls);
378 CubemapStateProto loaded_state;
379 struct timeval serialize_start;
380 set<string> deserialized_urls;
381 map<sockaddr_in6, Acceptor *, Sockaddr6Compare> deserialized_acceptors;
382 multimap<string, InputWithRefcount> inputs; // multimap due to older versions without deduplication.
383 if (state_fd != -1) {
384 log(INFO, "Deserializing state from previous process...");
386 if (!read_tempfile_and_close(state_fd, &serialized)) {
389 if (!loaded_state.ParseFromString(serialized)) {
390 log(ERROR, "Failed deserialization of state.");
394 serialize_start.tv_sec = loaded_state.serialize_start_sec();
395 serialize_start.tv_usec = loaded_state.serialize_start_usec();
397 // Deserialize the streams.
398 map<string, string> stream_headers_for_url; // See below.
399 for (int i = 0; i < loaded_state.streams_size(); ++i) {
400 const StreamProto &stream = loaded_state.streams(i);
402 if (deleted_urls.count(stream.url()) != 0) {
403 // Delete the stream backlogs.
404 for (int j = 0; j < stream.data_fds_size(); ++j) {
405 safe_close(stream.data_fds(j));
408 vector<int> data_fds;
409 for (int j = 0; j < stream.data_fds_size(); ++j) {
410 data_fds.push_back(stream.data_fds(j));
413 servers->add_stream_from_serialized(stream, data_fds);
414 deserialized_urls.insert(stream.url());
416 stream_headers_for_url.insert(make_pair(stream.url(), stream.stream_header()));
420 // Deserialize the inputs. Note that we don't actually add them to any stream yet.
421 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
422 InputProto serialized_input = loaded_state.inputs(i);
424 InputWithRefcount iwr;
425 iwr.input = create_input(serialized_input);
427 inputs.insert(make_pair(serialized_input.url(), iwr));
430 // Deserialize the acceptors.
431 for (int i = 0; i < loaded_state.acceptors_size(); ++i) {
432 sockaddr_in6 sin6 = extract_address_from_acceptor_proto(loaded_state.acceptors(i));
433 deserialized_acceptors.insert(make_pair(
435 new Acceptor(loaded_state.acceptors(i))));
438 log(INFO, "Deserialization done.");
441 // Add any new inputs coming from the config.
442 create_config_inputs(config, &inputs);
444 // Find all streams in the configuration file, create them, and connect to the inputs.
445 create_streams(config, deserialized_urls, &inputs);
446 vector<Acceptor *> acceptors = create_acceptors(config, &deserialized_acceptors);
448 // Put back the existing clients. It doesn't matter which server we
449 // allocate them to, so just do round-robin.
450 for (int i = 0; i < loaded_state.clients_size(); ++i) {
451 if (deleted_urls.count(loaded_state.clients(i).url()) != 0) {
452 safe_close(loaded_state.clients(i).sock());
454 servers->add_client_from_serialized(loaded_state.clients(i));
460 // Now delete all inputs that are longer in use, and start the others.
461 for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
462 input_it != inputs.end(); ) {
463 if (input_it->second.refcount == 0) {
464 log(WARNING, "Input '%s' no longer in use, closing.",
465 input_it->first.c_str());
466 input_it->second.input->close_socket();
467 delete input_it->second.input;
468 inputs.erase(input_it++);
470 input_it->second.input->run();
475 // Start writing statistics.
476 StatsThread *stats_thread = NULL;
477 if (!config.stats_file.empty()) {
478 stats_thread = new StatsThread(config.stats_file, config.stats_interval);
482 InputStatsThread *input_stats_thread = NULL;
483 if (!config.input_stats_file.empty()) {
484 vector<Input*> inputs_no_refcount;
485 for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
486 input_it != inputs.end(); ++input_it) {
487 inputs_no_refcount.push_back(input_it->second.input);
490 input_stats_thread = new InputStatsThread(config.input_stats_file, config.input_stats_interval, inputs_no_refcount);
491 input_stats_thread->run();
494 struct timeval server_start;
495 gettimeofday(&server_start, NULL);
496 if (state_fd != -1) {
497 // Measure time from we started deserializing (below) to now, when basically everything
498 // is up and running. This is, in other words, a conservative estimate of how long our
499 // “glitch” period was, not counting of course reconnects if the configuration changed.
500 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
501 1e-6 * (server_start.tv_usec - serialize_start.tv_usec);
502 log(INFO, "Re-exec happened in approx. %.0f ms.", glitch_time * 1000.0);
509 // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
510 gettimeofday(&serialize_start, NULL);
512 if (input_stats_thread != NULL) {
513 input_stats_thread->stop();
514 delete input_stats_thread;
516 if (stats_thread != NULL) {
517 stats_thread->stop();
520 for (size_t i = 0; i < acceptors.size(); ++i) {
521 acceptors[i]->stop();
523 for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
524 input_it != inputs.end();
526 input_it->second.input->stop();
530 CubemapStateProto state;
532 log(INFO, "Shutting down.");
534 log(INFO, "Serializing state and re-execing...");
535 state = collect_state(
536 serialize_start, acceptors, inputs, servers);
538 state.SerializeToString(&serialized);
539 state_fd = make_tempfile(serialized);
540 if (state_fd == -1) {
554 // OK, so the signal was SIGHUP. Check that the new config is okay, then exec the new binary.
555 if (!dry_run_config(argv0_canon, config_filename_canon)) {
556 open_logs(config.log_destinations);
557 log(ERROR, "%s --test-config failed. Restarting old version instead of new.", argv[0]);
564 sprintf(buf, "%d", state_fd);
567 execlp(argv0_canon, argv0_canon, config_filename_canon, "--state", buf, NULL);
568 open_logs(config.log_destinations);
569 log_perror("execlp");
570 log(ERROR, "re-exec of %s failed. Waiting 0.2 seconds and trying again...", argv0_canon);