-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathhttpserver_extension.cpp
More file actions
774 lines (654 loc) · 27.7 KB
/
httpserver_extension.cpp
File metadata and controls
774 lines (654 loc) · 27.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
#define DUCKDB_EXTENSION_MAIN
#include "httpserver_extension.hpp"
#include "duckdb.hpp"
#include "duckdb/common/exception.hpp"
#include "duckdb/common/string_util.hpp"
#include "duckdb/function/scalar_function.hpp"
#include "duckdb/main/extension_util.hpp"
#include "duckdb/common/atomic.hpp"
#include "duckdb/common/exception/http_exception.hpp"
#include "duckdb/common/allocator.hpp"
#include <chrono>
#include <thread>
#include <memory>
#include <cstdlib>
#ifndef _WIN32
#include <syslog.h>
#endif
#define CPPHTTPLIB_OPENSSL_SUPPORT
#include "httplib.hpp"
#include "yyjson.hpp"
#include "discovery.hpp"
#include "play.h"
using namespace duckdb_yyjson; // NOLINT
namespace duckdb {
// Settings management
static std::string GetConfigValue(ClientContext &context, const string &var_name, const string &default_value) {
Value value;
auto &config = ClientConfig::GetConfig(context);
if (!config.GetUserVariable(var_name, value) || value.IsNull()) {
return default_value;
}
return value.ToString();
}
static void SetConfigValue(DataChunk &args, ExpressionState &state, Vector &result,
const string &var_name, const string &value_type) {
UnaryExecutor::Execute<string_t, string_t>(args.data[0], result, args.size(),
[&](string_t value) {
try {
if (value == "" || value.GetSize() == 0) {
throw std::invalid_argument(value_type + " cannot be empty.");
}
ClientConfig::GetConfig(state.GetContext()).SetUserVariable(
var_name,
Value::CreateValue(value.GetString())
);
return StringVector::AddString(result, value_type + " set to: " + value.GetString());
} catch (std::exception &e) {
return StringVector::AddString(result, "Failed to set " + value_type + ": " + e.what());
}
});
}
static void SetEnvValue(DataChunk &args, ExpressionState &state, Vector &result,
const string &var_name, const string &value_type) {
UnaryExecutor::Execute<string_t, string_t>(args.data[0], result, args.size(),
[&](string_t value) {
try {
if (value == "" || value.GetSize() == 0) {
throw std::invalid_argument(value_type + " cannot be empty.");
}
#ifdef _WIN32
_putenv_s(var_name.c_str(), value.GetString().c_str());
#else
setenv(var_name.c_str(), value.GetString().c_str(), true);
#endif
auto new_value = std::getenv("DUCKDB_HTTPSERVER_DISCOVERY");
return StringVector::AddString(result, value_type + " set ENV " + var_name + " to: " + new_value);
} catch (std::exception &e) {
return StringVector::AddString(result, "Failed to set ENV " + var_name + " to " + value_type + ": " + e.what());
}
});
}
static void SetEnableDiscovery(DataChunk &args, ExpressionState &state, Vector &result) {
//SetConfigValue(args, state, result, "httpserve__enable_discovery", "Enable Discovery API");
SetEnvValue(args, state, result, "DUCKDB_HTTPSERVER_DISCOVERY", "Enable Discovery API");
}
static void SetEnableForeground(DataChunk &args, ExpressionState &state, Vector &result) {
SetEnvValue(args, state, result, "DUCKDB_HTTPSERVER_FOREGROUND", "Enable Foreground Execution");
}
struct HttpServerState {
std::unique_ptr<duckdb_httplib_openssl::Server> server;
std::unique_ptr<std::thread> server_thread;
std::atomic<bool> is_running;
DatabaseInstance* db_instance;
unique_ptr<Allocator> allocator;
std::string auth_token;
HttpServerState() : is_running(false), db_instance(nullptr) {}
};
static HttpServerState global_state;
std::string GetColumnType(MaterializedQueryResult &result, idx_t column) {
if (result.RowCount() == 0) {
return "String";
}
switch (result.types[column].id()) {
case LogicalTypeId::FLOAT:
return "Float";
case LogicalTypeId::DOUBLE:
return "Double";
case LogicalTypeId::INTEGER:
return "Int32";
case LogicalTypeId::BIGINT:
return "Int64";
case LogicalTypeId::UINTEGER:
return "UInt32";
case LogicalTypeId::UBIGINT:
return "UInt64";
case LogicalTypeId::VARCHAR:
return "String";
case LogicalTypeId::TIME:
return "DateTime";
case LogicalTypeId::DATE:
return "Date";
case LogicalTypeId::TIMESTAMP:
return "DateTime";
case LogicalTypeId::BOOLEAN:
return "Int8";
default:
return "String";
}
return "String";
}
struct ReqStats {
float elapsed_sec;
int64_t read_bytes;
int64_t read_rows;
};
// Convert the query result to JSON format
static std::string ConvertResultToJSON(MaterializedQueryResult &result, ReqStats &req_stats) {
auto doc = yyjson_mut_doc_new(nullptr);
auto root = yyjson_mut_obj(doc);
yyjson_mut_doc_set_root(doc, root);
// Add meta information
auto meta_array = yyjson_mut_arr(doc);
for (idx_t col = 0; col < result.ColumnCount(); ++col) {
auto column_obj = yyjson_mut_obj(doc);
yyjson_mut_obj_add_str(doc, column_obj, "name", result.ColumnName(col).c_str());
yyjson_mut_arr_append(meta_array, column_obj);
std::string tp(GetColumnType(result, col));
yyjson_mut_obj_add_strcpy(doc, column_obj, "type", tp.c_str());
}
yyjson_mut_obj_add_val(doc, root, "meta", meta_array);
// Add data
auto data_array = yyjson_mut_arr(doc);
for (idx_t row = 0; row < result.RowCount(); ++row) {
auto row_array = yyjson_mut_arr(doc);
for (idx_t col = 0; col < result.ColumnCount(); ++col) {
Value value = result.GetValue(col, row);
if (value.IsNull()) {
yyjson_mut_arr_append(row_array, yyjson_mut_null(doc));
} else {
std::string value_str = value.ToString();
yyjson_mut_arr_append(row_array, yyjson_mut_strncpy(doc, value_str.c_str(), value_str.length()));
}
}
yyjson_mut_arr_append(data_array, row_array);
}
yyjson_mut_obj_add_val(doc, root, "data", data_array);
// Add row count
yyjson_mut_obj_add_int(doc, root, "rows", result.RowCount());
//"statistics":{"elapsed":0.00031403,"rows_read":1,"bytes_read":0}}
auto stat_obj = yyjson_mut_obj_add_obj(doc, root, "statistics");
yyjson_mut_obj_add_real(doc, stat_obj, "elapsed", req_stats.elapsed_sec);
yyjson_mut_obj_add_int(doc, stat_obj, "rows_read", req_stats.read_rows);
yyjson_mut_obj_add_int(doc, stat_obj, "bytes_read", req_stats.read_bytes);
// Write to string
auto data = yyjson_mut_write(doc, 0, nullptr);
if (!data) {
yyjson_mut_doc_free(doc);
throw InternalException("Failed to render the result as JSON, yyjson failed");
}
std::string json_output(data);
free(data);
yyjson_mut_doc_free(doc);
return json_output;
}
// New: Base64 decoding function
std::string base64_decode(const std::string &in) {
std::string out;
std::vector<int> T(256, -1);
for (int i = 0; i < 64; i++)
T["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[i]] = i;
int val = 0, valb = -8;
for (unsigned char c : in) {
if (T[c] == -1) break;
val = (val << 6) + T[c];
valb += 6;
if (valb >= 0) {
out.push_back(char((val >> valb) & 0xFF));
valb -= 8;
}
}
return out;
}
// Auth Check
bool IsAuthenticated(const duckdb_httplib_openssl::Request& req) {
if (global_state.auth_token.empty()) {
return true; // No authentication required if no token is set
}
// Check for X-API-Key header
auto api_key = req.get_header_value("X-API-Key");
if (!api_key.empty() && api_key == global_state.auth_token) {
return true;
}
// Check for Basic Auth
auto auth = req.get_header_value("Authorization");
if (!auth.empty() && auth.compare(0, 6, "Basic ") == 0) {
std::string decoded_auth = base64_decode(auth.substr(6));
if (decoded_auth == global_state.auth_token) {
return true;
}
}
return false;
}
// Convert the query result to NDJSON (JSONEachRow) format
static std::string ConvertResultToNDJSON(MaterializedQueryResult &result) {
std::string ndjson_output;
for (idx_t row = 0; row < result.RowCount(); ++row) {
// Create a new JSON document for each row
auto doc = yyjson_mut_doc_new(nullptr);
auto root = yyjson_mut_obj(doc);
yyjson_mut_doc_set_root(doc, root);
for (idx_t col = 0; col < result.ColumnCount(); ++col) {
Value value = result.GetValue(col, row);
const char* column_name = result.ColumnName(col).c_str();
// Handle null values and add them to the JSON object
if (value.IsNull()) {
yyjson_mut_obj_add_null(doc, root, column_name);
} else {
// Convert value to string and add it to the JSON object
std::string value_str = value.ToString();
yyjson_mut_obj_add_strncpy(doc, root, column_name, value_str.c_str(), value_str.length());
}
}
char *json_line = yyjson_mut_write(doc, 0, nullptr);
if (!json_line) {
yyjson_mut_doc_free(doc);
throw InternalException("Failed to render a row as JSON, yyjson failed");
}
ndjson_output += json_line;
ndjson_output += "\n";
// Free allocated memory for this row
free(json_line);
yyjson_mut_doc_free(doc);
}
return ndjson_output;
}
static void HandleQuery(const string& query, duckdb_httplib_openssl::Response& res) {
try {
if (!global_state.db_instance) {
throw IOException("Database instance not initialized");
}
Connection con(*global_state.db_instance);
const auto& start = std::chrono::system_clock::now();
auto result = con.Query(query);
const auto end = std::chrono::system_clock::now();
const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
ReqStats req_stats{
static_cast<float>(elapsed.count()) / 1000,
0,
0
};
if (result->HasError()) {
res.status = 400;
res.set_content(result->GetError(), "text/plain");
return;
}
// Convert result to JSON
std::string json_output = ConvertResultToJSON(*result, req_stats);
res.set_content(json_output, "application/json");
} catch (const Exception& ex) {
res.status = 400;
res.set_content(ex.what(), "text/plain");
}
}
// Handle both GET and POST requests
void HandleHttpRequest(const duckdb_httplib_openssl::Request& req, duckdb_httplib_openssl::Response& res) {
std::string query;
// Check authentication
if (!IsAuthenticated(req)) {
res.status = 401;
res.set_content("Unauthorized", "text/plain");
return;
}
// CORS allow
res.set_header("Access-Control-Allow-Origin", "*");
res.set_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT");
res.set_header("Access-Control-Allow-Headers", "*");
res.set_header("Access-Control-Allow-Credentials", "true");
res.set_header("Access-Control-Max-Age", "86400");
// Handle preflight OPTIONS request
if (req.method == "OPTIONS") {
res.status = 204; // No content
return;
}
// Check if the query is in the URL parameters
if (req.has_param("query")) {
query = req.get_param_value("query");
}
else if (req.has_param("q")) {
query = req.get_param_value("q");
}
// If not in URL, and it's a POST request, check the body
else if (req.method == "POST" && !req.body.empty()) {
query = req.body;
}
// If no query found, return an error
else {
res.status = 200;
res.set_content(playContent, "text/html");
return;
}
// Set default format to JSONCompact
std::string format = "JSONEachRow";
// Check for format in URL parameter or header
if (req.has_param("default_format")) {
format = req.get_param_value("default_format");
} else if (req.has_header("X-ClickHouse-Format")) {
format = req.get_header_value("X-ClickHouse-Format");
} else if (req.has_header("format")) {
format = req.get_header_value("format");
}
try {
if (!global_state.db_instance) {
throw IOException("Database instance not initialized");
}
Connection con(*global_state.db_instance);
auto start = std::chrono::system_clock::now();
auto result = con.Query(query);
auto end = std::chrono::system_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
if (result->HasError()) {
res.status = 500;
res.set_content(result->GetError(), "text/plain");
return;
}
ReqStats stats{
static_cast<float>(elapsed.count()) / 1000,
0,
0
};
// Format Options
if (format == "JSONEachRow") {
std::string json_output = ConvertResultToNDJSON(*result);
res.set_content(json_output, "application/x-ndjson");
} else if (format == "JSONCompact") {
std::string json_output = ConvertResultToJSON(*result, stats);
res.set_content(json_output, "application/json");
} else {
// Default to NDJSON for DuckDB's own queries
std::string json_output = ConvertResultToNDJSON(*result);
res.set_content(json_output, "application/x-ndjson");
}
} catch (const Exception& ex) {
res.status = 500;
std::string error_message = "Code: 59, e.displayText() = DB::Exception: " + std::string(ex.what());
res.set_content(error_message, "text/plain");
}
}
// Discovery Functions
void HandleDiscoverySubscribe(const duckdb_httplib_openssl::Request& req, duckdb_httplib_openssl::Response& res) {
string path = req.path;
string hash = path.substr(path.find_last_of('/') + 1);
auto doc = yyjson_read(req.body.c_str(), req.body.length(), 0);
if (!doc) {
res.status = 400;
res.set_content("Invalid JSON", "text/plain");
return;
}
auto root = yyjson_doc_get_root(doc);
PeerData data;
auto name_val = yyjson_obj_get(root, "name");
auto endpoint_val = yyjson_obj_get(root, "endpoint");
auto ttl_val = yyjson_obj_get(root, "ttl");
auto metadata_val = yyjson_obj_get(root, "metadata");
data.name = name_val ? yyjson_get_str(name_val) : "";
data.endpoint = endpoint_val ? yyjson_get_str(endpoint_val) : "";
data.ttl = ttl_val ? yyjson_get_int(ttl_val) : 300;
data.metadata = metadata_val ? yyjson_get_str(metadata_val) : "false";
data.sourceAddress = req.remote_addr;
try {
PeerDiscovery::Instance().registerPeer(hash, data);
std::string peerId = PeerDiscovery::generateDeterministicId(data.name, data.endpoint);
auto rdoc = yyjson_mut_doc_new(nullptr);
auto rroot = yyjson_mut_obj(rdoc);
yyjson_mut_doc_set_root(rdoc, rroot);
yyjson_mut_obj_add_str(rdoc, rroot, "peerId", peerId.c_str());
yyjson_mut_obj_add_str(rdoc, rroot, "message", "Successfully registered");
yyjson_mut_obj_add_int(rdoc, rroot, "ttl", data.ttl);
char* json = yyjson_mut_write(rdoc, 0, nullptr);
res.set_content(json, "application/json");
free(json);
yyjson_mut_doc_free(rdoc);
} catch (const Exception& ex) {
res.status = 500;
res.set_content(ex.what(), "text/plain");
}
yyjson_doc_free(doc);
// cleanup expired
// PeerDiscovery::Instance().cleanupExpired();
}
void HandleDiscoveryGet(const duckdb_httplib_openssl::Request& req, duckdb_httplib_openssl::Response& res) {
std::string path = req.path;
std::string hash = path.substr(path.find_last_of('/') + 1);
// Set default format to JSONCompact
std::string format = "JSONEachRow";
// Check for format in URL parameter or header
if (req.has_param("default_format")) {
format = req.get_param_value("default_format");
} else if (req.has_header("X-ClickHouse-Format")) {
format = req.get_header_value("X-ClickHouse-Format");
} else if (req.has_header("format")) {
format = req.get_header_value("format");
}
try {
auto start = std::chrono::system_clock::now();
auto result = PeerDiscovery::Instance().getPeers(hash, false);
auto end = std::chrono::system_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
// Check if the result has an error using HasError() and GetError()
if (!result || result->HasError()) {
res.status = 500;
res.set_content(result ? result->GetError() : "Query failed", "text/plain");
return;
}
ReqStats stats{
static_cast<float>(elapsed.count()) / 1000,
0,
0
};
// Format Options
if (format == "JSONEachRow") {
std::string json_output = ConvertResultToNDJSON(*result);
res.set_content(json_output, "application/x-ndjson");
} else if (format == "JSONCompact") {
std::string json_output = ConvertResultToJSON(*result, stats);
res.set_content(json_output, "application/json");
} else {
// Default to NDJSON for DuckDB's own queries
std::string json_output = ConvertResultToNDJSON(*result);
res.set_content(json_output, "application/x-ndjson");
}
} catch (const std::exception& ex) {
res.status = 500;
res.set_content(ex.what(), "text/plain");
}
}
void HandleHeartbeat(const duckdb_httplib_openssl::Request& req, duckdb_httplib_openssl::Response& res) {
const auto& hash = req.path_params.at("secretHash");
const auto& peerId = req.path_params.at("peerId");
try {
PeerDiscovery::Instance().updateHeartbeat(hash, peerId);
res.set_content("{\"message\":\"Heartbeat received\"}", "application/json");
} catch (const Exception& ex) {
res.status = 404;
res.set_content("{\"error\":\"Peer not found\"}", "application/json");
}
}
void HandleUnsubscribe(const duckdb_httplib_openssl::Request& req, duckdb_httplib_openssl::Response& res) {
const auto& hash = req.path_params.at("secretHash");
const auto& peerId = req.path_params.at("peerId");
try {
PeerDiscovery::Instance().removePeer(hash, peerId);
res.set_content("{\"message\":\"Successfully unsubscribed\"}", "application/json");
} catch (const Exception& ex) {
res.status = 500;
res.set_content(ex.what(), "text/plain");
}
}
// Server Start
void HttpServerStart(DatabaseInstance& db, string_t host, int32_t port, string_t auth = string_t()) {
if (global_state.is_running) {
throw IOException("HTTP server is already running");
}
global_state.db_instance = &db;
global_state.server = make_uniq<duckdb_httplib_openssl::Server>();
global_state.is_running = true;
global_state.auth_token = auth.GetString();
// CORS Preflight
global_state.server->Options("/",
[](const duckdb_httplib_openssl::Request& /*req*/, duckdb_httplib_openssl::Response& res) {
res.set_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
res.set_header("Content-Type", "text/html; charset=utf-8");
res.set_header("Access-Control-Allow-Headers", "*");
res.set_header("Access-Control-Allow-Origin", "*");
res.set_header("Access-Control-Allow-Credentials", "true");
res.set_header("Connection", "close");
return duckdb_httplib_openssl::Server::HandlerResponse::Handled;
});
// Create a new allocator for the server thread
global_state.allocator = make_uniq<Allocator>();
// Handle GET and POST requests
global_state.server->Get("/", HandleHttpRequest);
global_state.server->Post("/", HandleHttpRequest);
const char* discovery_service_env = std::getenv("DUCKDB_HTTPSERVER_DISCOVERY");
bool discovery_service = (discovery_service_env != nullptr && (std::string(discovery_service_env) == "1" || std::string(discovery_service_env) == "true" ) );
if (discovery_service) {
// Handle Discovery API
global_state.server->Post("/subscribe/[^/]+", [&](const duckdb_httplib_openssl::Request& req, duckdb_httplib_openssl::Response& res) {
HandleDiscoverySubscribe(req, res);
});
global_state.server->Get("/discovery/[^/]+", [&](const duckdb_httplib_openssl::Request& req, duckdb_httplib_openssl::Response& res) {
HandleDiscoveryGet(req, res);
});
global_state.server->Post("/heartbeat/[^/]+/[^/]+", [&](const duckdb_httplib_openssl::Request& req, duckdb_httplib_openssl::Response& res) {
HandleHeartbeat(req, res);
});
global_state.server->Delete("/unsubscribe/[^/]+/[^/]+", [&](const duckdb_httplib_openssl::Request& req, duckdb_httplib_openssl::Response& res) {
HandleUnsubscribe(req, res);
});
}
// Health check endpoint
global_state.server->Get("/ping", [](const duckdb_httplib_openssl::Request& req, duckdb_httplib_openssl::Response& res) {
res.set_content("OK", "text/plain");
});
// Initialize PeerDiscovery with the database instance
PeerDiscovery::Initialize(db);
string host_str = host.GetString();
#ifndef _WIN32
const char* debug_env = std::getenv("DUCKDB_HTTPSERVER_DEBUG");
const char* use_syslog = std::getenv("DUCKDB_HTTPSERVER_SYSLOG");
if (debug_env != nullptr && std::string(debug_env) == "1") {
global_state.server->set_logger([](const duckdb_httplib_openssl::Request& req, const duckdb_httplib_openssl::Response& res) {
time_t now_time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
char timestr[32];
strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S", localtime(&now_time));
// Use \r\n for consistent line endings
fprintf(stdout, "[%s] %s %s - %d - from %s:%d\r\n",
timestr,
req.method.c_str(),
req.path.c_str(),
res.status,
req.remote_addr.c_str(),
req.remote_port);
fflush(stdout);
});
} else if (use_syslog != nullptr && std::string(use_syslog) == "1") {
openlog("duckdb-httpserver", LOG_PID | LOG_NDELAY, LOG_LOCAL0);
global_state.server->set_logger([](const duckdb_httplib_openssl::Request& req, const duckdb_httplib_openssl::Response& res) {
syslog(LOG_INFO, "%s %s - %d - from %s:%d",
req.method.c_str(),
req.path.c_str(),
res.status,
req.remote_addr.c_str(),
req.remote_port);
});
std::atexit([]() {
closelog();
});
}
#endif
const char* run_in_same_thread_env = std::getenv("DUCKDB_HTTPSERVER_FOREGROUND");
bool run_in_same_thread = (run_in_same_thread_env != nullptr && ( std::string(run_in_same_thread_env) == "1" || std::string(run_in_same_thread_env) == "true" ));
if (run_in_same_thread) {
#ifdef _WIN32
throw IOException("Foreground mode not yet supported on WIN32 platforms.");
#else
// POSIX signal handler for SIGINT (Linux/macOS)
signal(SIGINT, [](int) {
if (global_state.server) {
global_state.server->stop();
}
global_state.is_running = false; // Update the running state
});
// Run the server in the same thread
if (!global_state.server->listen(host_str.c_str(), port)) {
global_state.is_running = false;
throw IOException("Failed to start HTTP server on " + host_str + ":" + std::to_string(port));
}
#endif
// The server has stopped (due to CTRL-C or other reasons)
global_state.is_running = false;
} else {
// Run the server in a dedicated thread (default)
global_state.server_thread = make_uniq<std::thread>([host_str, port]() {
if (!global_state.server->listen(host_str.c_str(), port)) {
global_state.is_running = false;
throw IOException("Failed to start HTTP server on " + host_str + ":" + std::to_string(port));
}
});
}
}
void HttpServerStop() {
if (global_state.is_running) {
global_state.server->stop();
if (global_state.server_thread && global_state.server_thread->joinable()) {
global_state.server_thread->join();
}
global_state.server.reset();
global_state.server_thread.reset();
global_state.db_instance = nullptr;
global_state.is_running = false;
// Reset the allocator
global_state.allocator.reset();
}
}
static void HttpServerCleanup() {
HttpServerStop();
}
static void LoadInternal(DatabaseInstance &instance) {
auto httpserve_start = ScalarFunction("httpserve_start",
{LogicalType::VARCHAR, LogicalType::INTEGER, LogicalType::VARCHAR},
LogicalType::VARCHAR,
[&](DataChunk &args, ExpressionState &state, Vector &result) {
auto &host_vector = args.data[0];
auto &port_vector = args.data[1];
auto &auth_vector = args.data[2];
UnaryExecutor::Execute<string_t, string_t>(
host_vector, result, args.size(),
[&](string_t host) {
auto port = ((int32_t*)port_vector.GetData())[0];
auto auth = ((string_t*)auth_vector.GetData())[0];
HttpServerStart(instance, host, port, auth);
return StringVector::AddString(result, "HTTP server started on " + host.GetString() + ":" + std::to_string(port));
});
});
auto httpserve_stop = ScalarFunction("httpserve_stop",
{},
LogicalType::VARCHAR,
[](DataChunk &args, ExpressionState &state, Vector &result) {
HttpServerStop();
result.SetValue(0, Value("HTTP server stopped"));
});
ExtensionUtil::RegisterFunction(instance, httpserve_start);
ExtensionUtil::RegisterFunction(instance, httpserve_stop);
// Register settings functions
ExtensionUtil::RegisterFunction(instance, ScalarFunction(
"httpserve_enable_discovery", {LogicalType::VARCHAR}, LogicalType::VARCHAR, SetEnableDiscovery));
ExtensionUtil::RegisterFunction(instance, ScalarFunction(
"httpserve_enable_foreground", {LogicalType::VARCHAR}, LogicalType::VARCHAR, SetEnableForeground));
// Register the cleanup function to be called at exit
std::atexit(HttpServerCleanup);
}
void HttpserverExtension::Load(DuckDB &db) {
LoadInternal(*db.instance);
}
std::string HttpserverExtension::Name() {
return "httpserver";
}
std::string HttpserverExtension::Version() const {
#ifdef EXT_VERSION_HTTPSERVER
return EXT_VERSION_HTTPSERVER;
#else
return "";
#endif
}
} // namespace duckdb
extern "C" {
DUCKDB_EXTENSION_API void httpserver_init(duckdb::DatabaseInstance &db) {
duckdb::DuckDB db_wrapper(db);
db_wrapper.LoadExtension<duckdb::HttpserverExtension>();
}
DUCKDB_EXTENSION_API const char *httpserver_version() {
return duckdb::DuckDB::LibraryVersion();
}
}