20 #include "accesslog.h"
23 #include "input_stats.h"
26 #include "sa_compare.h"
27 #include "serverpool.h"
36 AccessLogThread *access_log = NULL;
37 ServerPool *servers = NULL;
38 vector<MarkPool *> mark_pools;
39 volatile bool hupped = false;
40 volatile bool stopped = false;
42 struct InputWithRefcount {
50 if (signum == SIGINT) {
55 void do_nothing(int signum)
59 CubemapStateProto collect_state(const timeval &serialize_start,
60 const vector<Acceptor *> acceptors,
61 const multimap<string, InputWithRefcount> inputs,
64 CubemapStateProto state = servers->serialize(); // Fills streams() and clients().
65 state.set_serialize_start_sec(serialize_start.tv_sec);
66 state.set_serialize_start_usec(serialize_start.tv_usec);
68 for (size_t i = 0; i < acceptors.size(); ++i) {
69 state.add_acceptors()->MergeFrom(acceptors[i]->serialize());
72 for (multimap<string, InputWithRefcount>::const_iterator input_it = inputs.begin();
73 input_it != inputs.end();
75 state.add_inputs()->MergeFrom(input_it->second.input->serialize());
81 // Find all port statements in the configuration file, and create acceptors for htem.
82 vector<Acceptor *> create_acceptors(
84 map<sockaddr_in6, Acceptor *, Sockaddr6Compare> *deserialized_acceptors)
86 vector<Acceptor *> acceptors;
87 for (unsigned i = 0; i < config.acceptors.size(); ++i) {
88 const AcceptorConfig &acceptor_config = config.acceptors[i];
89 Acceptor *acceptor = NULL;
90 map<sockaddr_in6, Acceptor *, Sockaddr6Compare>::iterator deserialized_acceptor_it =
91 deserialized_acceptors->find(acceptor_config.addr);
92 if (deserialized_acceptor_it != deserialized_acceptors->end()) {
93 acceptor = deserialized_acceptor_it->second;
94 deserialized_acceptors->erase(deserialized_acceptor_it);
96 int server_sock = create_server_socket(acceptor_config.addr, TCP_SOCKET);
97 acceptor = new Acceptor(server_sock, acceptor_config.addr);
100 acceptors.push_back(acceptor);
103 // Close all acceptors that are no longer in the configuration file.
104 for (map<sockaddr_in6, Acceptor *, Sockaddr6Compare>::iterator
105 acceptor_it = deserialized_acceptors->begin();
106 acceptor_it != deserialized_acceptors->end();
108 acceptor_it->second->close_socket();
109 delete acceptor_it->second;
115 void create_config_input(const string &src, multimap<string, InputWithRefcount> *inputs)
120 if (inputs->count(src) != 0) {
124 InputWithRefcount iwr;
125 iwr.input = create_input(src);
126 if (iwr.input == NULL) {
127 log(ERROR, "did not understand URL '%s', clients will not get any data.",
132 inputs->insert(make_pair(src, iwr));
135 // Find all streams in the configuration file, and create inputs for them.
136 void create_config_inputs(const Config &config, multimap<string, InputWithRefcount> *inputs)
138 for (unsigned i = 0; i < config.streams.size(); ++i) {
139 const StreamConfig &stream_config = config.streams[i];
140 if (stream_config.src != "delete") {
141 create_config_input(stream_config.src, inputs);
144 for (unsigned i = 0; i < config.udpstreams.size(); ++i) {
145 const UDPStreamConfig &udpstream_config = config.udpstreams[i];
146 create_config_input(udpstream_config.src, inputs);
150 void create_streams(const Config &config,
151 const set<string> &deserialized_urls,
152 multimap<string, InputWithRefcount> *inputs)
154 for (unsigned i = 0; i < config.mark_pools.size(); ++i) {
155 const MarkPoolConfig &mp_config = config.mark_pools[i];
156 mark_pools.push_back(new MarkPool(mp_config.from, mp_config.to));
160 set<string> expecting_urls = deserialized_urls;
161 for (unsigned i = 0; i < config.streams.size(); ++i) {
162 const StreamConfig &stream_config = config.streams[i];
165 expecting_urls.erase(stream_config.url);
167 // Special-case deleted streams; they were never deserialized in the first place,
168 // so just ignore them.
169 if (stream_config.src == "delete") {
173 if (deserialized_urls.count(stream_config.url) == 0) {
174 stream_index = servers->add_stream(stream_config.url,
175 stream_config.backlog_size,
176 Stream::Encoding(stream_config.encoding));
178 stream_index = servers->lookup_stream_by_url(stream_config.url);
179 assert(stream_index != -1);
180 servers->set_backlog_size(stream_index, stream_config.backlog_size);
181 servers->set_encoding(stream_index,
182 Stream::Encoding(stream_config.encoding));
185 if (stream_config.mark_pool != -1) {
186 servers->set_mark_pool(stream_index, mark_pools[stream_config.mark_pool]);
189 servers->set_pacing_rate(stream_index, stream_config.pacing_rate);
191 string src = stream_config.src;
193 multimap<string, InputWithRefcount>::iterator input_it = inputs->find(src);
194 if (input_it != inputs->end()) {
195 input_it->second.input->add_destination(stream_index);
196 ++input_it->second.refcount;
201 // Warn about any streams servers we've lost.
202 for (set<string>::const_iterator stream_it = expecting_urls.begin();
203 stream_it != expecting_urls.end();
205 string url = *stream_it;
206 log(WARNING, "stream '%s' disappeared from the configuration file. "
207 "It will not be deleted, but clients will not get any new inputs. "
208 "If you really meant to delete it, set src=delete and reload.",
213 for (unsigned i = 0; i < config.udpstreams.size(); ++i) {
214 const UDPStreamConfig &udpstream_config = config.udpstreams[i];
215 MarkPool *mark_pool = NULL;
216 if (udpstream_config.mark_pool != -1) {
217 mark_pool = mark_pools[udpstream_config.mark_pool];
219 int stream_index = servers->add_udpstream(udpstream_config.dst, mark_pool, udpstream_config.pacing_rate);
221 string src = udpstream_config.src;
223 multimap<string, InputWithRefcount>::iterator input_it = inputs->find(src);
224 assert(input_it != inputs->end());
225 input_it->second.input->add_destination(stream_index);
226 ++input_it->second.refcount;
231 void open_logs(const vector<LogConfig> &log_destinations)
233 for (size_t i = 0; i < log_destinations.size(); ++i) {
234 if (log_destinations[i].type == LogConfig::LOG_TYPE_FILE) {
235 add_log_destination_file(log_destinations[i].filename);
236 } else if (log_destinations[i].type == LogConfig::LOG_TYPE_CONSOLE) {
237 add_log_destination_console();
238 } else if (log_destinations[i].type == LogConfig::LOG_TYPE_SYSLOG) {
239 add_log_destination_syslog();
247 bool dry_run_config(const std::string &argv0, const std::string &config_filename)
249 char *argv0_copy = strdup(argv0.c_str());
250 char *config_filename_copy = strdup(config_filename.c_str());
255 log_perror("fork()");
257 free(config_filename_copy);
261 execlp(argv0_copy, argv0_copy, "--test-config", config_filename_copy, NULL);
262 log_perror(argv0_copy);
270 free(config_filename_copy);
275 err = waitpid(pid, &status, 0);
276 } while (err == -1 && errno == EINTR);
279 log_perror("waitpid()");
283 return (WIFEXITED(status) && WEXITSTATUS(status) == 0);
286 void find_deleted_streams(const Config &config, set<string> *deleted_urls)
288 for (unsigned i = 0; i < config.streams.size(); ++i) {
289 const StreamConfig &stream_config = config.streams[i];
290 if (stream_config.src == "delete") {
291 log(INFO, "Deleting stream '%s'.", stream_config.url.c_str());
292 deleted_urls->insert(stream_config.url);
297 int main(int argc, char **argv)
301 signal(SIGUSR1, do_nothing); // Used in internal signalling.
302 signal(SIGPIPE, SIG_IGN);
306 bool test_config = false;
308 static const option long_options[] = {
309 { "state", required_argument, 0, 's' },
310 { "test-config", no_argument, 0, 't' },
313 int option_index = 0;
314 int c = getopt_long(argc, argv, "s:t", long_options, &option_index);
321 state_fd = atoi(optarg);
327 fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
332 string config_filename = "cubemap.config";
334 config_filename = argv[optind++];
337 // Canonicalize argv[0] and config_filename.
338 char argv0_canon[PATH_MAX];
339 char config_filename_canon[PATH_MAX];
341 if (realpath("/proc/self/exe", argv0_canon) == NULL) {
345 if (realpath(config_filename.c_str(), config_filename_canon) == NULL) {
346 log_perror(config_filename.c_str());
350 // Now parse the configuration file.
352 if (!parse_config(config_filename_canon, &config)) {
359 // Ideally we'd like to daemonize only when we've started up all threads etc.,
360 // but daemon() forks, which is not good in multithreaded software, so we'll
361 // have to do it here.
362 if (config.daemonize) {
363 if (daemon(0, 0) == -1) {
364 log_perror("daemon");
370 // Open logs as soon as possible.
371 open_logs(config.log_destinations);
373 log(INFO, "Cubemap " SERVER_VERSION " starting.");
374 if (config.access_log_file.empty()) {
375 // Create a dummy logger.
376 access_log = new AccessLogThread();
378 access_log = new AccessLogThread(config.access_log_file);
382 servers = new ServerPool(config.num_servers);
384 // Find all the streams that are to be deleted.
385 set<string> deleted_urls;
386 find_deleted_streams(config, &deleted_urls);
388 CubemapStateProto loaded_state;
389 struct timeval serialize_start;
390 set<string> deserialized_urls;
391 map<sockaddr_in6, Acceptor *, Sockaddr6Compare> deserialized_acceptors;
392 multimap<string, InputWithRefcount> inputs; // multimap due to older versions without deduplication.
393 if (state_fd != -1) {
394 log(INFO, "Deserializing state from previous process...");
396 if (!read_tempfile(state_fd, &serialized)) {
399 if (!loaded_state.ParseFromString(serialized)) {
400 log(ERROR, "Failed deserialization of state.");
404 serialize_start.tv_sec = loaded_state.serialize_start_sec();
405 serialize_start.tv_usec = loaded_state.serialize_start_usec();
407 // Deserialize the streams.
408 map<string, string> stream_headers_for_url; // See below.
409 for (int i = 0; i < loaded_state.streams_size(); ++i) {
410 const StreamProto &stream = loaded_state.streams(i);
412 if (deleted_urls.count(stream.url()) != 0) {
413 // Delete the stream backlogs.
414 for (int j = 0; j < stream.data_fds_size(); ++j) {
415 safe_close(stream.data_fds(j));
418 vector<int> data_fds;
419 for (int j = 0; j < stream.data_fds_size(); ++j) {
420 data_fds.push_back(stream.data_fds(j));
423 servers->add_stream_from_serialized(stream, data_fds);
424 deserialized_urls.insert(stream.url());
426 stream_headers_for_url.insert(make_pair(stream.url(), stream.stream_header()));
430 // Deserialize the inputs. Note that we don't actually add them to any stream yet.
431 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
432 InputProto serialized_input = loaded_state.inputs(i);
434 InputWithRefcount iwr;
435 iwr.input = create_input(serialized_input);
437 inputs.insert(make_pair(serialized_input.url(), iwr));
440 // Deserialize the acceptors.
441 for (int i = 0; i < loaded_state.acceptors_size(); ++i) {
442 sockaddr_in6 sin6 = ExtractAddressFromAcceptorProto(loaded_state.acceptors(i));
443 deserialized_acceptors.insert(make_pair(
445 new Acceptor(loaded_state.acceptors(i))));
448 log(INFO, "Deserialization done.");
451 // Add any new inputs coming from the config.
452 create_config_inputs(config, &inputs);
454 // Find all streams in the configuration file, create them, and connect to the inputs.
455 create_streams(config, deserialized_urls, &inputs);
456 vector<Acceptor *> acceptors = create_acceptors(config, &deserialized_acceptors);
458 // Put back the existing clients. It doesn't matter which server we
459 // allocate them to, so just do round-robin. However, we need to add
460 // them after the mark pools have been set up.
461 for (int i = 0; i < loaded_state.clients_size(); ++i) {
462 if (deleted_urls.count(loaded_state.clients(i).url()) != 0) {
463 safe_close(loaded_state.clients(i).sock());
465 servers->add_client_from_serialized(loaded_state.clients(i));
471 // Now delete all inputs that are longer in use, and start the others.
472 for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
473 input_it != inputs.end(); ) {
474 if (input_it->second.refcount == 0) {
475 log(WARNING, "Input '%s' no longer in use, closing.",
476 input_it->first.c_str());
477 input_it->second.input->close_socket();
478 delete input_it->second.input;
479 inputs.erase(input_it++);
481 input_it->second.input->run();
486 // Start writing statistics.
487 StatsThread *stats_thread = NULL;
488 if (!config.stats_file.empty()) {
489 stats_thread = new StatsThread(config.stats_file, config.stats_interval);
493 InputStatsThread *input_stats_thread = NULL;
494 if (!config.input_stats_file.empty()) {
495 vector<Input*> inputs_no_refcount;
496 for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
497 input_it != inputs.end(); ++input_it) {
498 inputs_no_refcount.push_back(input_it->second.input);
501 input_stats_thread = new InputStatsThread(config.input_stats_file, config.input_stats_interval, inputs_no_refcount);
502 input_stats_thread->run();
505 struct timeval server_start;
506 gettimeofday(&server_start, NULL);
507 if (state_fd != -1) {
508 // Measure time from we started deserializing (below) to now, when basically everything
509 // is up and running. This is, in other words, a conservative estimate of how long our
510 // “glitch” period was, not counting of course reconnects if the configuration changed.
511 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
512 1e-6 * (server_start.tv_usec - serialize_start.tv_usec);
513 log(INFO, "Re-exec happened in approx. %.0f ms.", glitch_time * 1000.0);
520 // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
521 gettimeofday(&serialize_start, NULL);
523 if (input_stats_thread != NULL) {
524 input_stats_thread->stop();
525 delete input_stats_thread;
527 if (stats_thread != NULL) {
528 stats_thread->stop();
531 for (size_t i = 0; i < acceptors.size(); ++i) {
532 acceptors[i]->stop();
534 for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
535 input_it != inputs.end();
537 input_it->second.input->stop();
541 CubemapStateProto state;
543 log(INFO, "Shutting down.");
545 log(INFO, "Serializing state and re-execing...");
546 state = collect_state(
547 serialize_start, acceptors, inputs, servers);
549 state.SerializeToString(&serialized);
550 state_fd = make_tempfile(serialized);
551 if (state_fd == -1) {
557 for (unsigned i = 0; i < mark_pools.size(); ++i) {
558 delete mark_pools[i];
570 // OK, so the signal was SIGHUP. Check that the new config is okay, then exec the new binary.
571 if (!dry_run_config(argv0_canon, config_filename_canon)) {
572 open_logs(config.log_destinations);
573 log(ERROR, "%s --test-config failed. Restarting old version instead of new.", argv[0]);
580 sprintf(buf, "%d", state_fd);
583 execlp(argv0_canon, argv0_canon, config_filename_canon, "--state", buf, NULL);
584 open_logs(config.log_destinations);
585 log_perror("execlp");
586 log(ERROR, "re-exec of %s failed. Waiting 0.2 seconds and trying again...", argv0_canon);