]> git.sesse.net Git - cubemap/blob - cubemap.cpp
008126c5c97273762b5144cf8a9d077efc940b5d
[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 #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         sockaddr_in6 addr;
62         memset(&addr, 0, sizeof(addr));
63         addr.sin6_family = AF_INET6;
64         addr.sin6_port = htons(port);
65
66         if (bind(server_sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
67                 perror("bind");
68                 exit(1);
69         }
70
71         if (listen(server_sock, 128) == -1) {
72                 perror("listen");
73                 exit(1);
74         }
75
76         return server_sock;
77 }
78
79 void *acceptor_thread_run(void *arg)
80 {
81         int server_sock = int(intptr_t(arg));
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                         usleep(100000);
94                         continue;
95                 }
96
97                 // Set the socket as nonblocking.
98                 int one = 1;
99                 if (ioctl(sock, FIONBIO, &one) == -1) {
100                         perror("FIONBIO");
101                         exit(1);
102                 }
103
104                 // Pick a server, round-robin, and hand over the socket to it.
105                 servers->add_client(sock);
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 int main(int argc, char **argv)
176 {
177         fprintf(stderr, "\nCubemap starting.\n");
178
179         string config_filename = (argc == 1) ? "cubemap.config" : argv[1];
180         vector<ConfigLine> config = parse_config(config_filename);
181
182         int port = fetch_config_int(config, "port", 1, 65535);
183         int num_servers = fetch_config_int(config, "num_servers", 1, 20000);  // Insanely high max limit.
184
185         servers = new ServerPool(num_servers);
186
187         int server_sock = -1, old_port = -1;
188         set<string> deserialized_stream_ids;
189         if (argc == 4 && strcmp(argv[2], "-state") == 0) {
190                 fprintf(stderr, "Deserializing state from previous process... ");
191                 int state_fd = atoi(argv[3]);
192                 CubemapStateProto loaded_state = read_tempfile(state_fd);
193
194                 // Deserialize the streams.
195                 for (int i = 0; i < loaded_state.streams_size(); ++i) {
196                         servers->add_stream_from_serialized(loaded_state.streams(i));
197                         deserialized_stream_ids.insert(loaded_state.streams(i).stream_id());
198                 }
199
200                 // Put back the existing clients. It doesn't matter which server we
201                 // allocate them to, so just do round-robin.
202                 for (int i = 0; i < loaded_state.clients_size(); ++i) {
203                         servers->add_client_from_serialized(loaded_state.clients(i));
204                 }
205
206                 // Deserialize the server socket.
207                 server_sock = loaded_state.server_sock();
208                 old_port = loaded_state.port();
209
210                 fprintf(stderr, "done.\n");
211         }
212
213         // Find all streams in the configuration file, and create them.
214         set<string> expecting_stream_ids = deserialized_stream_ids;
215         for (unsigned i = 0; i < config.size(); ++i) {
216                 if (config[i].keyword != "stream") {
217                         continue;
218                 }
219                 if (config[i].arguments.size() != 1) {
220                         fprintf(stderr, "ERROR: 'stream' takes exactly one argument\n");
221                         exit(1);
222                 }
223                 string stream_id = config[i].arguments[0];
224                 if (deserialized_stream_ids.count(stream_id) == 0) {
225                         servers->add_stream(stream_id);
226                 }
227                 expecting_stream_ids.erase(stream_id);
228         }
229
230         // Warn about any servers we've lost.
231         // TODO: Make an option (delete=yes?) to actually shut down streams.
232         for (set<string>::const_iterator stream_it = expecting_stream_ids.begin();
233              stream_it != expecting_stream_ids.end();
234              ++stream_it) {
235                 fprintf(stderr, "WARNING: stream '%s' disappeared from the configuration file.\n",
236                         stream_it->c_str());
237                 fprintf(stderr, "         It will not be deleted, but clients will not get any new inputs.\n");
238         }
239
240         // Open a new server socket if we do not already have one, or if we changed ports.
241         if (server_sock != -1 && port != old_port) {
242                 fprintf(stderr, "NOTE: Port changed from %d to %d; opening new socket.\n", old_port, port);
243                 close(server_sock);
244                 server_sock = -1;
245         }
246         if (server_sock == -1) {
247                 server_sock = create_server_socket(port);
248         }
249
250         servers->run();
251
252         pthread_t acceptor_thread;
253         pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
254
255         // Find all streams in the configuration file, and create inputs for them.
256         vector<Input *> inputs;
257         for (unsigned i = 0; i < config.size(); ++i) {
258                 if (config[i].keyword != "stream") {
259                         continue;
260                 }
261                 assert(config[i].arguments.size() == 1);
262                 string stream_id = config[i].arguments[0];
263
264                 if (config[i].parameters.count("src") == 0) {
265                         fprintf(stderr, "WARNING: stream '%s' has no src= attribute, clients will not get any data.\n",
266                                 stream_id.c_str());
267                         continue;
268                 }
269
270                 string src = config[i].parameters["src"];
271                 Input *input = new Input(stream_id, src);
272                 input->run();
273                 inputs.push_back(input);
274         }
275
276         signal(SIGHUP, hup);
277
278         while (!hupped) {
279                 usleep(100000);
280         }
281
282         // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
283         for (size_t i = 0; i < inputs.size(); ++i) {
284                 inputs[i]->stop();
285                 delete inputs[i];  // TODO: serialize instead of using libcurl.
286         }
287
288         CubemapStateProto state;
289         state.set_server_sock(server_sock);
290         state.set_port(port);
291         for (int i = 0; i < num_servers; ++i) { 
292                 servers->get_server(i)->stop();
293
294                 CubemapStateProto local_state = servers->get_server(i)->serialize();
295
296                 // The stream state should be identical between the servers, so we only store it once.
297                 if (i == 0) {
298                         state.mutable_streams()->MergeFrom(local_state.streams());
299                 }
300                 for (int j = 0; j < local_state.clients_size(); ++j) {
301                         state.add_clients()->MergeFrom(local_state.clients(j));
302                 }
303         }
304         delete servers;
305
306         fprintf(stderr, "Serializing state and re-execing...\n");
307         int state_fd = make_tempfile(state);
308
309         char buf[16];
310         sprintf(buf, "%d", state_fd);
311
312         for ( ;; ) {
313                 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
314                 perror("execlp");
315                 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);
316                 usleep(200000);
317         }
318 }