]> git.sesse.net Git - cubemap/blob - cubemap.cpp
Support parsing streams from config file. Also support multiple streams (includes...
[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
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         sockaddr_in6 addr;
61         memset(&addr, 0, sizeof(addr));
62         addr.sin6_family = AF_INET6;
63         addr.sin6_port = htons(port);
64
65         if (bind(server_sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
66                 perror("bind");
67                 exit(1);
68         }
69
70         if (listen(server_sock, 128) == -1) {
71                 perror("listen");
72                 exit(1);
73         }
74
75         return server_sock;
76 }
77
78 void *acceptor_thread_run(void *arg)
79 {
80         int server_sock = int(intptr_t(arg));
81         int num_accepted = 0;
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                 ++num_accepted; 
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         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                 // TODO: Pick up new streams from the configuration file.
195                 for (int i = 0; i < loaded_state.streams_size(); ++i) {
196                         servers->add_stream_from_serialized(loaded_state.streams(i));
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         } else {
211                 // Find all streams in the configuration file, and create them.
212                 for (unsigned i = 0; i < config.size(); ++i) {
213                         if (config[i].keyword != "stream") {
214                                 continue;
215                         }
216                         if (config[i].arguments.size() != 1) {
217                                 fprintf(stderr, "ERROR: 'stream' takes exactly one argument\n");
218                                 exit(1);
219                         }
220                         string stream_id = config[i].arguments[0];
221                         servers->add_stream(stream_id);
222                 }
223         }
224
225         // Open a new server socket if we do not already have one, or if we changed ports.
226         if (server_sock != -1 && port != old_port) {
227                 fprintf(stderr, "NOTE: Port changed from %d to %d; opening new socket.\n", old_port, port);
228                 close(server_sock);
229                 server_sock = -1;
230         }
231         if (server_sock == -1) {
232                 server_sock = create_server_socket(port);
233         }
234
235         servers->run();
236
237         pthread_t acceptor_thread;
238         pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
239
240         // Find all streams in the configuration file, and create inputs for them.
241         vector<Input *> inputs;
242         for (unsigned i = 0; i < config.size(); ++i) {
243                 if (config[i].keyword != "stream") {
244                         continue;
245                 }
246                 assert(config[i].arguments.size() == 1);
247                 string stream_id = config[i].arguments[0];
248
249                 if (config[i].parameters.count("src") == 0) {
250                         fprintf(stderr, "WARNING: stream '%s' has no src= attribute, clients will not get any data.\n",
251                                 stream_id.c_str());
252                         continue;
253                 }
254
255                 string src = config[i].parameters["src"];
256                 Input *input = new Input(stream_id, src);
257                 input->run();
258                 inputs.push_back(input);
259         }
260
261         signal(SIGHUP, hup);
262
263         while (!hupped) {
264                 usleep(100000);
265         }
266
267         // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
268         for (size_t i = 0; i < inputs.size(); ++i) {
269                 inputs[i]->stop();
270                 delete inputs[i];  // TODO: serialize instead of using libcurl.
271         }
272
273         CubemapStateProto state;
274         state.set_server_sock(server_sock);
275         state.set_port(port);
276         for (int i = 0; i < num_servers; ++i) { 
277                 servers->get_server(i)->stop();
278
279                 CubemapStateProto local_state = servers->get_server(i)->serialize();
280
281                 // The stream state should be identical between the servers, so we only store it once.
282                 if (i == 0) {
283                         state.mutable_streams()->MergeFrom(local_state.streams());
284                 }
285                 for (int j = 0; j < local_state.clients_size(); ++j) {
286                         state.add_clients()->MergeFrom(local_state.clients(j));
287                 }
288         }
289         delete servers;
290
291         fprintf(stderr, "Serializing state and re-execing...\n");
292         int state_fd = make_tempfile(state);
293
294         char buf[16];
295         sprintf(buf, "%d", state_fd);
296
297         for ( ;; ) {
298                 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
299                 perror("execlp");
300                 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);
301                 usleep(200000);
302         }
303 }