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