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