]> git.sesse.net Git - cubemap/blob - main.cpp
Support writing a stats file listing the number of clients currently connected.
[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 <signal.h>
12 #include <errno.h>
13 #include <ctype.h>
14 #include <fcntl.h>
15 #include <vector>
16 #include <string>
17 #include <map>
18 #include <set>
19
20 #include "metacube.h"
21 #include "parse.h"
22 #include "server.h"
23 #include "serverpool.h"
24 #include "input.h"
25 #include "state.pb.h"
26
27 #define STREAM_ID "stream"
28 #define STREAM_URL "http://gruessi.zrh.sesse.net:4013/"
29
30 using namespace std;
31
32 ServerPool *servers = NULL;
33 volatile bool hupped = false;
34
35 void hup(int ignored)
36 {
37         hupped = true;
38 }
39
40 int create_server_socket(int port)
41 {
42         int server_sock = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
43         if (server_sock == -1) {
44                 perror("socket");
45                 exit(1);
46         }
47
48         int one = 1;
49         if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) {
50                 perror("setsockopt(SO_REUSEADDR)");
51                 exit(1);
52         }
53
54         // We want dual-stack sockets. (Sorry, OpenBSD and Windows XP...)
55         int zero = 0;
56         if (setsockopt(server_sock, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof(zero)) == -1) {
57                 perror("setsockopt(IPV6_V6ONLY)");
58                 exit(1);
59         }
60
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)");
64                 exit(1);
65         }
66
67         sockaddr_in6 addr;
68         memset(&addr, 0, sizeof(addr));
69         addr.sin6_family = AF_INET6;
70         addr.sin6_port = htons(port);
71
72         if (bind(server_sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
73                 perror("bind");
74                 exit(1);
75         }
76
77         if (listen(server_sock, 128) == -1) {
78                 perror("listen");
79                 exit(1);
80         }
81
82         return server_sock;
83 }
84
85 void *acceptor_thread_run(void *arg)
86 {
87         int server_sock = int(intptr_t(arg));
88         while (!hupped) {
89                 // Since we are non-blocking, we need to wait for the right state first.
90                 // Wait up to 50 ms, then check hupped.
91                 pollfd pfd;
92                 pfd.fd = server_sock;
93                 pfd.events = POLLIN;
94
95                 int nfds = poll(&pfd, 1, 50);
96                 if (nfds == 0 || (nfds == -1 && errno == EAGAIN)) {
97                         continue;
98                 }
99                 if (nfds == -1) {
100                         perror("poll");
101                         usleep(100000);
102                         continue;
103                 }
104
105                 sockaddr_in6 addr;
106                 socklen_t addrlen = sizeof(addr);
107
108                 // Get a new socket.
109                 int sock = accept(server_sock, reinterpret_cast<sockaddr *>(&addr), &addrlen);
110                 if (sock == -1 && errno == EINTR) {
111                         continue;
112                 }
113                 if (sock == -1) {
114                         perror("accept");
115                         usleep(100000);
116                         continue;
117                 }
118
119                 // Set the socket as nonblocking.
120                 int one = 1;
121                 if (ioctl(sock, FIONBIO, &one) == -1) {
122                         perror("FIONBIO");
123                         exit(1);
124                 }
125
126                 // Pick a server, round-robin, and hand over the socket to it.
127                 servers->add_client(sock);
128         }
129         return NULL;
130 }
131
132 struct StatsThreadParameters {
133         string stats_file;
134         int stats_interval;
135 };
136                 
137 void *stats_thread_run(void *arg)
138 {
139         const StatsThreadParameters *parms = reinterpret_cast<StatsThreadParameters *>(arg);
140         while (!hupped) {
141                 int fd;
142                 FILE *fp;
143                 time_t now;
144                 vector<ClientStats> client_stats;
145
146                 // Open a new, temporary file.
147                 char *filename = strdup((parms->stats_file + ".new.XXXXXX").c_str());
148                 fd = mkostemp(filename, O_WRONLY);
149                 if (fd == -1) {
150                         perror(filename);
151                         free(filename);
152                         goto sleep;
153                 }
154
155                 fp = fdopen(fd, "w");
156                 if (fp == NULL) {
157                         perror("fdopen");
158                         close(fd);
159                         unlink(filename);
160                         free(filename);
161                         goto sleep;
162                 }
163
164                 now = time(NULL);
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));
172                 }
173                 if (fclose(fp) == EOF) {
174                         perror("fclose");
175                         unlink(filename);
176                         free(filename);
177                         goto sleep;
178                 }
179                 
180                 if (rename(filename, parms->stats_file.c_str()) == -1) {
181                         perror("rename");
182                         unlink(filename);
183                 }
184
185 sleep:
186                 int left_to_sleep = parms->stats_interval;
187                 do {
188                         left_to_sleep = sleep(left_to_sleep);
189                 } while (left_to_sleep > 0);
190         }
191         return NULL;
192 }
193
194 // Serialize the given state to a file descriptor, and return the (still open)
195 // descriptor.
196 int make_tempfile(const CubemapStateProto &state)
197 {
198         char tmpl[] = "/tmp/cubemapstate.XXXXXX";
199         int state_fd = mkstemp(tmpl);
200         if (state_fd == -1) {
201                 perror("mkstemp");
202                 exit(1);
203         }
204
205         string serialized;
206         state.SerializeToString(&serialized);
207
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);
212                 if (ret == -1) {
213                         perror("write");
214                         exit(1);
215                 }
216
217                 ptr += ret;
218                 to_write -= ret;
219         }
220
221         return state_fd;
222 }
223
224 // Read the state back from the file descriptor made by make_tempfile,
225 // and close it.
226 CubemapStateProto read_tempfile(int state_fd)
227 {
228         if (lseek(state_fd, 0, SEEK_SET) == -1) {
229                 perror("lseek");
230                 exit(1);
231         }
232
233         string serialized;
234         char buf[4096];
235         for ( ;; ) {
236                 ssize_t ret = read(state_fd, buf, sizeof(buf));
237                 if (ret == -1) {
238                         perror("read");
239                         exit(1);
240                 }
241                 if (ret == 0) {
242                         // EOF.
243                         break;
244                 }
245
246                 serialized.append(string(buf, buf + ret));
247         }
248
249         close(state_fd);  // Implicitly deletes the file.
250
251         CubemapStateProto state;
252         if (!state.ParseFromString(serialized)) {
253                 fprintf(stderr, "PANIC: Failed deserialization of state.\n");
254                 exit(1);
255         }
256
257         return state;
258 }
259
260 int main(int argc, char **argv)
261 {
262         fprintf(stderr, "\nCubemap starting.\n");
263
264         string config_filename = (argc == 1) ? "cubemap.config" : argv[1];
265         vector<ConfigLine> config = parse_config(config_filename);
266
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.
269
270         servers = new ServerPool(num_servers);
271
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);
279
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());
284                 }
285
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));
290                 }
291
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))));
297                 } 
298
299                 // Deserialize the server socket.
300                 server_sock = loaded_state.server_sock();
301                 old_port = loaded_state.port();
302
303                 fprintf(stderr, "done.\n");
304         }
305
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") {
310                         continue;
311                 }
312                 if (config[i].arguments.size() != 1) {
313                         fprintf(stderr, "ERROR: 'stream' takes exactly one argument\n");
314                         exit(1);
315                 }
316                 string stream_id = config[i].arguments[0];
317                 if (deserialized_stream_ids.count(stream_id) == 0) {
318                         servers->add_stream(stream_id);
319                 }
320                 expecting_stream_ids.erase(stream_id);
321         }
322
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();
327              ++stream_it) {
328                 string stream_id = *stream_it;
329                 fprintf(stderr, "WARNING: stream '%s' disappeared from the configuration file.\n",
330                         stream_id.c_str());
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);
335                 }
336         }
337
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);
341                 close(server_sock);
342                 server_sock = -1;
343         }
344         if (server_sock == -1) {
345                 server_sock = create_server_socket(port);
346         }
347
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");
353         }
354
355         servers->run();
356
357         pthread_t acceptor_thread;
358         pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
359
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") {
364                         continue;
365                 }
366                 assert(config[i].arguments.size() == 1);
367                 string stream_id = config[i].arguments[0];
368
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",
371                                 stream_id.c_str());
372                         continue;
373                 }
374
375                 string src = config[i].parameters["src"];
376                 Input *input = NULL;
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());
382                                 delete input;
383                                 input = NULL;
384                         }
385                         deserialized_inputs.erase(stream_id);
386                 }
387                 if (input == NULL) {
388                         input = new Input(stream_id, src);
389                 }
390                 input->run();
391                 inputs.push_back(input);
392         }
393
394         // All deserialized inputs should now have been taken care of, one way or the other.
395         assert(deserialized_inputs.empty());
396
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);
404         }
405
406         signal(SIGHUP, hup);
407
408         while (!hupped) {
409                 usleep(100000);
410         }
411
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");
416                         exit(1);
417                 }
418         }
419         if (pthread_join(acceptor_thread, NULL) == -1) {
420                 perror("pthread_join");
421                 exit(1);
422         }
423
424         CubemapStateProto state;
425         state.set_server_sock(server_sock);
426         state.set_port(port);
427
428         for (size_t i = 0; i < inputs.size(); ++i) {
429                 inputs[i]->stop();
430                 state.add_inputs()->MergeFrom(inputs[i]->serialize());
431         }
432
433         for (int i = 0; i < num_servers; ++i) { 
434                 servers->get_server(i)->stop();
435
436                 CubemapStateProto local_state = servers->get_server(i)->serialize();
437
438                 // The stream state should be identical between the servers, so we only store it once.
439                 if (i == 0) {
440                         state.mutable_streams()->MergeFrom(local_state.streams());
441                 }
442                 for (int j = 0; j < local_state.clients_size(); ++j) {
443                         state.add_clients()->MergeFrom(local_state.clients(j));
444                 }
445         }
446         delete servers;
447
448         fprintf(stderr, "Serializing state and re-execing...\n");
449         int state_fd = make_tempfile(state);
450
451         char buf[16];
452         sprintf(buf, "%d", state_fd);
453
454         for ( ;; ) {
455                 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
456                 perror("execlp");
457                 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);
458                 usleep(200000);
459         }
460 }