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