6 #include <sys/socket.h>
24 #include "serverpool.h"
28 #define STREAM_ID "stream"
29 #define STREAM_URL "http://gruessi.zrh.sesse.net:4013/"
33 ServerPool *servers = NULL;
34 volatile bool hupped = false;
41 int create_server_socket(int port)
43 int server_sock = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
44 if (server_sock == -1) {
50 if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) {
51 perror("setsockopt(SO_REUSEADDR)");
55 // We want dual-stack sockets. (Sorry, OpenBSD and Windows XP...)
57 if (setsockopt(server_sock, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof(zero)) == -1) {
58 perror("setsockopt(IPV6_V6ONLY)");
62 // Set as non-blocking, so the acceptor thread can notice that we want to shut it down.
63 if (ioctl(server_sock, FIONBIO, &one) == -1) {
64 perror("ioctl(FIONBIO)");
69 memset(&addr, 0, sizeof(addr));
70 addr.sin6_family = AF_INET6;
71 addr.sin6_port = htons(port);
73 if (bind(server_sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
78 if (listen(server_sock, 128) == -1) {
86 void *acceptor_thread_run(void *arg)
88 int server_sock = int(intptr_t(arg));
90 // Since we are non-blocking, we need to wait for the right state first.
91 // Wait up to 50 ms, then check hupped.
96 int nfds = poll(&pfd, 1, 50);
97 if (nfds == 0 || (nfds == -1 && errno == EAGAIN)) {
107 socklen_t addrlen = sizeof(addr);
110 int sock = accept(server_sock, reinterpret_cast<sockaddr *>(&addr), &addrlen);
111 if (sock == -1 && errno == EINTR) {
120 // Set the socket as nonblocking.
122 if (ioctl(sock, FIONBIO, &one) == -1) {
127 // Pick a server, round-robin, and hand over the socket to it.
128 servers->add_client(sock);
133 struct StatsThreadParameters {
138 void *stats_thread_run(void *arg)
140 const StatsThreadParameters *parms = reinterpret_cast<StatsThreadParameters *>(arg);
145 vector<ClientStats> client_stats;
147 // Open a new, temporary file.
148 char *filename = strdup((parms->stats_file + ".new.XXXXXX").c_str());
149 fd = mkostemp(filename, O_WRONLY);
156 fp = fdopen(fd, "w");
166 client_stats = servers->get_client_stats();
167 for (size_t i = 0; i < client_stats.size(); ++i) {
168 fprintf(fp, "%s %s %d %llu\n",
169 client_stats[i].remote_addr.c_str(),
170 client_stats[i].stream_id.c_str(),
171 int(now - client_stats[i].connect_time),
172 (long long unsigned)(client_stats[i].bytes_sent));
174 if (fclose(fp) == EOF) {
181 if (rename(filename, parms->stats_file.c_str()) == -1) {
187 int left_to_sleep = parms->stats_interval;
189 left_to_sleep = sleep(left_to_sleep);
190 } while (left_to_sleep > 0);
195 // Serialize the given state to a file descriptor, and return the (still open)
197 int make_tempfile(const CubemapStateProto &state)
199 char tmpl[] = "/tmp/cubemapstate.XXXXXX";
200 int state_fd = mkstemp(tmpl);
201 if (state_fd == -1) {
207 state.SerializeToString(&serialized);
209 const char *ptr = serialized.data();
210 size_t to_write = serialized.size();
211 while (to_write > 0) {
212 ssize_t ret = write(state_fd, ptr, to_write);
225 // Read the state back from the file descriptor made by make_tempfile,
227 CubemapStateProto read_tempfile(int state_fd)
229 if (lseek(state_fd, 0, SEEK_SET) == -1) {
237 ssize_t ret = read(state_fd, buf, sizeof(buf));
247 serialized.append(string(buf, buf + ret));
250 close(state_fd); // Implicitly deletes the file.
252 CubemapStateProto state;
253 if (!state.ParseFromString(serialized)) {
254 fprintf(stderr, "PANIC: Failed deserialization of state.\n");
261 int main(int argc, char **argv)
263 fprintf(stderr, "\nCubemap starting.\n");
265 struct timeval serialize_start;
266 bool is_reexec = false;
268 string config_filename = (argc == 1) ? "cubemap.config" : argv[1];
269 vector<ConfigLine> config = parse_config(config_filename);
271 int port = fetch_config_int(config, "port", 1, 65535, PARAMATER_MANDATORY);
272 int num_servers = fetch_config_int(config, "num_servers", 1, 20000, PARAMATER_MANDATORY); // Insanely high max limit.
274 servers = new ServerPool(num_servers);
276 int server_sock = -1, old_port = -1;
277 set<string> deserialized_stream_ids;
278 map<string, Input *> deserialized_inputs;
279 if (argc == 4 && strcmp(argv[2], "-state") == 0) {
282 fprintf(stderr, "Deserializing state from previous process... ");
283 int state_fd = atoi(argv[3]);
284 CubemapStateProto loaded_state = read_tempfile(state_fd);
286 serialize_start.tv_sec = loaded_state.serialize_start_sec();
287 serialize_start.tv_usec = loaded_state.serialize_start_usec();
289 // Deserialize the streams.
290 for (int i = 0; i < loaded_state.streams_size(); ++i) {
291 servers->add_stream_from_serialized(loaded_state.streams(i));
292 deserialized_stream_ids.insert(loaded_state.streams(i).stream_id());
295 // Put back the existing clients. It doesn't matter which server we
296 // allocate them to, so just do round-robin.
297 for (int i = 0; i < loaded_state.clients_size(); ++i) {
298 servers->add_client_from_serialized(loaded_state.clients(i));
301 // Deserialize the inputs. Note that we don't actually add them to any state yet.
302 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
303 deserialized_inputs.insert(make_pair(
304 loaded_state.inputs(i).stream_id(),
305 new Input(loaded_state.inputs(i))));
308 // Deserialize the server socket.
309 server_sock = loaded_state.server_sock();
310 old_port = loaded_state.port();
312 fprintf(stderr, "done.\n");
315 // Find all streams in the configuration file, and create them.
316 set<string> expecting_stream_ids = deserialized_stream_ids;
317 for (unsigned i = 0; i < config.size(); ++i) {
318 if (config[i].keyword != "stream") {
321 if (config[i].arguments.size() != 1) {
322 fprintf(stderr, "ERROR: 'stream' takes exactly one argument\n");
325 string stream_id = config[i].arguments[0];
326 if (deserialized_stream_ids.count(stream_id) == 0) {
327 servers->add_stream(stream_id);
329 expecting_stream_ids.erase(stream_id);
332 // Warn about any servers we've lost.
333 // TODO: Make an option (delete=yes?) to actually shut down streams.
334 for (set<string>::const_iterator stream_it = expecting_stream_ids.begin();
335 stream_it != expecting_stream_ids.end();
337 string stream_id = *stream_it;
338 fprintf(stderr, "WARNING: stream '%s' disappeared from the configuration file.\n",
340 fprintf(stderr, " It will not be deleted, but clients will not get any new inputs.\n");
341 if (deserialized_inputs.count(stream_id) != 0) {
342 delete deserialized_inputs[stream_id];
343 deserialized_inputs.erase(stream_id);
347 // Open a new server socket if we do not already have one, or if we changed ports.
348 if (server_sock != -1 && port != old_port) {
349 fprintf(stderr, "NOTE: Port changed from %d to %d; opening new socket.\n", old_port, port);
353 if (server_sock == -1) {
354 server_sock = create_server_socket(port);
357 // See if the user wants stats.
358 string stats_file = fetch_config_string(config, "stats_file", PARAMETER_OPTIONAL);
359 int stats_interval = fetch_config_int(config, "stats_interval", 1, INT_MAX, PARAMETER_OPTIONAL, -1);
360 if (stats_interval != -1 && stats_file.empty()) {
361 fprintf(stderr, "WARNING: 'stats_interval' given, but no 'stats_file'. No statistics will be written.\n");
366 pthread_t acceptor_thread;
367 pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
369 // Find all streams in the configuration file, and create inputs for them.
370 vector<Input *> inputs;
371 for (unsigned i = 0; i < config.size(); ++i) {
372 if (config[i].keyword != "stream") {
375 assert(config[i].arguments.size() == 1);
376 string stream_id = config[i].arguments[0];
378 if (config[i].parameters.count("src") == 0) {
379 fprintf(stderr, "WARNING: stream '%s' has no src= attribute, clients will not get any data.\n",
384 string src = config[i].parameters["src"];
386 if (deserialized_inputs.count(stream_id) != 0) {
387 input = deserialized_inputs[stream_id];
388 if (input->get_url() != src) {
389 fprintf(stderr, "INFO: Stream '%s' has changed URL from '%s' to '%s', restarting input.\n",
390 stream_id.c_str(), input->get_url().c_str(), src.c_str());
394 deserialized_inputs.erase(stream_id);
397 input = new Input(stream_id, src);
400 inputs.push_back(input);
403 // All deserialized inputs should now have been taken care of, one way or the other.
404 assert(deserialized_inputs.empty());
406 // Start writing statistics.
407 pthread_t stats_thread;
408 StatsThreadParameters stats_parameters; // Must live for as long as the stats thread does.
409 if (!stats_file.empty()) {
410 stats_parameters.stats_file = stats_file;
411 stats_parameters.stats_interval = stats_interval;
412 pthread_create(&stats_thread, NULL, stats_thread_run, &stats_parameters);
417 struct timeval server_start;
418 gettimeofday(&server_start, NULL);
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 fprintf(stderr, "Re-exec happened in approx. %.0f ms.\n", 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_file.empty()) {
436 if (pthread_join(stats_thread, NULL) == -1) {
437 perror("pthread_join");
441 if (pthread_join(acceptor_thread, NULL) == -1) {
442 perror("pthread_join");
446 CubemapStateProto state;
447 state.set_serialize_start_sec(serialize_start.tv_sec);
448 state.set_serialize_start_usec(serialize_start.tv_usec);
449 state.set_server_sock(server_sock);
450 state.set_port(port);
452 for (size_t i = 0; i < inputs.size(); ++i) {
454 state.add_inputs()->MergeFrom(inputs[i]->serialize());
457 for (int i = 0; i < num_servers; ++i) {
458 servers->get_server(i)->stop();
460 CubemapStateProto local_state = servers->get_server(i)->serialize();
462 // The stream state should be identical between the servers, so we only store it once.
464 state.mutable_streams()->MergeFrom(local_state.streams());
466 for (int j = 0; j < local_state.clients_size(); ++j) {
467 state.add_clients()->MergeFrom(local_state.clients(j));
472 fprintf(stderr, "Serializing state and re-execing...\n");
473 int state_fd = make_tempfile(state);
476 sprintf(buf, "%d", state_fd);
479 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
481 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);