]> git.sesse.net Git - cubemap/blob - cubemap.cpp
Parse a config file. Not used for anything yet.
[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 "input.h"
22 #include "state.pb.h"
23
24 #define NUM_SERVERS 4
25 #define STREAM_ID "stream"
26 #define STREAM_URL "http://gruessi.zrh.sesse.net:4013/"
27 #define PORT 9094
28
29 using namespace std;
30
31 Server *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[num_accepted % NUM_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 }
257
258 int main(int argc, char **argv)
259 {
260         fprintf(stderr, "\nCubemap starting.\n");
261
262         string config_filename = (argc == 1) ? "cubemap.config" : argv[1];
263         vector<ConfigLine> config = parse_config(config_filename);
264
265         servers = new Server[NUM_SERVERS];
266
267         int server_sock;
268         if (argc == 4 && strcmp(argv[2], "-state") == 0) {
269                 fprintf(stderr, "Deserializing state from previous process... ");
270                 int state_fd = atoi(argv[3]);
271                 CubemapStateProto loaded_state = read_tempfile(state_fd);
272
273                 // Deserialize the streams.
274                 for (int i = 0; i < loaded_state.streams_size(); ++i) {
275                         for (int j = 0; j < NUM_SERVERS; ++j) {
276                                 servers[j].add_stream_from_serialized(loaded_state.streams(i));
277                         }
278                 }
279
280                 // Put back the existing clients. It doesn't matter which server we
281                 // allocate them to, so just do round-robin.
282                 for (int i = 0; i < loaded_state.clients_size(); ++i) {
283                         servers[i % NUM_SERVERS].add_client_from_serialized(loaded_state.clients(i));
284                 }
285
286                 // Deserialize the server socket.
287                 server_sock = loaded_state.server_sock();
288
289                 fprintf(stderr, "done.\n");
290         } else {
291                 // TODO: This should come from a config file.
292                 server_sock = create_server_socket(PORT);
293                 for (int i = 0; i < NUM_SERVERS; ++i) {
294                         servers[i].add_stream(STREAM_ID);
295                 }
296         }
297
298         for (int i = 0; i < NUM_SERVERS; ++i) {
299                 servers[i].run();
300         }
301
302         pthread_t acceptor_thread;
303         pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
304
305         Input input(STREAM_ID, STREAM_URL);
306         input.run();
307
308         signal(SIGHUP, hup);
309
310         while (!hupped) {
311                 usleep(100000);
312         }
313
314         input.stop();
315
316         CubemapStateProto state;
317         state.set_server_sock(server_sock);
318         for (int i = 0; i < NUM_SERVERS; ++i) {
319                 servers[i].stop();
320
321                 CubemapStateProto local_state = servers[i].serialize();
322
323                 // The stream state should be identical between the servers, so we only store it once.
324                 if (i == 0) {
325                         state.mutable_streams()->MergeFrom(local_state.streams());
326                 }
327                 for (int j = 0; j < local_state.clients_size(); ++j) {
328                         state.add_clients()->MergeFrom(local_state.clients(j));
329                 }
330         }
331         delete[] servers;
332
333         fprintf(stderr, "Serializing state and re-execing...\n");
334         int state_fd = make_tempfile(state);
335
336         char buf[16];
337         sprintf(buf, "%d", state_fd);
338
339         for ( ;; ) {
340                 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
341                 perror("execlp");
342                 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);
343                 usleep(200000);
344         }
345 }