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;
42 if (signum == SIGINT) {
47 CubemapStateProto collect_state(const timeval &serialize_start,
48 const vector<Acceptor *> acceptors,
49 const vector<Input *> inputs,
52 CubemapStateProto state = servers->serialize(); // Fills streams() and clients().
53 state.set_serialize_start_sec(serialize_start.tv_sec);
54 state.set_serialize_start_usec(serialize_start.tv_usec);
56 for (size_t i = 0; i < acceptors.size(); ++i) {
57 state.add_acceptors()->MergeFrom(acceptors[i]->serialize());
60 for (size_t i = 0; i < inputs.size(); ++i) {
61 state.add_inputs()->MergeFrom(inputs[i]->serialize());
67 // Find all port statements in the configuration file, and create acceptors for htem.
68 vector<Acceptor *> create_acceptors(
70 map<int, Acceptor *> *deserialized_acceptors)
72 vector<Acceptor *> acceptors;
73 for (unsigned i = 0; i < config.acceptors.size(); ++i) {
74 const AcceptorConfig &acceptor_config = config.acceptors[i];
75 Acceptor *acceptor = NULL;
76 map<int, Acceptor *>::iterator deserialized_acceptor_it =
77 deserialized_acceptors->find(acceptor_config.port);
78 if (deserialized_acceptor_it != deserialized_acceptors->end()) {
79 acceptor = deserialized_acceptor_it->second;
80 deserialized_acceptors->erase(deserialized_acceptor_it);
82 int server_sock = create_server_socket(acceptor_config.port, TCP_SOCKET);
83 acceptor = new Acceptor(server_sock, acceptor_config.port);
86 acceptors.push_back(acceptor);
89 // Close all acceptors that are no longer in the configuration file.
90 for (map<int, Acceptor *>::iterator acceptor_it = deserialized_acceptors->begin();
91 acceptor_it != deserialized_acceptors->end();
93 acceptor_it->second->close_socket();
94 delete acceptor_it->second;
100 // Find all streams in the configuration file, and create inputs for them.
101 vector<Input *> create_inputs(const Config &config,
102 map<string, Input *> *deserialized_inputs)
104 vector<Input *> inputs;
105 for (unsigned i = 0; i < config.streams.size(); ++i) {
106 const StreamConfig &stream_config = config.streams[i];
107 if (stream_config.src.empty()) {
111 string stream_id = stream_config.stream_id;
112 string src = stream_config.src;
115 map<string, Input *>::iterator deserialized_input_it =
116 deserialized_inputs->find(stream_id);
117 if (deserialized_input_it != deserialized_inputs->end()) {
118 input = deserialized_input_it->second;
119 if (input->get_url() != src) {
120 log(INFO, "Stream '%s' has changed URL from '%s' to '%s', restarting input.",
121 stream_id.c_str(), input->get_url().c_str(), src.c_str());
122 input->close_socket();
126 deserialized_inputs->erase(deserialized_input_it);
129 input = create_input(stream_id, src);
131 log(ERROR, "did not understand URL '%s', clients will not get any data.",
137 inputs.push_back(input);
142 void create_streams(const Config &config,
143 const set<string> &deserialized_stream_ids,
144 map<string, Input *> *deserialized_inputs)
146 for (unsigned i = 0; i < config.mark_pools.size(); ++i) {
147 const MarkPoolConfig &mp_config = config.mark_pools[i];
148 mark_pools.push_back(new MarkPool(mp_config.from, mp_config.to));
151 set<string> expecting_stream_ids = deserialized_stream_ids;
152 for (unsigned i = 0; i < config.streams.size(); ++i) {
153 const StreamConfig &stream_config = config.streams[i];
154 if (deserialized_stream_ids.count(stream_config.stream_id) == 0) {
155 servers->add_stream(stream_config.stream_id, stream_config.backlog_size);
157 servers->set_backlog_size(stream_config.stream_id, stream_config.backlog_size);
159 expecting_stream_ids.erase(stream_config.stream_id);
161 if (stream_config.mark_pool != -1) {
162 servers->set_mark_pool(stream_config.stream_id,
163 mark_pools[stream_config.mark_pool]);
167 // Warn about any servers we've lost.
168 // TODO: Make an option (delete=yes?) to actually shut down streams.
169 for (set<string>::const_iterator stream_it = expecting_stream_ids.begin();
170 stream_it != expecting_stream_ids.end();
172 string stream_id = *stream_it;
173 log(WARNING, "stream '%s' disappeared from the configuration file. "
174 "It will not be deleted, but clients will not get any new inputs.",
176 if (deserialized_inputs->count(stream_id) != 0) {
177 delete (*deserialized_inputs)[stream_id];
178 deserialized_inputs->erase(stream_id);
183 void open_logs(const vector<LogConfig> &log_destinations)
185 for (size_t i = 0; i < log_destinations.size(); ++i) {
186 if (log_destinations[i].type == LogConfig::LOG_TYPE_FILE) {
187 add_log_destination_file(log_destinations[i].filename);
188 } else if (log_destinations[i].type == LogConfig::LOG_TYPE_CONSOLE) {
189 add_log_destination_console();
190 } else if (log_destinations[i].type == LogConfig::LOG_TYPE_SYSLOG) {
191 add_log_destination_syslog();
199 bool dry_run_config(const std::string &argv0, const std::string &config_filename)
201 char *argv0_copy = strdup(argv0.c_str());
202 char *config_filename_copy = strdup(config_filename.c_str());
207 log_perror("fork()");
209 free(config_filename_copy);
213 execlp(argv0_copy, argv0_copy, "--test-config", config_filename_copy, NULL);
214 log_perror(argv0_copy);
222 free(config_filename_copy);
227 err = waitpid(pid, &status, 0);
228 } while (err == -1 && errno == EINTR);
231 log_perror("waitpid()");
235 return (WIFEXITED(status) && WEXITSTATUS(status) == 0);
238 int main(int argc, char **argv)
242 signal(SIGPIPE, SIG_IGN);
246 bool test_config = false;
248 static const option long_options[] = {
249 { "state", required_argument, 0, 's' },
250 { "test-config", no_argument, 0, 't' },
253 int option_index = 0;
254 int c = getopt_long(argc, argv, "s:t", long_options, &option_index);
261 state_fd = atoi(optarg);
267 fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
272 string config_filename = "cubemap.config";
274 config_filename = argv[optind++];
277 // Canonicalize argv[0] and config_filename.
278 char argv0_canon[PATH_MAX];
279 char config_filename_canon[PATH_MAX];
281 if (realpath(argv[0], argv0_canon) == NULL) {
285 if (realpath(config_filename.c_str(), config_filename_canon) == NULL) {
286 log_perror(config_filename.c_str());
290 // Now parse the configuration file.
292 if (!parse_config(config_filename_canon, &config)) {
299 // Ideally we'd like to daemonize only when we've started up all threads etc.,
300 // but daemon() forks, which is not good in multithreaded software, so we'll
301 // have to do it here.
302 if (config.daemonize) {
303 if (daemon(0, 0) == -1) {
304 log_perror("daemon");
310 // Open logs as soon as possible.
311 open_logs(config.log_destinations);
313 log(INFO, "Cubemap " SERVER_VERSION " starting.");
314 if (config.access_log_file.empty()) {
315 // Create a dummy logger.
316 access_log = new AccessLogThread();
318 access_log = new AccessLogThread(config.access_log_file);
322 servers = new ServerPool(config.num_servers);
324 CubemapStateProto loaded_state;
325 struct timeval serialize_start;
326 set<string> deserialized_stream_ids;
327 map<string, Input *> deserialized_inputs;
328 map<int, Acceptor *> deserialized_acceptors;
329 if (state_fd != -1) {
330 log(INFO, "Deserializing state from previous process...");
332 if (!read_tempfile(state_fd, &serialized)) {
335 if (!loaded_state.ParseFromString(serialized)) {
336 log(ERROR, "Failed deserialization of state.");
340 serialize_start.tv_sec = loaded_state.serialize_start_sec();
341 serialize_start.tv_usec = loaded_state.serialize_start_usec();
343 // Deserialize the streams.
344 for (int i = 0; i < loaded_state.streams_size(); ++i) {
345 servers->add_stream_from_serialized(loaded_state.streams(i));
346 deserialized_stream_ids.insert(loaded_state.streams(i).stream_id());
349 // Deserialize the inputs. Note that we don't actually add them to any state yet.
350 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
351 deserialized_inputs.insert(make_pair(
352 loaded_state.inputs(i).stream_id(),
353 create_input(loaded_state.inputs(i))));
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 // Find all streams in the configuration file, and create them.
367 create_streams(config, deserialized_stream_ids, &deserialized_inputs);
369 vector<Acceptor *> acceptors = create_acceptors(config, &deserialized_acceptors);
370 vector<Input *> inputs = create_inputs(config, &deserialized_inputs);
372 // All deserialized inputs should now have been taken care of, one way or the other.
373 assert(deserialized_inputs.empty());
375 // Put back the existing clients. It doesn't matter which server we
376 // allocate them to, so just do round-robin. However, we need to add
377 // them after the mark pools have been set up.
378 for (int i = 0; i < loaded_state.clients_size(); ++i) {
379 servers->add_client_from_serialized(loaded_state.clients(i));
384 // Start writing statistics.
385 StatsThread *stats_thread = NULL;
386 if (!config.stats_file.empty()) {
387 stats_thread = new StatsThread(config.stats_file, config.stats_interval);
391 struct timeval server_start;
392 gettimeofday(&server_start, NULL);
393 if (state_fd != -1) {
394 // Measure time from we started deserializing (below) to now, when basically everything
395 // is up and running. This is, in other words, a conservative estimate of how long our
396 // “glitch” period was, not counting of course reconnects if the configuration changed.
397 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
398 1e-6 * (server_start.tv_usec - serialize_start.tv_usec);
399 log(INFO, "Re-exec happened in approx. %.0f ms.", glitch_time * 1000.0);
406 // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
407 gettimeofday(&serialize_start, NULL);
409 if (stats_thread != NULL) {
410 stats_thread->stop();
413 for (size_t i = 0; i < acceptors.size(); ++i) {
414 acceptors[i]->stop();
416 for (size_t i = 0; i < inputs.size(); ++i) {
421 CubemapStateProto state;
423 log(INFO, "Shutting down.");
425 log(INFO, "Serializing state and re-execing...");
426 state = collect_state(
427 serialize_start, acceptors, inputs, servers);
429 state.SerializeToString(&serialized);
430 state_fd = make_tempfile(serialized);
431 if (state_fd == -1) {
437 for (unsigned i = 0; i < mark_pools.size(); ++i) {
438 delete mark_pools[i];
450 // OK, so the signal was SIGHUP. Check that the new config is okay, then exec the new binary.
451 if (!dry_run_config(argv0_canon, config_filename_canon)) {
452 open_logs(config.log_destinations);
453 log(ERROR, "%s --test-config failed. Restarting old version instead of new.", argv[0]);
460 sprintf(buf, "%d", state_fd);
463 execlp(argv0_canon, argv0_canon, config_filename_canon, "--state", buf, NULL);
464 open_logs(config.log_destinations);
465 log_perror("execlp");
466 log(ERROR, "re-exec of %s failed. Waiting 0.2 seconds and trying again...", argv0_canon);