Remove some leftover code.
[cubemap] / cubemap.cpp
index 2bccac39f12a38e546ddc1189bd207dd425d85ab..9b98ebab999fe6e0818528305df992c92b378f7e 100644 (file)
 #include <arpa/inet.h>
 #include <curl/curl.h>
 #include <sys/socket.h>
+#include <pthread.h>
+#include <sys/types.h>
+#include <sys/ioctl.h>
+#include <sys/epoll.h>
+#include <signal.h>
+#include <errno.h>
+#include <ctype.h>
 #include <vector>
 #include <string>
 #include <map>
+#include <set>
+
 #include "metacube.h"
+#include "parse.h"
+#include "server.h"
+#include "serverpool.h"
+#include "input.h"
+#include "state.pb.h"
 
-#define NUM_SERVERS 4
 #define STREAM_ID "stream"
 #define STREAM_URL "http://gruessi.zrh.sesse.net:4013/"
-#define BACKLOG_SIZE 1048576
 
 using namespace std;
 
-struct Client {
-       enum State { READING_REQUEST, SENDING_HEADER, SENDING_DATA };
-       State state;
-
-       // The HTTP request, as sent by the client. If we are in READING_REQUEST,
-       // this might not be finished.
-       string client_request;
-
-#if 0
-       // What stream we're connecting to; parsed from client_request.
-       // Not relevant for READING_REQUEST.
-       string stream_id;
-#endif
-
-       // Number of bytes we've sent of the header. Only relevant for SENDING_HEADER.
-       size_t header_bytes_sent;
-
-       // Number of bytes we've sent of data. Only relevant for SENDING_DATA.
-       size_t bytes_sent;
-};
-
-struct Stream {
-       // The HTTP response header, plus the video stream header (if any).
-       string header;
-
-       // The stream data itself, stored in a circular buffer.
-       char data[BACKLOG_SIZE];
-
-       // How many bytes <data> contains. Can very well be larger than BACKLOG_SIZE,
-       // since the buffer wraps.
-       size_t data_size;
-};
-
-class Server {
-public:
-       void add_socket(int server_sock);
-       void add_stream(const string &stream_id);
-       void set_header(const string &stream_id, const string &header);
-       void add_data(const string &stream_id, const char *data, size_t bytes);
-
-private:
-       map<string, Stream> streams;
-};
-
-class Input {
-public:
-       Input();
-       void curl_callback(char *ptr, size_t bytes);
-
-private:
-       void process_block(const char *data, uint32_t size, uint32_t flags);
-       void drop_pending_data(size_t num_bytes);
-
-       // Data we have received but not fully processed yet.
-       vector<char> pending_data;
-
-       // If <pending_data> starts with a Metacube header,
-       // this is true.
-       bool has_metacube_header;
-};
-
-Input::Input()
-       : has_metacube_header(false)
+ServerPool *servers = NULL;
+volatile bool hupped = false;
+
+void hup(int ignored)
 {
+       hupped = true;
 }
