7 #include <sys/socket.h>
10 #include <sys/ioctl.h>
11 #include <sys/epoll.h>
21 #include "serverpool.h"
25 #define STREAM_ID "stream"
26 #define STREAM_URL "http://gruessi.zrh.sesse.net:4013/"
30 ServerPool *servers = NULL;
31 volatile bool hupped = false;
38 int create_server_socket(int port)
40 int server_sock = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
41 if (server_sock == -1) {
47 if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) {
48 perror("setsockopt(SO_REUSEADDR)");
52 // We want dual-stack sockets. (Sorry, OpenBSD and Windows XP...)
54 if (setsockopt(server_sock, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof(zero)) == -1) {
55 perror("setsockopt(IPV6_V6ONLY)");
60 memset(&addr, 0, sizeof(addr));
61 addr.sin6_family = AF_INET6;
62 addr.sin6_port = htons(port);
64 if (bind(server_sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
69 if (listen(server_sock, 128) == -1) {
77 void *acceptor_thread_run(void *arg)
79 int server_sock = int(intptr_t(arg));
83 socklen_t addrlen = sizeof(addr);
86 int sock = accept(server_sock, reinterpret_cast<sockaddr *>(&addr), &addrlen);
87 if (sock == -1 && errno == EINTR) {
95 // Set the socket as nonblocking.
97 if (ioctl(sock, FIONBIO, &one) == -1) {
102 // Pick a server, round-robin, and hand over the socket to it.
103 servers->add_client(sock);
108 // Serialize the given state to a file descriptor, and return the (still open)
110 int make_tempfile(const CubemapStateProto &state)
112 char tmpl[] = "/tmp/cubemapstate.XXXXXX";
113 int state_fd = mkstemp(tmpl);
114 if (state_fd == -1) {
120 state.SerializeToString(&serialized);
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);
138 // Read the state back from the file descriptor made by make_tempfile,
140 CubemapStateProto read_tempfile(int state_fd)
142 if (lseek(state_fd, 0, SEEK_SET) == -1) {
150 ssize_t ret = read(state_fd, buf, sizeof(buf));
160 serialized.append(string(buf, buf + ret));
163 close(state_fd); // Implicitly deletes the file.
165 CubemapStateProto state;
166 if (!state.ParseFromString(serialized)) {
167 fprintf(stderr, "PANIC: Failed deserialization of state.\n");
174 // Split a line on whitespace, e.g. "foo bar baz" -> {"foo", "bar", "baz"}.
175 vector<string> split_tokens(const string &line)
178 string current_token;
180 for (size_t i = 0; i < line.size(); ++i) {
181 if (isspace(line[i])) {
182 if (!current_token.empty()) {
183 ret.push_back(current_token);
185 current_token.clear();
187 current_token.push_back(line[i]);
190 if (!current_token.empty()) {
191 ret.push_back(current_token);
198 vector<string> arguments;
199 map<string, string> parameters;
202 // Parse the configuration file.
203 vector<ConfigLine> parse_config(const string &filename)
205 vector<ConfigLine> ret;
207 FILE *fp = fopen(filename.c_str(), "r");
209 perror(filename.c_str());
215 if (fgets(buf, sizeof(buf), fp) == NULL) {
219 // Chop off the string at the first #, \r or \n.
220 buf[strcspn(buf, "#\r\n")] = 0;
222 // Remove all whitespace from the end of the string.
223 size_t len = strlen(buf);
224 while (len > 0 && isspace(buf[len - 1])) {
228 // If the line is now all blank, ignore it.
233 vector<string> tokens = split_tokens(buf);
234 assert(!tokens.empty());
237 line.keyword = tokens[0];
239 for (size_t i = 1; i < tokens.size(); ++i) {
240 // foo=bar is a parameter; anything else is an argument.
241 size_t equals_pos = tokens[i].find_first_of('=');
242 if (equals_pos == string::npos) {
243 line.arguments.push_back(tokens[i]);
245 string key = tokens[i].substr(0, equals_pos);
246 string value = tokens[i].substr(equals_pos + 1, string::npos);
247 line.parameters.insert(make_pair(key, value));
258 int main(int argc, char **argv)
260 fprintf(stderr, "\nCubemap starting.\n");
262 string config_filename = (argc == 1) ? "cubemap.config" : argv[1];
263 vector<ConfigLine> config = parse_config(config_filename);
265 // Go through each (parsed) configuration line.
266 int port = -1, num_servers = -1;
267 for (unsigned i = 0; i < config.size(); ++i) {
268 if (config[i].keyword == "port") {
269 if (config[i].parameters.size() > 0 ||
270 config[i].arguments.size() != 1) {
271 fprintf(stderr, "ERROR: 'port' takes one argument and no parameters\n");
274 port = atoi(config[i].arguments[0].c_str());
276 if (config[i].keyword == "num_servers") {
277 if (config[i].parameters.size() > 0 ||
278 config[i].arguments.size() != 1) {
279 fprintf(stderr, "ERROR: 'num_servers' takes one argument and no parameters\n");
282 num_servers = atoi(config[i].arguments[0].c_str());
285 if (port <= 0 || port > 65535) {
286 fprintf(stderr, "ERROR: Missing or invalid 'port' statement in config file\n");
289 if (num_servers <= 0 || num_servers > 20000) { // 20000 is an insanely high max limit.
290 fprintf(stderr, "ERROR: Missing or invalid 'num_servers' statement in config file\n");
294 servers = new ServerPool(num_servers);
296 int server_sock = -1, old_port = -1;
297 if (argc == 4 && strcmp(argv[2], "-state") == 0) {
298 fprintf(stderr, "Deserializing state from previous process... ");
299 int state_fd = atoi(argv[3]);
300 CubemapStateProto loaded_state = read_tempfile(state_fd);
302 // Deserialize the streams.
303 for (int i = 0; i < loaded_state.streams_size(); ++i) {
304 servers->add_stream_from_serialized(loaded_state.streams(i));
307 // Put back the existing clients. It doesn't matter which server we
308 // allocate them to, so just do round-robin.
309 for (int i = 0; i < loaded_state.clients_size(); ++i) {
310 servers->add_client_from_serialized(loaded_state.clients(i));
313 // Deserialize the server socket.
314 server_sock = loaded_state.server_sock();
315 old_port = loaded_state.port();
317 fprintf(stderr, "done.\n");
319 // TODO: This should come from the config file.
320 servers->add_stream(STREAM_ID);
323 // Open a new server socket if we do not already have one, or if we changed ports.
324 if (server_sock != -1 && port != old_port) {
325 fprintf(stderr, "NOTE: Port changed from %d to %d; opening new socket.\n", old_port, port);
329 if (server_sock == -1) {
330 server_sock = create_server_socket(port);
335 pthread_t acceptor_thread;
336 pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
338 // TODO: This should come from the config file.
339 Input input(STREAM_ID, STREAM_URL);
350 CubemapStateProto state;
351 state.set_server_sock(server_sock);
352 state.set_port(port);
353 for (int i = 0; i < num_servers; ++i) {
354 servers->get_server(i)->stop();
356 CubemapStateProto local_state = servers->get_server(i)->serialize();
358 // The stream state should be identical between the servers, so we only store it once.
360 state.mutable_streams()->MergeFrom(local_state.streams());
362 for (int j = 0; j < local_state.clients_size(); ++j) {
363 state.add_clients()->MergeFrom(local_state.clients(j));
368 fprintf(stderr, "Serializing state and re-execing...\n");
369 int state_fd = make_tempfile(state);
372 sprintf(buf, "%d", state_fd);
375 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
377 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);