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 const StreamProto &stream = loaded_state.streams(i);
346 vector<int> data_fds;
347 for (int j = 0; j < stream.data_fds_size(); ++j) {
348 data_fds.push_back(stream.data_fds(j));
351 // Older versions stored the data once in the protobuf instead of
352 // sending around file descriptors.
353 if (data_fds.empty() && stream.has_data()) {
354 data_fds.push_back(make_tempfile(stream.data()));
357 servers->add_stream_from_serialized(stream, data_fds);
358 deserialized_stream_ids.insert(stream.stream_id());
361 // Deserialize the inputs. Note that we don't actually add them to any stream yet.
362 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
363 InputWithRefcount iwr;
364 iwr.input = create_input(loaded_state.inputs(i));
366 inputs.insert(make_pair(loaded_state.inputs(i).url(), iwr));
369 // Deserialize the acceptors.
370 for (int i = 0; i < loaded_state.acceptors_size(); ++i) {
371 deserialized_acceptors.insert(make_pair(
372 loaded_state.acceptors(i).port(),
373 new Acceptor(loaded_state.acceptors(i))));
376 log(INFO, "Deserialization done.");
379 // Add any new inputs coming from the config.
380 create_config_inputs(config, &inputs);
382 // Find all streams in the configuration file, create them, and connect to the inputs.
383 create_streams(config, deserialized_stream_ids, &inputs);
384 vector<Acceptor *> acceptors = create_acceptors(config, &deserialized_acceptors);
386 // Put back the existing clients. It doesn't matter which server we
387 // allocate them to, so just do round-robin. However, we need to add
388 // them after the mark pools have been set up.
389 for (int i = 0; i < loaded_state.clients_size(); ++i) {
390 servers->add_client_from_serialized(loaded_state.clients(i));
395 // Now delete all inputs that are longer in use, and start the others.
396 for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
397 input_it != inputs.end(); ) {
398 if (input_it->second.refcount == 0) {
399 log(WARNING, "Input '%s' no longer in use, closing.",
400 input_it->first.c_str());
401 input_it->second.input->close_socket();
402 delete input_it->second.input;
403 inputs.erase(input_it++);
405 input_it->second.input->run();
410 // Start writing statistics.
411 StatsThread *stats_thread = NULL;
412 if (!config.stats_file.empty()) {
413 stats_thread = new StatsThread(config.stats_file, config.stats_interval);
417 struct timeval server_start;
418 gettimeofday(&server_start, NULL);
419 if (state_fd != -1) {
420 // Measure time from we started deserializing (below) to now, when basically everything
421 // is up and running. This is, in other words, a conservative estimate of how long our
422 // “glitch” period was, not counting of course reconnects if the configuration changed.
423 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
424 1e-6 * (server_start.tv_usec - serialize_start.tv_usec);
425 log(INFO, "Re-exec happened in approx. %.0f ms.", glitch_time * 1000.0);
432 // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
433 gettimeofday(&serialize_start, NULL);
435 if (stats_thread != NULL) {
436 stats_thread->stop();
439 for (size_t i = 0; i < acceptors.size(); ++i) {
440 acceptors[i]->stop();
442 for (multimap<string, InputWithRefcount>::iterator input_it = inputs.begin();
443 input_it != inputs.end();
445 input_it->second.input->stop();
449 CubemapStateProto state;
451 log(INFO, "Shutting down.");
453 log(INFO, "Serializing state and re-execing...");
454 state = collect_state(
455 serialize_start, acceptors, inputs, servers);
457 state.SerializeToString(&serialized);
458 state_fd = make_tempfile(serialized);
459 if (state_fd == -1) {
465 for (unsigned i = 0; i < mark_pools.size(); ++i) {
466 delete mark_pools[i];
478 // OK, so the signal was SIGHUP. Check that the new config is okay, then exec the new binary.
479 if (!dry_run_config(argv0_canon, config_filename_canon)) {
480 open_logs(config.log_destinations);
481 log(ERROR, "%s --test-config failed. Restarting old version instead of new.", argv[0]);
488 sprintf(buf, "%d", state_fd);
491 execlp(argv0_canon, argv0_canon, config_filename_canon, "--state", buf, NULL);
492 open_logs(config.log_destinations);
493 log_perror("execlp");
494 log(ERROR, "re-exec of %s failed. Waiting 0.2 seconds and trying again...", argv0_canon);