6 #include <sys/socket.h>
25 #include "serverpool.h"
31 ServerPool *servers = NULL;
32 volatile bool hupped = false;
39 int create_server_socket(int port)
41 int server_sock = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
42 if (server_sock == -1) {
48 if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) {
49 perror("setsockopt(SO_REUSEADDR)");
53 // We want dual-stack sockets. (Sorry, OpenBSD and Windows XP...)
55 if (setsockopt(server_sock, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof(zero)) == -1) {
56 perror("setsockopt(IPV6_V6ONLY)");
60 // Set as non-blocking, so the acceptor thread can notice that we want to shut it down.
61 if (ioctl(server_sock, FIONBIO, &one) == -1) {
62 perror("ioctl(FIONBIO)");
67 memset(&addr, 0, sizeof(addr));
68 addr.sin6_family = AF_INET6;
69 addr.sin6_port = htons(port);
71 if (bind(server_sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
76 if (listen(server_sock, 128) == -1) {
84 void *acceptor_thread_run(void *arg)
86 int server_sock = int(intptr_t(arg));
88 // Since we are non-blocking, we need to wait for the right state first.
89 // Wait up to 50 ms, then check hupped.
94 int nfds = poll(&pfd, 1, 50);
95 if (nfds == 0 || (nfds == -1 && errno == EINTR)) {
105 socklen_t addrlen = sizeof(addr);
108 int sock = accept(server_sock, reinterpret_cast<sockaddr *>(&addr), &addrlen);
109 if (sock == -1 && errno == EINTR) {
118 // Set the socket as nonblocking.
120 if (ioctl(sock, FIONBIO, &one) == -1) {
125 // Pick a server, round-robin, and hand over the socket to it.
126 servers->add_client(sock);
131 struct StatsThreadParameters {
136 void *stats_thread_run(void *arg)
138 const StatsThreadParameters *parms = reinterpret_cast<StatsThreadParameters *>(arg);
143 vector<ClientStats> client_stats;
145 // Open a new, temporary file.
146 char *filename = strdup((parms->stats_file + ".new.XXXXXX").c_str());
147 fd = mkostemp(filename, O_WRONLY);
154 fp = fdopen(fd, "w");
164 client_stats = servers->get_client_stats();
165 for (size_t i = 0; i < client_stats.size(); ++i) {
166 fprintf(fp, "%s %s %d %llu\n",
167 client_stats[i].remote_addr.c_str(),
168 client_stats[i].stream_id.c_str(),
169 int(now - client_stats[i].connect_time),
170 (long long unsigned)(client_stats[i].bytes_sent));
172 if (fclose(fp) == EOF) {
179 if (rename(filename, parms->stats_file.c_str()) == -1) {
185 int left_to_sleep = parms->stats_interval;
187 left_to_sleep = sleep(left_to_sleep);
188 } while (left_to_sleep > 0 && !hupped);
193 // Serialize the given state to a file descriptor, and return the (still open)
195 int make_tempfile(const CubemapStateProto &state)
197 char tmpl[] = "/tmp/cubemapstate.XXXXXX";
198 int state_fd = mkstemp(tmpl);
199 if (state_fd == -1) {
205 state.SerializeToString(&serialized);
207 const char *ptr = serialized.data();
208 size_t to_write = serialized.size();
209 while (to_write > 0) {
210 ssize_t ret = write(state_fd, ptr, to_write);
223 // Read the state back from the file descriptor made by make_tempfile,
225 CubemapStateProto read_tempfile(int state_fd)
227 if (lseek(state_fd, 0, SEEK_SET) == -1) {
235 ssize_t ret = read(state_fd, buf, sizeof(buf));
245 serialized.append(string(buf, buf + ret));
248 close(state_fd); // Implicitly deletes the file.
250 CubemapStateProto state;
251 if (!state.ParseFromString(serialized)) {
252 fprintf(stderr, "PANIC: Failed deserialization of state.\n");
259 // Reuse mark pools if one already exists.
260 MarkPool *get_mark_pool(map<pair<int, int>, MarkPool *> *mark_pools, int from, int to)
262 pair<int, int> mark_range(from, to);
263 if (mark_pools->count(mark_range) != 0) {
264 return (*mark_pools)[mark_range];
267 // Check if we're overlapping some other mark pool.
268 for (map<pair<int, int>, MarkPool *>::const_iterator mp_it = mark_pools->begin();
269 mp_it != mark_pools->end();
271 int other_from = mp_it->first.first;
272 int other_to = mp_it->first.second;
273 if ((from >= other_from && from < other_to) ||
274 (to >= other_from && to < other_to)) {
275 fprintf(stderr, "WARNING: Mark pool %d-%d partially overlaps with %d-%d, you may get duplicate marks.\n",
276 from, to, other_from, other_to);
277 fprintf(stderr, " Mark pools must either be completely disjunct, or completely overlapping.\n");
281 MarkPool *mark_pool = new MarkPool(from, to);
282 mark_pools->insert(make_pair(mark_range, mark_pool));
286 int main(int argc, char **argv)
288 fprintf(stderr, "\nCubemap starting.\n");
290 struct timeval serialize_start;
291 bool is_reexec = false;
293 string config_filename = (argc == 1) ? "cubemap.config" : argv[1];
294 vector<ConfigLine> config = parse_config(config_filename);
296 int port = fetch_config_int(config, "port", 1, 65535, PARAMATER_MANDATORY);
297 int num_servers = fetch_config_int(config, "num_servers", 1, 20000, PARAMATER_MANDATORY); // Insanely high max limit.
299 servers = new ServerPool(num_servers);
301 CubemapStateProto loaded_state;
302 int server_sock = -1, old_port = -1;
303 set<string> deserialized_stream_ids;
304 map<string, Input *> deserialized_inputs;
305 if (argc == 4 && strcmp(argv[2], "-state") == 0) {
308 fprintf(stderr, "Deserializing state from previous process... ");
309 int state_fd = atoi(argv[3]);
310 loaded_state = read_tempfile(state_fd);
312 serialize_start.tv_sec = loaded_state.serialize_start_sec();
313 serialize_start.tv_usec = loaded_state.serialize_start_usec();
315 // Deserialize the streams.
316 for (int i = 0; i < loaded_state.streams_size(); ++i) {
317 servers->add_stream_from_serialized(loaded_state.streams(i));
318 deserialized_stream_ids.insert(loaded_state.streams(i).stream_id());
321 // Deserialize the inputs. Note that we don't actually add them to any state yet.
322 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
323 deserialized_inputs.insert(make_pair(
324 loaded_state.inputs(i).stream_id(),
325 new Input(loaded_state.inputs(i))));
328 // Deserialize the server socket.
329 server_sock = loaded_state.server_sock();
330 old_port = loaded_state.port();
332 fprintf(stderr, "done.\n");
335 // Find all streams in the configuration file, and create them.
336 set<string> expecting_stream_ids = deserialized_stream_ids;
337 map<pair<int, int>, MarkPool *> mark_pools;
338 for (unsigned i = 0; i < config.size(); ++i) {
339 if (config[i].keyword != "stream") {
342 if (config[i].arguments.size() != 1) {
343 fprintf(stderr, "ERROR: 'stream' takes exactly one argument\n");
346 string stream_id = config[i].arguments[0];
347 if (deserialized_stream_ids.count(stream_id) == 0) {
348 servers->add_stream(stream_id);
350 expecting_stream_ids.erase(stream_id);
352 // Set up marks, if so desired.
353 if (config[i].parameters.count("mark")) {
354 string mark_str = config[i].parameters["mark"];
355 size_t split = mark_str.find_first_of('-');
356 if (split == string::npos) {
357 fprintf(stderr, "WARNING: Invalid mark specification '%s' (expected 'X-Y'), ignoring.\n",
362 string from_str(mark_str.begin(), mark_str.begin() + split);
363 string to_str(mark_str.begin() + split + 1, mark_str.end());
364 int from = atoi(from_str.c_str());
365 int to = atoi(to_str.c_str());
367 if (from <= 0 || from >= 65536 || to <= 0 || to >= 65536) {
368 fprintf(stderr, "WARNING: Mark pool range %d-%d is outside legal range [1,65536>, ignoring.\n",
373 MarkPool *mark_pool = get_mark_pool(&mark_pools, from, to);
374 servers->set_mark_pool(stream_id, mark_pool);
378 // Warn about any servers we've lost.
379 // TODO: Make an option (delete=yes?) to actually shut down streams.
380 for (set<string>::const_iterator stream_it = expecting_stream_ids.begin();
381 stream_it != expecting_stream_ids.end();
383 string stream_id = *stream_it;
384 fprintf(stderr, "WARNING: stream '%s' disappeared from the configuration file.\n",
386 fprintf(stderr, " It will not be deleted, but clients will not get any new inputs.\n");
387 if (deserialized_inputs.count(stream_id) != 0) {
388 delete deserialized_inputs[stream_id];
389 deserialized_inputs.erase(stream_id);
393 // Open a new server socket if we do not already have one, or if we changed ports.
394 if (server_sock != -1 && port != old_port) {
395 fprintf(stderr, "NOTE: Port changed from %d to %d; opening new socket.\n", old_port, port);
399 if (server_sock == -1) {
400 server_sock = create_server_socket(port);
403 // See if the user wants stats.
404 string stats_file = fetch_config_string(config, "stats_file", PARAMETER_OPTIONAL);
405 int stats_interval = fetch_config_int(config, "stats_interval", 1, INT_MAX, PARAMETER_OPTIONAL, -1);
406 if (stats_interval != -1 && stats_file.empty()) {
407 fprintf(stderr, "WARNING: 'stats_interval' given, but no 'stats_file'. No statistics will be written.\n");
412 pthread_t acceptor_thread;
413 pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
415 // Find all streams in the configuration file, and create inputs for them.
416 vector<Input *> inputs;
417 for (unsigned i = 0; i < config.size(); ++i) {
418 if (config[i].keyword != "stream") {
421 assert(config[i].arguments.size() == 1);
422 string stream_id = config[i].arguments[0];
424 if (config[i].parameters.count("src") == 0) {
425 fprintf(stderr, "WARNING: stream '%s' has no src= attribute, clients will not get any data.\n",
430 string src = config[i].parameters["src"];
432 if (deserialized_inputs.count(stream_id) != 0) {
433 input = deserialized_inputs[stream_id];
434 if (input->get_url() != src) {
435 fprintf(stderr, "INFO: Stream '%s' has changed URL from '%s' to '%s', restarting input.\n",
436 stream_id.c_str(), input->get_url().c_str(), src.c_str());
440 deserialized_inputs.erase(stream_id);
443 input = new Input(stream_id, src);
446 inputs.push_back(input);
450 // Put back the existing clients. It doesn't matter which server we
451 // allocate them to, so just do round-robin. However, we need to add
452 // them after the mark pools have been set up.
453 for (int i = 0; i < loaded_state.clients_size(); ++i) {
454 servers->add_client_from_serialized(loaded_state.clients(i));
458 // All deserialized inputs should now have been taken care of, one way or the other.
459 assert(deserialized_inputs.empty());
461 // Start writing statistics.
462 pthread_t stats_thread;
463 StatsThreadParameters stats_parameters; // Must live for as long as the stats thread does.
464 if (!stats_file.empty()) {
465 stats_parameters.stats_file = stats_file;
466 stats_parameters.stats_interval = stats_interval;
467 pthread_create(&stats_thread, NULL, stats_thread_run, &stats_parameters);
472 struct timeval server_start;
473 gettimeofday(&server_start, NULL);
475 // Measure time from we started deserializing (below) to now, when basically everything
476 // is up and running. This is, in other words, a conservative estimate of how long our
477 // “glitch” period was, not counting of course reconnects if the configuration changed.
478 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
479 1e-6 * (server_start.tv_usec - serialize_start.tv_usec);
480 fprintf(stderr, "Re-exec happened in approx. %.0f ms.\n", glitch_time * 1000.0);
487 // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
488 gettimeofday(&serialize_start, NULL);
490 if (!stats_file.empty()) {
491 pthread_kill(stats_thread, SIGHUP);
492 if (pthread_join(stats_thread, NULL) == -1) {
493 perror("pthread_join");
497 pthread_kill(acceptor_thread, SIGHUP);
498 if (pthread_join(acceptor_thread, NULL) == -1) {
499 perror("pthread_join");
503 CubemapStateProto state;
504 state.set_serialize_start_sec(serialize_start.tv_sec);
505 state.set_serialize_start_usec(serialize_start.tv_usec);
506 state.set_server_sock(server_sock);
507 state.set_port(port);
509 for (size_t i = 0; i < inputs.size(); ++i) {
511 state.add_inputs()->MergeFrom(inputs[i]->serialize());
514 for (int i = 0; i < num_servers; ++i) {
515 servers->get_server(i)->stop();
517 CubemapStateProto local_state = servers->get_server(i)->serialize();
519 // The stream state should be identical between the servers, so we only store it once.
521 state.mutable_streams()->MergeFrom(local_state.streams());
523 for (int j = 0; j < local_state.clients_size(); ++j) {
524 state.add_clients()->MergeFrom(local_state.clients(j));
529 fprintf(stderr, "Serializing state and re-execing...\n");
530 int state_fd = make_tempfile(state);
533 sprintf(buf, "%d", state_fd);
536 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
538 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);