]> git.sesse.net Git - cubemap/blob - server.cpp
Rewrite the entire internal signal handling/wakeup.
[cubemap] / server.cpp
1 #include <assert.h>
2 #include <errno.h>
3 #include <netinet/in.h>
4 #include <pthread.h>
5 #include <stdint.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <sys/epoll.h>
10 #include <sys/sendfile.h>
11 #include <sys/socket.h>
12 #include <sys/types.h>
13 #include <unistd.h>
14 #include <algorithm>
15 #include <map>
16 #include <string>
17 #include <utility>
18 #include <vector>
19
20 #include "accesslog.h"
21 #include "log.h"
22 #include "markpool.h"
23 #include "metacube.h"
24 #include "mutexlock.h"
25 #include "parse.h"
26 #include "server.h"
27 #include "state.pb.h"
28 #include "stream.h"
29 #include "util.h"
30
31 using namespace std;
32
33 extern AccessLogThread *access_log;
34
35 Server::Server()
36 {
37         pthread_mutex_init(&mutex, NULL);
38         pthread_mutex_init(&queued_data_mutex, NULL);
39
40         epoll_fd = epoll_create(1024);  // Size argument is ignored.
41         if (epoll_fd == -1) {
42                 log_perror("epoll_fd");
43                 exit(1);
44         }
45 }
46
47 Server::~Server()
48 {
49         for (map<string, Stream *>::iterator stream_it = streams.begin();
50              stream_it != streams.end();
51              ++stream_it) {
52                 delete stream_it->second;
53         }
54
55         safe_close(epoll_fd);
56 }
57
58 vector<ClientStats> Server::get_client_stats() const
59 {
60         vector<ClientStats> ret;
61
62         MutexLock lock(&mutex);
63         for (map<int, Client>::const_iterator client_it = clients.begin();
64              client_it != clients.end();
65              ++client_it) {
66                 ret.push_back(client_it->second.get_stats());
67         }
68         return ret;
69 }
70
71 void Server::do_work()
72 {
73         while (!should_stop()) {
74                 // Wait until there's activity on at least one of the fds,
75                 // or we are waken up due to new queued clients or data.
76                 int nfds = epoll_pwait(epoll_fd, events, EPOLL_MAX_EVENTS, -1, &sigset_without_usr1_block);
77                 if (nfds == -1 && errno != EINTR) {
78                         log_perror("epoll_wait");
79                         exit(1);
80                 }
81
82                 MutexLock lock(&mutex);  // We release the mutex between iterations.
83         
84                 process_queued_data();
85
86                 for (int i = 0; i < nfds; ++i) {
87                         Client *client = reinterpret_cast<Client *>(events[i].data.u64);
88
89                         if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
90                                 close_client(client);
91                                 continue;
92                         }
93
94                         process_client(client);
95                 }
96
97                 for (map<string, Stream *>::iterator stream_it = streams.begin();
98                      stream_it != streams.end();
99                      ++stream_it) {
100                         vector<Client *> to_process;
101                         swap(stream_it->second->to_process, to_process);
102                         for (size_t i = 0; i < to_process.size(); ++i) {
103                                 process_client(to_process[i]);
104                         }
105                 }
106         }
107 }
108
109 CubemapStateProto Server::serialize()
110 {
111         // We don't serialize anything queued, so empty the queues.
112         process_queued_data();
113
114         CubemapStateProto serialized;
115         for (map<int, Client>::const_iterator client_it = clients.begin();
116              client_it != clients.end();
117              ++client_it) {
118                 serialized.add_clients()->MergeFrom(client_it->second.serialize());
119         }
120         for (map<string, Stream *>::const_iterator stream_it = streams.begin();
121              stream_it != streams.end();
122              ++stream_it) {
123                 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
124         }
125         return serialized;
126 }
127
128 void Server::add_client_deferred(int sock)
129 {
130         MutexLock lock(&queued_data_mutex);
131         queued_add_clients.push_back(sock);
132         wakeup();
133 }
134
135 void Server::add_client(int sock)
136 {
137         pair<map<int, Client>::iterator, bool> ret =
138                 clients.insert(make_pair(sock, Client(sock)));
139         assert(ret.second == true);  // Should not already exist.
140         Client *client_ptr = &ret.first->second;
141
142         // Start listening on data from this socket.
143         epoll_event ev;
144         ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
145         ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
146         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
147                 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
148                 exit(1);
149         }
150
151         process_client(client_ptr);
152 }
153
154 void Server::add_client_from_serialized(const ClientProto &client)
155 {
156         MutexLock lock(&mutex);
157         Stream *stream;
158         map<string, Stream *>::iterator stream_it = streams.find(client.stream_id());
159         if (stream_it == streams.end()) {
160                 stream = NULL;
161         } else {
162                 stream = stream_it->second;
163         }
164         pair<map<int, Client>::iterator, bool> ret =
165                 clients.insert(make_pair(client.sock(), Client(client, stream)));
166         assert(ret.second == true);  // Should not already exist.
167         Client *client_ptr = &ret.first->second;
168
169         // Start listening on data from this socket.
170         epoll_event ev;
171         if (client.state() == Client::READING_REQUEST) {
172                 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
173         } else {
174                 // If we don't have more data for this client, we'll be putting it into
175                 // the sleeping array again soon.
176                 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
177         }
178         ev.data.u64 = 0;  // Keep Valgrind happy.
179         ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
180         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
181                 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
182                 exit(1);
183         }
184
185         if (client_ptr->state == Client::SENDING_DATA && 
186             client_ptr->stream_pos == client_ptr->stream->bytes_received) {
187                 client_ptr->stream->put_client_to_sleep(client_ptr);
188         } else {
189                 process_client(client_ptr);
190         }
191 }
192
193 void Server::add_stream(const string &stream_id, size_t backlog_size, Stream::Encoding encoding)
194 {
195         MutexLock lock(&mutex);
196         streams.insert(make_pair(stream_id, new Stream(stream_id, backlog_size, encoding)));
197 }
198
199 void Server::add_stream_from_serialized(const StreamProto &stream, int data_fd)
200 {
201         MutexLock lock(&mutex);
202         streams.insert(make_pair(stream.stream_id(), new Stream(stream, data_fd)));
203 }
204         
205 void Server::set_backlog_size(const string &stream_id, size_t new_size)
206 {
207         MutexLock lock(&mutex);
208         assert(streams.count(stream_id) != 0);
209         streams[stream_id]->set_backlog_size(new_size);
210 }
211         
212 void Server::set_encoding(const string &stream_id, Stream::Encoding encoding)
213 {
214         MutexLock lock(&mutex);
215         assert(streams.count(stream_id) != 0);
216         streams[stream_id]->encoding = encoding;
217 }
218         
219 void Server::set_header(const string &stream_id, const string &http_header, const string &stream_header)
220 {
221         MutexLock lock(&mutex);
222         find_stream(stream_id)->http_header = http_header;
223         find_stream(stream_id)->stream_header = stream_header;
224
225         // If there are clients we haven't sent anything to yet, we should give
226         // them the header, so push back into the SENDING_HEADER state.
227         for (map<int, Client>::iterator client_it = clients.begin();
228              client_it != clients.end();
229              ++client_it) {
230                 Client *client = &client_it->second;
231                 if (client->state == Client::SENDING_DATA &&
232                     client->stream_pos == 0) {
233                         construct_header(client);
234                 }
235         }
236 }
237         
238 void Server::set_mark_pool(const string &stream_id, MarkPool *mark_pool)
239 {
240         MutexLock lock(&mutex);
241         assert(clients.empty());
242         find_stream(stream_id)->mark_pool = mark_pool;
243 }
244
245 void Server::add_data_deferred(const string &stream_id, const char *data, size_t bytes)
246 {
247         MutexLock lock(&queued_data_mutex);
248         queued_data[stream_id].append(string(data, data + bytes));
249         wakeup();
250 }
251
252 // See the .h file for postconditions after this function.      
253 void Server::process_client(Client *client)
254 {
255         switch (client->state) {
256         case Client::READING_REQUEST: {
257 read_request_again:
258                 // Try to read more of the request.
259                 char buf[1024];
260                 int ret;
261                 do {
262                         ret = read(client->sock, buf, sizeof(buf));
263                 } while (ret == -1 && errno == EINTR);
264
265                 if (ret == -1 && errno == EAGAIN) {
266                         // No more data right now. Nothing to do.
267                         // This is postcondition #2.
268                         return;
269                 }
270                 if (ret == -1) {
271                         log_perror("read");
272                         close_client(client);
273                         return;
274                 }
275                 if (ret == 0) {
276                         // OK, the socket is closed.
277                         close_client(client);
278                         return;
279                 }
280
281                 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
282         
283                 switch (status) {
284                 case RP_OUT_OF_SPACE:
285                         log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
286                         close_client(client);
287                         return;
288                 case RP_NOT_FINISHED_YET:
289                         // OK, we don't have the entire header yet. Fine; we'll get it later.
290                         // See if there's more data for us.
291                         goto read_request_again;
292                 case RP_EXTRA_DATA:
293                         log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
294                         close_client(client);
295                         return;
296                 case RP_FINISHED:
297                         break;
298                 }
299
300                 assert(status == RP_FINISHED);
301
302                 int error_code = parse_request(client);
303                 if (error_code == 200) {
304                         construct_header(client);
305                 } else {
306                         construct_error(client, error_code);
307                 }
308
309                 // We've changed states, so fall through.
310                 assert(client->state == Client::SENDING_ERROR ||
311                        client->state == Client::SENDING_HEADER);
312         }
313         case Client::SENDING_ERROR:
314         case Client::SENDING_HEADER: {
315 sending_header_or_error_again:
316                 int ret;
317                 do {
318                         ret = write(client->sock,
319                                     client->header_or_error.data() + client->header_or_error_bytes_sent,
320                                     client->header_or_error.size() - client->header_or_error_bytes_sent);
321                 } while (ret == -1 && errno == EINTR);
322
323                 if (ret == -1 && errno == EAGAIN) {
324                         // We're out of socket space, so now we're at the “low edge” of epoll's
325                         // edge triggering. epoll will tell us when there is more room, so for now,
326                         // just return.
327                         // This is postcondition #4.
328                         return;
329                 }
330
331                 if (ret == -1) {
332                         // Error! Postcondition #1.
333                         log_perror("write");
334                         close_client(client);
335                         return;
336                 }
337                 
338                 client->header_or_error_bytes_sent += ret;
339                 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
340
341                 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
342                         // We haven't sent all yet. Fine; go another round.
343                         goto sending_header_or_error_again;
344                 }
345
346                 // We're done sending the header or error! Clear it to release some memory.
347                 client->header_or_error.clear();
348
349                 if (client->state == Client::SENDING_ERROR) {
350                         // We're done sending the error, so now close.  
351                         // This is postcondition #1.
352                         close_client(client);
353                         return;
354                 }
355
356                 // Start sending from the end. In other words, we won't send any of the backlog,
357                 // but we'll start sending immediately as we get data.
358                 // This is postcondition #3.
359                 client->state = Client::SENDING_DATA;
360                 client->stream_pos = client->stream->bytes_received;
361                 client->stream->put_client_to_sleep(client);
362                 return;
363         }
364         case Client::SENDING_DATA: {
365 sending_data_again:
366                 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
367                 // but resync will be the mux's problem.
368                 Stream *stream = client->stream;
369                 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
370                 if (bytes_to_send == 0) {
371                         return;
372                 }
373                 if (bytes_to_send > stream->backlog_size) {
374                         size_t bytes_lost = bytes_to_send - stream->backlog_size;
375                         client->stream_pos = stream->bytes_received - stream->backlog_size;
376                         client->bytes_lost += bytes_lost;
377                         ++client->num_loss_events;
378                         bytes_to_send = stream->backlog_size;
379
380                         double loss_fraction = double(client->bytes_lost) / double(client->bytes_lost + client->bytes_sent);
381                         log(WARNING, "[%s] Client lost %lld bytes (total loss: %.2f%%), maybe too slow connection",
382                                 client->remote_addr.c_str(),
383                                 (long long int)(bytes_lost),
384                                 100.0 * loss_fraction);
385                 }
386
387                 // See if we need to split across the circular buffer.
388                 bool more_data = false;
389                 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
390                         bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
391                         more_data = true;
392                 }
393
394                 ssize_t ret;
395                 do {
396                         loff_t offset = client->stream_pos % stream->backlog_size;
397                         ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
398                 } while (ret == -1 && errno == EINTR);
399
400                 if (ret == -1 && errno == EAGAIN) {
401                         // We're out of socket space, so return; epoll will wake us up
402                         // when there is more room.
403                         // This is postcondition #4.
404                         return;
405                 }
406                 if (ret == -1) {
407                         // Error, close; postcondition #1.
408                         log_perror("sendfile");
409                         close_client(client);
410                         return;
411                 }
412                 client->stream_pos += ret;
413                 client->bytes_sent += ret;
414
415                 if (client->stream_pos == stream->bytes_received) {
416                         // We don't have any more data for this client, so put it to sleep.
417                         // This is postcondition #3.
418                         stream->put_client_to_sleep(client);
419                 } else if (more_data && size_t(ret) == bytes_to_send) {
420                         goto sending_data_again;
421                 }
422                 break;
423         }
424         default:
425                 assert(false);
426         }
427 }
428
429 int Server::parse_request(Client *client)
430 {
431         vector<string> lines = split_lines(client->request);
432         if (lines.empty()) {
433                 return 400;  // Bad request (empty).
434         }
435
436         vector<string> request_tokens = split_tokens(lines[0]);
437         if (request_tokens.size() < 2) {
438                 return 400;  // Bad request (empty).
439         }
440         if (request_tokens[0] != "GET") {
441                 return 400;  // Should maybe be 405 instead?
442         }
443         if (streams.count(request_tokens[1]) == 0) {
444                 return 404;  // Not found.
445         }
446
447         client->stream_id = request_tokens[1];
448         client->stream = find_stream(client->stream_id);
449         if (client->stream->mark_pool != NULL) {
450                 client->fwmark = client->stream->mark_pool->get_mark();
451         } else {
452                 client->fwmark = 0;  // No mark.
453         }
454         if (setsockopt(client->sock, SOL_SOCKET, SO_MARK, &client->fwmark, sizeof(client->fwmark)) == -1) {                          
455                 if (client->fwmark != 0) {
456                         log_perror("setsockopt(SO_MARK)");
457                 }
458         }
459         client->request.clear();
460
461         return 200;  // OK!
462 }
463
464 void Server::construct_header(Client *client)
465 {
466         Stream *stream = find_stream(client->stream_id);
467         if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
468                 client->header_or_error = stream->http_header +
469                         "\r\n" +
470                         stream->stream_header;
471         } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
472                 client->header_or_error = stream->http_header +
473                         "Content-encoding: metacube\r\n" +
474                         "\r\n";
475                 if (!stream->stream_header.empty()) {
476                         metacube_block_header hdr;
477                         memcpy(hdr.sync, METACUBE_SYNC, sizeof(hdr.sync));
478                         hdr.size = htonl(stream->stream_header.size());
479                         hdr.flags = htonl(METACUBE_FLAGS_HEADER);
480                         client->header_or_error.append(
481                                 string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
482                 }
483                 client->header_or_error.append(stream->stream_header);
484         } else {
485                 assert(false);
486         }
487
488         // Switch states.
489         client->state = Client::SENDING_HEADER;
490
491         epoll_event ev;
492         ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
493         ev.data.u64 = reinterpret_cast<uint64_t>(client);
494
495         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
496                 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
497                 exit(1);
498         }
499 }
500         
501 void Server::construct_error(Client *client, int error_code)
502 {
503         char error[256];
504         snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
505                 error_code);
506         client->header_or_error = error;
507
508         // Switch states.
509         client->state = Client::SENDING_ERROR;
510
511         epoll_event ev;
512         ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
513         ev.data.u64 = reinterpret_cast<uint64_t>(client);
514
515         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
516                 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
517                 exit(1);
518         }
519 }
520
521 template<class T>
522 void delete_from(vector<T> *v, T elem)
523 {
524         typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
525         v->erase(new_end, v->end());
526 }
527         
528 void Server::close_client(Client *client)
529 {
530         if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
531                 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
532                 exit(1);
533         }
534
535         // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
536         if (client->stream != NULL) {
537                 delete_from(&client->stream->sleeping_clients, client);
538                 delete_from(&client->stream->to_process, client);
539                 if (client->stream->mark_pool != NULL) {
540                         int fwmark = client->fwmark;
541                         client->stream->mark_pool->release_mark(fwmark);
542                 }
543         }
544
545         // Log to access_log.
546         access_log->write(client->get_stats());
547
548         // Bye-bye!
549         safe_close(client->sock);
550
551         clients.erase(client->sock);
552 }
553         
554 Stream *Server::find_stream(const string &stream_id)
555 {
556         map<string, Stream *>::iterator it = streams.find(stream_id);
557         assert(it != streams.end());
558         return it->second;
559 }
560
561 void Server::process_queued_data()
562 {
563         MutexLock lock(&queued_data_mutex);
564
565         for (size_t i = 0; i < queued_add_clients.size(); ++i) {
566                 add_client(queued_add_clients[i]);
567         }
568         queued_add_clients.clear();     
569         
570         for (map<string, string>::iterator queued_it = queued_data.begin();
571              queued_it != queued_data.end();
572              ++queued_it) {
573                 Stream *stream = find_stream(queued_it->first);
574                 stream->add_data(queued_it->second.data(), queued_it->second.size());
575                 stream->wake_up_all_clients();
576         }
577         queued_data.clear();
578 }