forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathRestCatalog.cpp
More file actions
1618 lines (1387 loc) · 60.1 KB
/
Copy pathRestCatalog.cpp
File metadata and controls
1618 lines (1387 loc) · 60.1 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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <Poco/JSON/Object.h>
#include <Poco/JSON/Stringifier.h>
#include <Poco/Net/HTTPRequest.h>
#include <Common/Exception.h>
#include <Common/logger_useful.h>
#include <Common/setThreadName.h>
#include <Common/CurrentThread.h>
#include <Storages/ObjectStorage/DataLakes/Iceberg/IcebergWrites.h>
#include <mutex>
#include <chrono>
#include <Core/SettingsEnums.h>
#include "config.h"
#if USE_AVRO
#include <Databases/DataLake/RestCatalog.h>
#include <Databases/DataLake/StorageCredentials.h>
#include <base/find_symbols.h>
#include <Core/Settings.h>
#include <Common/escapeForFileName.h>
#include <Common/threadPoolCallbackRunner.h>
#include <Common/Base64.h>
#include <Common/checkStackSize.h>
#include <IO/ConnectionTimeouts.h>
#include <IO/GCPOAuth.h>
#include <IO/HTTPCommon.h>
#include <IO/ReadBuffer.h>
#include <IO/ReadBufferFromFile.h>
#include <IO/WriteBufferFromString.h>
#include <IO/Operators.h>
#include <Interpreters/Context.h>
#include <filesystem>
#include <Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.h>
#include <Server/HTTP/HTMLForm.h>
#include <Formats/FormatFactory.h>
#include <Poco/URI.h>
#include <Poco/JSON/Array.h>
#include <Poco/JSON/Parser.h>
#include <Poco/Net/HTTPClientSession.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/Net/HTTPSClientSession.h>
#include <Poco/Net/SSLManager.h>
#include <Poco/StreamCopier.h>
#include <Poco/DateTime.h>
#include <Poco/DateTimeFormat.h>
#include <Poco/DateTimeParser.h>
#include <Poco/StringTokenizer.h>
#include <Poco/Timestamp.h>
namespace DB::ErrorCodes
{
extern const int DATALAKE_DATABASE_ERROR;
extern const int LOGICAL_ERROR;
extern const int BAD_ARGUMENTS;
extern const int CATALOG_NAMESPACE_DISABLED;
}
namespace ProfileEvents
{
extern const Event DataLakeRestCatalogLoadConfig;
extern const Event DataLakeRestCatalogLoadConfigMicroseconds;
extern const Event DataLakeRestCatalogGetNamespaces;
extern const Event DataLakeRestCatalogGetNamespacesMicroseconds;
extern const Event DataLakeRestCatalogGetTables;
extern const Event DataLakeRestCatalogGetTablesMicroseconds;
extern const Event DataLakeRestCatalogGetTableMetadata;
extern const Event DataLakeRestCatalogGetTableMetadataMicroseconds;
extern const Event DataLakeRestCatalogGetCredentials;
extern const Event DataLakeRestCatalogGetCredentialsMicroseconds;
extern const Event DataLakeRestCatalogCredentialsVended;
extern const Event DataLakeRestCatalogCredentialsCacheHits;
extern const Event DataLakeRestCatalogAuthTokenCacheHits;
extern const Event DataLakeRestCatalogAuthTokenRefreshed;
extern const Event DataLakeRestCatalogAuthTokenRefreshedMicroseconds;
extern const Event DataLakeRestCatalogAuthTokenRefreshedOnUnauthorized;
extern const Event DataLakeRestCatalogCreateNamespace;
extern const Event DataLakeRestCatalogCreateNamespaceMicroseconds;
extern const Event DataLakeRestCatalogCreateTable;
extern const Event DataLakeRestCatalogCreateTableMicroseconds;
extern const Event DataLakeRestCatalogUpdateTable;
extern const Event DataLakeRestCatalogUpdateTableMicroseconds;
extern const Event DataLakeRestCatalogDropTable;
extern const Event DataLakeRestCatalogDropTableMicroseconds;
}
namespace DataLake
{
static constexpr auto CONFIG_ENDPOINT = "config";
static constexpr auto NAMESPACES_ENDPOINT = "namespaces";
namespace
{
std::pair<std::string, std::string> parseCatalogCredential(const std::string & catalog_credential)
{
/// Parse a string of format "<client_id>:<client_secret>"
/// into separare strings client_id and client_secret.
std::string client_id;
std::string client_secret;
if (!catalog_credential.empty())
{
auto pos = catalog_credential.find(':');
if (pos == std::string::npos)
{
throw DB::Exception(
DB::ErrorCodes::BAD_ARGUMENTS, "Unexpected format of catalog credential: "
"expected client_id and client_secret separated by `:`");
}
client_id = catalog_credential.substr(0, pos);
client_secret = catalog_credential.substr(pos + 1);
}
return std::pair(client_id, client_secret);
}
DB::HTTPHeaderEntry parseAuthHeader(const std::string & auth_header)
{
/// Parse a string of format "Authorization: <auth_scheme> <auth_token>"
/// into a key-value header "Authorization", "<auth_scheme> <auth_token>"
auto pos = auth_header.find(':');
if (pos == std::string::npos)
throw DB::Exception(DB::ErrorCodes::BAD_ARGUMENTS, "Unexpected format of auth header");
return DB::HTTPHeaderEntry(auth_header.substr(0, pos), auth_header.substr(pos + 1));
}
std::string correctAPIURI(const std::string & uri)
{
if (uri.ends_with("v1"))
return uri;
return std::filesystem::path(uri) / "v1";
}
String encodeNamespaceForURI(const String & namespace_name)
{
String encoded;
for (const auto & ch : namespace_name)
{
if (ch == '.')
encoded += "%1F";
else
encoded.push_back(ch);
}
return encoded;
}
}
std::string RestCatalog::Config::toString() const
{
DB::WriteBufferFromOwnString wb;
if (!prefix.empty())
wb << "prefix: " << prefix.string() << ", ";
if (!default_base_location.empty())
wb << "default_base_location: " << default_base_location << ", ";
return wb.str();
}
RestCatalog::RestCatalog(
const std::string & warehouse_,
const std::string & base_url_,
const std::string & catalog_credential_,
const std::string & auth_scope_,
const std::string & auth_header_,
const std::string & oauth_server_uri_,
bool oauth_server_use_request_body_,
const std::string & namespaces_,
DB::ContextPtr context_)
: ICatalog(warehouse_)
, DB::WithContext(context_)
, base_url(correctAPIURI(base_url_))
, log(getLogger("RestCatalog(" + warehouse_ + ")"))
, auth_scope(auth_scope_)
, oauth_server_uri(oauth_server_uri_)
, oauth_server_use_request_body(oauth_server_use_request_body_)
, allowed_namespaces(namespaces_)
{
if (!catalog_credential_.empty())
{
std::tie(client_id, client_secret) = parseCatalogCredential(catalog_credential_);
update_token_if_expired = true;
}
else if (!auth_header_.empty())
{
auth_header = parseAuthHeader(auth_header_);
}
config = loadConfig();
}
RestCatalog::RestCatalog(
const std::string & warehouse_,
const std::string & base_url_,
const std::string & auth_scope_,
const std::string & oauth_server_uri_,
bool oauth_server_use_request_body_,
const std::string & namespaces_,
DB::ContextPtr context_)
: ICatalog(warehouse_)
, DB::WithContext(context_)
, base_url(correctAPIURI(base_url_))
, log(getLogger("RestCatalog(" + warehouse_ + ")"))
, auth_scope(auth_scope_)
, oauth_server_uri(oauth_server_uri_)
, oauth_server_use_request_body(oauth_server_use_request_body_)
, allowed_namespaces(namespaces_)
{
}
RestCatalog::Config RestCatalog::loadConfig()
{
Poco::URI::QueryParameters params = {{"warehouse", warehouse}};
std::string json_str;
{
ProfileEvents::increment(ProfileEvents::DataLakeRestCatalogLoadConfig);
auto timer = DB::CurrentThread::getProfileEvents().timer(ProfileEvents::DataLakeRestCatalogLoadConfigMicroseconds);
auto buf = createReadBuffer(CONFIG_ENDPOINT, params);
readJSONObjectPossiblyInvalid(json_str, *buf);
}
LOG_DEBUG(log, "Received catalog configuration settings: {}", json_str);
Poco::JSON::Parser parser;
Poco::Dynamic::Var json = parser.parse(json_str);
const Poco::JSON::Object::Ptr & object = json.extract<Poco::JSON::Object::Ptr>();
Config result;
auto defaults_object = object->get("defaults").extract<Poco::JSON::Object::Ptr>();
parseCatalogConfigurationSettings(defaults_object, result);
auto overrides_object = object->get("overrides").extract<Poco::JSON::Object::Ptr>();
parseCatalogConfigurationSettings(overrides_object, result);
LOG_DEBUG(log, "Parsed catalog configuration settings: {}", result.toString());
return result;
}
void RestCatalog::parseCatalogConfigurationSettings(const Poco::JSON::Object::Ptr & object, Config & result)
{
if (!object)
return;
if (object->has("prefix"))
result.prefix = object->get("prefix").extract<String>();
if (object->has("default-base-location"))
result.default_base_location = object->get("default-base-location").extract<String>();
}
DB::HTTPHeaderEntries RestCatalog::getAuthHeaders(
bool update_token,
const String & /*method*/,
const Poco::URI & /*url*/,
const DB::HTTPHeaderEntries & /*extra_headers*/,
const String & /*body*/,
bool * used_cached_oauth_token) const
{
if (used_cached_oauth_token)
*used_cached_oauth_token = false;
/// Option 1: user specified auth header manually.
/// Header has format: 'Authorization: <scheme> <token>'.
if (auth_header.has_value())
{
return DB::HTTPHeaderEntries{auth_header.value()};
}
/// Option 2: user provided grant_type, client_id and client_secret.
/// We would make OAuthClientCredentialsRequest
/// https://github.com/apache/iceberg/blob/3badfe0c1fcf0c0adfc7aa4a10f0b50365c48cf9/open-api/rest-catalog-open-api.yaml#L3498C5-L3498C34
if (!client_id.empty())
{
if (!access_token.has_value() || update_token || access_token->isExpired())
{
access_token = retrieveAccessToken();
}
else if (used_cached_oauth_token)
{
*used_cached_oauth_token = true;
}
DB::HTTPHeaderEntries headers;
headers.emplace_back("Authorization", "Bearer " + access_token.value().token);
return headers;
}
return {};
}
OneLakeCatalog::OneLakeCatalog(
const std::string & warehouse_,
const std::string & base_url_,
const std::string & onelake_tenant_id,
const std::string & onelake_client_id,
const std::string & onelake_client_secret,
const std::string & auth_scope_,
const std::string & oauth_server_uri_,
bool oauth_server_use_request_body_,
const std::string & namespaces_,
DB::ContextPtr context_)
: RestCatalog(warehouse_, base_url_, auth_scope_, oauth_server_uri_, oauth_server_use_request_body_, namespaces_, context_)
, tenant_id(onelake_tenant_id)
{
client_id = onelake_client_id;
client_secret = onelake_client_secret;
update_token_if_expired = true;
// Get token before loading config so getAuthHeaders() can work
if (!client_id.empty() && !client_secret.empty())
{
access_token = retrieveAccessToken();
}
config = loadConfig();
}
AccessToken RestCatalog::retrieveAccessToken() const
{
ProfileEvents::increment(ProfileEvents::DataLakeRestCatalogAuthTokenRefreshed);
auto timer = DB::CurrentThread::getProfileEvents().timer(ProfileEvents::DataLakeRestCatalogAuthTokenRefreshedMicroseconds);
static constexpr auto oauth_tokens_endpoint = "oauth/tokens";
/// TODO:
/// 1. support oauth2-server-uri
/// https://github.com/apache/iceberg/blob/918f81f3c3f498f46afcea17c1ac9cdc6913cb5c/open-api/rest-catalog-open-api.yaml#L183C82-L183C99
Poco::URI url;
DB::ReadWriteBufferFromHTTP::OutStreamCallback out_stream_callback;
size_t body_size = 0;
String body;
if (oauth_server_uri.empty() && !oauth_server_use_request_body)
{
url = Poco::URI(base_url / oauth_tokens_endpoint);
Poco::URI::QueryParameters params = {
{"grant_type", "client_credentials"},
{"scope", auth_scope},
{"client_id", client_id},
{"client_secret", client_secret},
};
url.setQueryParameters(params);
}
else
{
String encoded_auth_scope;
String encoded_client_id;
String encoded_client_secret;
Poco::URI::encode(auth_scope, auth_scope, encoded_auth_scope);
Poco::URI::encode(client_id, client_id, encoded_client_id);
Poco::URI::encode(client_secret, client_secret, encoded_client_secret);
body = fmt::format(
"grant_type=client_credentials&scope={}&client_id={}&client_secret={}",
encoded_auth_scope, encoded_client_id, encoded_client_secret);
body_size = body.size();
out_stream_callback = [&](std::ostream & os)
{
os << body;
};
if (oauth_server_uri.empty())
url = Poco::URI(base_url / oauth_tokens_endpoint);
else
url = Poco::URI(oauth_server_uri);
}
const auto & context = getContext();
auto timeouts = DB::ConnectionTimeouts::getHTTPTimeouts(context->getSettingsRef(), context->getServerSettings());
auto session = makeHTTPSession(DB::HTTPConnectionGroupType::HTTP, url, timeouts, {});
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, url.getPathAndQuery(),
Poco::Net::HTTPMessage::HTTP_1_1);
request.setContentType("application/x-www-form-urlencoded");
request.setContentLength(body_size);
request.set("Accept", "application/json");
std::ostream & os = session->sendRequest(request);
out_stream_callback(os);
Poco::Net::HTTPResponse response;
std::istream & rs = session->receiveResponse(response);
std::string json_str;
Poco::StreamCopier::copyToString(rs, json_str);
Poco::JSON::Parser parser;
Poco::Dynamic::Var res_json = parser.parse(json_str);
const Poco::JSON::Object::Ptr & object = res_json.extract<Poco::JSON::Object::Ptr>();
AccessToken token;
token.token = object->get("access_token").extract<String>();
if (object->has("expires_in"))
{
Int64 expires_in = object->getValue<Int64>("expires_in");
/// Use 90% of the token lifetime as the validity window so that short-lived tokens
/// (e.g. expires_in=300) still get a sensible buffer instead of going non-positive.
token.expires_at = std::chrono::system_clock::now() + std::chrono::seconds(expires_in * 9 / 10);
}
return token;
}
BigLakeCatalog::BigLakeCatalog(
const std::string & warehouse_,
const std::string & base_url_,
const std::string & google_project_id_,
const std::string & google_service_account_,
const std::string & google_metadata_service_,
const std::string & google_adc_client_id_,
const std::string & google_adc_client_secret_,
const std::string & google_adc_refresh_token_,
const std::string & google_adc_quota_project_id_,
const std::string & namespaces_,
DB::ContextPtr context_)
: RestCatalog(warehouse_, base_url_, "", "", false, namespaces_, context_)
, google_project_id(google_project_id_)
, google_service_account(google_service_account_)
, google_metadata_service(google_metadata_service_)
, google_adc_client_id(google_adc_client_id_)
, google_adc_client_secret(google_adc_client_secret_)
, google_adc_refresh_token(google_adc_refresh_token_)
, google_adc_quota_project_id(google_adc_quota_project_id_)
{
update_token_if_expired = true;
// Get token before loading config so getAuthHeaders() can work
if (!google_project_id.empty() || !google_adc_client_id.empty())
{
access_token = retrieveGoogleCloudAccessToken();
}
config = loadConfig();
}
DB::HTTPHeaderEntries BigLakeCatalog::getAuthHeaders(
bool update_token,
const String & method,
const Poco::URI & url,
const DB::HTTPHeaderEntries & extra_headers,
const String & body,
bool * used_cached_oauth_token) const
{
/// Google Cloud OAuth2 for BigLake.
/// Uses GCP metadata service or Application Default Credentials to get access token.
/// Only use Google OAuth if explicitly configured (google_project_id or google_adc_client_id).
/// https://developers.google.com/identity/protocols/oauth2
if (!google_project_id.empty() || !google_adc_client_id.empty())
{
if (used_cached_oauth_token)
*used_cached_oauth_token = false;
if (!access_token.has_value() || update_token || access_token->isExpired())
{
access_token = retrieveGoogleCloudAccessToken();
}
else if (used_cached_oauth_token)
{
*used_cached_oauth_token = true;
}
DB::HTTPHeaderEntries headers;
headers.emplace_back("Authorization", "Bearer " + access_token->token);
std::string project_id = google_project_id;
if (project_id.empty() && !google_adc_quota_project_id.empty())
{
project_id = google_adc_quota_project_id;
}
if (!project_id.empty())
{
headers.emplace_back("x-goog-user-project", project_id);
}
return headers;
}
return RestCatalog::getAuthHeaders(update_token, method, url, extra_headers, body, used_cached_oauth_token);
}
AccessToken BigLakeCatalog::retrieveGoogleCloudAccessTokenFromRefreshToken() const
{
if (google_adc_client_id.empty() || google_adc_client_secret.empty() || google_adc_refresh_token.empty())
throw DB::Exception(
DB::ErrorCodes::BAD_ARGUMENTS,
"Invalid ADC credentials: client_id, client_secret, and refresh_token are required");
const auto & context = getContext();
auto timeouts = DB::ConnectionTimeouts::getHTTPTimeouts(context->getSettingsRef(), context->getServerSettings());
auto result = fetchGCPOAuthToken(google_adc_client_id, google_adc_client_secret, google_adc_refresh_token, timeouts);
AccessToken token;
token.token = std::move(result.access_token);
token.expires_at = std::chrono::system_clock::now() + std::chrono::seconds(result.expires_in * 9 / 10);
return token;
}
AccessToken BigLakeCatalog::retrieveGoogleCloudAccessToken() const
{
ProfileEvents::increment(ProfileEvents::DataLakeRestCatalogAuthTokenRefreshed);
auto timer = DB::CurrentThread::getProfileEvents().timer(ProfileEvents::DataLakeRestCatalogAuthTokenRefreshedMicroseconds);
if (!google_adc_client_id.empty() && !google_adc_client_secret.empty() && !google_adc_refresh_token.empty())
{
try
{
return retrieveGoogleCloudAccessTokenFromRefreshToken();
}
catch (const DB::Exception & e)
{
LOG_DEBUG(log, "Failed to use ADC credentials, falling back to metadata service: {}", e.what());
}
}
/// Fallback to GCP metadata service (works inside GCP infrastructure)
/// https://cloud.google.com/compute/docs/metadata/overview
static constexpr auto DEFAULT_REQUEST_TOKEN_PATH = "/computeMetadata/v1/instance/service-accounts";
Poco::URI url;
url.setScheme("http");
url.setHost(google_metadata_service);
url.setPath(fmt::format("{}/{}/token", DEFAULT_REQUEST_TOKEN_PATH, google_service_account));
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, url.toString(), Poco::Net::HTTPRequest::HTTP_1_1);
request.add("metadata-flavor", "Google");
LOG_DEBUG(log, "Requesting Google Cloud access token from metadata service: {}", url.toString());
const auto & context = getContext();
auto timeouts = DB::ConnectionTimeouts::getHTTPTimeouts(context->getSettingsRef(), context->getServerSettings());
auto session = makeHTTPSession(DB::HTTPConnectionGroupType::HTTP, url, timeouts, {});
if (!session)
throw DB::Exception(DB::ErrorCodes::BAD_ARGUMENTS, "Can not create HTTP session");
session->sendRequest(request);
Poco::Net::HTTPResponse response;
auto & in = session->receiveResponse(response);
if (response.getStatus() != Poco::Net::HTTPResponse::HTTP_OK)
{
throw DB::Exception(
DB::ErrorCodes::BAD_ARGUMENTS,
"Failed to request Google Cloud bearer token from metadata service: {} (status: {})",
response.getReason(),
static_cast<int>(response.getStatus()));
}
String token_json_raw;
Poco::StreamCopier::copyToString(in, token_json_raw);
LOG_DEBUG(log, "Received Google Cloud token response from metadata service");
Poco::JSON::Parser parser;
auto object = parser.parse(token_json_raw).extract<Poco::JSON::Object::Ptr>();
if (!object->has("access_token") || !object->has("expires_in") || !object->has("token_type"))
{
throw DB::Exception(
DB::ErrorCodes::BAD_ARGUMENTS,
"Unexpected structure of Google Cloud token response. Response should have fields: 'access_token', 'expires_in', 'token_type'");
}
auto token_type = object->getValue<String>("token_type");
if (token_type != "Bearer")
{
throw DB::Exception(
DB::ErrorCodes::BAD_ARGUMENTS,
"Unexpected token type in Google Cloud response. Expected Bearer token, got {}",
token_type);
}
AccessToken token;
token.token = object->getValue<String>("access_token");
if (object->has("expires_in"))
{
Int64 expires_in = object->getValue<Int64>("expires_in");
token.expires_at = std::chrono::system_clock::now() + std::chrono::seconds(expires_in * 9 / 10);
}
return token;
}
std::optional<StorageType> RestCatalog::getStorageType() const
{
if (config.default_base_location.empty())
return std::nullopt;
return parseStorageTypeFromLocation(config.default_base_location);
}
DB::ReadWriteBufferFromHTTPPtr RestCatalog::createReadBuffer(
const std::string & endpoint,
const Poco::URI::QueryParameters & params,
const DB::HTTPHeaderEntries & headers) const
{
const auto & context = getContext();
/// enable_url_encoding=false to allow use tables with encoded sequences in names like 'foo%2Fbar'
Poco::URI url(base_url / endpoint, /* enable_url_encoding */ false);
if (!params.empty())
url.setQueryParameters(params);
auto create_buffer = [&](bool update_token, bool & used_cached_oauth_token)
{
auto result_headers = getAuthHeaders(update_token, Poco::Net::HTTPRequest::HTTP_GET, url, headers, {}, &used_cached_oauth_token);
std::move(headers.begin(), headers.end(), std::back_inserter(result_headers));
return DB::BuilderRWBufferFromHTTP(url)
.withConnectionGroup(DB::HTTPConnectionGroupType::HTTP)
.withSettings(getContext()->getReadSettings())
.withTimeouts(DB::ConnectionTimeouts::getHTTPTimeouts(context->getSettingsRef(), context->getServerSettings()))
.withHostFilter(&getContext()->getRemoteHostFilter())
.withHeaders(result_headers)
.withDelayInit(false)
.withSkipNotFound(false)
.create(credentials);
};
LOG_DEBUG(log, "Requesting: {}", url.toString());
try
{
bool used_cached_oauth_token = false;
auto buf = create_buffer(false, used_cached_oauth_token);
if (used_cached_oauth_token)
ProfileEvents::increment(ProfileEvents::DataLakeRestCatalogAuthTokenCacheHits);
return buf;
}
catch (const DB::HTTPException & e)
{
const auto status = e.getHTTPStatus();
if (update_token_if_expired &&
(status == Poco::Net::HTTPResponse::HTTPStatus::HTTP_UNAUTHORIZED
|| status == Poco::Net::HTTPResponse::HTTPStatus::HTTP_FORBIDDEN))
{
ProfileEvents::increment(ProfileEvents::DataLakeRestCatalogAuthTokenRefreshedOnUnauthorized);
bool used_cached_oauth_token_on_retry = false;
return create_buffer(true, used_cached_oauth_token_on_retry);
}
throw;
}
}
bool RestCatalog::empty() const
{
/// TODO: add a test with empty namespaces and zero namespaces.
bool found_table = false;
auto stop_condition = [&](const std::string & namespace_name) -> bool
{
if (!allowed_namespaces.isNamespaceAllowed(namespace_name, /*nested*/ false))
return false;
const auto tables = getTables(namespace_name, /* limit */1);
found_table = !tables.empty();
return found_table;
};
Namespaces namespaces;
getNamespacesRecursive("", namespaces, stop_condition, /* execute_func */{});
return found_table;
}
DB::Names RestCatalog::getTables() const
{
auto & pool = getContext()->getIcebergCatalogThreadpool();
DB::Names tables;
std::mutex mutex;
{
/// Ensure tables and mutex (capture by reference) outlive runner
DB::ThreadPoolCallbackRunnerLocal<void> runner(pool, DB::ThreadName::DATALAKE_REST_CATALOG);
auto execute_for_each_namespace = [&](const std::string & current_namespace)
{
if (!allowed_namespaces.isNamespaceAllowed(current_namespace, /*nested*/ false))
return;
runner.enqueueAndKeepTrack(
[=, &tables, &mutex, this]
{
auto tables_in_namespace = getTables(current_namespace);
std::lock_guard lock(mutex);
std::move(tables_in_namespace.begin(), tables_in_namespace.end(), std::back_inserter(tables));
});
};
Namespaces namespaces;
getNamespacesRecursive(
/* base_namespace */"", /// Empty base namespace means starting from root.
namespaces,
/* stop_condition */{},
/* execute_func */execute_for_each_namespace);
runner.waitForAllToFinishAndRethrowFirstError();
}
return tables;
}
void RestCatalog::getNamespacesRecursive(
const std::string & base_namespace,
Namespaces & result,
StopCondition stop_condition,
ExecuteFunc func) const
{
checkStackSize();
auto namespaces = getNamespaces(base_namespace);
result.reserve(result.size() + namespaces.size());
result.insert(result.end(), namespaces.begin(), namespaces.end());
for (const auto & current_namespace : namespaces)
{
chassert(current_namespace.starts_with(base_namespace));
/// Protection from subnamepsaces with empty names
if (current_namespace == base_namespace)
{
LOG_WARNING(log, "Namespace {} has a subnamespace with empty name. This is an error in catalog implementation.", base_namespace);
continue;
}
if (stop_condition && stop_condition(current_namespace))
break;
if (func)
{
if (allowed_namespaces.isNamespaceAllowed(current_namespace, /*nested*/ false))
func(current_namespace);
else
{
LOG_DEBUG(log, "Tables in namespace {} are filtered", current_namespace);
}
}
if (allowed_namespaces.isNamespaceAllowed(current_namespace, /*nested*/ true))
getNamespacesRecursive(current_namespace, result, stop_condition, func);
else
{
LOG_DEBUG(log, "Nested namespaces in namespace {} are filtered", current_namespace);
}
}
}
Poco::URI::QueryParameters RestCatalog::createParentNamespaceParams(const std::string & base_namespace) const
{
std::vector<std::string_view> parts;
splitInto<'.'>(parts, base_namespace);
std::string parent_param;
for (const auto & part : parts)
{
/// 0x1F is a unit separator
/// https://github.com/apache/iceberg/blob/70d87f1750627b14b3b25a0216a97db86a786992/open-api/rest-catalog-open-api.yaml#L264
if (!parent_param.empty())
parent_param += static_cast<char>(0x1F);
parent_param += part;
}
return {{"parent", parent_param}};
}
RestCatalog::Namespaces RestCatalog::getNamespaces(const std::string & base_namespace) const
{
Poco::URI::QueryParameters params;
if (!base_namespace.empty())
params = createParentNamespaceParams(base_namespace);
try
{
ProfileEvents::increment(ProfileEvents::DataLakeRestCatalogGetNamespaces);
auto timer = DB::CurrentThread::getProfileEvents().timer(ProfileEvents::DataLakeRestCatalogGetNamespacesMicroseconds);
auto buf = createReadBuffer(config.prefix / NAMESPACES_ENDPOINT, params);
auto namespaces = parseNamespaces(*buf, base_namespace);
LOG_DEBUG(log, "Loaded {} namespaces in base namespace {}", namespaces.size(), base_namespace);
return namespaces;
}
catch (const DB::HTTPException & e)
{
std::string message = fmt::format(
"Received error while fetching list of namespaces from iceberg catalog `{}`. ",
warehouse);
if (e.code() == Poco::Net::HTTPResponse::HTTPStatus::HTTP_NOT_FOUND)
message += "Namespace provided in the `parent` query parameter is not found. ";
message += fmt::format(
"Code: {}, status: {}, message: {}",
e.code(), e.getHTTPStatus(), e.displayText());
throw DB::Exception(DB::ErrorCodes::DATALAKE_DATABASE_ERROR, "{}", message);
}
}
RestCatalog::Namespaces RestCatalog::parseNamespaces(DB::ReadBuffer & buf, const std::string & base_namespace) const
{
if (buf.eof())
return {};
String json_str;
readJSONObjectPossiblyInvalid(json_str, buf);
LOG_DEBUG(log, "Received response: {}", json_str);
try
{
Poco::JSON::Parser parser;
Poco::Dynamic::Var json = parser.parse(json_str);
if (json.type() == typeid(Poco::JSON::Object::Ptr))
{
const Poco::JSON::Object::Ptr & obj = json.extract<Poco::JSON::Object::Ptr>();
if (obj->size() == 0)
return {};
}
const Poco::JSON::Object::Ptr & object = json.extract<Poco::JSON::Object::Ptr>();
auto namespaces_object = object->get("namespaces").extract<Poco::JSON::Array::Ptr>();
if (!namespaces_object)
throw DB::Exception(DB::ErrorCodes::LOGICAL_ERROR, "Cannot parse result");
Namespaces namespaces;
for (size_t i = 0; i < namespaces_object->size(); ++i)
{
auto current_namespace_array = namespaces_object->get(static_cast<int>(i)).extract<Poco::JSON::Array::Ptr>();
if (current_namespace_array->size() == 0)
throw DB::Exception(DB::ErrorCodes::LOGICAL_ERROR, "Expected namespace array to be non-empty");
const int idx = static_cast<int>(current_namespace_array->size()) - 1;
const auto current_namespace = current_namespace_array->get(idx).extract<String>();
/// BigLake does not support multi-level namespaces. When asked for sub-namespaces of
/// a non-empty parent (via ?parent=X), BigLake ignores the filter and returns other
/// top-level namespaces instead. Skip all sub-namespace results to avoid constructing
/// fake multi-level paths like "ns1.ns2" that BigLake will reject with HTTP 400.
if (getCatalogType() == DB::DatabaseDataLakeCatalogType::ICEBERG_BIGLAKE && !base_namespace.empty())
{
continue;
}
const auto full_namespace = base_namespace.empty()
? current_namespace
: base_namespace + "." + current_namespace;
namespaces.push_back(full_namespace);
}
return namespaces;
}
catch (DB::Exception & e)
{
e.addMessage("while parsing JSON: " + json_str);
throw;
}
}
DB::Names RestCatalog::getTables(const std::string & base_namespace, size_t limit) const
{
if (!allowed_namespaces.isNamespaceAllowed(base_namespace, /*nested*/ false))
throw DB::Exception(DB::ErrorCodes::CATALOG_NAMESPACE_DISABLED,
"Namespace {} is filtered by `namespaces` database parameter", base_namespace);
auto encoded_namespace = encodeNamespaceForURI(base_namespace);
const std::string endpoint = std::filesystem::path(NAMESPACES_ENDPOINT) / encoded_namespace / "tables";
ProfileEvents::increment(ProfileEvents::DataLakeRestCatalogGetTables);
auto timer = DB::CurrentThread::getProfileEvents().timer(ProfileEvents::DataLakeRestCatalogGetTablesMicroseconds);
auto buf = createReadBuffer(config.prefix / endpoint);
return parseTables(*buf, base_namespace, limit);
}
DB::Names RestCatalog::parseTables(DB::ReadBuffer & buf, const std::string & base_namespace, size_t limit) const
{
if (buf.eof())
return {};
String json_str;
readJSONObjectPossiblyInvalid(json_str, buf);
LOG_DEBUG(log, "Received tables response for namespace: {}", base_namespace);
try
{
Poco::JSON::Parser parser;
Poco::Dynamic::Var json = parser.parse(json_str);
const Poco::JSON::Object::Ptr & object = json.extract<Poco::JSON::Object::Ptr>();
auto identifiers_object = object->get("identifiers").extract<Poco::JSON::Array::Ptr>();
if (!identifiers_object)
throw DB::Exception(DB::ErrorCodes::LOGICAL_ERROR, "Cannot parse result");
DB::Names tables;
for (size_t i = 0; i < identifiers_object->size(); ++i)
{
const auto current_table_json = identifiers_object->get(static_cast<int>(i)).extract<Poco::JSON::Object::Ptr>();
/// If table has encoded sequence (like 'foo%2Fbar')
/// catalog returns decoded character instead of sequence ('foo/bar')
/// Here name encoded back to 'foo%2Fbar' format
const auto table_name_raw = current_table_json->get("name").extract<String>();
std::string table_name;
Poco::URI::encode(table_name_raw, "/", table_name);
tables.push_back(base_namespace + "." + table_name);
if (limit && tables.size() >= limit)
break;
}
return tables;
}
catch (DB::Exception & e)
{
e.addMessage("while parsing JSON: " + json_str);
throw;
}
}
bool RestCatalog::existsTable(const std::string & namespace_name, const std::string & table_name) const
{
TableMetadata table_metadata;
return tryGetTableMetadata(namespace_name, table_name, getContext(), table_metadata);
}
bool RestCatalog::tryGetTableMetadata(
const std::string & namespace_name,
const std::string & table_name,
DB::ContextPtr context_,
TableMetadata & result) const
{
try
{
return getTableMetadataImpl(namespace_name, table_name, context_, result);
}
catch (const DB::Exception & ex)
{
if (ex.code() == DB::ErrorCodes::CATALOG_NAMESPACE_DISABLED)
throw;
LOG_DEBUG(log, "tryGetTableMetadata response: {}", ex.what());
return false;
}
}
void RestCatalog::getTableMetadata(
const std::string & namespace_name,
const std::string & table_name,
DB::ContextPtr context_,
TableMetadata & result) const
{
if (!getTableMetadataImpl(namespace_name, table_name, context_, result))
throw DB::Exception(DB::ErrorCodes::DATALAKE_DATABASE_ERROR, "No response from iceberg catalog");
}
bool RestCatalog::getTableMetadataImpl(
const std::string & namespace_name,
const std::string & table_name,
DB::ContextPtr context_,
TableMetadata & result) const
{
LOG_DEBUG(log, "Checking table {} in namespace {}", table_name, namespace_name);
if (!allowed_namespaces.isNamespaceAllowed(namespace_name, /*nested*/ false))
throw DB::Exception(DB::ErrorCodes::CATALOG_NAMESPACE_DISABLED,
"Namespace {} is filtered by `namespaces` database parameter", namespace_name);
DB::HTTPHeaderEntries headers;
const bool want_credentials = result.requiresCredentials();
/// Reuse previously vended credentials is possible
std::optional<VendedStorageCredentials> cached_credentials;
if (want_credentials)
{
cached_credentials = tryGetCachedCredentials(namespace_name, table_name);
/// Header `X-Iceberg-Access-Delegation` tells catalog to include storage credentials in LoadTableResponse.
/// Value can be one of the two:
/// 1. `vended-credentials`
/// 2. `remote-signing`
/// Currently we support only the first.
/// https://github.com/apache/iceberg/blob/3badfe0c1fcf0c0adfc7aa4a10f0b50365c48cf9/open-api/rest-catalog-open-api.yaml#L1832
if (cached_credentials)
ProfileEvents::increment(ProfileEvents::DataLakeRestCatalogCredentialsCacheHits);
else
{
ProfileEvents::increment(ProfileEvents::DataLakeRestCatalogCredentialsVended);
headers.emplace_back("X-Iceberg-Access-Delegation", "vended-credentials");
}
}
const std::string endpoint = std::filesystem::path(NAMESPACES_ENDPOINT) / encodeNamespaceForURI(namespace_name) / "tables" / table_name;
String json_str;
{
ProfileEvents::increment(ProfileEvents::DataLakeRestCatalogGetTableMetadata);
auto timer = DB::CurrentThread::getProfileEvents().timer(ProfileEvents::DataLakeRestCatalogGetTableMetadataMicroseconds);
auto buf = createReadBuffer(config.prefix / endpoint, /* params */{}, headers);