]> git.sesse.net Git - cubemap/blob - main.cpp
2af1996fe670d7152c81552e00018f17052f3aac
[cubemap] / main.cpp
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdint.h>
4 #include <assert.h>
5 #include <arpa/inet.h>
6 #include <sys/socket.h>
7 #include <pthread.h>
8 #include <sys/types.h>
9 #include <sys/ioctl.h>
10 #include <sys/poll.h>
11 #include <sys/time.h>
12 #include <signal.h>
13 #include <errno.h>
14 #include <ctype.h>
15 #include <fcntl.h>
16 #include <vector>
17 #include <string>
18 #include <map>
19 #include <set>
20
21 #include "metacube.h"
22 #include "parse.h"
23 #include "server.h"
24 #include "serverpool.h"
25 #include "input.h"
26 #include "state.pb.h"
27
28 #define STREAM_ID "stream"
29 #define STREAM_URL "http://gruessi.zrh.sesse.net:4013/"
30
31 using namespace std;
32
33 ServerPool *servers = NULL;
34 volatile bool hupped = false;
35
36 void hup(int ignored)
37 {
38         hupped = true;
39 }
40
41 int create_server_socket(int port)
42 {
43         int server_sock = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
44         if (server_sock == -1) {
45                 perror("socket");
46                 exit(1);
47         }
48
49         int one = 1;
50         if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) {
51                 perror("setsockopt(SO_REUSEADDR)");
52                 exit(1);
53         }
54
55         // We want dual-stack sockets. (Sorry, OpenBSD and Windows XP...)
56         int zero = 0;
57         if (setsockopt(server_sock, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof(zero)) == -1) {
58                 perror("setsockopt(IPV6_V6ONLY)");
59                 exit(1);
60         }
61
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)");
65                 exit(1);
66         }
67
68         sockaddr_in6 addr;
69         memset(&addr, 0, sizeof(addr));
70         addr.sin6_family = AF_INET6;
71         addr.sin6_port = htons(port);
72
73         if (bind(server_sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
74                 perror("bind");
75                 exit(1);
76         }
77
78         if (listen(server_sock, 128) == -1) {
79                 perror("listen");
80                 exit(1);
81         }
82
83         return server_sock;
84 }
85
86 void *acceptor_thread_run(void *arg)
87 {
88         int server_sock = int(intptr_t(arg));
89         while (!hupped) {
90                 // Since we are non-blocking, we need to wait for the right state first.
91                 // Wait up to 50 ms, then check hupped.
92                 pollfd pfd;
93                 pfd.fd = server_sock;
94                 pfd.events = POLLIN;
95
96                 int nfds = poll(&pfd, 1, 50);
97                 if (nfds == 0 || (nfds == -1 && errno == EAGAIN)) {
98                         continue;
99                 }
100                 if (nfds == -1) {
101                         perror("poll");
102                         usleep(100000);
103                         continue;
104                 }
105
106                 sockaddr_in6 addr;
107                 socklen_t addrlen = sizeof(addr);
108
109                 // Get a new socket.
110                 int sock = accept(server_sock, reinterpret_cast<sockaddr *>(&addr), &addrlen);
111                 if (sock == -1 && errno == EINTR) {
112                         continue;
113                 }
114                 if (sock == -1) {
115                         perror("accept");
116                         usleep(100000);
117                         continue;
118                 }
119
120                 // Set the socket as nonblocking.
121                 int one = 1;
122                 if (ioctl(sock, FIONBIO, &one) == -1) {
123                         perror("FIONBIO");
124                         exit(1);
125                 }
126
127                 // Pick a server, round-robin, and hand over the socket to it.
128                 servers->add_client(sock);
129         }
130         return NULL;
131 }
132
133 struct StatsThreadParameters {
134         string stats_file;
135         int stats_interval;
136 };
137                 
138 void *stats_thread_run(void *arg)
139 {
140         const StatsThreadParameters *parms = reinterpret_cast<StatsThreadParameters *>(arg);
141         while (!hupped) {
142                 int fd;
143                 FILE *fp;
144                 time_t now;
145                 vector<ClientStats> client_stats;
146
147                 // Open a new, temporary file.
148                 char *filename = strdup((parms->stats_file + ".new.XXXXXX").c_str());
149                 fd = mkostemp(filename, O_WRONLY);
150                 if (fd == -1) {
151                         perror(filename);
152                         free(filename);
153                         goto sleep;
154                 }
155
156                 fp = fdopen(fd, "w");
157                 if (fp == NULL) {
158                         perror("fdopen");
159                         close(fd);
160                         unlink(filename);
161                         free(filename);
162                         goto sleep;
163                 }
164
165                 now = time(NULL);
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));
173                 }
174                 if (fclose(fp) == EOF) {
175                         perror("fclose");
176                         unlink(filename);
177                         free(filename);
178                         goto sleep;
179                 }
180                 
181                 if (rename(filename, parms->stats_file.c_str()) == -1) {
182                         perror("rename");
183                         unlink(filename);
184                 }
185
186 sleep:
187                 int left_to_sleep = parms->stats_interval;
188                 do {
189                         left_to_sleep = sleep(left_to_sleep);
190                 } while (left_to_sleep > 0);
191         }
192         return NULL;
193 }
194
195 // Serialize the given state to a file descriptor, and return the (still open)
196 // descriptor.
197 int make_tempfile(const CubemapStateProto &state)
198 {
199         char tmpl[] = "/tmp/cubemapstate.XXXXXX";
200         int state_fd = mkstemp(tmpl);
201         if (state_fd == -1) {
202                 perror("mkstemp");
203                 exit(1);
204         }
205
206         string serialized;
207         state.SerializeToString(&serialized);
208
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);
213                 if (ret == -1) {
214                         perror("write");
215                         exit(1);
216                 }
217
218                 ptr += ret;
219                 to_write -= ret;
220         }
221
222         return state_fd;
223 }
224
225 // Read the state back from the file descriptor made by make_tempfile,
226 // and close it.
227 CubemapStateProto read_tempfile(int state_fd)
228 {
229         if (lseek(state_fd, 0, SEEK_SET) == -1) {
230                 perror("lseek");
231                 exit(1);
232         }
233
234         string serialized;
235         char buf[4096];
236         for ( ;; ) {
237                 ssize_t ret = read(state_fd, buf, sizeof(buf));
238                 if (ret == -1) {
239                         perror("read");
240                         exit(1);
241                 }
242                 if (ret == 0) {
243                         // EOF.
244                         break;
245                 }
246
247                 serialized.append(string(buf, buf + ret));
248         }
249
250         close(state_fd);  // Implicitly deletes the file.
251
252         CubemapStateProto state;
253         if (!state.ParseFromString(serialized)) {
254                 fprintf(stderr, "PANIC: Failed deserialization of state.\n");
255                 exit(1);
256         }
257
258         return state;
259 }
260
261 int main(int argc, char **argv)
262 {
263         fprintf(stderr, "\nCubemap starting.\n");
264
265         struct timeval serialize_start;
266         bool is_reexec = false;
267
268         string config_filename = (argc == 1) ? "cubemap.config" : argv[1];
269         vector<ConfigLine> config = parse_config(config_filename);
270
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.
273
274         servers = new ServerPool(num_servers);
275
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) {
280                 is_reexec = true;
281
282                 fprintf(stderr, "Deserializing state from previous process... ");
283                 int state_fd = atoi(argv[3]);
284                 CubemapStateProto loaded_state = read_tempfile(state_fd);
285
286                 serialize_start.tv_sec = loaded_state.serialize_start_sec();
287                 serialize_start.tv_usec = loaded_state.serialize_start_usec();
288
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());
293                 }
294
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));
299                 }
300
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))));
306                 } 
307
308                 // Deserialize the server socket.
309                 server_sock = loaded_state.server_sock();
310                 old_port = loaded_state.port();
311
312                 fprintf(stderr, "done.\n");
313         }
314
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") {
319                         continue;
320                 }
321                 if (config[i].arguments.size() != 1) {
322                         fprintf(stderr, "ERROR: 'stream' takes exactly one argument\n");
323                         exit(1);
324                 }
325                 string stream_id = config[i].arguments[0];
326                 if (deserialized_stream_ids.count(stream_id) == 0) {
327                         servers->add_stream(stream_id);
328                 }
329                 expecting_stream_ids.erase(stream_id);
330         }
331
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();
336              ++stream_it) {
337                 string stream_id = *stream_it;
338                 fprintf(stderr, "WARNING: stream '%s' disappeared from the configuration file.\n",
339                         stream_id.c_str());
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);
344                 }
345         }
346
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);
350                 close(server_sock);
351                 server_sock = -1;
352         }
353         if (server_sock == -1) {
354                 server_sock = create_server_socket(port);
355         }
356
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");
362         }
363
364         servers->run();
365
366         pthread_t acceptor_thread;
367         pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
368
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") {
373                         continue;
374                 }
375                 assert(config[i].arguments.size() == 1);
376                 string stream_id = config[i].arguments[0];
377
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",
380                                 stream_id.c_str());
381                         continue;
382                 }
383
384                 string src = config[i].parameters["src"];
385                 Input *input = NULL;
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());
391                                 delete input;
392                                 input = NULL;
393                         }
394                         deserialized_inputs.erase(stream_id);
395                 }
396                 if (input == NULL) {
397                         input = new Input(stream_id, src);
398                 }
399                 input->run();
400                 inputs.push_back(input);
401         }
402
403         // All deserialized inputs should now have been taken care of, one way or the other.
404         assert(deserialized_inputs.empty());
405
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);
413         }
414
415         signal(SIGHUP, hup);
416         
417         struct timeval server_start;
418         gettimeofday(&server_start, NULL);
419         if (is_reexec) {
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);
426         }
427
428         while (!hupped) {
429                 usleep(100000);
430         }
431
432         // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
433         gettimeofday(&serialize_start, NULL);
434
435         if (!stats_file.empty()) {
436                 if (pthread_join(stats_thread, NULL) == -1) {
437                         perror("pthread_join");
438                         exit(1);
439                 }
440         }
441         if (pthread_join(acceptor_thread, NULL) == -1) {
442                 perror("pthread_join");
443                 exit(1);
444         }
445
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);
451
452         for (size_t i = 0; i < inputs.size(); ++i) {
453                 inputs[i]->stop();
454                 state.add_inputs()->MergeFrom(inputs[i]->serialize());
455         }
456
457         for (int i = 0; i < num_servers; ++i) { 
458                 servers->get_server(i)->stop();
459
460                 CubemapStateProto local_state = servers->get_server(i)->serialize();
461
462                 // The stream state should be identical between the servers, so we only store it once.
463                 if (i == 0) {
464                         state.mutable_streams()->MergeFrom(local_state.streams());
465                 }
466                 for (int j = 0; j < local_state.clients_size(); ++j) {
467                         state.add_clients()->MergeFrom(local_state.clients(j));
468                 }
469         }
470         delete servers;
471
472         fprintf(stderr, "Serializing state and re-execing...\n");
473         int state_fd = make_tempfile(state);
474
475         char buf[16];
476         sprintf(buf, "%d", state_fd);
477
478         for ( ;; ) {
479                 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
480                 perror("execlp");
481                 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);
482                 usleep(200000);
483         }
484 }