]> git.sesse.net Git - cubemap/blob - main.cpp
1300508f314dc7b5909e6567c80832ac01432345
[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 "markpool.h"
22 #include "metacube.h"
23 #include "parse.h"
24 #include "server.h"
25 #include "serverpool.h"
26 #include "input.h"
27 #include "state.pb.h"
28
29 using namespace std;
30
31 ServerPool *servers = NULL;
32 volatile bool hupped = false;
33
34 void hup(int ignored)
35 {
36         hupped = true;
37 }
38
39 int create_server_socket(int port)
40 {
41         int server_sock = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
42         if (server_sock == -1) {
43                 perror("socket");
44                 exit(1);
45         }
46
47         int one = 1;
48         if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) {
49                 perror("setsockopt(SO_REUSEADDR)");
50                 exit(1);
51         }
52
53         // We want dual-stack sockets. (Sorry, OpenBSD and Windows XP...)
54         int zero = 0;
55         if (setsockopt(server_sock, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof(zero)) == -1) {
56                 perror("setsockopt(IPV6_V6ONLY)");
57                 exit(1);
58         }
59
60         // Set as non-blocking, so the acceptor thread can notice that we want to shut it down.
61         if (ioctl(server_sock, FIONBIO, &one) == -1) {
62                 perror("ioctl(FIONBIO)");
63                 exit(1);
64         }
65
66         sockaddr_in6 addr;
67         memset(&addr, 0, sizeof(addr));
68         addr.sin6_family = AF_INET6;
69         addr.sin6_port = htons(port);
70
71         if (bind(server_sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
72                 perror("bind");
73                 exit(1);
74         }
75
76         if (listen(server_sock, 128) == -1) {
77                 perror("listen");
78                 exit(1);
79         }
80
81         return server_sock;
82 }
83
84 void *acceptor_thread_run(void *arg)
85 {
86         int server_sock = int(intptr_t(arg));
87         while (!hupped) {
88                 // Since we are non-blocking, we need to wait for the right state first.
89                 // Wait up to 50 ms, then check hupped.
90                 pollfd pfd;
91                 pfd.fd = server_sock;
92                 pfd.events = POLLIN;
93
94                 int nfds = poll(&pfd, 1, 50);
95                 if (nfds == 0 || (nfds == -1 && errno == EINTR)) {
96                         continue;
97                 }
98                 if (nfds == -1) {
99                         perror("poll");
100                         usleep(100000);
101                         continue;
102                 }
103
104                 sockaddr_in6 addr;
105                 socklen_t addrlen = sizeof(addr);
106
107                 // Get a new socket.
108                 int sock = accept(server_sock, reinterpret_cast<sockaddr *>(&addr), &addrlen);
109                 if (sock == -1 && errno == EINTR) {
110                         continue;
111                 }
112                 if (sock == -1) {
113                         perror("accept");
114                         usleep(100000);
115                         continue;
116                 }
117
118                 // Set the socket as nonblocking.
119                 int one = 1;
120                 if (ioctl(sock, FIONBIO, &one) == -1) {
121                         perror("FIONBIO");
122                         exit(1);
123                 }
124
125                 // Pick a server, round-robin, and hand over the socket to it.
126                 servers->add_client(sock);
127         }
128         return NULL;
129 }
130
131 struct StatsThreadParameters {
132         string stats_file;
133         int stats_interval;
134 };
135                 
136 void *stats_thread_run(void *arg)
137 {
138         const StatsThreadParameters *parms = reinterpret_cast<StatsThreadParameters *>(arg);
139         while (!hupped) {
140                 int fd;
141                 FILE *fp;
142                 time_t now;
143                 vector<ClientStats> client_stats;
144
145                 // Open a new, temporary file.
146                 char *filename = strdup((parms->stats_file + ".new.XXXXXX").c_str());
147                 fd = mkostemp(filename, O_WRONLY);
148                 if (fd == -1) {
149                         perror(filename);
150                         free(filename);
151                         goto sleep;
152                 }
153
154                 fp = fdopen(fd, "w");
155                 if (fp == NULL) {
156                         perror("fdopen");
157                         close(fd);
158                         unlink(filename);
159                         free(filename);
160                         goto sleep;
161                 }
162
163                 now = time(NULL);
164                 client_stats = servers->get_client_stats();
165                 for (size_t i = 0; i < client_stats.size(); ++i) {
166                         fprintf(fp, "%s %s %d %llu\n",
167                                 client_stats[i].remote_addr.c_str(),
168                                 client_stats[i].stream_id.c_str(),
169                                 int(now - client_stats[i].connect_time),
170                                 (long long unsigned)(client_stats[i].bytes_sent));
171                 }
172                 if (fclose(fp) == EOF) {
173                         perror("fclose");
174                         unlink(filename);
175                         free(filename);
176                         goto sleep;
177                 }
178                 
179                 if (rename(filename, parms->stats_file.c_str()) == -1) {
180                         perror("rename");
181                         unlink(filename);
182                 }
183
184 sleep:
185                 int left_to_sleep = parms->stats_interval;
186                 do {
187                         left_to_sleep = sleep(left_to_sleep);
188                 } while (left_to_sleep > 0 && !hupped);
189         }
190         return NULL;
191 }
192
193 // Serialize the given state to a file descriptor, and return the (still open)
194 // descriptor.
195 int make_tempfile(const CubemapStateProto &state)
196 {
197         char tmpl[] = "/tmp/cubemapstate.XXXXXX";
198         int state_fd = mkstemp(tmpl);
199         if (state_fd == -1) {
200                 perror("mkstemp");
201                 exit(1);
202         }
203
204         string serialized;
205         state.SerializeToString(&serialized);
206
207         const char *ptr = serialized.data();
208         size_t to_write = serialized.size();
209         while (to_write > 0) {
210                 ssize_t ret = write(state_fd, ptr, to_write);
211                 if (ret == -1) {
212                         perror("write");
213                         exit(1);
214                 }
215
216                 ptr += ret;
217                 to_write -= ret;
218         }
219
220         return state_fd;
221 }
222
223 // Read the state back from the file descriptor made by make_tempfile,
224 // and close it.
225 CubemapStateProto read_tempfile(int state_fd)
226 {
227         if (lseek(state_fd, 0, SEEK_SET) == -1) {
228                 perror("lseek");
229                 exit(1);
230         }
231
232         string serialized;
233         char buf[4096];
234         for ( ;; ) {
235                 ssize_t ret = read(state_fd, buf, sizeof(buf));
236                 if (ret == -1) {
237                         perror("read");
238                         exit(1);
239                 }
240                 if (ret == 0) {
241                         // EOF.
242                         break;
243                 }
244
245                 serialized.append(string(buf, buf + ret));
246         }
247
248         close(state_fd);  // Implicitly deletes the file.
249
250         CubemapStateProto state;
251         if (!state.ParseFromString(serialized)) {
252                 fprintf(stderr, "PANIC: Failed deserialization of state.\n");
253                 exit(1);
254         }
255
256         return state;
257 }
258         
259 // Reuse mark pools if one already exists.
260 MarkPool *get_mark_pool(map<pair<int, int>, MarkPool *> *mark_pools, int from, int to)
261 {
262         pair<int, int> mark_range(from, to);
263         if (mark_pools->count(mark_range) != 0) {
264                 return (*mark_pools)[mark_range];
265         }
266
267         // Check if we're overlapping some other mark pool.
268         for (map<pair<int, int>, MarkPool *>::const_iterator mp_it = mark_pools->begin();
269              mp_it != mark_pools->end();
270              ++mp_it) {
271                 int other_from = mp_it->first.first;
272                 int other_to = mp_it->first.second;
273                 if ((from >= other_from && from < other_to) ||
274                     (to >= other_from && to < other_to)) {
275                         fprintf(stderr, "WARNING: Mark pool %d-%d partially overlaps with %d-%d, you may get duplicate marks.\n",
276                                 from, to, other_from, other_to);
277                         fprintf(stderr, "         Mark pools must either be completely disjunct, or completely overlapping.\n");
278                 }
279         }       
280
281         MarkPool *mark_pool = new MarkPool(from, to);
282         mark_pools->insert(make_pair(mark_range, mark_pool));
283         return mark_pool;
284 }
285
286 int main(int argc, char **argv)
287 {
288         fprintf(stderr, "\nCubemap starting.\n");
289
290         struct timeval serialize_start;
291         bool is_reexec = false;
292
293         string config_filename = (argc == 1) ? "cubemap.config" : argv[1];
294         vector<ConfigLine> config = parse_config(config_filename);
295
296         int port = fetch_config_int(config, "port", 1, 65535, PARAMATER_MANDATORY);
297         int num_servers = fetch_config_int(config, "num_servers", 1, 20000, PARAMATER_MANDATORY);  // Insanely high max limit.
298
299         servers = new ServerPool(num_servers);
300
301         CubemapStateProto loaded_state;
302         int server_sock = -1, old_port = -1;
303         set<string> deserialized_stream_ids;
304         map<string, Input *> deserialized_inputs;
305         if (argc == 4 && strcmp(argv[2], "-state") == 0) {
306                 is_reexec = true;
307
308                 fprintf(stderr, "Deserializing state from previous process... ");
309                 int state_fd = atoi(argv[3]);
310                 loaded_state = read_tempfile(state_fd);
311
312                 serialize_start.tv_sec = loaded_state.serialize_start_sec();
313                 serialize_start.tv_usec = loaded_state.serialize_start_usec();
314
315                 // Deserialize the streams.
316                 for (int i = 0; i < loaded_state.streams_size(); ++i) {
317                         servers->add_stream_from_serialized(loaded_state.streams(i));
318                         deserialized_stream_ids.insert(loaded_state.streams(i).stream_id());
319                 }
320
321                 // Deserialize the inputs. Note that we don't actually add them to any state yet.
322                 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
323                         deserialized_inputs.insert(make_pair(
324                                 loaded_state.inputs(i).stream_id(),
325                                 new Input(loaded_state.inputs(i))));
326                 } 
327
328                 // Deserialize the server socket.
329                 server_sock = loaded_state.server_sock();
330                 old_port = loaded_state.port();
331
332                 fprintf(stderr, "done.\n");
333         }
334
335         // Find all streams in the configuration file, and create them.
336         set<string> expecting_stream_ids = deserialized_stream_ids;
337         map<pair<int, int>, MarkPool *> mark_pools;
338         for (unsigned i = 0; i < config.size(); ++i) {
339                 if (config[i].keyword != "stream") {
340                         continue;
341                 }
342                 if (config[i].arguments.size() != 1) {
343                         fprintf(stderr, "ERROR: 'stream' takes exactly one argument\n");
344                         exit(1);
345                 }
346                 string stream_id = config[i].arguments[0];
347                 if (deserialized_stream_ids.count(stream_id) == 0) {
348                         servers->add_stream(stream_id);
349                 }
350                 expecting_stream_ids.erase(stream_id);
351
352                 // Set up marks, if so desired.
353                 if (config[i].parameters.count("mark")) {
354                         string mark_str = config[i].parameters["mark"];
355                         size_t split = mark_str.find_first_of('-');
356                         if (split == string::npos) {
357                                 fprintf(stderr, "WARNING: Invalid mark specification '%s' (expected 'X-Y'), ignoring.\n",
358                                         mark_str.c_str());
359                                 continue;
360                         }
361
362                         string from_str(mark_str.begin(), mark_str.begin() + split);
363                         string to_str(mark_str.begin() + split + 1, mark_str.end());
364                         int from = atoi(from_str.c_str());
365                         int to = atoi(to_str.c_str());
366
367                         if (from <= 0 || from >= 65536 || to <= 0 || to >= 65536) {
368                                 fprintf(stderr, "WARNING: Mark pool range %d-%d is outside legal range [1,65536>, ignoring.\n",
369                                         from, to);
370                                 continue;
371                         }
372
373                         MarkPool *mark_pool = get_mark_pool(&mark_pools, from, to);
374                         servers->set_mark_pool(stream_id, mark_pool);
375                 }
376         }
377
378         // Warn about any servers we've lost.
379         // TODO: Make an option (delete=yes?) to actually shut down streams.
380         for (set<string>::const_iterator stream_it = expecting_stream_ids.begin();
381              stream_it != expecting_stream_ids.end();
382              ++stream_it) {
383                 string stream_id = *stream_it;
384                 fprintf(stderr, "WARNING: stream '%s' disappeared from the configuration file.\n",
385                         stream_id.c_str());
386                 fprintf(stderr, "         It will not be deleted, but clients will not get any new inputs.\n");
387                 if (deserialized_inputs.count(stream_id) != 0) {
388                         delete deserialized_inputs[stream_id];
389                         deserialized_inputs.erase(stream_id);
390                 }
391         }
392
393         // Open a new server socket if we do not already have one, or if we changed ports.
394         if (server_sock != -1 && port != old_port) {
395                 fprintf(stderr, "NOTE: Port changed from %d to %d; opening new socket.\n", old_port, port);
396                 close(server_sock);
397                 server_sock = -1;
398         }
399         if (server_sock == -1) {
400                 server_sock = create_server_socket(port);
401         }
402
403         // See if the user wants stats.
404         string stats_file = fetch_config_string(config, "stats_file", PARAMETER_OPTIONAL);
405         int stats_interval = fetch_config_int(config, "stats_interval", 1, INT_MAX, PARAMETER_OPTIONAL, -1);
406         if (stats_interval != -1 && stats_file.empty()) {
407                 fprintf(stderr, "WARNING: 'stats_interval' given, but no 'stats_file'. No statistics will be written.\n");
408         }
409
410         servers->run();
411
412         pthread_t acceptor_thread;
413         pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
414
415         // Find all streams in the configuration file, and create inputs for them.
416         vector<Input *> inputs;
417         for (unsigned i = 0; i < config.size(); ++i) {
418                 if (config[i].keyword != "stream") {
419                         continue;
420                 }
421                 assert(config[i].arguments.size() == 1);
422                 string stream_id = config[i].arguments[0];
423
424                 if (config[i].parameters.count("src") == 0) {
425                         fprintf(stderr, "WARNING: stream '%s' has no src= attribute, clients will not get any data.\n",
426                                 stream_id.c_str());
427                         continue;
428                 }
429
430                 string src = config[i].parameters["src"];
431                 Input *input = NULL;
432                 if (deserialized_inputs.count(stream_id) != 0) {
433                         input = deserialized_inputs[stream_id];
434                         if (input->get_url() != src) {
435                                 fprintf(stderr, "INFO: Stream '%s' has changed URL from '%s' to '%s', restarting input.\n",
436                                         stream_id.c_str(), input->get_url().c_str(), src.c_str());
437                                 delete input;
438                                 input = NULL;
439                         }
440                         deserialized_inputs.erase(stream_id);
441                 }
442                 if (input == NULL) {
443                         input = new Input(stream_id, src);
444                 }
445                 input->run();
446                 inputs.push_back(input);
447         }
448         
449         if (is_reexec) {        
450                 // Put back the existing clients. It doesn't matter which server we
451                 // allocate them to, so just do round-robin. However, we need to add
452                 // them after the mark pools have been set up.
453                 for (int i = 0; i < loaded_state.clients_size(); ++i) {
454                         servers->add_client_from_serialized(loaded_state.clients(i));
455                 }
456         }
457
458         // All deserialized inputs should now have been taken care of, one way or the other.
459         assert(deserialized_inputs.empty());
460
461         // Start writing statistics.
462         pthread_t stats_thread;
463         StatsThreadParameters stats_parameters;  // Must live for as long as the stats thread does.
464         if (!stats_file.empty()) {
465                 stats_parameters.stats_file = stats_file;
466                 stats_parameters.stats_interval = stats_interval;
467                 pthread_create(&stats_thread, NULL, stats_thread_run, &stats_parameters);
468         }
469
470         signal(SIGHUP, hup);
471         
472         struct timeval server_start;
473         gettimeofday(&server_start, NULL);
474         if (is_reexec) {
475                 // Measure time from we started deserializing (below) to now, when basically everything
476                 // is up and running. This is, in other words, a conservative estimate of how long our
477                 // “glitch” period was, not counting of course reconnects if the configuration changed.
478                 double glitch_time = server_start.tv_sec - serialize_start.tv_sec +
479                         1e-6 * (server_start.tv_usec - serialize_start.tv_usec);
480                 fprintf(stderr, "Re-exec happened in approx. %.0f ms.\n", glitch_time * 1000.0);
481         }
482
483         while (!hupped) {
484                 usleep(100000);
485         }
486
487         // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
488         gettimeofday(&serialize_start, NULL);
489
490         if (!stats_file.empty()) {
491                 pthread_kill(stats_thread, SIGHUP);
492                 if (pthread_join(stats_thread, NULL) == -1) {
493                         perror("pthread_join");
494                         exit(1);
495                 }
496         }
497         pthread_kill(acceptor_thread, SIGHUP);
498         if (pthread_join(acceptor_thread, NULL) == -1) {
499                 perror("pthread_join");
500                 exit(1);
501         }
502
503         CubemapStateProto state;
504         state.set_serialize_start_sec(serialize_start.tv_sec);
505         state.set_serialize_start_usec(serialize_start.tv_usec);
506         state.set_server_sock(server_sock);
507         state.set_port(port);
508
509         for (size_t i = 0; i < inputs.size(); ++i) {
510                 inputs[i]->stop();
511                 state.add_inputs()->MergeFrom(inputs[i]->serialize());
512         }
513
514         for (int i = 0; i < num_servers; ++i) { 
515                 servers->get_server(i)->stop();
516
517                 CubemapStateProto local_state = servers->get_server(i)->serialize();
518
519                 // The stream state should be identical between the servers, so we only store it once.
520                 if (i == 0) {
521                         state.mutable_streams()->MergeFrom(local_state.streams());
522                 }
523                 for (int j = 0; j < local_state.clients_size(); ++j) {
524                         state.add_clients()->MergeFrom(local_state.clients(j));
525                 }
526         }
527         delete servers;
528
529         fprintf(stderr, "Serializing state and re-execing...\n");
530         int state_fd = make_tempfile(state);
531
532         char buf[16];
533         sprintf(buf, "%d", state_fd);
534
535         for ( ;; ) {
536                 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
537                 perror("execlp");
538                 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);
539                 usleep(200000);
540         }
541 }