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