7 #include <sys/socket.h>
10 #include <sys/ioctl.h>
23 #include "serverpool.h"
27 #define STREAM_ID "stream"
28 #define STREAM_URL "http://gruessi.zrh.sesse.net:4013/"
32 ServerPool *servers = NULL;
33 volatile bool hupped = false;
40 int create_server_socket(int port)
42 int server_sock = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
43 if (server_sock == -1) {
49 if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) {
50 perror("setsockopt(SO_REUSEADDR)");
54 // We want dual-stack sockets. (Sorry, OpenBSD and Windows XP...)
56 if (setsockopt(server_sock, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof(zero)) == -1) {
57 perror("setsockopt(IPV6_V6ONLY)");
61 // Set as non-blocking, so the acceptor thread can notice that we want to shut it down.
62 if (ioctl(server_sock, FIONBIO, &one) == -1) {
63 perror("ioctl(FIONBIO)");
68 memset(&addr, 0, sizeof(addr));
69 addr.sin6_family = AF_INET6;
70 addr.sin6_port = htons(port);
72 if (bind(server_sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
77 if (listen(server_sock, 128) == -1) {
85 void *acceptor_thread_run(void *arg)
87 int server_sock = int(intptr_t(arg));
89 // Since we are non-blocking, we need to wait for the right state first.
90 // Wait up to 50 ms, then check hupped.
95 int nfds = poll(&pfd, 1, 50);
96 if (nfds == 0 || (nfds == -1 && errno == EAGAIN)) {
106 socklen_t addrlen = sizeof(addr);
109 int sock = accept(server_sock, reinterpret_cast<sockaddr *>(&addr), &addrlen);
110 if (sock == -1 && errno == EINTR) {
119 // Set the socket as nonblocking.
121 if (ioctl(sock, FIONBIO, &one) == -1) {
126 // Pick a server, round-robin, and hand over the socket to it.
127 servers->add_client(sock);
132 // Serialize the given state to a file descriptor, and return the (still open)
134 int make_tempfile(const CubemapStateProto &state)
136 char tmpl[] = "/tmp/cubemapstate.XXXXXX";
137 int state_fd = mkstemp(tmpl);
138 if (state_fd == -1) {
144 state.SerializeToString(&serialized);
146 const char *ptr = serialized.data();
147 size_t to_write = serialized.size();
148 while (to_write > 0) {
149 ssize_t ret = write(state_fd, ptr, to_write);
162 // Read the state back from the file descriptor made by make_tempfile,
164 CubemapStateProto read_tempfile(int state_fd)
166 if (lseek(state_fd, 0, SEEK_SET) == -1) {
174 ssize_t ret = read(state_fd, buf, sizeof(buf));
184 serialized.append(string(buf, buf + ret));
187 close(state_fd); // Implicitly deletes the file.
189 CubemapStateProto state;
190 if (!state.ParseFromString(serialized)) {
191 fprintf(stderr, "PANIC: Failed deserialization of state.\n");
198 int main(int argc, char **argv)
200 fprintf(stderr, "\nCubemap starting.\n");
202 string config_filename = (argc == 1) ? "cubemap.config" : argv[1];
203 vector<ConfigLine> config = parse_config(config_filename);
205 int port = fetch_config_int(config, "port", 1, 65535);
206 int num_servers = fetch_config_int(config, "num_servers", 1, 20000); // Insanely high max limit.
208 servers = new ServerPool(num_servers);
210 int server_sock = -1, old_port = -1;
211 set<string> deserialized_stream_ids;
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);
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());
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));
229 // Deserialize the server socket.
230 server_sock = loaded_state.server_sock();
231 old_port = loaded_state.port();
233 fprintf(stderr, "done.\n");
236 // Find all streams in the configuration file, and create them.
237 set<string> expecting_stream_ids = deserialized_stream_ids;
238 for (unsigned i = 0; i < config.size(); ++i) {
239 if (config[i].keyword != "stream") {
242 if (config[i].arguments.size() != 1) {
243 fprintf(stderr, "ERROR: 'stream' takes exactly one argument\n");
246 string stream_id = config[i].arguments[0];
247 if (deserialized_stream_ids.count(stream_id) == 0) {
248 servers->add_stream(stream_id);
250 expecting_stream_ids.erase(stream_id);
253 // Warn about any servers we've lost.
254 // TODO: Make an option (delete=yes?) to actually shut down streams.
255 for (set<string>::const_iterator stream_it = expecting_stream_ids.begin();
256 stream_it != expecting_stream_ids.end();
258 fprintf(stderr, "WARNING: stream '%s' disappeared from the configuration file.\n",
260 fprintf(stderr, " It will not be deleted, but clients will not get any new inputs.\n");
263 // Open a new server socket if we do not already have one, or if we changed ports.
264 if (server_sock != -1 && port != old_port) {
265 fprintf(stderr, "NOTE: Port changed from %d to %d; opening new socket.\n", old_port, port);
269 if (server_sock == -1) {
270 server_sock = create_server_socket(port);
275 pthread_t acceptor_thread;
276 pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
278 // Find all streams in the configuration file, and create inputs for them.
279 vector<Input *> inputs;
280 for (unsigned i = 0; i < config.size(); ++i) {
281 if (config[i].keyword != "stream") {
284 assert(config[i].arguments.size() == 1);
285 string stream_id = config[i].arguments[0];
287 if (config[i].parameters.count("src") == 0) {
288 fprintf(stderr, "WARNING: stream '%s' has no src= attribute, clients will not get any data.\n",
293 string src = config[i].parameters["src"];
294 Input *input = new Input(stream_id, src);
296 inputs.push_back(input);
305 // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
306 for (size_t i = 0; i < inputs.size(); ++i) {
308 delete inputs[i]; // TODO: serialize instead of using libcurl.
311 if (pthread_join(acceptor_thread, NULL) == -1) {
312 perror("pthread_join");
316 CubemapStateProto state;
317 state.set_server_sock(server_sock);
318 state.set_port(port);
319 for (int i = 0; i < num_servers; ++i) {
320 servers->get_server(i)->stop();
322 CubemapStateProto local_state = servers->get_server(i)->serialize();
324 // The stream state should be identical between the servers, so we only store it once.
326 state.mutable_streams()->MergeFrom(local_state.streams());
328 for (int j = 0; j < local_state.clients_size(); ++j) {
329 state.add_clients()->MergeFrom(local_state.clients(j));
334 fprintf(stderr, "Serializing state and re-execing...\n");
335 int state_fd = make_tempfile(state);
338 sprintf(buf, "%d", state_fd);
341 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
343 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);