7 #include <sys/socket.h>
10 #include <sys/ioctl.h>
11 #include <sys/epoll.h>
21 #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)");
61 memset(&addr, 0, sizeof(addr));
62 addr.sin6_family = AF_INET6;
63 addr.sin6_port = htons(port);
65 if (bind(server_sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
70 if (listen(server_sock, 128) == -1) {
78 void *acceptor_thread_run(void *arg)
80 int server_sock = int(intptr_t(arg));
84 socklen_t addrlen = sizeof(addr);
87 int sock = accept(server_sock, reinterpret_cast<sockaddr *>(&addr), &addrlen);
88 if (sock == -1 && errno == EINTR) {
96 // Set the socket as nonblocking.
98 if (ioctl(sock, FIONBIO, &one) == -1) {
103 // Pick a server, round-robin, and hand over the socket to it.
104 servers->add_client(sock);
109 // Serialize the given state to a file descriptor, and return the (still open)
111 int make_tempfile(const CubemapStateProto &state)
113 char tmpl[] = "/tmp/cubemapstate.XXXXXX";
114 int state_fd = mkstemp(tmpl);
115 if (state_fd == -1) {
121 state.SerializeToString(&serialized);
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);
139 // Read the state back from the file descriptor made by make_tempfile,
141 CubemapStateProto read_tempfile(int state_fd)
143 if (lseek(state_fd, 0, SEEK_SET) == -1) {
151 ssize_t ret = read(state_fd, buf, sizeof(buf));
161 serialized.append(string(buf, buf + ret));
164 close(state_fd); // Implicitly deletes the file.
166 CubemapStateProto state;
167 if (!state.ParseFromString(serialized)) {
168 fprintf(stderr, "PANIC: Failed deserialization of state.\n");
175 // Split a line on whitespace, e.g. "foo bar baz" -> {"foo", "bar", "baz"}.
176 vector<string> split_tokens(const string &line)
179 string current_token;
181 for (size_t i = 0; i < line.size(); ++i) {
182 if (isspace(line[i])) {
183 if (!current_token.empty()) {
184 ret.push_back(current_token);
186 current_token.clear();
188 current_token.push_back(line[i]);
191 if (!current_token.empty()) {
192 ret.push_back(current_token);
199 vector<string> arguments;
200 map<string, string> parameters;
203 // Parse the configuration file.
204 vector<ConfigLine> parse_config(const string &filename)
206 vector<ConfigLine> ret;
208 FILE *fp = fopen(filename.c_str(), "r");
210 perror(filename.c_str());
216 if (fgets(buf, sizeof(buf), fp) == NULL) {
220 // Chop off the string at the first #, \r or \n.
221 buf[strcspn(buf, "#\r\n")] = 0;
223 // Remove all whitespace from the end of the string.
224 size_t len = strlen(buf);
225 while (len > 0 && isspace(buf[len - 1])) {
229 // If the line is now all blank, ignore it.
234 vector<string> tokens = split_tokens(buf);
235 assert(!tokens.empty());
238 line.keyword = tokens[0];
240 for (size_t i = 1; i < tokens.size(); ++i) {
241 // foo=bar is a parameter; anything else is an argument.
242 size_t equals_pos = tokens[i].find_first_of('=');
243 if (equals_pos == string::npos) {
244 line.arguments.push_back(tokens[i]);
246 string key = tokens[i].substr(0, equals_pos);
247 string value = tokens[i].substr(equals_pos + 1, string::npos);
248 line.parameters.insert(make_pair(key, value));
259 int main(int argc, char **argv)
261 fprintf(stderr, "\nCubemap starting.\n");
263 string config_filename = (argc == 1) ? "cubemap.config" : argv[1];
264 vector<ConfigLine> config = parse_config(config_filename);
266 // Go through each (parsed) configuration line.
268 for (unsigned i = 0; i < config.size(); ++i) {
269 if (config[i].keyword == "port") {
270 if (config[i].parameters.size() > 0 ||
271 config[i].arguments.size() != 1) {
272 fprintf(stderr, "ERROR: 'port' takes one argument and no parameters\n");
275 port = atoi(config[i].arguments[0].c_str());
278 if (port <= 0 || port > 65535) {
279 fprintf(stderr, "ERROR: Missing or invalid 'port' statement in config file\n");
283 servers = new ServerPool(NUM_SERVERS);
285 int server_sock = -1, old_port = -1;
286 if (argc == 4 && strcmp(argv[2], "-state") == 0) {
287 fprintf(stderr, "Deserializing state from previous process... ");
288 int state_fd = atoi(argv[3]);
289 CubemapStateProto loaded_state = read_tempfile(state_fd);
291 // Deserialize the streams.
292 for (int i = 0; i < loaded_state.streams_size(); ++i) {
293 servers->add_stream_from_serialized(loaded_state.streams(i));
296 // Put back the existing clients. It doesn't matter which server we
297 // allocate them to, so just do round-robin.
298 for (int i = 0; i < loaded_state.clients_size(); ++i) {
299 servers->add_client_from_serialized(loaded_state.clients(i));
302 // Deserialize the server socket.
303 server_sock = loaded_state.server_sock();
304 old_port = loaded_state.port();
306 fprintf(stderr, "done.\n");
308 // TODO: This should come from the config file.
309 servers->add_stream(STREAM_ID);
312 // Open a new server socket if we do not already have one, or if we changed ports.
313 if (server_sock != -1 && port != old_port) {
314 fprintf(stderr, "NOTE: Port changed from %d to %d; opening new socket.\n", old_port, port);
318 if (server_sock == -1) {
319 server_sock = create_server_socket(port);
324 pthread_t acceptor_thread;
325 pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
327 // TODO: This should come from the config file.
328 Input input(STREAM_ID, STREAM_URL);
339 CubemapStateProto state;
340 state.set_server_sock(server_sock);
341 state.set_port(port);
342 for (int i = 0; i < NUM_SERVERS; ++i) {
343 servers->get_server(i)->stop();
345 CubemapStateProto local_state = servers->get_server(i)->serialize();
347 // The stream state should be identical between the servers, so we only store it once.
349 state.mutable_streams()->MergeFrom(local_state.streams());
351 for (int j = 0; j < local_state.clients_size(); ++j) {
352 state.add_clients()->MergeFrom(local_state.clients(j));
357 fprintf(stderr, "Serializing state and re-execing...\n");
358 int state_fd = make_tempfile(state);
361 sprintf(buf, "%d", state_fd);
364 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
366 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);