6 #include <sys/socket.h>
22 #include "serverpool.h"
26 #define STREAM_ID "stream"
27 #define STREAM_URL "http://gruessi.zrh.sesse.net:4013/"
31 ServerPool *servers = NULL;
32 volatile bool hupped = false;
39 int create_server_socket(int port)
41 int server_sock = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
42 if (server_sock == -1) {
48 if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) {
49 perror("setsockopt(SO_REUSEADDR)");
53 // We want dual-stack sockets. (Sorry, OpenBSD and Windows XP...)
55 if (setsockopt(server_sock, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof(zero)) == -1) {
56 perror("setsockopt(IPV6_V6ONLY)");
60 // Set as non-blocking, so the acceptor thread can notice that we want to shut it down.
61 if (ioctl(server_sock, FIONBIO, &one) == -1) {
62 perror("ioctl(FIONBIO)");
67 memset(&addr, 0, sizeof(addr));
68 addr.sin6_family = AF_INET6;
69 addr.sin6_port = htons(port);
71 if (bind(server_sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
76 if (listen(server_sock, 128) == -1) {
84 void *acceptor_thread_run(void *arg)
86 int server_sock = int(intptr_t(arg));
88 // Since we are non-blocking, we need to wait for the right state first.
89 // Wait up to 50 ms, then check hupped.
94 int nfds = poll(&pfd, 1, 50);
95 if (nfds == 0 || (nfds == -1 && errno == EAGAIN)) {
105 socklen_t addrlen = sizeof(addr);
108 int sock = accept(server_sock, reinterpret_cast<sockaddr *>(&addr), &addrlen);
109 if (sock == -1 && errno == EINTR) {
118 // Set the socket as nonblocking.
120 if (ioctl(sock, FIONBIO, &one) == -1) {
125 // Pick a server, round-robin, and hand over the socket to it.
126 servers->add_client(sock);
131 // Serialize the given state to a file descriptor, and return the (still open)
133 int make_tempfile(const CubemapStateProto &state)
135 char tmpl[] = "/tmp/cubemapstate.XXXXXX";
136 int state_fd = mkstemp(tmpl);
137 if (state_fd == -1) {
143 state.SerializeToString(&serialized);
145 const char *ptr = serialized.data();
146 size_t to_write = serialized.size();
147 while (to_write > 0) {
148 ssize_t ret = write(state_fd, ptr, to_write);
161 // Read the state back from the file descriptor made by make_tempfile,
163 CubemapStateProto read_tempfile(int state_fd)
165 if (lseek(state_fd, 0, SEEK_SET) == -1) {
173 ssize_t ret = read(state_fd, buf, sizeof(buf));
183 serialized.append(string(buf, buf + ret));
186 close(state_fd); // Implicitly deletes the file.
188 CubemapStateProto state;
189 if (!state.ParseFromString(serialized)) {
190 fprintf(stderr, "PANIC: Failed deserialization of state.\n");
197 int main(int argc, char **argv)
199 fprintf(stderr, "\nCubemap starting.\n");
201 string config_filename = (argc == 1) ? "cubemap.config" : argv[1];
202 vector<ConfigLine> config = parse_config(config_filename);
204 int port = fetch_config_int(config, "port", 1, 65535);
205 int num_servers = fetch_config_int(config, "num_servers", 1, 20000); // Insanely high max limit.
207 servers = new ServerPool(num_servers);
209 int server_sock = -1, old_port = -1;
210 set<string> deserialized_stream_ids;
211 map<string, Input *> deserialized_inputs;
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 inputs. Note that we don't actually add them to any state yet.
230 for (int i = 0; i < loaded_state.inputs_size(); ++i) {
231 deserialized_inputs.insert(make_pair(
232 loaded_state.inputs(i).stream_id(),
233 new Input(loaded_state.inputs(i))));
236 // Deserialize the server socket.
237 server_sock = loaded_state.server_sock();
238 old_port = loaded_state.port();
240 fprintf(stderr, "done.\n");
243 // Find all streams in the configuration file, and create them.
244 set<string> expecting_stream_ids = deserialized_stream_ids;
245 for (unsigned i = 0; i < config.size(); ++i) {
246 if (config[i].keyword != "stream") {
249 if (config[i].arguments.size() != 1) {
250 fprintf(stderr, "ERROR: 'stream' takes exactly one argument\n");
253 string stream_id = config[i].arguments[0];
254 if (deserialized_stream_ids.count(stream_id) == 0) {
255 servers->add_stream(stream_id);
257 expecting_stream_ids.erase(stream_id);
260 // Warn about any servers we've lost.
261 // TODO: Make an option (delete=yes?) to actually shut down streams.
262 for (set<string>::const_iterator stream_it = expecting_stream_ids.begin();
263 stream_it != expecting_stream_ids.end();
265 string stream_id = *stream_it;
266 fprintf(stderr, "WARNING: stream '%s' disappeared from the configuration file.\n",
268 fprintf(stderr, " It will not be deleted, but clients will not get any new inputs.\n");
269 if (deserialized_inputs.count(stream_id) != 0) {
270 delete deserialized_inputs[stream_id];
271 deserialized_inputs.erase(stream_id);
275 // Open a new server socket if we do not already have one, or if we changed ports.
276 if (server_sock != -1 && port != old_port) {
277 fprintf(stderr, "NOTE: Port changed from %d to %d; opening new socket.\n", old_port, port);
281 if (server_sock == -1) {
282 server_sock = create_server_socket(port);
287 pthread_t acceptor_thread;
288 pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
290 // Find all streams in the configuration file, and create inputs for them.
291 vector<Input *> inputs;
292 for (unsigned i = 0; i < config.size(); ++i) {
293 if (config[i].keyword != "stream") {
296 assert(config[i].arguments.size() == 1);
297 string stream_id = config[i].arguments[0];
299 if (config[i].parameters.count("src") == 0) {
300 fprintf(stderr, "WARNING: stream '%s' has no src= attribute, clients will not get any data.\n",
305 string src = config[i].parameters["src"];
307 if (deserialized_inputs.count(stream_id) != 0) {
308 input = deserialized_inputs[stream_id];
309 if (input->get_url() != src) {
310 fprintf(stderr, "INFO: Stream '%s' has changed URL from '%s' to '%s', restarting input.\n",
311 stream_id.c_str(), input->get_url().c_str(), src.c_str());
315 deserialized_inputs.erase(stream_id);
318 input = new Input(stream_id, src);
321 inputs.push_back(input);
324 // All deserialized inputs should now have been taken care of, one way or the other.
325 assert(deserialized_inputs.empty());
333 // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
334 if (pthread_join(acceptor_thread, NULL) == -1) {
335 perror("pthread_join");
339 CubemapStateProto state;
340 state.set_server_sock(server_sock);
341 state.set_port(port);
343 for (size_t i = 0; i < inputs.size(); ++i) {
345 state.add_inputs()->MergeFrom(inputs[i]->serialize());
348 for (int i = 0; i < num_servers; ++i) {
349 servers->get_server(i)->stop();
351 CubemapStateProto local_state = servers->get_server(i)->serialize();
353 // The stream state should be identical between the servers, so we only store it once.
355 state.mutable_streams()->MergeFrom(local_state.streams());
357 for (int j = 0; j < local_state.clients_size(); ++j) {
358 state.add_clients()->MergeFrom(local_state.clients(j));
363 fprintf(stderr, "Serializing state and re-execing...\n");
364 int state_fd = make_tempfile(state);
367 sprintf(buf, "%d", state_fd);
370 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
372 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);