]> git.sesse.net Git - cubemap/blob - server.h
300ec0d41115f53640068691947481cc24f44c45
[cubemap] / server.h
1 #ifndef _SERVER_H
2 #define _SERVER_H 1
3
4 #include <stdint.h>
5 #include <pthread.h>
6 #include <sys/epoll.h>
7 #include <time.h>
8 #include <string>
9 #include <map>
10 #include <vector>
11
12 #define BACKLOG_SIZE 1048576
13 #define EPOLL_MAX_EVENTS 8192
14 #define EPOLL_TIMEOUT_MS 20
15 #define MAX_CLIENT_REQUEST 16384
16
17 class ClientProto;
18 class CubemapStateProto;
19 class Stream;
20 class StreamProto;
21
22 // Digested statistics for writing to logs etc.
23 struct ClientStats {
24         std::string stream_id;
25         std::string remote_addr;
26         time_t connect_time;
27         size_t bytes_sent;
28 };
29
30 struct Client {
31         Client() {}
32         Client(int sock);
33
34         // Serialization/deserialization.
35         Client(const ClientProto &serialized, Stream *stream);
36         ClientProto serialize() const;
37
38         ClientStats get_stats() const;
39
40         // The file descriptor associated with this socket.
41         int sock;
42
43         // Some information only used for logging.
44         std::string remote_addr;
45         time_t connect_time;
46
47         enum State { READING_REQUEST, SENDING_HEADER, SENDING_DATA, SENDING_ERROR };
48         State state;
49
50         // The HTTP request, as sent by the client. If we are in READING_REQUEST,
51         // this might not be finished.
52         std::string request;
53
54         // What stream we're connecting to; parsed from <request>.
55         // Not relevant for READING_REQUEST.
56         std::string stream_id;
57         Stream *stream;
58
59         // The header we want to send. This is nominally a copy of Stream::header,
60         // but since that might change on reconnects etc., we keep a local copy here.
61         // Only relevant for SENDING_HEADER or SENDING_ERROR; blank otherwise.
62         std::string header_or_error;
63
64         // Number of bytes we've sent of the header. Only relevant for SENDING_HEADER
65         // or SENDING_ERROR.
66         size_t header_or_error_bytes_sent;
67
68         // Number of bytes we've sent of data. Only relevant for SENDING_DATA.
69         size_t bytes_sent;
70 };
71
72 struct Stream {
73         Stream(const std::string &stream_id);
74         ~Stream();
75
76         // Serialization/deserialization.
77         Stream(const StreamProto &serialized);
78         StreamProto serialize() const;
79
80         std::string stream_id;
81
82         // The HTTP response header, plus the video stream header (if any).
83         std::string header;
84
85         // The stream data itself, stored in a circular buffer.
86         char *data;
87
88         // How many bytes <data> contains. Can very well be larger than BACKLOG_SIZE,
89         // since the buffer wraps.
90         size_t data_size;
91         
92         // Clients that are in SENDING_DATA, but that we don't listen on,
93         // because we currently don't have any data for them.
94         // See put_client_to_sleep() and wake_up_all_clients().
95         std::vector<Client *> sleeping_clients;
96
97         // Clients that we recently got data for (when they were in
98         // <sleeping_clients>).
99         std::vector<Client *> to_process;
100
101         // Put client to sleep, since there is no more data for it; we will on
102         // longer listen on POLLOUT until we get more data. Also, it will be put
103         // in the list of clients to wake up when we do.
104         void put_client_to_sleep(Client *client);
105
106         // We have more data, so mark all clients that are sleeping as ready to go.
107         void wake_up_all_clients();
108
109 private:
110         Stream(const Stream& other);
111 };
112
113 class Server {
114 public:
115         Server();
116         ~Server();
117
118         // Start a new thread that handles clients.
119         void run();
120
121         // Stop the thread.
122         void stop();
123         
124         // Get the list of all currently connected clients.     
125         std::vector<ClientStats> get_client_stats() const;
126
127         // Set header (both HTTP header and any stream headers) for the given stream.
128         void set_header(const std::string &stream_id, const std::string &header);
129
130         // These will be deferred until the next time an iteration in do_work() happens,
131         // and the order between them are undefined.
132         // XXX: header should ideally be ordered with respect to data.
133         void add_client_deferred(int sock);
134         void add_data_deferred(const std::string &stream_id, const char *data, size_t bytes);
135
136         // These should not be called while running, since that would violate
137         // threading assumptions (ie., that epoll is only called from one thread
138         // at the same time).
139         CubemapStateProto serialize();
140         void add_client_from_serialized(const ClientProto &client);
141         void add_stream(const std::string &stream_id);
142         void add_stream_from_serialized(const StreamProto &stream);
143
144 private:
145         pthread_t worker_thread;
146
147         // Mutex protecting queued_data only. Note that if you want to hold both this
148         // and <mutex> below, you will need to take <mutex> before this one.
149         mutable pthread_mutex_t queued_data_mutex;
150
151         // Deferred commands that should be run from the do_work() thread as soon as possible.
152         // We defer these for two reasons:
153         //
154         //  - We only want to fiddle with epoll from one thread at any given time,
155         //    and doing add_client() from the acceptor thread would violate that.
156         //  - We don't want the input thread(s) hanging on <mutex> when doing
157         //    add_data(), since they want to do add_data() rather often, and <mutex>
158         //    can be taken a lot of the time.
159         //      
160         // Protected by <queued_data_mutex>.
161         std::vector<int> queued_add_clients;
162         std::map<std::string, std::string> queued_data;
163
164         // All variables below this line are protected by the mutex.
165         mutable pthread_mutex_t mutex;
166
167         // If the thread should stop or not.
168         bool should_stop;       
169
170         // Map from stream ID to stream.
171         std::map<std::string, Stream *> streams;
172
173         // Map from file descriptor to client.
174         std::map<int, Client> clients;
175
176         // Used for epoll implementation (obviously).
177         int epoll_fd;
178         epoll_event events[EPOLL_MAX_EVENTS];
179
180         // Recover the this pointer, and call do_work().
181         static void *do_work_thunk(void *arg);
182
183         // The actual worker thread.
184         void do_work();
185
186         // Process a client; read and write data as far as we can.
187         // After this call, one of these four is true:
188         //
189         //  1. The socket is closed, and the client deleted.
190         //  2. We are still waiting for more data from the client.
191         //  3. We've sent all the data we have to the client,
192         //     and put it in <sleeping_clients>.
193         //  4. The socket buffer is full (which means we still have
194         //     data outstanding).
195         //
196         // For #2, we listen for EPOLLIN events. For #3 and #4, we listen
197         // for EPOLLOUT in edge-triggered mode; it will never fire for #3,
198         // but it's cheaper than taking it in and out all the time.
199         void process_client(Client *client);
200
201         // Close a given client socket, and clean up after it.
202         void close_client(Client *client);
203
204         // Parse the HTTP request. Returns a HTTP status code (200/400/404).
205         int parse_request(Client *client);
206
207         // Construct the HTTP header, and set the client into
208         // the SENDING_HEADER state.
209         void construct_header(Client *client);
210
211         // Construct a generic error with the given line, and set the client into
212         // the SENDING_ERROR state.
213         void construct_error(Client *client, int error_code);
214
215         // TODO: This function should probably die.
216         Stream *find_stream(const std::string &stream_id);
217
218         void process_queued_data();
219
220         void add_client(int sock);
221         void add_data(const std::string &stream_id, const char *data, size_t bytes);
222 };
223
224 #endif  // !defined(_SERVER_H)