]> git.sesse.net Git - cubemap/blob - main.cpp
Rename cubemap.cpp to main.cpp. Aaaa....
[cubemap] / main.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         map<string, Input *> deserialized_inputs;
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 inputs. Note that we don't actually add them to any state yet.
230                 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
231                         deserialized_inputs.insert(make_pair(
232                                 loaded_state.inputs(i).stream_id(),
233                                 new Input(loaded_state.inputs(i))));
234                 } 
235
236                 // Deserialize the server socket.
237                 server_sock = loaded_state.server_sock();
238                 old_port = loaded_state.port();
239
240                 fprintf(stderr, "done.\n");
241         }
242
243         // Find all streams in the configuration file, and create them.
244         set<string> expecting_stream_ids = deserialized_stream_ids;
245         for (unsigned i = 0; i < config.size(); ++i) {
246                 if (config[i].keyword != "stream") {
247                         continue;
248                 }
249                 if (config[i].arguments.size() != 1) {
250                         fprintf(stderr, "ERROR: 'stream' takes exactly one argument\n");
251                         exit(1);
252                 }
253                 string stream_id = config[i].arguments[0];
254                 if (deserialized_stream_ids.count(stream_id) == 0) {
255                         servers->add_stream(stream_id);
256                 }
257                 expecting_stream_ids.erase(stream_id);
258         }
259
260         // Warn about any servers we've lost.
261         // TODO: Make an option (delete=yes?) to actually shut down streams.
262         for (set<string>::const_iterator stream_it = expecting_stream_ids.begin();
263              stream_it != expecting_stream_ids.end();
264              ++stream_it) {
265                 string stream_id = *stream_it;
266                 fprintf(stderr, "WARNING: stream '%s' disappeared from the configuration file.\n",
267                         stream_id.c_str());
268                 fprintf(stderr, "         It will not be deleted, but clients will not get any new inputs.\n");
269                 if (deserialized_inputs.count(stream_id) != 0) {
270                         delete deserialized_inputs[stream_id];
271                         deserialized_inputs.erase(stream_id);
272                 }
273         }
274
275         // Open a new server socket if we do not already have one, or if we changed ports.
276         if (server_sock != -1 && port != old_port) {
277                 fprintf(stderr, "NOTE: Port changed from %d to %d; opening new socket.\n", old_port, port);
278                 close(server_sock);
279                 server_sock = -1;
280         }
281         if (server_sock == -1) {
282                 server_sock = create_server_socket(port);
283         }
284
285         servers->run();
286
287         pthread_t acceptor_thread;
288         pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
289
290         // Find all streams in the configuration file, and create inputs for them.
291         vector<Input *> inputs;
292         for (unsigned i = 0; i < config.size(); ++i) {
293                 if (config[i].keyword != "stream") {
294                         continue;
295                 }
296                 assert(config[i].arguments.size() == 1);
297                 string stream_id = config[i].arguments[0];
298
299                 if (config[i].parameters.count("src") == 0) {
300                         fprintf(stderr, "WARNING: stream '%s' has no src= attribute, clients will not get any data.\n",
301                                 stream_id.c_str());
302                         continue;
303                 }
304
305                 string src = config[i].parameters["src"];
306                 Input *input = NULL;
307                 if (deserialized_inputs.count(stream_id) != 0) {
308                         input = deserialized_inputs[stream_id];
309                         if (input->get_url() != src) {
310                                 fprintf(stderr, "INFO: Stream '%s' has changed URL from '%s' to '%s', restarting input.\n",
311                                         stream_id.c_str(), input->get_url().c_str(), src.c_str());
312                                 delete input;
313                                 input = NULL;
314                         }
315                         deserialized_inputs.erase(stream_id);
316                 }
317                 if (input == NULL) {
318                         input = new Input(stream_id, src);
319                 }
320                 input->run();
321                 inputs.push_back(input);
322         }
323
324         // All deserialized inputs should now have been taken care of, one way or the other.
325         assert(deserialized_inputs.empty());
326
327         signal(SIGHUP, hup);
328
329         while (!hupped) {
330                 usleep(100000);
331         }
332
333         // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
334         if (pthread_join(acceptor_thread, NULL) == -1) {
335                 perror("pthread_join");
336                 exit(1);
337         }
338
339         CubemapStateProto state;
340         state.set_server_sock(server_sock);
341         state.set_port(port);
342
343         for (size_t i = 0; i < inputs.size(); ++i) {
344                 inputs[i]->stop();
345                 state.add_inputs()->MergeFrom(inputs[i]->serialize());
346         }
347
348         for (int i = 0; i < num_servers; ++i) { 
349                 servers->get_server(i)->stop();
350
351                 CubemapStateProto local_state = servers->get_server(i)->serialize();
352
353                 // The stream state should be identical between the servers, so we only store it once.
354                 if (i == 0) {
355                         state.mutable_streams()->MergeFrom(local_state.streams());
356                 }
357                 for (int j = 0; j < local_state.clients_size(); ++j) {
358                         state.add_clients()->MergeFrom(local_state.clients(j));
359                 }
360         }
361         delete servers;
362
363         fprintf(stderr, "Serializing state and re-execing...\n");
364         int state_fd = make_tempfile(state);
365
366         char buf[16];
367         sprintf(buf, "%d", state_fd);
368
369         for ( ;; ) {
370                 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
371                 perror("execlp");
372                 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);
373                 usleep(200000);
374         }
375 }