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