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