-       
-void Input::curl_callback(char *ptr, size_t bytes)
-{
-       pending_data.insert(pending_data.end(), ptr, ptr + bytes);
 
-       for ( ;; ) {
-               // If we don't have enough data (yet) for even the Metacube header, just return.
-               if (pending_data.size() < sizeof(metacube_block_header)) {
-                       return;
-               }
+int create_server_socket(int port)
+{
+       int server_sock = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
+       if (server_sock == -1) {
+               perror("socket");
+               exit(1);
+       }
 
-               // Make sure we have the Metacube sync header at the start.
-               // We may need to skip over junk data (it _should_ not happen, though).
-               if (!has_metacube_header) {
-                       char *ptr = static_cast<char *>(
-                               memmem(pending_data.data(), pending_data.size(),
-                                      METACUBE_SYNC, strlen(METACUBE_SYNC)));
-                       if (ptr == NULL) {
-                               // OK, so we didn't find the sync marker. We know then that
-                               // we do not have the _full_ marker in the buffer, but we
-                               // could have N-1 bytes. Drop everything before that,
-                               // and then give up.
-                               drop_pending_data(pending_data.size() - (strlen(METACUBE_SYNC) - 1));
-                               return;
-                       } else {
-                               // Yay, we found the header. Drop everything (if anything) before it.
-                               drop_pending_data(ptr - pending_data.data());
-                               has_metacube_header = true;
-
-                               // Re-check that we have the entire header; we could have dropped data.
-                               if (pending_data.size() < sizeof(metacube_block_header)) {
-                                       return;
-                               }
-                       }
-               }
+       int one = 1;
+       if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) {
+               perror("setsockopt(SO_REUSEADDR)");
+               exit(1);
+       }
 
-               // Now it's safe to read the header.
-               metacube_block_header *hdr = reinterpret_cast<metacube_block_header *>(pending_data.data());    
-               assert(memcmp(hdr->sync, METACUBE_SYNC, sizeof(hdr->sync)) == 0);
-               uint32_t size = ntohl(hdr->size);
-               uint32_t flags = ntohl(hdr->flags);
+       // We want dual-stack sockets. (Sorry, OpenBSD and Windows XP...)
+       int zero = 0;
+       if (setsockopt(server_sock, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof(zero)) == -1) {
+               perror("setsockopt(IPV6_V6ONLY)");
+               exit(1);
+       }
 
-               // See if we have the entire block. If not, wait for more data.
-               if (pending_data.size() < sizeof(metacube_block_header) + size) {
-                       return;
-               }
+       sockaddr_in6 addr;
+       memset(&addr, 0, sizeof(addr));
+       addr.sin6_family = AF_INET6;
+       addr.sin6_port = htons(port);
 
-               process_block(pending_data.data(), size, flags);
+       if (bind(server_sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
+               perror("bind");
+               exit(1);
+       }
 
-               // Consume this block. This isn't the most efficient way of dealing with things
-               // should we have many blocks, but these routines don't need to be too efficient
-               // anyway.
-               pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube_block_header) + size);
+       if (listen(server_sock, 128) == -1) {
+               perror("listen");
+               exit(1);
        }
+
+       return server_sock;
 }
-               
-void Input::process_block(const char *data, uint32_t size, uint32_t flags)
+
+void *acceptor_thread_run(void *arg)
 {
-       // TODO: treat it right here
-       printf("Block: %d bytes, flags=0x%x\n", size, flags);
+       int server_sock = int(intptr_t(arg));
+       for ( ;; ) {
+               sockaddr_in6 addr;
+               socklen_t addrlen = sizeof(addr);
+
+               // Get a new socket.
+               int sock = accept(server_sock, reinterpret_cast<sockaddr *>(&addr), &addrlen);
+               if (sock == -1 && errno == EINTR) {
+                       continue;
+               }
+               if (sock == -1) {
+                       perror("accept");
+                       exit(1);
+               }
+
+               // Set the socket as nonblocking.
+               int one = 1;
+               if (ioctl(sock, FIONBIO, &one) == -1) {
+                       perror("FIONBIO");
+                       exit(1);
+               }
+
+               // Pick a server, round-robin, and hand over the socket to it.
+               servers->add_client(sock);
+       }
 }
-                       
-void Input::drop_pending_data(size_t num_bytes)
+
+// Serialize the given state to a file descriptor, and return the (still open)
+// descriptor.
+int make_tempfile(const CubemapStateProto &state)
 {
-       if (num_bytes == 0) {
-               return;
+       char tmpl[] = "/tmp/cubemapstate.XXXXXX";
+       int state_fd = mkstemp(tmpl);
+       if (state_fd == -1) {
+               perror("mkstemp");
+               exit(1);
+       }
+
+       string serialized;
+       state.SerializeToString(&serialized);
+
+       const char *ptr = serialized.data();
+       size_t to_write = serialized.size();
+       while (to_write > 0) {
+               ssize_t ret = write(state_fd, ptr, to_write);
+               if (ret == -1) {
+                       perror("write");
+                       exit(1);
+               }
+
+               ptr += ret;
+               to_write -= ret;
        }
-       fprintf(stderr, "Warning: Dropping %lld junk bytes from stream, maybe it is not a Metacube stream?\n",
-               (long long)num_bytes);
-       pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);
+
+       return state_fd;
 }
 
