7 #include <sys/socket.h>
10 #include <sys/ioctl.h>
11 #include <sys/epoll.h>
25 #define STREAM_ID "stream"
26 #define STREAM_URL "http://gruessi.zrh.sesse.net:4013/"
31 Server *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[num_accepted % NUM_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));
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 servers = new Server[NUM_SERVERS];
268 if (argc == 4 && strcmp(argv[2], "-state") == 0) {
269 fprintf(stderr, "Deserializing state from previous process... ");
270 int state_fd = atoi(argv[3]);
271 CubemapStateProto loaded_state = read_tempfile(state_fd);
273 // Deserialize the streams.
274 for (int i = 0; i < loaded_state.streams_size(); ++i) {
275 for (int j = 0; j < NUM_SERVERS; ++j) {
276 servers[j].add_stream_from_serialized(loaded_state.streams(i));
280 // Put back the existing clients. It doesn't matter which server we
281 // allocate them to, so just do round-robin.
282 for (int i = 0; i < loaded_state.clients_size(); ++i) {
283 servers[i % NUM_SERVERS].add_client_from_serialized(loaded_state.clients(i));
286 // Deserialize the server socket.
287 server_sock = loaded_state.server_sock();
289 fprintf(stderr, "done.\n");
291 // TODO: This should come from a config file.
292 server_sock = create_server_socket(PORT);
293 for (int i = 0; i < NUM_SERVERS; ++i) {
294 servers[i].add_stream(STREAM_ID);
298 for (int i = 0; i < NUM_SERVERS; ++i) {
302 pthread_t acceptor_thread;
303 pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
305 Input input(STREAM_ID, STREAM_URL);
316 CubemapStateProto state;
317 state.set_server_sock(server_sock);
318 for (int i = 0; i < NUM_SERVERS; ++i) {
321 CubemapStateProto local_state = servers[i].serialize();
323 // The stream state should be identical between the servers, so we only store it once.
325 state.mutable_streams()->MergeFrom(local_state.streams());
327 for (int j = 0; j < local_state.clients_size(); ++j) {
328 state.add_clients()->MergeFrom(local_state.clients(j));
333 fprintf(stderr, "Serializing state and re-execing...\n");
334 int state_fd = make_tempfile(state);
337 sprintf(buf, "%d", state_fd);
340 execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
342 fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);