410b3b6e1b92b655530f2de415653916ddde54f0
[cubemap] / accesslog.cpp
1 #include <errno.h>
2 #include <poll.h>
3 #include <stddef.h>
4 #include <stdio.h>
5 #include <time.h>
6 #include <unistd.h>
7 #include <string>
8 #include <vector>
9
10 #include "accesslog.h"
11 #include "client.h"
12 #include "log.h"
13 #include "mutexlock.h"
14
15 using namespace std;
16
17 AccessLogThread::AccessLogThread()
18 {
19         pthread_mutex_init(&mutex, NULL);
20 }
21
22 AccessLogThread::AccessLogThread(const string &filename)
23         : filename(filename) {
24         pthread_mutex_init(&mutex, NULL);
25 }
26
27 void AccessLogThread::write(const ClientStats& client)
28 {
29         MutexLock lock(&mutex);
30         pending_writes.push_back(client);
31 }
32
33 void AccessLogThread::do_work()
34 {
35         // Open the file.
36         if (filename.empty()) {
37                 logfp = NULL;
38         } else {
39                 logfp = fopen(filename.c_str(), "a+");
40                 if (logfp == NULL) {
41                         log_perror(filename.c_str());
42                         // Continue as before.
43                 }
44         }
45
46         while (!should_stop()) {
47                 // Empty the queue.
48                 vector<ClientStats> writes;
49                 {
50                         MutexLock lock(&mutex);
51                         swap(pending_writes, writes);
52                 }
53
54                 if (logfp != NULL) {
55                         // Do the actual writes.
56                         time_t now = time(NULL);
57                         for (size_t i = 0; i < writes.size(); ++i) {
58                                 fprintf(logfp, "%llu %s %s %d %llu %llu %llu\n",
59                                         (long long unsigned)(writes[i].connect_time),
60                                         writes[i].remote_addr.c_str(),
61                                         writes[i].url.c_str(),
62                                         int(now - writes[i].connect_time),
63                                         (long long unsigned)(writes[i].bytes_sent),
64                                         (long long unsigned)(writes[i].bytes_lost),
65                                         (long long unsigned)(writes[i].num_loss_events));
66                         }
67                         fflush(logfp);
68                 }
69
70                 // Wait until we are being woken up, either to quit or because
71                 // there is material in pending_writes.
72                 wait_for_wakeup(NULL);
73         }
74
75         if (logfp != NULL) {    
76                 if (fclose(logfp) == EOF) {
77                         log_perror("fclose");
78                 }
79         }
80
81         logfp = NULL;
82 }