]> git.sesse.net Git - cubemap/blob - cubemap.cpp
4f03feae49f5073abc4d8f66bde35cd4632d8146
[cubemap] / cubemap.cpp
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdint.h>
4 #include <assert.h>
5 #include <arpa/inet.h>
6 #include <curl/curl.h>
7 #include <sys/socket.h>
8 #include <pthread.h>
9 #include <sys/types.h>
10 #include <sys/ioctl.h>
11 #include <sys/epoll.h>
12 #include <signal.h>
13 #include <errno.h>
14 #include <ctype.h>
15 #include <vector>
16 #include <string>
17 #include <map>
18
19 #include "metacube.h"
20 #include "server.h"
21 #include "serverpool.h"
22 #include "input.h"
23 #include "state.pb.h"
24
25 #define NUM_SERVERS 4
26 #define STREAM_ID "stream"
27 #define STREAM_URL "http://gruessi.zrh.sesse.net:4013/"
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         sockaddr_in6 addr;
61         memset(&addr, 0, sizeof(addr));
62         addr.sin6_family = AF_INET6;
63         addr.sin6_port = htons(port);
64
65         if (bind(server_sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
66                 perror("bind");
67                 exit(1);
68         }
69
70         if (listen(server_sock, 128) == -1) {
71                 perror("listen");
72                 exit(1);
73         }
74
75         return server_sock;
76 }
77
78 void *acceptor_thread_run(void *arg)
79 {
80         int server_sock = int(intptr_t(arg));
81         int num_accepted = 0;
82         for ( ;; ) {
83                 sockaddr_in6 addr;
84                 socklen_t addrlen = sizeof(addr);
85
86                 // Get a new socket.
87                 int sock = accept(server_sock, reinterpret_cast<sockaddr *>(&addr), &addrlen);
88                 if (sock == -1 && errno == EINTR) {
89                         continue;
90                 }
91                 if (sock == -1) {
92                         perror("accept");
93                         exit(1);
94                 }
95
96                 // Set the socket as nonblocking.
97                 int one = 1;
98                 if (ioctl(sock, FIONBIO, &one) == -1) {
99                         perror("FIONBIO");
100                         exit(1);
101                 }
102
103                 // Pick a server, round-robin, and hand over the socket to it.
104                 servers->add_client(sock);
105                 ++num_accepted; 
106         }
107 }
108
109 // Serialize the given state to a file descriptor, and return the (still open)
110 // descriptor.
111 int make_tempfile(const CubemapStateProto &state)
112 {
113         char tmpl[] = "/tmp/cubemapstate.XXXXXX";
114         int state_fd = mkstemp(tmpl);
115         if (state_fd == -1) {
116                 perror("mkstemp");
117                 exit(1);
118         }
119
120         string serialized;
121         state.SerializeToString(&serialized);
122
123         const char *ptr = serialized.data();
124         size_t to_write = serialized.size();
125         while (to_write > 0) {
126                 ssize_t ret = write(state_fd, ptr, to_write);
127                 if (ret == -1) {
128                         perror("write");
129                         exit(1);
130                 }
131
132                 ptr += ret;
133                 to_write -= ret;
134         }
135
136         return state_fd;
137 }
138
139 // Read the state back from the file descriptor made by make_tempfile,
140 // and close it.
141 CubemapStateProto read_tempfile(int state_fd)
142 {
143         if (lseek(state_fd, 0, SEEK_SET) == -1) {
144                 perror("lseek");
145                 exit(1);
146         }
147
148         string serialized;
149         char buf[4096];
150         for ( ;; ) {
151                 ssize_t ret = read(state_fd, buf, sizeof(buf));
152                 if (ret == -1) {
153                         perror("read");
154                         exit(1);
155                 }
156                 if (ret == 0) {
157                         // EOF.
158                         break;
159                 }
160
161                 serialized.append(string(buf, buf + ret));
162         }
163
164         close(state_fd);  // Implicitly deletes the file.
165
166         CubemapStateProto state;
167         if (!state.ParseFromString(serialized)) {
168                 fprintf(stderr, "PANIC: Failed deserialization of state.\n");
169                 exit(1);
170         }
171
172         return state;
173 }
174
175 // Split a line on whitespace, e.g. "foo  bar baz" -> {"foo", "bar", "baz"}.
176 vector<string> split_tokens(const string &line)
177 {
178         vector<string> ret;
179         string current_token;
180
181         for (size_t i = 0; i < line.size(); ++i) {
182                 if (isspace(line[i])) {
183                         if (!current_token.empty()) {
184                                 ret.push_back(current_token);
185                         }
186                         current_token.clear();
187                 } else {
188                         current_token.push_back(line[i]);
189                 }
190         }
191         if (!current_token.empty()) {
192                 ret.push_back(current_token);
193         }
194         return ret;
195 }
196
197 struct ConfigLine {
198         string keyword;
199         vector<string> arguments;
200         map<string, string> parameters;
201 };
202
203 // Parse the configuration file.
204 vector<ConfigLine> parse_config(const string &filename)
205 {
206         vector<ConfigLine> ret;
207
208         FILE *fp = fopen(filename.c_str(), "r");
209         if (fp == NULL) {
210                 perror(filename.c_str());
211                 exit(1);
212         }
213
214         char buf[4096];
215         while (!feof(fp)) {
216                 if (fgets(buf, sizeof(buf), fp) == NULL) {
217                         break;
218                 }
219
220                 // Chop off the string at the first #, \r or \n.
221                 buf[strcspn(buf, "#\r\n")] = 0;
222
223                 // Remove all whitespace from the end of the string.
224                 size_t len = strlen(buf);
225                 while (len > 0 && isspace(buf[len - 1])) {
226                         buf[--len] = 0;
227                 }
228
229                 // If the line is now all blank, ignore it.
230                 if (len == 0) {
231                         continue;
232                 }
233
234                 vector<string> tokens = split_tokens(buf);
235                 assert(!tokens.empty());
236                 
237                 ConfigLine line;
238                 line.keyword = tokens[0];
239
240                 for (size_t i = 1; i < tokens.size(); ++i) {
241                         // foo=bar is a parameter; anything else is an argument.
242                         size_t equals_pos = tokens[i].find_first_of('=');
243                         if (equals_pos == string::npos) {
244                                 line.arguments.push_back(tokens[i]);
245                         } else {
246                                 string key = tokens[i].substr(0, equals_pos);
247                                 string value = tokens[i].substr(equals_pos + 1, string::npos);
248                                 line.parameters.insert(make_pair(key, value));
249                         }
250                 }
251
252                 ret.push_back(line);
253         }
254
255         fclose(fp);
256         return ret;
257 }
258
259 int main(int argc, char **argv)
260 {
261         fprintf(stderr, "\nCubemap starting.\n");
262
263         string config_filename = (argc == 1) ? "cubemap.config" : argv[1];
264         vector<ConfigLine> config = parse_config(config_filename);
265
266         // Go through each (parsed) configuration line.
267         int port = -1;
268         for (unsigned i = 0; i < config.size(); ++i) {
269                 if (config[i].keyword == "port") {
270                         if (config[i].parameters.size() > 0 ||
271                             config[i].arguments.size() != 1) {
272                                 fprintf(stderr, "ERROR: 'port' takes one argument and no parameters\n");
273                                 exit(1);
274                         }
275                         port = atoi(config[i].arguments[0].c_str());
276                 }
277         }
278         if (port <= 0 || port > 65535) {
279                 fprintf(stderr, "ERROR: Missing or invalid 'port' statement in config file\n");
280                 exit(1);
281         }
282
283         servers = new ServerPool(NUM_SERVERS);
284
285         int server_sock = -1, old_port = -1;
286         if (argc == 4 && strcmp(argv[2], "-state") == 0) {
287                 fprintf(stderr, "Deserializing state from previous process... ");
288                 int state_fd = atoi(argv[3]);
289                 CubemapStateProto loaded_state = read_tempfile(state_fd);
290
291                 // Deserialize the streams.
292                 for (int i = 0; i < loaded_state.streams_size(); ++i) {
293                         servers->add_stream_from_serialized(loaded_state.streams(i));
294                 }
295
296                 // Put back the existing clients. It doesn't matter which server we
297                 // allocate them to, so just do round-robin.
298                 for (int i = 0; i < loaded_state.clients_size(); ++i) {
299                         servers->add_client_from_serialized(loaded_state.clients(i));
300                 }
301
302                 // Deserialize the server socket.
303                 server_sock = loaded_state.server_sock();
304                 old_port = loaded_state.port();
305
306                 fprintf(stderr, "done.\n");
307         } else{
308                 // TODO: This should come from the config file.
309                 servers->add_stream(STREAM_ID);
310         }
311
312         // Open a new server socket if we do not already have one, or if we changed ports.
313         if (server_sock != -1 && port != old_port) {
314                 fprintf(stderr, "NOTE: Port changed from %d to %d; opening new socket.\n", old_port, port);
315                 close(server_sock);
316                 server_sock = -1;
317         }
318         if (server_sock == -1) {
319                 server_sock = create_server_socket(port);
320         }
321
322         servers->run();
323
324         pthread_t acceptor_thread;
325         pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
326
327         // TODO: This should come from the config file.
328         Input input(STREAM_ID, STREAM_URL);
329         input.run();
330
331         signal(SIGHUP, hup);
332
333         while (!hupped) {
334                 usleep(100000);
335         }
336
337         input.stop();
338
339         CubemapStateProto state;
340         state.set_server_sock(server_sock);
341         state.set_port(port);
342         for (int i = 0; i < NUM_SERVERS; ++i) { 
343                 servers->get_server(i)->stop();
344
345                 CubemapStateProto local_state = servers->get_server(i)->serialize();
346
347                 // The stream state should be identical between the servers, so we only store it once.
348                 if (i == 0) {
349                         state.mutable_streams()->MergeFrom(local_state.streams());
350                 }
351                 for (int j = 0; j < local_state.clients_size(); ++j) {
352                         state.add_clients()->MergeFrom(local_state.clients(j));
353                 }
354         }
355         delete servers;
356
357         fprintf(stderr, "Serializing state and re-execing...\n");
358         int state_fd = make_tempfile(state);
359
360         char buf[16];
361         sprintf(buf, "%d", state_fd);
362
363         for ( ;; ) {
364                 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
365                 perror("execlp");
366                 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);
367                 usleep(200000);
368         }
369 }