6 #include <sys/socket.h>
24 #include "serverpool.h"
30 ServerPool *servers = NULL;
31 volatile bool hupped = false;
38 int create_server_socket(int port)
40 int server_sock = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
41 if (server_sock == -1) {
47 if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) {
48 perror("setsockopt(SO_REUSEADDR)");
52 // We want dual-stack sockets. (Sorry, OpenBSD and Windows XP...)
54 if (setsockopt(server_sock, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof(zero)) == -1) {
55 perror("setsockopt(IPV6_V6ONLY)");
59 // Set as non-blocking, so the acceptor thread can notice that we want to shut it down.
60 if (ioctl(server_sock, FIONBIO, &one) == -1) {
61 perror("ioctl(FIONBIO)");
66 memset(&addr, 0, sizeof(addr));
67 addr.sin6_family = AF_INET6;
68 addr.sin6_port = htons(port);
70 if (bind(server_sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
75 if (listen(server_sock, 128) == -1) {
83 void *acceptor_thread_run(void *arg)
85 int server_sock = int(intptr_t(arg));
87 // Since we are non-blocking, we need to wait for the right state first.
88 // Wait up to 50 ms, then check hupped.
93 int nfds = poll(&pfd, 1, 50);
94 if (nfds == 0 || (nfds == -1 && errno == EINTR)) {
104 socklen_t addrlen = sizeof(addr);
107 int sock = accept(server_sock, reinterpret_cast<sockaddr *>(&addr), &addrlen);
108 if (sock == -1 && errno == EINTR) {
117 // Set the socket as nonblocking.
119 if (ioctl(sock, FIONBIO, &one) == -1) {
124 // Pick a server, round-robin, and hand over the socket to it.
125 servers->add_client(sock);
130 struct StatsThreadParameters {
135 void *stats_thread_run(void *arg)
137 const StatsThreadParameters *parms = reinterpret_cast<StatsThreadParameters *>(arg);
142 vector<ClientStats> client_stats;
144 // Open a new, temporary file.
145 char *filename = strdup((parms->stats_file + ".new.XXXXXX").c_str());
146 fd = mkostemp(filename, O_WRONLY);
153 fp = fdopen(fd, "w");
163 client_stats = servers->get_client_stats();
164 for (size_t i = 0; i < client_stats.size(); ++i) {
165 fprintf(fp, "%s %s %d %llu\n",
166 client_stats[i].remote_addr.c_str(),
167 client_stats[i].stream_id.c_str(),
168 int(now - client_stats[i].connect_time),
169 (long long unsigned)(client_stats[i].bytes_sent));
171 if (fclose(fp) == EOF) {
178 if (rename(filename, parms->stats_file.c_str()) == -1) {
184 int left_to_sleep = parms->stats_interval;
186 left_to_sleep = sleep(left_to_sleep);
187 } while (left_to_sleep > 0 && !hupped);
192 // Serialize the given state to a file descriptor, and return the (still open)
194 int make_tempfile(const CubemapStateProto &state)
196 char tmpl[] = "/tmp/cubemapstate.XXXXXX";
197 int state_fd = mkstemp(tmpl);
198 if (state_fd == -1) {
204 state.SerializeToString(&serialized);
206 const char *ptr = serialized.data();
207 size_t to_write = serialized.size();
208 while (to_write > 0) {
209 ssize_t ret = write(state_fd, ptr, to_write);
222 // Read the state back from the file descriptor made by make_tempfile,
224 CubemapStateProto read_tempfile(int state_fd)
226 if (lseek(state_fd, 0, SEEK_SET) == -1) {
234 ssize_t ret = read(state_fd, buf, sizeof(buf));
244 serialized.append(string(buf, buf + ret));
247 close(state_fd); // Implicitly deletes the file.
249 CubemapStateProto state;
250 if (!state.ParseFromString(serialized)) {
251 fprintf(stderr, "PANIC: Failed deserialization of state.\n");
258 int main(int argc, char **argv)
260 fprintf(stderr, "\nCubemap starting.\n");
262 struct timeval serialize_start;
263 bool is_reexec = false;
265 string config_filename = (argc == 1) ? "cubemap.config" : argv[1];
266 vector<ConfigLine> config = parse_config(config_filename);
268 int port = fetch_config_int(config, "port", 1, 65535, PARAMATER_MANDATORY);
269 int num_servers = fetch_config_int(config, "num_servers", 1, 20000, PARAMATER_MANDATORY); // Insanely high max limit.
271 servers = new ServerPool(num_servers);
273 int server_sock = -1, old_port = -1;
274 set<string> deserialized_stream_ids;
275 map<string, Input *> deserialized_inputs;
276 if (argc == 4 && strcmp(argv[2], "-state") == 0) {
279 fprintf(stderr, "Deserializing state from previous process... ");
280 int state_fd = atoi(argv[3]);
281 CubemapStateProto loaded_state = read_tempfile(state_fd);
283 serialize_start.tv_sec = loaded_state.serialize_start_sec();
284 serialize_start.tv_usec = loaded_state.serialize_start_usec();
286 // Deserialize the streams.
287 for (int i = 0; i < loaded_state.streams_size(); ++i) {
288 servers->add_stream_from_serialized(loaded_state.streams(i));
289 deserialized_stream_ids.insert(loaded_state.streams(i).stream_id());
292 // Put back the existing clients. It doesn't matter which server we
293 // allocate them to, so just do round-robin.
294 for (int i = 0; i < loaded_state.clients_size(); ++i) {
295 servers->add_client_from_serialized(loaded_state.clients(i));
298 // Deserialize the inputs. Note that we don't actually add them to any state yet.
299 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
300 deserialized_inputs.insert(make_pair(
301 loaded_state.inputs(i).stream_id(),
302 new Input(loaded_state.inputs(i))));
305 // Deserialize the server socket.
306 server_sock = loaded_state.server_sock();
307 old_port = loaded_state.port();
309 fprintf(stderr, "done.\n");
312 // Find all streams in the configuration file, and create them.
313 set<string> expecting_stream_ids = deserialized_stream_ids;
314 for (unsigned i = 0; i < config.size(); ++i) {
315 if (config[i].keyword != "stream") {
318 if (config[i].arguments.size() != 1) {
319 fprintf(stderr, "ERROR: 'stream' takes exactly one argument\n");
322 string stream_id = config[i].arguments[0];
323 if (deserialized_stream_ids.count(stream_id) == 0) {
324 servers->add_stream(stream_id);
326 expecting_stream_ids.erase(stream_id);
329 // Warn about any servers we've lost.
330 // TODO: Make an option (delete=yes?) to actually shut down streams.
331 for (set<string>::const_iterator stream_it = expecting_stream_ids.begin();
332 stream_it != expecting_stream_ids.end();
334 string stream_id = *stream_it;
335 fprintf(stderr, "WARNING: stream '%s' disappeared from the configuration file.\n",
337 fprintf(stderr, " It will not be deleted, but clients will not get any new inputs.\n");
338 if (deserialized_inputs.count(stream_id) != 0) {
339 delete deserialized_inputs[stream_id];
340 deserialized_inputs.erase(stream_id);
344 // Open a new server socket if we do not already have one, or if we changed ports.
345 if (server_sock != -1 && port != old_port) {
346 fprintf(stderr, "NOTE: Port changed from %d to %d; opening new socket.\n", old_port, port);
350 if (server_sock == -1) {
351 server_sock = create_server_socket(port);
354 // See if the user wants stats.
355 string stats_file = fetch_config_string(config, "stats_file", PARAMETER_OPTIONAL);
356 int stats_interval = fetch_config_int(config, "stats_interval", 1, INT_MAX, PARAMETER_OPTIONAL, -1);
357 if (stats_interval != -1 && stats_file.empty()) {
358 fprintf(stderr, "WARNING: 'stats_interval' given, but no 'stats_file'. No statistics will be written.\n");
363 pthread_t acceptor_thread;
364 pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
366 // Find all streams in the configuration file, and create inputs for them.
367 vector<Input *> inputs;
368 for (unsigned i = 0; i < config.size(); ++i) {
369 if (config[i].keyword != "stream") {
372 assert(config[i].arguments.size() == 1);
373 string stream_id = config[i].arguments[0];
375 if (config[i].parameters.count("src") == 0) {
376 fprintf(stderr, "WARNING: stream '%s' has no src= attribute, clients will not get any data.\n",
381 string src = config[i].parameters["src"];
383 if (deserialized_inputs.count(stream_id) != 0) {
384 input = deserialized_inputs[stream_id];
385 if (input->get_url() != src) {
386 fprintf(stderr, "INFO: Stream '%s' has changed URL from '%s' to '%s', restarting input.\n",
387 stream_id.c_str(), input->get_url().c_str(), src.c_str());
391 deserialized_inputs.erase(stream_id);
394 input = new Input(stream_id, src);
397 inputs.push_back(input);
400 // All deserialized inputs should now have been taken care of, one way or the other.
401 assert(deserialized_inputs.empty());
403 // Start writing statistics.
404 pthread_t stats_thread;
405 StatsThreadParameters stats_parameters; // Must live for as long as the stats thread does.
406 if (!stats_file.empty()) {
407 stats_parameters.stats_file = stats_file;
408 stats_parameters.stats_interval = stats_interval;
409 pthread_create(&stats_thread, NULL, stats_thread_run, &stats_parameters);
414 struct timeval server_start;
415 gettimeofday(&server_start, NULL);
417 // Measure time from we started deserializing (below) to now, when basically everything
418 // is up and running. This is, in other words, a conservative estimate of how long our
419 // “glitch” period was, not counting of course reconnects if the configuration changed.
420 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
421 1e-6 * (server_start.tv_usec - serialize_start.tv_usec);
422 fprintf(stderr, "Re-exec happened in approx. %.0f ms.\n", glitch_time * 1000.0);
429 // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
430 gettimeofday(&serialize_start, NULL);
432 if (!stats_file.empty()) {
433 pthread_kill(stats_thread, SIGHUP);
434 if (pthread_join(stats_thread, NULL) == -1) {
435 perror("pthread_join");
439 pthread_kill(acceptor_thread, SIGHUP);
440 if (pthread_join(acceptor_thread, NULL) == -1) {
441 perror("pthread_join");
445 CubemapStateProto state;
446 state.set_serialize_start_sec(serialize_start.tv_sec);
447 state.set_serialize_start_usec(serialize_start.tv_usec);
448 state.set_server_sock(server_sock);
449 state.set_port(port);
451 for (size_t i = 0; i < inputs.size(); ++i) {
453 state.add_inputs()->MergeFrom(inputs[i]->serialize());
456 for (int i = 0; i < num_servers; ++i) {
457 servers->get_server(i)->stop();
459 CubemapStateProto local_state = servers->get_server(i)->serialize();
461 // The stream state should be identical between the servers, so we only store it once.
463 state.mutable_streams()->MergeFrom(local_state.streams());
465 for (int j = 0; j < local_state.clients_size(); ++j) {
466 state.add_clients()->MergeFrom(local_state.clients(j));
471 fprintf(stderr, "Serializing state and re-execing...\n");
472 int state_fd = make_tempfile(state);
475 sprintf(buf, "%d", state_fd);
478 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
480 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);