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