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