-size_t curl_callback(char *ptr, size_t size, size_t nmemb, void *userdata)
+// Read the state back from the file descriptor made by make_tempfile,
+// and close it.
+CubemapStateProto read_tempfile(int state_fd)
 {
-       Input *input = static_cast<Input *>(userdata);
-       size_t bytes = size * nmemb;
-       input->curl_callback(ptr, bytes);       
-       return bytes;
+       if (lseek(state_fd, 0, SEEK_SET) == -1) {
+               perror("lseek");
+               exit(1);
+       }
+
+       string serialized;
+       char buf[4096];
+       for ( ;; ) {
+               ssize_t ret = read(state_fd, buf, sizeof(buf));
+               if (ret == -1) {
+                       perror("read");
+                       exit(1);
+               }
+               if (ret == 0) {
+                       // EOF.
+                       break;
+               }
+
+               serialized.append(string(buf, buf + ret));
+       }
+
+       close(state_fd);  // Implicitly deletes the file.
+
+       CubemapStateProto state;
+       if (!state.ParseFromString(serialized)) {
+               fprintf(stderr, "PANIC: Failed deserialization of state.\n");
+               exit(1);
+       }
+
+       return state;
 }
 
 int main(int argc, char **argv)
 {
-       Input input;
-       CURL *curl = curl_easy_init();
-       curl_easy_setopt(curl, CURLOPT_URL, "http://gruessi.zrh.sesse.net:4013/");
-       // curl_easy_setopt(curl, CURLOPT_URL, "http://www.google.com/");
-       curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
-       curl_easy_setopt(curl, CURLOPT_WRITEDATA, &input);
-       curl_easy_perform(curl);
+       fprintf(stderr, "\nCubemap starting.\n");
+
+       string config_filename = (argc == 1) ? "cubemap.config" : argv[1];
+       vector<ConfigLine> config = parse_config(config_filename);
+
+       int port = fetch_config_int(config, "port", 1, 65535);
+       int num_servers = fetch_config_int(config, "num_servers", 1, 20000);  // Insanely high max limit.
+
+       servers = new ServerPool(num_servers);
+
+       int server_sock = -1, old_port = -1;
+       set<string> deserialized_stream_ids;
+       if (argc == 4 && strcmp(argv[2], "-state") == 0) {
+               fprintf(stderr, "Deserializing state from previous process... ");
+               int state_fd = atoi(argv[3]);
+               CubemapStateProto loaded_state = read_tempfile(state_fd);
+
+               // Deserialize the streams.
+               for (int i = 0; i < loaded_state.streams_size(); ++i) {
+                       servers->add_stream_from_serialized(loaded_state.streams(i));
+                       deserialized_stream_ids.insert(loaded_state.streams(i).stream_id());
+               }
+
+               // Put back the existing clients. It doesn't matter which server we
+               // allocate them to, so just do round-robin.
+               for (int i = 0; i < loaded_state.clients_size(); ++i) {
+                       servers->add_client_from_serialized(loaded_state.clients(i));
+               }
+
+               // Deserialize the server socket.
+               server_sock = loaded_state.server_sock();
+               old_port = loaded_state.port();
+
+               fprintf(stderr, "done.\n");
+       }
+
+       // Find all streams in the configuration file, and create them.
+       set<string> expecting_stream_ids = deserialized_stream_ids;
+       for (unsigned i = 0; i < config.size(); ++i) {
+               if (config[i].keyword != "stream") {
+                       continue;
+               }
+               if (config[i].arguments.size() != 1) {
+                       fprintf(stderr, "ERROR: 'stream' takes exactly one argument\n");
+                       exit(1);
+               }
+               string stream_id = config[i].arguments[0];
+               if (deserialized_stream_ids.count(stream_id) == 0) {
+                       servers->add_stream(stream_id);
+               }
+               expecting_stream_ids.erase(stream_id);
+       }
+
+       // Warn about any servers we've lost.
+       // TODO: Make an option (delete=yes?) to actually shut down streams.
+       for (set<string>::const_iterator stream_it = expecting_stream_ids.begin();
+            stream_it != expecting_stream_ids.end();
+            ++stream_it) {
+               fprintf(stderr, "WARNING: stream '%s' disappeared from the configuration file.\n",
+                       stream_it->c_str());
+               fprintf(stderr, "         It will not be deleted, but clients will not get any new inputs.\n");
+       }
+
+       // Open a new server socket if we do not already have one, or if we changed ports.
+       if (server_sock != -1 && port != old_port) {
+               fprintf(stderr, "NOTE: Port changed from %d to %d; opening new socket.\n", old_port, port);
+               close(server_sock);
+               server_sock = -1;
+       }
+       if (server_sock == -1) {
+               server_sock = create_server_socket(port);
+       }
+
+       servers->run();
+
+       pthread_t acceptor_thread;
+       pthread_create(&acceptor_thread, NULL, acceptor_thread_run, reinterpret_cast<void *>(server_sock));
+
+       // Find all streams in the configuration file, and create inputs for them.
+       vector<Input *> inputs;
+       for (unsigned i = 0; i < config.size(); ++i) {
+               if (config[i].keyword != "stream") {
+                       continue;
+               }
+               assert(config[i].arguments.size() == 1);
+               string stream_id = config[i].arguments[0];
+
+               if (config[i].parameters.count("src") == 0) {
+                       fprintf(stderr, "WARNING: stream '%s' has no src= attribute, clients will not get any data.\n",
+                               stream_id.c_str());
+                       continue;
+               }
+
+               string src = config[i].parameters["src"];
+               Input *input = new Input(stream_id, src);
+               input->run();
+               inputs.push_back(input);
+       }
+
+       signal(SIGHUP, hup);
+
+       while (!hupped) {
+               usleep(100000);
+       }
+
+       // OK, we've been HUPed. Time to shut down everything, serialize, and re-exec.
+       for (size_t i = 0; i < inputs.size(); ++i) {
+               inputs[i]->stop();
+               delete inputs[i];  // TODO: serialize instead of using libcurl.
+       }
+
+       CubemapStateProto state;
+       state.set_server_sock(server_sock);
+       state.set_port(port);
+       for (int i = 0; i < num_servers; ++i) { 
+               servers->get_server(i)->stop();
+
+               CubemapStateProto local_state = servers->get_server(i)->serialize();
+
+               // The stream state should be identical between the servers, so we only store it once.
+               if (i == 0) {
+                       state.mutable_streams()->MergeFrom(local_state.streams());
+               }
+               for (int j = 0; j < local_state.clients_size(); ++j) {
+                       state.add_clients()->MergeFrom(local_state.clients(j));
+               }
+       }
+       delete servers;
+
+       fprintf(stderr, "Serializing state and re-execing...\n");
+       int state_fd = make_tempfile(state);
+
+       char buf[16];
+       sprintf(buf, "%d", state_fd);
+
+       for ( ;; ) {
+               execlp(argv[0], argv[0], config_filename.c_str(), "-state", buf, NULL);
+               perror("execlp");
+               fprintf(stderr, "PANIC: re-exec of %s failed. Waiting 0.2 seconds and trying again...\n", argv[0]);
+               usleep(200000);
+       }
 }