6 #include <sys/socket.h>
23 #include "serverpool.h"
27 #define STREAM_ID "stream"
28 #define STREAM_URL "http://gruessi.zrh.sesse.net:4013/"
32 ServerPool *servers = NULL;
33 volatile bool hupped = false;
40 int create_server_socket(int port)
42 int server_sock = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
43 if (server_sock == -1) {
49 if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) {
50 perror("setsockopt(SO_REUSEADDR)");
54 // We want dual-stack sockets. (Sorry, OpenBSD and Windows XP...)
56 if (setsockopt(server_sock, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof(zero)) == -1) {
57 perror("setsockopt(IPV6_V6ONLY)");
61 // Set as non-blocking, so the acceptor thread can notice that we want to shut it down.
62 if (ioctl(server_sock, FIONBIO, &one) == -1) {
63 perror("ioctl(FIONBIO)");
68 memset(&addr, 0, sizeof(addr));
69 addr.sin6_family = AF_INET6;
70 addr.sin6_port = htons(port);
72 if (bind(server_sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
77 if (listen(server_sock, 128) == -1) {
85 void *acceptor_thread_run(void *arg)
87 int server_sock = int(intptr_t(arg));
89 // Since we are non-blocking, we need to wait for the right state first.
90 // Wait up to 50 ms, then check hupped.
95 int nfds = poll(&pfd, 1, 50);
96 if (nfds == 0 || (nfds == -1 && errno == EAGAIN)) {
106 socklen_t addrlen = sizeof(addr);
109 int sock = accept(server_sock, reinterpret_cast<sockaddr *>(&addr), &addrlen);
110 if (sock == -1 && errno == EINTR) {
119 // Set the socket as nonblocking.
121 if (ioctl(sock, FIONBIO, &one) == -1) {
126 // Pick a server, round-robin, and hand over the socket to it.
127 servers->add_client(sock);
132 struct StatsThreadParameters {
137 void *stats_thread_run(void *arg)
139 const StatsThreadParameters *parms = reinterpret_cast<StatsThreadParameters *>(arg);
144 vector<ClientStats> client_stats;
146 // Open a new, temporary file.
147 char *filename = strdup((parms->stats_file + ".new.XXXXXX").c_str());
148 fd = mkostemp(filename, O_WRONLY);
155 fp = fdopen(fd, "w");
165 client_stats = servers->get_client_stats();
166 for (size_t i = 0; i < client_stats.size(); ++i) {
167 fprintf(fp, "%s %s %d %llu\n",
168 client_stats[i].remote_addr.c_str(),
169 client_stats[i].stream_id.c_str(),
170 int(now - client_stats[i].connect_time),
171 (long long unsigned)(client_stats[i].bytes_sent));
173 if (fclose(fp) == EOF) {
180 if (rename(filename, parms->stats_file.c_str()) == -1) {
186 int left_to_sleep = parms->stats_interval;
188 left_to_sleep = sleep(left_to_sleep);
189 } while (left_to_sleep > 0);
194 // Serialize the given state to a file descriptor, and return the (still open)
196 int make_tempfile(const CubemapStateProto &state)
198 char tmpl[] = "/tmp/cubemapstate.XXXXXX";
199 int state_fd = mkstemp(tmpl);
200 if (state_fd == -1) {
206 state.SerializeToString(&serialized);
208 const char *ptr = serialized.data();
209 size_t to_write = serialized.size();
210 while (to_write > 0) {
211 ssize_t ret = write(state_fd, ptr, to_write);
224 // Read the state back from the file descriptor made by make_tempfile,
226 CubemapStateProto read_tempfile(int state_fd)
228 if (lseek(state_fd, 0, SEEK_SET) == -1) {
236 ssize_t ret = read(state_fd, buf, sizeof(buf));
246 serialized.append(string(buf, buf + ret));
249 close(state_fd); // Implicitly deletes the file.
251 CubemapStateProto state;
252 if (!state.ParseFromString(serialized)) {
253 fprintf(stderr, "PANIC: Failed deserialization of state.\n");
260 int main(int argc, char **argv)
262 fprintf(stderr, "\nCubemap starting.\n");
264 string config_filename = (argc == 1) ? "cubemap.config" : argv[1];
265 vector<ConfigLine> config = parse_config(config_filename);
267 int port = fetch_config_int(config, "port", 1, 65535, PARAMATER_MANDATORY);
268 int num_servers = fetch_config_int(config, "num_servers", 1, 20000, PARAMATER_MANDATORY); // Insanely high max limit.
270 servers = new ServerPool(num_servers);
272 int server_sock = -1, old_port = -1;
273 set<string> deserialized_stream_ids;
274 map<string, Input *> deserialized_inputs;
275 if (argc == 4 && strcmp(argv[2], "-state") == 0) {
276 fprintf(stderr, "Deserializing state from previous process... ");
277 int state_fd = atoi(argv[3]);
278 CubemapStateProto loaded_state = read_tempfile(state_fd);
280 // Deserialize the streams.
281 for (int i = 0; i < loaded_state.streams_size(); ++i) {
282 servers->add_stream_from_serialized(loaded_state.streams(i));
283 deserialized_stream_ids.insert(loaded_state.streams(i).stream_id());
286 // Put back the existing clients. It doesn't matter which server we
287 // allocate them to, so just do round-robin.
288 for (int i = 0; i < loaded_state.clients_size(); ++i) {
289 servers->add_client_from_serialized(loaded_state.clients(i));
292 // Deserialize the inputs. Note that we don't actually add them to any state yet.
293 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
294 deserialized_inputs.insert(make_pair(
295 loaded_state.inputs(i).stream_id(),
296 new Input(loaded_state.inputs(i))));
299 // Deserialize the server socket.
300 server_sock = loaded_state.server_sock();
301 old_port = loaded_state.port();
303 fprintf(stderr, "done.\n");
306 // Find all streams in the configuration file, and create them.
307 set<string> expecting_stream_ids = deserialized_stream_ids;
308 for (unsigned i = 0; i < config.size(); ++i) {
309 if (config[i].keyword != "stream") {
312 if (config[i].arguments.size() != 1) {
313 fprintf(stderr, "ERROR: 'stream' takes exactly one argument\n");
316 string stream_id = config[i].arguments[0];
317 if (deserialized_stream_ids.count(stream_id) == 0) {
318 servers->add_stream(stream_id);
320 expecting_stream_ids.erase(stream_id);
323 // Warn about any servers we've lost.
324 // TODO: Make an option (delete=yes?) to actually shut down streams.
325 for (set<string>::const_iterator stream_it = expecting_stream_ids.begin();
326 stream_it != expecting_stream_ids.end();
328 string stream_id = *stream_it;
329 fprintf(stderr, "WARNING: stream '%s' disappeared from the configuration file.\n",
331 fprintf(stderr, " It will not be deleted, but clients will not get any new inputs.\n");
332 if (deserialized_inputs.count(stream_id) != 0) {
333 delete deserialized_inputs[stream_id];
334 deserialized_inputs.erase(stream_id);
338 // Open a new server socket if we do not already have one, or if we changed ports.
339 if (server_sock != -1 && port != old_port) {
340 fprintf(stderr, "NOTE: Port changed from %d to %d; opening new socket.\n", old_port, port);
344 if (server_sock == -1) {
345 server_sock = create_server_socket(port);
348 // See if the user wants stats.
349 string stats_file = fetch_config_string(config, "stats_file", PARAMETER_OPTIONAL);
350 int stats_interval = fetch_config_int(config, "stats_interval", 1, INT_MAX, PARAMETER_OPTIONAL, -1);
351 if (stats_interval != -1 && stats_file.empty()) {
352 fprintf(stderr, "WARNING: 'stats_interval' given, but no 'stats_file'. No statistics will be written.\n");
357 pthread_t acceptor_thread;
358 pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
360 // Find all streams in the configuration file, and create inputs for them.
361 vector<Input *> inputs;
362 for (unsigned i = 0; i < config.size(); ++i) {
363 if (config[i].keyword != "stream") {
366 assert(config[i].arguments.size() == 1);
367 string stream_id = config[i].arguments[0];
369 if (config[i].parameters.count("src") == 0) {
370 fprintf(stderr, "WARNING: stream '%s' has no src= attribute, clients will not get any data.\n",
375 string src = config[i].parameters["src"];
377 if (deserialized_inputs.count(stream_id) != 0) {
378 input = deserialized_inputs[stream_id];
379 if (input->get_url() != src) {
380 fprintf(stderr, "INFO: Stream '%s' has changed URL from '%s' to '%s', restarting input.\n",
381 stream_id.c_str(), input->get_url().c_str(), src.c_str());
385 deserialized_inputs.erase(stream_id);
388 input = new Input(stream_id, src);
391 inputs.push_back(input);
394 // All deserialized inputs should now have been taken care of, one way or the other.
395 assert(deserialized_inputs.empty());
397 // Start writing statistics.
398 pthread_t stats_thread;
399 StatsThreadParameters stats_parameters; // Must live for as long as the stats thread does.
400 if (!stats_file.empty()) {
401 stats_parameters.stats_file = stats_file;
402 stats_parameters.stats_interval = stats_interval;
403 pthread_create(&stats_thread, NULL, stats_thread_run, &stats_parameters);
412 // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
413 if (!stats_file.empty()) {
414 if (pthread_join(stats_thread, NULL) == -1) {
415 perror("pthread_join");
419 if (pthread_join(acceptor_thread, NULL) == -1) {
420 perror("pthread_join");
424 CubemapStateProto state;
425 state.set_server_sock(server_sock);
426 state.set_port(port);
428 for (size_t i = 0; i < inputs.size(); ++i) {
430 state.add_inputs()->MergeFrom(inputs[i]->serialize());
433 for (int i = 0; i < num_servers; ++i) {
434 servers->get_server(i)->stop();
436 CubemapStateProto local_state = servers->get_server(i)->serialize();
438 // The stream state should be identical between the servers, so we only store it once.
440 state.mutable_streams()->MergeFrom(local_state.streams());
442 for (int j = 0; j < local_state.clients_size(); ++j) {
443 state.add_clients()->MergeFrom(local_state.clients(j));
448 fprintf(stderr, "Serializing state and re-execing...\n");
449 int state_fd = make_tempfile(state);
452 sprintf(buf, "%d", state_fd);
455 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
457 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);