]> git.sesse.net Git - cubemap/blob - cubemap.cpp
Write our own HTTP client instead of using curl. Not finished yet (missing URL parsin...
[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 <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 <vector>
15 #include <string>
16 #include <map>
17 #include <set>
18
19 #include "metacube.h"
20 #include "parse.h"
21 #include "server.h"
22 #include "serverpool.h"
23 #include "input.h"
24 #include "state.pb.h"
25
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         // 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 == EAGAIN)) {
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 // Serialize the given state to a file descriptor, and return the (still open)
132 // descriptor.
133 int make_tempfile(const CubemapStateProto &state)
134 {
135         char tmpl[] = "/tmp/cubemapstate.XXXXXX";
136         int state_fd = mkstemp(tmpl);
137         if (state_fd == -1) {
138                 perror("mkstemp");
139                 exit(1);
140         }
141
142         string serialized;
143         state.SerializeToString(&serialized);
144
145         const char *ptr = serialized.data();
146         size_t to_write = serialized.size();
147         while (to_write > 0) {
148                 ssize_t ret = write(state_fd, ptr, to_write);
149                 if (ret == -1) {
150                         perror("write");
151                         exit(1);
152                 }
153
154                 ptr += ret;
155                 to_write -= ret;
156         }
157
158         return state_fd;
159 }
160
161 // Read the state back from the file descriptor made by make_tempfile,
162 // and close it.
163 CubemapStateProto read_tempfile(int state_fd)
164 {
165         if (lseek(state_fd, 0, SEEK_SET) == -1) {
166                 perror("lseek");
167                 exit(1);
168         }
169
170         string serialized;
171         char buf[4096];
172         for ( ;; ) {
173                 ssize_t ret = read(state_fd, buf, sizeof(buf));
174                 if (ret == -1) {
175                         perror("read");
176                         exit(1);
177                 }
178                 if (ret == 0) {
179                         // EOF.
180                         break;
181                 }
182
183                 serialized.append(string(buf, buf + ret));
184         }
185
186         close(state_fd);  // Implicitly deletes the file.
187
188         CubemapStateProto state;
189         if (!state.ParseFromString(serialized)) {
190                 fprintf(stderr, "PANIC: Failed deserialization of state.\n");
191                 exit(1);
192         }
193
194         return state;
195 }
196
197 int main(int argc, char **argv)
198 {
199         fprintf(stderr, "\nCubemap starting.\n");
200
201         string config_filename = (argc == 1) ? "cubemap.config" : argv[1];
202         vector<ConfigLine> config = parse_config(config_filename);
203
204         int port = fetch_config_int(config, "port", 1, 65535);
205         int num_servers = fetch_config_int(config, "num_servers", 1, 20000);  // Insanely high max limit.
206
207         servers = new ServerPool(num_servers);
208
209         int server_sock = -1, old_port = -1;
210         set<string> deserialized_stream_ids;
211         if (argc == 4 && strcmp(argv[2], "-state") == 0) {
212                 fprintf(stderr, "Deserializing state from previous process... ");
213                 int state_fd = atoi(argv[3]);
214                 CubemapStateProto loaded_state = read_tempfile(state_fd);
215
216                 // Deserialize the streams.
217                 for (int i = 0; i < loaded_state.streams_size(); ++i) {
218                         servers->add_stream_from_serialized(loaded_state.streams(i));
219                         deserialized_stream_ids.insert(loaded_state.streams(i).stream_id());
220                 }
221
222                 // Put back the existing clients. It doesn't matter which server we
223                 // allocate them to, so just do round-robin.
224                 for (int i = 0; i < loaded_state.clients_size(); ++i) {
225                         servers->add_client_from_serialized(loaded_state.clients(i));
226                 }
227
228                 // Deserialize the server socket.
229                 server_sock = loaded_state.server_sock();
230                 old_port = loaded_state.port();
231
232                 fprintf(stderr, "done.\n");
233         }
234
235         // Find all streams in the configuration file, and create them.
236         set<string> expecting_stream_ids = deserialized_stream_ids;
237         for (unsigned i = 0; i < config.size(); ++i) {
238                 if (config[i].keyword != "stream") {
239                         continue;
240                 }
241                 if (config[i].arguments.size() != 1) {
242                         fprintf(stderr, "ERROR: 'stream' takes exactly one argument\n");
243                         exit(1);
244                 }
245                 string stream_id = config[i].arguments[0];
246                 if (deserialized_stream_ids.count(stream_id) == 0) {
247                         servers->add_stream(stream_id);
248                 }
249                 expecting_stream_ids.erase(stream_id);
250         }
251
252         // Warn about any servers we've lost.
253         // TODO: Make an option (delete=yes?) to actually shut down streams.
254         for (set<string>::const_iterator stream_it = expecting_stream_ids.begin();
255              stream_it != expecting_stream_ids.end();
256              ++stream_it) {
257                 fprintf(stderr, "WARNING: stream '%s' disappeared from the configuration file.\n",
258                         stream_it->c_str());
259                 fprintf(stderr, "         It will not be deleted, but clients will not get any new inputs.\n");
260         }
261
262         // Open a new server socket if we do not already have one, or if we changed ports.
263         if (server_sock != -1 && port != old_port) {
264                 fprintf(stderr, "NOTE: Port changed from %d to %d; opening new socket.\n", old_port, port);
265                 close(server_sock);
266                 server_sock = -1;
267         }
268         if (server_sock == -1) {
269                 server_sock = create_server_socket(port);
270         }
271
272         servers->run();
273
274         pthread_t acceptor_thread;
275         pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
276
277         // Find all streams in the configuration file, and create inputs for them.
278         vector<Input *> inputs;
279         for (unsigned i = 0; i < config.size(); ++i) {
280                 if (config[i].keyword != "stream") {
281                         continue;
282                 }
283                 assert(config[i].arguments.size() == 1);
284                 string stream_id = config[i].arguments[0];
285
286                 if (config[i].parameters.count("src") == 0) {
287                         fprintf(stderr, "WARNING: stream '%s' has no src= attribute, clients will not get any data.\n",
288                                 stream_id.c_str());
289                         continue;
290                 }
291
292                 string src = config[i].parameters["src"];
293                 Input *input = new Input(stream_id, src);
294                 input->run();
295                 inputs.push_back(input);
296         }
297
298         signal(SIGHUP, hup);
299
300         while (!hupped) {
301                 usleep(100000);
302         }
303
304         // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
305         for (size_t i = 0; i < inputs.size(); ++i) {
306                 inputs[i]->stop();
307                 delete inputs[i];  // TODO: Serialize.
308         }
309
310         if (pthread_join(acceptor_thread, NULL) == -1) {
311                 perror("pthread_join");
312                 exit(1);
313         }
314
315         CubemapStateProto state;
316         state.set_server_sock(server_sock);
317         state.set_port(port);
318         for (int i = 0; i < num_servers; ++i) { 
319                 servers->get_server(i)->stop();
320
321                 CubemapStateProto local_state = servers->get_server(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 }