]> git.sesse.net Git - nageru/blob - httpd.cpp
Add the first beginnings of Prometheus metrics.
[nageru] / httpd.cpp
1 #include "httpd.h"
2
3 #include <assert.h>
4 #include <byteswap.h>
5 #include <endian.h>
6 #include <microhttpd.h>
7 #include <netinet/in.h>
8 #include <stdio.h>
9 #include <string.h>
10 #include <sys/time.h>
11 #include <time.h>
12 #include <memory>
13
14 #include "defs.h"
15 #include "metacube2.h"
16 #include "metrics.h"
17
18 struct MHD_Connection;
19 struct MHD_Response;
20
21 using namespace std;
22
23 HTTPD::HTTPD()
24 {
25 }
26
27 HTTPD::~HTTPD()
28 {
29         if (mhd) {
30                 MHD_quiesce_daemon(mhd);
31                 for (Stream *stream : streams) {
32                         stream->stop();
33                 }
34                 MHD_stop_daemon(mhd);
35         }
36 }
37
38 void HTTPD::start(int port)
39 {
40         mhd = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION | MHD_USE_POLL_INTERNALLY | MHD_USE_DUAL_STACK,
41                                port,
42                                nullptr, nullptr,
43                                &answer_to_connection_thunk, this,
44                                MHD_OPTION_NOTIFY_COMPLETED, nullptr, this,
45                                MHD_OPTION_END);
46         if (mhd == nullptr) {
47                 fprintf(stderr, "Warning: Could not open HTTP server. (Port already in use?)\n");
48         }
49 }
50
51 void HTTPD::add_data(const char *buf, size_t size, bool keyframe)
52 {
53         unique_lock<mutex> lock(streams_mutex);
54         for (Stream *stream : streams) {
55                 stream->add_data(buf, size, keyframe ? Stream::DATA_TYPE_KEYFRAME : Stream::DATA_TYPE_OTHER);
56         }
57 }
58
59 int HTTPD::answer_to_connection_thunk(void *cls, MHD_Connection *connection,
60                                       const char *url, const char *method,
61                                       const char *version, const char *upload_data,
62                                       size_t *upload_data_size, void **con_cls)
63 {
64         HTTPD *httpd = (HTTPD *)cls;
65         return httpd->answer_to_connection(connection, url, method, version, upload_data, upload_data_size, con_cls);
66 }
67
68 int HTTPD::answer_to_connection(MHD_Connection *connection,
69                                 const char *url, const char *method,
70                                 const char *version, const char *upload_data,
71                                 size_t *upload_data_size, void **con_cls)
72 {
73         // See if the URL ends in “.metacube”.
74         HTTPD::Stream::Framing framing;
75         if (strstr(url, ".metacube") == url + strlen(url) - strlen(".metacube")) {
76                 framing = HTTPD::Stream::FRAMING_METACUBE;
77         } else {
78                 framing = HTTPD::Stream::FRAMING_RAW;
79         }
80
81         HTTPD::Stream *stream = new HTTPD::Stream(this, framing);
82         stream->add_data(header.data(), header.size(), Stream::DATA_TYPE_HEADER);
83         {
84                 unique_lock<mutex> lock(streams_mutex);
85                 streams.insert(stream);
86         }
87         *con_cls = stream;
88
89         MHD_Response *response;
90
91         if (strcmp(url, "/metrics") == 0) {
92                 string contents = global_metrics.serialize();
93                 response = MHD_create_response_from_buffer(
94                         contents.size(), &contents[0], MHD_RESPMEM_MUST_COPY);
95                 MHD_add_response_header(response, "Content-type", "text/plain");
96         } else {
97                 // Does not strictly have to be equal to MUX_BUFFER_SIZE.
98                 response = MHD_create_response_from_callback(
99                         (size_t)-1, MUX_BUFFER_SIZE, &HTTPD::Stream::reader_callback_thunk, stream, &HTTPD::free_stream);
100                 // TODO: Content-type?
101                 if (framing == HTTPD::Stream::FRAMING_METACUBE) {
102                         MHD_add_response_header(response, "Content-encoding", "metacube");
103                 }
104         }
105
106         int ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
107         MHD_destroy_response(response);  // Only decreases the refcount; actual free is after the request is done.
108
109         return ret;
110 }
111
112 void HTTPD::free_stream(void *cls)
113 {
114         HTTPD::Stream *stream = (HTTPD::Stream *)cls;
115         HTTPD *httpd = stream->get_parent();
116         {
117                 unique_lock<mutex> lock(httpd->streams_mutex);
118                 delete stream;
119                 httpd->streams.erase(stream);
120         }
121 }
122
123 ssize_t HTTPD::Stream::reader_callback_thunk(void *cls, uint64_t pos, char *buf, size_t max)
124 {
125         HTTPD::Stream *stream = (HTTPD::Stream *)cls;
126         return stream->reader_callback(pos, buf, max);
127 }
128
129 ssize_t HTTPD::Stream::reader_callback(uint64_t pos, char *buf, size_t max)
130 {
131         unique_lock<mutex> lock(buffer_mutex);
132         has_buffered_data.wait(lock, [this]{ return should_quit || !buffered_data.empty(); });
133         if (should_quit) {
134                 return 0;
135         }
136
137         ssize_t ret = 0;
138         while (max > 0 && !buffered_data.empty()) {
139                 const string &s = buffered_data.front();
140                 assert(s.size() > used_of_buffered_data);
141                 size_t len = s.size() - used_of_buffered_data;
142                 if (max >= len) {
143                         // Consume the entire (rest of the) string.
144                         memcpy(buf, s.data() + used_of_buffered_data, len);
145                         buf += len;
146                         ret += len;
147                         max -= len;
148                         buffered_data.pop_front();
149                         used_of_buffered_data = 0;
150                 } else {
151                         // We don't need the entire string; just use the first part of it.
152                         memcpy(buf, s.data() + used_of_buffered_data, max);
153                         buf += max;
154                         used_of_buffered_data += max;
155                         ret += max;
156                         max = 0;
157                 }
158         }
159
160         return ret;
161 }
162
163 void HTTPD::Stream::add_data(const char *buf, size_t buf_size, HTTPD::Stream::DataType data_type)
164 {
165         if (buf_size == 0) {
166                 return;
167         }
168         if (data_type == DATA_TYPE_KEYFRAME) {
169                 seen_keyframe = true;
170         } else if (data_type == DATA_TYPE_OTHER && !seen_keyframe) {
171                 // Start sending only once we see a keyframe.
172                 return;
173         }
174
175         unique_lock<mutex> lock(buffer_mutex);
176
177         if (framing == FRAMING_METACUBE) {
178                 metacube2_block_header hdr;
179                 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
180                 hdr.size = htonl(buf_size);
181                 int flags = 0;
182                 if (data_type == DATA_TYPE_HEADER) {
183                         flags |= METACUBE_FLAGS_HEADER;
184                 } else if (data_type == DATA_TYPE_OTHER) {
185                         flags |= METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START;
186                 }
187                 hdr.flags = htons(flags);
188                 hdr.csum = htons(metacube2_compute_crc(&hdr));
189                 buffered_data.emplace_back((char *)&hdr, sizeof(hdr));
190         }
191         buffered_data.emplace_back(buf, buf_size);
192
193         // Send a Metacube2 timestamp every keyframe.
194         if (framing == FRAMING_METACUBE && data_type == DATA_TYPE_KEYFRAME) {
195                 timespec now;
196                 clock_gettime(CLOCK_REALTIME, &now);
197
198                 metacube2_timestamp_packet packet;
199                 packet.type = htobe64(METACUBE_METADATA_TYPE_ENCODER_TIMESTAMP);
200                 packet.tv_sec = htobe64(now.tv_sec);
201                 packet.tv_nsec = htobe64(now.tv_nsec);
202
203                 metacube2_block_header hdr;
204                 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
205                 hdr.size = htonl(sizeof(packet));
206                 hdr.flags = htons(METACUBE_FLAGS_METADATA);
207                 hdr.csum = htons(metacube2_compute_crc(&hdr));
208                 buffered_data.emplace_back((char *)&hdr, sizeof(hdr));
209                 buffered_data.emplace_back((char *)&packet, sizeof(packet));
210         }
211
212         has_buffered_data.notify_all(); 
213 }
214
215 void HTTPD::Stream::stop()
216 {
217         unique_lock<mutex> lock(buffer_mutex);
218         should_quit = true;
219         has_buffered_data.notify_all();
220 }