19 #include "accesslog.h"
25 #include "serverpool.h"
33 AccessLogThread *access_log = NULL;
34 ServerPool *servers = NULL;
35 vector<MarkPool *> mark_pools;
36 volatile bool hupped = false;
37 volatile bool stopped = false;
39 struct InputWithRefcount {
47 if (signum == SIGINT) {
52 CubemapStateProto collect_state(const timeval &serialize_start,
53 const vector<Acceptor *> acceptors,
54 const multimap<string, InputWithRefcount> inputs,
57 CubemapStateProto state = servers->serialize(); // Fills streams() and clients().
58 state.set_serialize_start_sec(serialize_start.tv_sec);
59 state.set_serialize_start_usec(serialize_start.tv_usec);
61 for (size_t i = 0; i < acceptors.size(); ++i) {
62 state.add_acceptors()->MergeFrom(acceptors[i]->serialize());
65 for (multimap<string, InputWithRefcount>::const_iterator input_it = inputs.begin();
66 input_it != inputs.end();
68 state.add_inputs()->MergeFrom(input_it->second.input->serialize());
74 // Find all port statements in the configuration file, and create acceptors for htem.
75 vector<Acceptor *> create_acceptors(
77 map<int, Acceptor *> *deserialized_acceptors)
79 vector<Acceptor *> acceptors;
80 for (unsigned i = 0; i < config.acceptors.size(); ++i) {
81 const AcceptorConfig &acceptor_config = config.acceptors[i];
82 Acceptor *acceptor = NULL;
83 map<int, Acceptor *>::iterator deserialized_acceptor_it =
84 deserialized_acceptors->find(acceptor_config.port);
85 if (deserialized_acceptor_it != deserialized_acceptors->end()) {
86 acceptor = deserialized_acceptor_it->second;
87 deserialized_acceptors->erase(deserialized_acceptor_it);
89 int server_sock = create_server_socket(acceptor_config.port, TCP_SOCKET);
90 acceptor = new Acceptor(server_sock, acceptor_config.port);
93 acceptors.push_back(acceptor);
96 // Close all acceptors that are no longer in the configuration file.
97 for (map<int, Acceptor *>::iterator acceptor_it = deserialized_acceptors->begin();
98 acceptor_it != deserialized_acceptors->end();
100 acceptor_it->second->close_socket();
101 delete acceptor_it->second;
107 // Find all streams in the configuration file, and create inputs for them.
108 void create_config_inputs(const Config &config, multimap<string, InputWithRefcount> *inputs)
110 for (unsigned i = 0; i < config.streams.size(); ++i) {
111 const StreamConfig &stream_config = config.streams[i];
112 if (stream_config.src.empty()) {
116 string src = stream_config.src;
117 if (inputs->count(src) != 0) {
121 InputWithRefcount iwr;
122 iwr.input = create_input(src);
123 if (iwr.input == NULL) {
124 log(ERROR, "did not understand URL '%s', clients will not get any data.",
129 inputs->insert(make_pair(src, iwr));
133 void create_streams(const Config &config,
134 const set<string> &deserialized_stream_ids,
135 multimap<string, InputWithRefcount> *inputs)
137 for (unsigned i = 0; i < config.mark_pools.size(); ++i) {
138 const MarkPoolConfig &mp_config = config.mark_pools[i];
139 mark_pools.push_back(new MarkPool(mp_config.from, mp_config.to));
142 set<string> expecting_stream_ids = deserialized_stream_ids;
143 for (unsigned i = 0; i < config.streams.size(); ++i) {
144 const StreamConfig &stream_config = config.streams[i];
145 if (deserialized_stream_ids.count(stream_config.stream_id) == 0) {
146 servers->add_stream(stream_config.stream_id,
147 stream_config.backlog_size,
148 Stream::Encoding(stream_config.encoding));
150 servers->set_backlog_size(stream_config.stream_id, stream_config.backlog_size);
151 servers->set_encoding(stream_config.stream_id,
152 Stream::Encoding(stream_config.encoding));
154 expecting_stream_ids.erase(stream_config.stream_id);
156 if (stream_config.mark_pool != -1) {
157 servers->set_mark_pool(stream_config.stream_id,
158 mark_pools[stream_config.mark_pool]);
161 string src = stream_config.src;
163 multimap<string, InputWithRefcount>::iterator input_it = inputs->find(src);
164 assert(input_it != inputs->end());
165 input_it->second.input->add_destination(stream_config.stream_id);
166 ++input_it->second.refcount;
170 // Warn about any servers we've lost.
171 // TODO: Make an option (delete=yes?) to actually shut down streams.
172 for (set<string>::const_iterator stream_it = expecting_stream_ids.begin();
173 stream_it != expecting_stream_ids.end();
175 string stream_id = *stream_it;
176 log(WARNING, "stream '%s' disappeared from the configuration file. "
177 "It will not be deleted, but clients will not get any new inputs.",
182 void open_logs(const vector<LogConfig> &log_destinations)
184 for (size_t i = 0; i < log_destinations.size(); ++i) {
185 if (log_destinations[i].type == LogConfig::LOG_TYPE_FILE) {
186 add_log_destination_file(log_destinations[i].filename);
187 } else if (log_destinations[i].type == LogConfig::LOG_TYPE_CONSOLE) {
188 add_log_destination_console();
189 } else if (log_destinations[i].type == LogConfig::LOG_TYPE_SYSLOG) {
190 add_log_destination_syslog();
198 bool dry_run_config(const std::string &argv0, const std::string &config_filename)
200 char *argv0_copy = strdup(argv0.c_str());
201 char *config_filename_copy = strdup(config_filename.c_str());
206 log_perror("fork()");
208 free(config_filename_copy);
212 execlp(argv0_copy, argv0_copy, "--test-config", config_filename_copy, NULL);
213 log_perror(argv0_copy);
221 free(config_filename_copy);
226 err = waitpid(pid, &status, 0);
227 } while (err == -1 && errno == EINTR);
230 log_perror("waitpid()");
234 return (WIFEXITED(status) && WEXITSTATUS(status) == 0);
237 int main(int argc, char **argv)
241 signal(SIGPIPE, SIG_IGN);
245 bool test_config = false;
247 static const option long_options[] = {
248 { "state", required_argument, 0, 's' },
249 { "test-config", no_argument, 0, 't' },
252 int option_index = 0;
253 int c = getopt_long(argc, argv, "s:t", long_options, &option_index);
260 state_fd = atoi(optarg);
266 fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
271 string config_filename = "cubemap.config";
273 config_filename = argv[optind++];
276 // Canonicalize argv[0] and config_filename.
277 char argv0_canon[PATH_MAX];
278 char config_filename_canon[PATH_MAX];
280 if (realpath(argv[0], argv0_canon) == NULL) {
284 if (realpath(config_filename.c_str(), config_filename_canon) == NULL) {
285 log_perror(config_filename.c_str());
289 // Now parse the configuration file.
291 if (!parse_config(config_filename_canon, &config)) {
298 // Ideally we'd like to daemonize only when we've started up all threads etc.,
299 // but daemon() forks, which is not good in multithreaded software, so we'll
300 // have to do it here.
301 if (config.daemonize) {
302 if (daemon(0, 0) == -1) {
303 log_perror("daemon");
309 // Open logs as soon as possible.
310 open_logs(config.log_destinations);
312 log(INFO, "Cubemap " SERVER_VERSION " starting.");
313 if (config.access_log_file.empty()) {
314 // Create a dummy logger.
315 access_log = new AccessLogThread();
317 access_log = new AccessLogThread(config.access_log_file);
321 servers = new ServerPool(config.num_servers);
323 CubemapStateProto loaded_state;
324 struct timeval serialize_start;
325 set<string> deserialized_stream_ids;
326 map<int, Acceptor *> deserialized_acceptors;
327 multimap<string, InputWithRefcount> inputs; // multimap due to older versions without deduplication.
328 if (state_fd != -1) {
329 log(INFO, "Deserializing state from previous process...");
331 if (!read_tempfile(state_fd, &serialized)) {
334 if (!loaded_state.ParseFromString(serialized)) {
335 log(ERROR, "Failed deserialization of state.");
339 serialize_start.tv_sec = loaded_state.serialize_start_sec();
340 serialize_start.tv_usec = loaded_state.serialize_start_usec();
342 // Deserialize the streams.
343 for (int i = 0; i < loaded_state.streams_size(); ++i) {
344 servers->add_stream_from_serialized(loaded_state.streams(i));
345 deserialized_stream_ids.insert(loaded_state.streams(i).stream_id());
348 // Deserialize the inputs. Note that we don't actually add them to any stream yet.
349 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
350 InputWithRefcount iwr;
351 iwr.input = create_input(loaded_state.inputs(i));
353 inputs.insert(make_pair(loaded_state.inputs(i).url(), iwr));
356 // Deserialize the acceptors.
357 for (int i = 0; i < loaded_state.acceptors_size(); ++i) {
358 deserialized_acceptors.insert(make_pair(
359 loaded_state.acceptors(i).port(),
360 new Acceptor(loaded_state.acceptors(i))));
363 log(INFO, "Deserialization done.");
366 // Add any new inputs coming from the config.
367 create_config_inputs(config, &inputs);
369 // Find all streams in the configuration file, create them, and connect to the inputs.
370 create_streams(config, deserialized_stream_ids, &inputs);
371 vector<Acceptor *> acceptors = create_acceptors(config, &deserialized_acceptors);
373 // Put back the existing clients. It doesn't matter which server we
374 // allocate them to, so just do round-robin. However, we need to add
375 // them after the mark pools have been set up.
376 for (int i = 0; i < loaded_state.clients_size(); ++i) {
377 servers->add_client_from_serialized(loaded_state.clients(i));
382 // Now delete all inputs that are longer in use, and start the others.
383 for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
384 input_it != inputs.end(); ) {
385 if (input_it->second.refcount == 0) {
386 log(WARNING, "Input '%s' no longer in use, closing.",
387 input_it->first.c_str());
388 delete input_it->second.input;
389 inputs.erase(input_it++);
391 input_it->second.input->run();
396 // Start writing statistics.
397 StatsThread *stats_thread = NULL;
398 if (!config.stats_file.empty()) {
399 stats_thread = new StatsThread(config.stats_file, config.stats_interval);
403 struct timeval server_start;
404 gettimeofday(&server_start, NULL);
405 if (state_fd != -1) {
406 // Measure time from we started deserializing (below) to now, when basically everything
407 // is up and running. This is, in other words, a conservative estimate of how long our
408 // “glitch” period was, not counting of course reconnects if the configuration changed.
409 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
410 1e-6 * (server_start.tv_usec - serialize_start.tv_usec);
411 log(INFO, "Re-exec happened in approx. %.0f ms.", glitch_time * 1000.0);
418 // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
419 gettimeofday(&serialize_start, NULL);
421 if (stats_thread != NULL) {
422 stats_thread->stop();
425 for (size_t i = 0; i < acceptors.size(); ++i) {
426 acceptors[i]->stop();
428 for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
429 input_it != inputs.end();
431 input_it->second.input->stop();
435 CubemapStateProto state;
437 log(INFO, "Shutting down.");
439 log(INFO, "Serializing state and re-execing...");
440 state = collect_state(
441 serialize_start, acceptors, inputs, servers);
443 state.SerializeToString(&serialized);
444 state_fd = make_tempfile(serialized);
445 if (state_fd == -1) {
451 for (unsigned i = 0; i < mark_pools.size(); ++i) {
452 delete mark_pools[i];
464 // OK, so the signal was SIGHUP. Check that the new config is okay, then exec the new binary.
465 if (!dry_run_config(argv0_canon, config_filename_canon)) {
466 open_logs(config.log_destinations);
467 log(ERROR, "%s --test-config failed. Restarting old version instead of new.", argv[0]);
474 sprintf(buf, "%d", state_fd);
477 execlp(argv0_canon, argv0_canon, config_filename_canon, "--state", buf, NULL);
478 open_logs(config.log_destinations);
479 log_perror("execlp");
480 log(ERROR, "re-exec of %s failed. Waiting 0.2 seconds and trying again...", argv0_canon);