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