20 #include "accesslog.h"
23 #include "input_stats.h"
26 #include "serverpool.h"
35 AccessLogThread *access_log = NULL;
36 ServerPool *servers = NULL;
37 vector<MarkPool *> mark_pools;
38 volatile bool hupped = false;
39 volatile bool stopped = false;
41 struct InputWithRefcount {
49 if (signum == SIGINT) {
54 void do_nothing(int signum)
58 CubemapStateProto collect_state(const timeval &serialize_start,
59 const vector<Acceptor *> acceptors,
60 const multimap<string, InputWithRefcount> inputs,
63 CubemapStateProto state = servers->serialize(); // Fills streams() and clients().
64 state.set_serialize_start_sec(serialize_start.tv_sec);
65 state.set_serialize_start_usec(serialize_start.tv_usec);
67 for (size_t i = 0; i < acceptors.size(); ++i) {
68 state.add_acceptors()->MergeFrom(acceptors[i]->serialize());
71 for (multimap<string, InputWithRefcount>::const_iterator input_it = inputs.begin();
72 input_it != inputs.end();
74 state.add_inputs()->MergeFrom(input_it->second.input->serialize());
80 // Find all port statements in the configuration file, and create acceptors for htem.
81 vector<Acceptor *> create_acceptors(
83 map<int, Acceptor *> *deserialized_acceptors)
85 vector<Acceptor *> acceptors;
86 for (unsigned i = 0; i < config.acceptors.size(); ++i) {
87 const AcceptorConfig &acceptor_config = config.acceptors[i];
88 Acceptor *acceptor = NULL;
89 map<int, Acceptor *>::iterator deserialized_acceptor_it =
90 deserialized_acceptors->find(acceptor_config.port);
91 if (deserialized_acceptor_it != deserialized_acceptors->end()) {
92 acceptor = deserialized_acceptor_it->second;
93 deserialized_acceptors->erase(deserialized_acceptor_it);
95 int server_sock = create_server_socket(acceptor_config.port, TCP_SOCKET);
96 acceptor = new Acceptor(server_sock, acceptor_config.port);
99 acceptors.push_back(acceptor);
102 // Close all acceptors that are no longer in the configuration file.
103 for (map<int, Acceptor *>::iterator 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 create_config_input(stream_config.src, inputs);
140 for (unsigned i = 0; i < config.udpstreams.size(); ++i) {
141 const UDPStreamConfig &udpstream_config = config.udpstreams[i];
142 create_config_input(udpstream_config.src, inputs);
146 void create_streams(const Config &config,
147 const set<string> &deserialized_urls,
148 multimap<string, InputWithRefcount> *inputs)
150 for (unsigned i = 0; i < config.mark_pools.size(); ++i) {
151 const MarkPoolConfig &mp_config = config.mark_pools[i];
152 mark_pools.push_back(new MarkPool(mp_config.from, mp_config.to));
156 set<string> expecting_urls = deserialized_urls;
157 for (unsigned i = 0; i < config.streams.size(); ++i) {
158 const StreamConfig &stream_config = config.streams[i];
160 if (deserialized_urls.count(stream_config.url) == 0) {
161 stream_index = servers->add_stream(stream_config.url,
162 stream_config.backlog_size,
163 Stream::Encoding(stream_config.encoding));
165 stream_index = servers->lookup_stream_by_url(stream_config.url);
166 assert(stream_index != -1);
167 servers->set_backlog_size(stream_index, stream_config.backlog_size);
168 servers->set_encoding(stream_index,
169 Stream::Encoding(stream_config.encoding));
171 expecting_urls.erase(stream_config.url);
173 if (stream_config.mark_pool != -1) {
174 servers->set_mark_pool(stream_index, mark_pools[stream_config.mark_pool]);
177 string src = stream_config.src;
179 multimap<string, InputWithRefcount>::iterator input_it = inputs->find(src);
180 assert(input_it != inputs->end());
181 input_it->second.input->add_destination(stream_index);
182 ++input_it->second.refcount;
186 // Warn about any HTTP servers we've lost.
187 // TODO: Make an option (delete=yes?) to actually shut down streams.
188 for (set<string>::const_iterator stream_it = expecting_urls.begin();
189 stream_it != expecting_urls.end();
191 string url = *stream_it;
192 log(WARNING, "stream '%s' disappeared from the configuration file. "
193 "It will not be deleted, but clients will not get any new inputs.",
198 for (unsigned i = 0; i < config.udpstreams.size(); ++i) {
199 const UDPStreamConfig &udpstream_config = config.udpstreams[i];
200 MarkPool *mark_pool = NULL;
201 if (udpstream_config.mark_pool != -1) {
202 mark_pool = mark_pools[udpstream_config.mark_pool];
204 int stream_index = servers->add_udpstream(udpstream_config.dst, mark_pool);
206 string src = udpstream_config.src;
208 multimap<string, InputWithRefcount>::iterator input_it = inputs->find(src);
209 assert(input_it != inputs->end());
210 input_it->second.input->add_destination(stream_index);
211 ++input_it->second.refcount;
216 void open_logs(const vector<LogConfig> &log_destinations)
218 for (size_t i = 0; i < log_destinations.size(); ++i) {
219 if (log_destinations[i].type == LogConfig::LOG_TYPE_FILE) {
220 add_log_destination_file(log_destinations[i].filename);
221 } else if (log_destinations[i].type == LogConfig::LOG_TYPE_CONSOLE) {
222 add_log_destination_console();
223 } else if (log_destinations[i].type == LogConfig::LOG_TYPE_SYSLOG) {
224 add_log_destination_syslog();
232 bool dry_run_config(const std::string &argv0, const std::string &config_filename)
234 char *argv0_copy = strdup(argv0.c_str());
235 char *config_filename_copy = strdup(config_filename.c_str());
240 log_perror("fork()");
242 free(config_filename_copy);
246 execlp(argv0_copy, argv0_copy, "--test-config", config_filename_copy, NULL);
247 log_perror(argv0_copy);
255 free(config_filename_copy);
260 err = waitpid(pid, &status, 0);
261 } while (err == -1 && errno == EINTR);
264 log_perror("waitpid()");
268 return (WIFEXITED(status) && WEXITSTATUS(status) == 0);
271 int main(int argc, char **argv)
275 signal(SIGUSR1, do_nothing); // Used in internal signalling.
276 signal(SIGPIPE, SIG_IGN);
280 bool test_config = false;
282 static const option long_options[] = {
283 { "state", required_argument, 0, 's' },
284 { "test-config", no_argument, 0, 't' },
287 int option_index = 0;
288 int c = getopt_long(argc, argv, "s:t", long_options, &option_index);
295 state_fd = atoi(optarg);
301 fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
306 string config_filename = "cubemap.config";
308 config_filename = argv[optind++];
311 // Canonicalize argv[0] and config_filename.
312 char argv0_canon[PATH_MAX];
313 char config_filename_canon[PATH_MAX];
315 if (realpath(argv[0], argv0_canon) == NULL) {
319 if (realpath(config_filename.c_str(), config_filename_canon) == NULL) {
320 log_perror(config_filename.c_str());
324 // Now parse the configuration file.
326 if (!parse_config(config_filename_canon, &config)) {
333 // Ideally we'd like to daemonize only when we've started up all threads etc.,
334 // but daemon() forks, which is not good in multithreaded software, so we'll
335 // have to do it here.
336 if (config.daemonize) {
337 if (daemon(0, 0) == -1) {
338 log_perror("daemon");
344 // Open logs as soon as possible.
345 open_logs(config.log_destinations);
347 log(INFO, "Cubemap " SERVER_VERSION " starting.");
348 if (config.access_log_file.empty()) {
349 // Create a dummy logger.
350 access_log = new AccessLogThread();
352 access_log = new AccessLogThread(config.access_log_file);
356 servers = new ServerPool(config.num_servers);
358 CubemapStateProto loaded_state;
359 struct timeval serialize_start;
360 set<string> deserialized_urls;
361 map<int, Acceptor *> deserialized_acceptors;
362 multimap<string, InputWithRefcount> inputs; // multimap due to older versions without deduplication.
363 if (state_fd != -1) {
364 log(INFO, "Deserializing state from previous process...");
366 if (!read_tempfile(state_fd, &serialized)) {
369 if (!loaded_state.ParseFromString(serialized)) {
370 log(ERROR, "Failed deserialization of state.");
374 serialize_start.tv_sec = loaded_state.serialize_start_sec();
375 serialize_start.tv_usec = loaded_state.serialize_start_usec();
377 // Deserialize the streams.
378 for (int i = 0; i < loaded_state.streams_size(); ++i) {
379 const StreamProto &stream = loaded_state.streams(i);
381 vector<int> data_fds;
382 for (int j = 0; j < stream.data_fds_size(); ++j) {
383 data_fds.push_back(stream.data_fds(j));
386 // Older versions stored the data once in the protobuf instead of
387 // sending around file descriptors.
388 if (data_fds.empty() && stream.has_data()) {
389 data_fds.push_back(make_tempfile(stream.data()));
392 servers->add_stream_from_serialized(stream, data_fds);
393 deserialized_urls.insert(stream.url());
396 // Deserialize the inputs. Note that we don't actually add them to any stream yet.
397 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
398 InputWithRefcount iwr;
399 iwr.input = create_input(loaded_state.inputs(i));
401 inputs.insert(make_pair(loaded_state.inputs(i).url(), iwr));
404 // Deserialize the acceptors.
405 for (int i = 0; i < loaded_state.acceptors_size(); ++i) {
406 deserialized_acceptors.insert(make_pair(
407 loaded_state.acceptors(i).port(),
408 new Acceptor(loaded_state.acceptors(i))));
411 log(INFO, "Deserialization done.");
414 // Add any new inputs coming from the config.
415 create_config_inputs(config, &inputs);
417 // Find all streams in the configuration file, create them, and connect to the inputs.
418 create_streams(config, deserialized_urls, &inputs);
419 vector<Acceptor *> acceptors = create_acceptors(config, &deserialized_acceptors);
421 // Put back the existing clients. It doesn't matter which server we
422 // allocate them to, so just do round-robin. However, we need to add
423 // them after the mark pools have been set up.
424 for (int i = 0; i < loaded_state.clients_size(); ++i) {
425 servers->add_client_from_serialized(loaded_state.clients(i));
430 // Now delete all inputs that are longer in use, and start the others.
431 for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
432 input_it != inputs.end(); ) {
433 if (input_it->second.refcount == 0) {
434 log(WARNING, "Input '%s' no longer in use, closing.",
435 input_it->first.c_str());
436 input_it->second.input->close_socket();
437 delete input_it->second.input;
438 inputs.erase(input_it++);
440 input_it->second.input->run();
445 // Start writing statistics.
446 StatsThread *stats_thread = NULL;
447 if (!config.stats_file.empty()) {
448 stats_thread = new StatsThread(config.stats_file, config.stats_interval);
452 InputStatsThread *input_stats_thread = NULL;
453 if (!config.input_stats_file.empty()) {
454 vector<Input*> inputs_no_refcount;
455 for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
456 input_it != inputs.end(); ++input_it) {
457 inputs_no_refcount.push_back(input_it->second.input);
460 input_stats_thread = new InputStatsThread(config.input_stats_file, config.input_stats_interval, inputs_no_refcount);
461 input_stats_thread->run();
464 struct timeval server_start;
465 gettimeofday(&server_start, NULL);
466 if (state_fd != -1) {
467 // Measure time from we started deserializing (below) to now, when basically everything
468 // is up and running. This is, in other words, a conservative estimate of how long our
469 // “glitch” period was, not counting of course reconnects if the configuration changed.
470 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
471 1e-6 * (server_start.tv_usec - serialize_start.tv_usec);
472 log(INFO, "Re-exec happened in approx. %.0f ms.", glitch_time * 1000.0);
479 // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
480 gettimeofday(&serialize_start, NULL);
482 if (input_stats_thread != NULL) {
483 input_stats_thread->stop();
484 delete input_stats_thread;
486 if (stats_thread != NULL) {
487 stats_thread->stop();
490 for (size_t i = 0; i < acceptors.size(); ++i) {
491 acceptors[i]->stop();
493 for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
494 input_it != inputs.end();
496 input_it->second.input->stop();
500 CubemapStateProto state;
502 log(INFO, "Shutting down.");
504 log(INFO, "Serializing state and re-execing...");
505 state = collect_state(
506 serialize_start, acceptors, inputs, servers);
508 state.SerializeToString(&serialized);
509 state_fd = make_tempfile(serialized);
510 if (state_fd == -1) {
516 for (unsigned i = 0; i < mark_pools.size(); ++i) {
517 delete mark_pools[i];
529 // OK, so the signal was SIGHUP. Check that the new config is okay, then exec the new binary.
530 if (!dry_run_config(argv0_canon, config_filename_canon)) {
531 open_logs(config.log_destinations);
532 log(ERROR, "%s --test-config failed. Restarting old version instead of new.", argv[0]);
539 sprintf(buf, "%d", state_fd);
542 execlp(argv0_canon, argv0_canon, config_filename_canon, "--state", buf, NULL);
543 open_logs(config.log_destinations);
544 log_perror("execlp");
545 log(ERROR, "re-exec of %s failed. Waiting 0.2 seconds and trying again...", argv0_canon);