forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.cpp
More file actions
1806 lines (1592 loc) · 80 KB
/
Copy pathClient.cpp
File metadata and controls
1806 lines (1592 loc) · 80 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 <Client.h>
#include <base/defines.h>
#include <Client/ConnectionString.h>
#include <Core/Protocol.h>
#include <Core/Settings.h>
/// musl defines stderr as (stderr) which is a self-referential macro
#pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
#include <boost/algorithm/string/replace.hpp>
#include <boost/program_options.hpp>
#include <Common/Config/parseConnectionCredentials.h>
#include <Common/ThreadPool.h>
#include <Common/ThreadStatus.h>
#include <Common/scope_guard_safe.h>
#include <Access/AccessControl.h>
#include <Columns/ColumnString.h>
#include <Common/Config/ConfigHelper.h>
#include <Common/Config/ConfigProcessor.h>
#include <Common/Config/getClientConfigPath.h>
#include <Common/CurrentThread.h>
#include <Common/DateLUT.h>
#include <Common/DateLUTImpl.h>
#include <Common/DNSResolver.h>
#include <Common/QueryScope.h>
#include <Common/Exception.h>
#include <Common/TerminalSize.h>
#include <Common/config_version.h>
#include <Common/formatReadable.h>
#include <IO/ReadBufferFromString.h>
#include <IO/ReadHelpers.h>
#include <IO/SharedThreadPools.h>
#include <IO/WriteBufferFromOStream.h>
#include <IO/WriteHelpers.h>
#include <Interpreters/Context.h>
#include <Client/JWTProvider.h>
#include <Client/ClientBaseHelpers.h>
#include <Client/PortsProbe.h>
#include <Common/NetException.h>
#include <Core/Defines.h>
#include <AggregateFunctions/registerAggregateFunctions.h>
#include <Formats/FormatFactory.h>
#include <Formats/registerFormats.h>
#include <Functions/registerFunctions.h>
#include <Storages/MergeTree/MergeTreeSettings.h>
#include <Poco/Util/Application.h>
#include <Poco/URI.h>
#include <filesystem>
#include "config.h"
#if USE_BUZZHOUSE
# include <Client/BuzzHouse/Generator/ExternalIntegrations.h>
# include <Client/BuzzHouse/Generator/FuzzConfig.h>
#endif
namespace fs = std::filesystem;
using namespace std::literals;
namespace DB
{
namespace Setting
{
extern const SettingsBool use_client_time_zone;
}
namespace ErrorCodes
{
extern const int BAD_ARGUMENTS;
extern const int UNKNOWN_PACKET_FROM_SERVER;
extern const int UNEXPECTED_PACKET_FROM_SERVER;
extern const int NETWORK_ERROR;
extern const int SOCKET_TIMEOUT;
extern const int ATTEMPT_TO_READ_AFTER_EOF;
extern const int AUTHENTICATION_FAILED;
extern const int REQUIRED_SECOND_FACTOR;
extern const int REQUIRED_PASSWORD;
extern const int USER_EXPIRED;
}
Client::Client()
{
fuzzer = QueryFuzzer(randomSeed(), &std::cout, &std::cerr);
}
Client::~Client() = default;
void Client::processError(std::string_view query) const
{
if (server_exception)
{
fmt::print(
stderr,
"Received exception from server (version {}):\n{}\n",
server_version,
getExceptionMessageForLogging(*server_exception, print_stack_trace, true));
if (server_exception->code() == ErrorCodes::USER_EXPIRED)
{
server_exception->rethrow();
}
if (is_interactive)
{
fmt::print(stderr, "\n");
}
else
{
fmt::print(stderr, "(query: {})\n", query);
}
}
if (client_exception)
{
fmt::print(stderr, "Error on processing query: {}\n", client_exception->message());
if (is_interactive)
{
fmt::print(stderr, "\n");
}
else
{
fmt::print(stderr, "(query: {})\n", query);
}
}
// A debug check -- at least some exception must be set, if the error
// flag is set, and vice versa.
chassert(have_error == (client_exception || server_exception));
}
void Client::showWarnings()
{
try
{
std::vector<String> messages = loadWarningMessages();
if (!messages.empty())
{
output_stream << "Warnings:" << std::endl;
for (const auto & message : messages)
output_stream << " * " << message << std::endl;
output_stream << std::endl;
}
}
catch (const std::exception &) // NOLINT(bugprone-empty-catch)
{
}
}
/// Make query to get all server warnings
std::vector<String> Client::loadWarningMessages()
{
/// Older server versions cannot execute the query loading warnings.
constexpr UInt64 min_server_revision_to_load_warnings = DBMS_MIN_PROTOCOL_VERSION_WITH_VIEW_IF_PERMITTED;
if (server_revision < min_server_revision_to_load_warnings)
return {};
std::vector<String> messages;
/// Unlike `\h`, autocomplete and the AI metadata query, this probe is not settings-agnostic: it
/// reads `system.warnings`, and part of that table is derived from the settings the server sees for
/// this query - a changed obsolete setting produces a warning of its own. So send what an ordinary
/// query sends (which also keeps a compatibility-derived value from being serialized as an explicit
/// change, and thus from tripping a profile that pins it read-only), rather than only the
/// compression knobs of `networkCompressionSettings`.
///
/// The one setting that has to be overridden is `dialect`: the probe below is ClickHouse SQL, so a
/// session that switched to another dialect could not parse it. `showWarnings` swallows any
/// exception from here, so that failure would not be an error the user sees, but server warnings
/// silently never being displayed.
///
/// The override is unconditional: only changed settings are serialized, so leaving `dialect` alone
/// when the local value is already `clickhouse` would let the server take the parser from the
/// effective `dialect` of the authenticated user, which a profile may default to Kusto or PRQL.
/// Sending the value a user already has is a no-op for setting constraints, so this does not trip a
/// profile that pins `dialect` as read-only to `clickhouse`.
Settings probe_settings = settingsWithoutCompatibilityDerived().value_or(client_context->getSettingsRef());
probe_settings.set("dialect", String("clickhouse"));
connection->sendQuery(connection_parameters.timeouts,
"SELECT * FROM viewIfPermitted(SELECT message FROM system.warnings ELSE null('message String'))",
{} /* query_parameters */,
"" /* query_id */,
QueryProcessingStage::Complete,
&probe_settings,
&client_context->getClientInfo(), false, {}, {});
while (true)
{
Packet packet = connection->receivePacket();
switch (packet.type)
{
case Protocol::Server::Data:
if (!packet.block.empty())
{
const ColumnString & column = typeid_cast<const ColumnString &>(*packet.block.getByPosition(0).column);
size_t rows = packet.block.rows();
for (size_t i = 0; i < rows; ++i)
messages.emplace_back(column[i].safeGet<String>());
}
continue;
case Protocol::Server::Progress:
case Protocol::Server::ProfileInfo:
case Protocol::Server::Totals:
case Protocol::Server::Extremes:
case Protocol::Server::Log:
continue;
case Protocol::Server::Exception:
packet.exception->rethrow();
return messages;
case Protocol::Server::EndOfStream:
return messages;
case Protocol::Server::ProfileEvents:
continue;
default:
throw Exception(
ErrorCodes::UNKNOWN_PACKET_FROM_SERVER, "Unknown packet {} from server {}", packet.type, connection->getDescription());
}
}
}
Poco::Util::LayeredConfiguration & Client::getClientConfiguration()
{
return config();
}
void Client::initialize(Poco::Util::Application & self)
{
Poco::Util::Application::initialize(self);
const char * home_path_cstr = getenv("HOME"); // NOLINT(concurrency-mt-unsafe)
if (home_path_cstr)
home_path = home_path_cstr;
const char * env_host = getenv("CLICKHOUSE_HOST"); // NOLINT(concurrency-mt-unsafe)
std::optional<std::string> config_path;
if (config().has("config-file"))
config_path.emplace(config().getString("config-file"));
else
config_path = getClientConfigPath(home_path);
if (config_path.has_value())
{
ConfigProcessor config_processor(*config_path);
auto loaded_config = config_processor.loadConfig();
auto & configuration = *loaded_config.configuration;
std::string default_host;
if (!hosts_and_ports.empty())
default_host = hosts_and_ports.front().host;
else if (config().has("host"))
default_host = config().getString("host");
else if (configuration.has("host"))
default_host = configuration.getString("host");
else if (env_host)
default_host = env_host;
else
default_host = "localhost";
std::optional<std::string> connection_name;
if (config().has("connection"))
connection_name.emplace(config().getString("connection"));
/// Connection credentials overrides should be set via loaded_config.configuration to have proper order.
auto overrides = parseConnectionsCredentials(configuration, default_host, connection_name);
if (overrides.hostname.has_value())
configuration.setString("host", overrides.hostname.value());
if (overrides.port.has_value())
configuration.setInt("port", overrides.port.value());
if (overrides.secure.has_value())
{
if (overrides.secure.value())
configuration.setBool("secure", true);
else
configuration.setBool("no-secure", true);
}
if (overrides.user.has_value())
configuration.setString("user", overrides.user.value());
if (overrides.password.has_value())
configuration.setString("password", overrides.password.value());
if (overrides.database.has_value())
configuration.setString("database", overrides.database.value());
if (overrides.history_file.has_value())
{
auto history_file = overrides.history_file.value();
if (history_file.starts_with("~/") && !home_path.empty())
history_file = home_path / history_file.substr(2);
configuration.setString("history_file", history_file);
}
if (overrides.history_max_entries.has_value())
configuration.setUInt("history_max_entries", overrides.history_max_entries.value());
if (overrides.accept_invalid_certificate.has_value())
configuration.setBool("accept-invalid-certificate", overrides.accept_invalid_certificate.value());
if (overrides.prompt.has_value())
configuration.setString("prompt", overrides.prompt.value());
config().add(loaded_config.configuration);
#if USE_JWT_CPP && USE_SSL
/// If config file has user/password credentials, don't use auto-detected OAuth login for cloud endpoints
if (login_was_auto_added &&
(loaded_config.configuration->has("user") || loaded_config.configuration->has("password")))
{
/// Config file has auth credentials, so disable the auto-added login flag
config().setBool("login", false);
}
#endif
}
else if (config().has("connection"))
throw Exception(ErrorCodes::BAD_ARGUMENTS, "--connection was specified, but config does not exist");
if (config().has("accept-invalid-certificate"))
{
config().setString("openSSL.client.invalidCertificateHandler.name", "AcceptCertificateHandler");
config().setString("openSSL.client.verificationMode", "none");
}
/** getenv is thread-safe in Linux glibc and in all sane libc implementations.
* But the standard does not guarantee that subsequent calls will not rewrite the value by returned pointer.
*
* man getenv:
*
* As typically implemented, getenv() returns a pointer to a string within the environment list.
* The caller must take care not to modify this string, since that would change the environment of
* the process.
*
* The implementation of getenv() is not required to be reentrant. The string pointed to by the return value of getenv()
* may be statically allocated, and can be modified by a subsequent call to getenv(), putenv(3), setenv(3), or unsetenv(3).
*/
const char * env_user = getenv("CLICKHOUSE_USER"); // NOLINT(concurrency-mt-unsafe)
if (env_user && !config().has("user"))
config().setString("user", env_user);
const char * env_password = getenv("CLICKHOUSE_PASSWORD"); // NOLINT(concurrency-mt-unsafe)
if (env_password && !config().has("password"))
config().setString("password", env_password);
if (env_host && !config().has("host"))
config().setString("host", env_host);
/// settings and limits could be specified in config file, but passed settings has higher priority
for (const auto & setting : client_context->getSettingsRef().getUnchangedNames())
{
String name{setting};
/// The `format` config key is owned by the client-side `--format` option, which in
/// `clickhouse-client` is output-only: it is mirrored into the `output_format` setting by
/// `setDefaultFormatsAndCompressionFromConfiguration` (see `mappedFormatOptionSetting`).
/// Feeding it into the bidirectional `format` setting here would make `--format` override
/// the `FORMAT` clause of `INSERT` queries on the input side.
if (name == "format")
continue;
if (config().has(name))
client_context->setSetting(name, config().getString(name));
}
/// Set path for format schema files
if (config().has("format_schema_path"))
client_context->setFormatSchemaPath(fs::weakly_canonical(config().getString("format_schema_path")));
/// Set the path for google proto files
if (config().has("google_protos_path"))
client_context->setGoogleProtosPath(fs::weakly_canonical(config().getString("google_protos_path")));
/// Use <server_client_version_message/> unless --server-client-version-message is specified
if (!config().has("no-server-client-version-message") && !config().getBool("server_client_version_message", true))
config().setBool("no-server-client-version-message", true);
/// Use <warnings/> unless --no-warnings is specified
if (!config().has("no-warnings") && !config().getBool("warnings", true))
config().setBool("no-warnings", true);
/// Use <echo_formatted/>, <echo_query_id/>, <enable_progress_table_toggle/> unless the
/// corresponding dashed CLI option is specified. Shared with `clickhouse-local`.
remapClientConfigurationAliases();
/// The config file is loaded after the command line is processed, so the option parser
/// never sees values that come only from the file. Validate them now, before any query
/// can start: a config typo must not fail open (e.g. run a mutating query and only then
/// throw from a lazy read at the use site).
validateClientConfiguration();
}
int Client::main(const std::vector<std::string> & /*args*/)
try
{
setupSignalHandler();
output_stream << std::fixed << std::setprecision(3);
error_stream << std::fixed << std::setprecision(3);
registerFormats();
registerFunctions();
registerAggregateFunctions();
processConfig();
adjustSettings(client_context);
initTTYBuffer(
toProgressOption(config().getString("progress", "default")), toProgressOption(config().getString("progress-table", "default")));
initKeystrokeInterceptor();
/// Includes delayed_interactive.
if (is_interactive)
{
clearTerminal();
showClientVersion();
}
#if USE_JWT_CPP && USE_SSL
if (config().getBool("login", false))
{
login();
}
#endif
bool asked_password = false;
bool asked_2fa = false;
for (;;)
{
try
{
connect();
break;
}
catch (const Exception & e)
{
auto code = e.code();
bool should_ask_password = !asked_password && is_interactive &&
(code == ErrorCodes::AUTHENTICATION_FAILED || code == ErrorCodes::REQUIRED_PASSWORD) &&
!config().has("password") && !config().getBool("ask-password", false) &&
!config().has("ssh-key-file");
if (should_ask_password)
{
asked_password = true;
config().setBool("ask-password", true);
preserve_announced_endpoint_for_retry = true;
continue;
}
bool should_ask_2fa = !asked_2fa && (code == ErrorCodes::REQUIRED_SECOND_FACTOR) &&
(config().getBool("ask-password", false) || is_interactive) && !config().has("one-time-password");
if (should_ask_2fa)
{
asked_2fa = true;
if (!connection_parameters.password.empty())
config().setString("password", connection_parameters.password);
config().setBool("ask-password", false);
config().setBool("ask-password-2fa", true);
preserve_announced_endpoint_for_retry = true;
continue;
}
throw;
}
}
/// Show warnings at the beginning of connection.
if (is_interactive && !config().has("no-warnings"))
showWarnings();
/// Set user password complexity rules
auto & access_control = client_context->getAccessControl();
access_control.setPasswordComplexityRules(connection->getPasswordComplexityRules());
if (is_interactive && !delayed_interactive && !buzz_house)
{
runInteractive();
}
else
{
connection->setDefaultDatabase(connection_parameters.default_database);
runNonInteractive();
// If exception code isn't zero, we should return non-zero return
// code anyway.
const auto * exception = server_exception ? server_exception.get() : client_exception.get();
if (exception)
{
return static_cast<UInt8>(exception->code()) ? exception->code() : -1;
}
if (have_error)
{
// Shouldn't be set without an exception, but check it just in
// case so that at least we don't lose an error.
return -1;
}
if (delayed_interactive)
runInteractive();
}
return 0;
}
catch (Exception & e)
{
bool need_print_stack_trace = config().getBool("stacktrace", false) && e.code() != ErrorCodes::NETWORK_ERROR;
std::cerr << getExceptionMessageForLogging(e, need_print_stack_trace, true) << std::endl << std::endl;
/// If exception code isn't zero, we should return non-zero return code anyway.
return static_cast<UInt8>(e.code()) ? e.code() : -1;
}
catch (...)
{
std::cerr << getCurrentExceptionMessage(false) << std::endl;
return getCurrentExceptionCode();
}
#if USE_JWT_CPP && USE_SSL
void Client::login()
{
/// `hosts_and_ports` is filled from explicit --host arguments only; the default host is added
/// later, in `connect`. A host given via config, --connection or the environment is still
/// sitting in the configuration at this point.
std::string host = hosts_and_ports.empty()
? getClientConfiguration().getString("host", "localhost")
: hosts_and_ports.front().host;
std::string auth_url = getClientConfiguration().getString("oauth-url", "");
std::string client_id = getClientConfiguration().getString("oauth-client-id", "");
std::string audience = getClientConfiguration().getString("oauth-audience", "");
if ((auth_url.empty() || client_id.empty()) && !isCloudEndpoint(host))
{
throw Exception(
ErrorCodes::BAD_ARGUMENTS,
"Could not retrieve authentication endpoints for host '{}'. Please specify --oauth-url and --oauth-client-id if you are "
"not using ClickHouse Cloud.",
host);
}
jwt_provider = createJwtProvider(auth_url, client_id, audience, host, output_stream, error_stream);
if (jwt_provider)
{
std::string jwt = jwt_provider->getJWT();
if (!jwt.empty())
{
getClientConfiguration().setString("jwt", jwt);
}
else
{
throw Exception(ErrorCodes::AUTHENTICATION_FAILED, "Login failed. Please check your credentials and try again.");
}
}
}
#endif
void Client::connect()
{
/// Only the immediate password or 2FA retry may reuse the previous announcement. Any later
/// reconnect is a separate attempt and must announce its endpoint, even if an earlier reconnect failed.
if (!preserve_announced_endpoint_for_retry)
announced_endpoint.clear();
preserve_announced_endpoint_for_retry = false;
String server_name;
UInt64 server_version_major = 0;
UInt64 server_version_minor = 0;
UInt64 server_version_patch = 0;
/// Capture the client local time zone before the branch below may switch the process default
/// to the server time zone. `serverTimezoneInstance()` reads the process default directly and
/// ignores `session_timezone`; `instance()` would fold in an explicit `--session_timezone` and
/// cache the wrong zone. `connect()` can run again on reconnect, so only capture once.
if (client_local_timezone.empty())
client_local_timezone = DateLUT::serverTimezoneInstance().getTimeZone();
if (hosts_and_ports.empty())
{
String host = config().getString("host", "localhost");
/// Keep the port unset when the configuration does not specify it: this enables the automatic
/// choice between the plain and the secure port below.
std::optional<UInt16> port;
if (config().has("port"))
port = static_cast<UInt16>(config().getInt("port"));
hosts_and_ports.emplace_back(HostAndPort{host, port, {}, {}, false});
}
for (size_t attempted_address_index = 0; attempted_address_index < hosts_and_ports.size(); ++attempted_address_index)
{
try
{
const auto host = ConnectionParameters::Host{hosts_and_ports[attempted_address_index].host};
const auto database = ConnectionParameters::Database{default_database};
connection_parameters = ConnectionParameters(
config(), host, database, hosts_and_ports[attempted_address_index].port);
/// Reuse the transport that already worked for this address (see below), so that a reconnect
/// does not have to probe the ports again.
if (hosts_and_ports[attempted_address_index].secure.has_value())
connection_parameters.security
= *hosts_and_ports[attempted_address_index].secure ? Protocol::Secure::Enable : Protocol::Secure::Disable;
#if USE_JWT_CPP && USE_SSL
connection_parameters.jwt_provider = jwt_provider;
#endif
/// Candidate endpoints for the connection, in the order of preference. Normally there is a
/// single candidate, resolved by `ConnectionParameters`. But when neither the port nor the TLS
/// mode is specified explicitly, both the plain and the secure default ports are probed
/// concurrently, and the one that answers first is used, with TLS enabled automatically when
/// it is the secure one. The probing is concurrent because waiting for a connection attempt to
/// time out first would take too long (for example, play.clickhouse.com serves TLS on 9440
/// while the plain port is silently firewalled).
struct Candidate
{
UInt16 port;
Protocol::Secure security;
/// The address to start from on this port, if any: the host can resolve to several
/// addresses, and the connection has to start with the right one, or it pays a whole
/// connection timeout for every unresponsive address in front of the working one.
std::optional<Poco::Net::SocketAddress> address;
/// The connection the probe has established, if it is this candidate that the probe chose.
/// It is taken over by the `Connection` instead of opening a second one, so that the
/// automatic choice does not leave a short-lived session on the server for every client
/// connection. Only the chosen candidate carries it: by the time a fallback candidate is
/// tried, the first one has spent an unbounded amount of time failing (a TLS handshake can
/// wait out `handshake_timeout_ms`), and the server drops a connection that has not
/// finished its handshake within `handshake_timeout_milliseconds`, so a connection the
/// probe left idle in the meantime is not safe to reuse.
std::optional<Poco::Net::StreamSocket> socket;
};
std::vector<Candidate> candidates;
const bool port_unspecified = !hosts_and_ports[attempted_address_index].port.has_value() && !config().has("port");
const bool secure_unspecified = !hosts_and_ports[attempted_address_index].secure.has_value() && !config().has("secure")
&& !config().has("no-secure") && !isCloudEndpoint(host.toUnderType());
/// Without TLS support in the build there is nothing to choose between: probing the secure port
/// would only replace a working plain connection with `SUPPORT_IS_DISABLED`, which
/// `Connection::connect` throws for every secure connection in such a build.
#if USE_SSL
const bool build_supports_tls = true;
#else
const bool build_supports_tls = false;
#endif
const bool detect_transport = port_unspecified && secure_unspecified && build_supports_tls;
if (detect_transport)
{
const auto plain_port = connection_parameters.port;
const auto secure_port = static_cast<UInt16>(config().getInt("tcp_port_secure", DBMS_DEFAULT_SECURE_PORT));
/// The addresses of a port are attempted one at a time, this much apart, so that a host
/// that resolves to several reachable backends is not connected to on all of them at once
/// (see `probePlainAndSecurePorts`). This is the default of RFC 8305 (Happy Eyeballs).
static const Poco::Timespan address_attempt_delay(0, 250000);
PortsProbeResult probe;
try
{
probe = probePlainAndSecurePorts(
connection_parameters.host,
connection_parameters.bind_host,
plain_port,
secure_port,
connection_parameters.timeouts.connection_timeout,
address_attempt_delay);
}
catch (...)
{
/// The probe runs before any `Connection` is created, so it has to drop possibly stale
/// DNS cache entries on its own: `Connection::connect` does it for every connect-level
/// failure, and without it a later reconnect or failover would reuse the same dead
/// addresses instead of resolving the host again.
DNSResolver::instance().removeHostFromCache(connection_parameters.host);
throw;
}
if (probe.endpoint)
{
const bool secure = probe.endpoint->secure;
candidates.push_back(
{secure ? secure_port : plain_port,
secure ? Protocol::Secure::Enable : Protocol::Secure::Disable,
probe.endpoint->address,
probe.endpoint->socket});
/// The port that answered the probe is not necessarily the port that works: the
/// connection to it can still fail at the native protocol level, e.g. when a proxy in
/// front of the server accepts TCP on the plain port but serves only TLS there, or when
/// the certificate of the automatically chosen secure port is not trusted. The other
/// port is then worth a try before giving up.
///
/// It matters the most for the secure port: TLS was not requested, it was chosen
/// automatically, so a secure port that turns out to be unusable must not make the
/// client fail. The plain port is what it would have connected to if there were no
/// automatic choice at all, so falling back to it takes nothing away from the user. The
/// common case is a server whose secure port has a self-signed or otherwise untrusted
/// certificate, which every client that does not pass `--accept-invalid-certificate`
/// rejects.
///
/// The fallback starts from the other port of the address that answered, because the
/// same backend is the best guess for where that port is; it keeps the fallback from
/// walking the resolved addresses again and paying a whole connection timeout for every
/// unresponsive one in front of it.
const UInt16 other_port = secure ? plain_port : secure_port;
candidates.push_back(
{other_port,
secure ? Protocol::Secure::Disable : Protocol::Secure::Enable,
Poco::Net::SocketAddress(probe.endpoint->address.host(), other_port),
{}});
}
else
{
/// See above: no connection was made, so the resolved addresses may be stale.
DNSResolver::instance().removeHostFromCache(connection_parameters.host);
throw NetException(
probe.timed_out ? ErrorCodes::SOCKET_TIMEOUT : ErrorCodes::NETWORK_ERROR,
"Cannot connect to {} on port {} or on the secure port {}: {}",
connection_parameters.host,
plain_port,
secure_port,
probe.failure_reason);
}
}
else
{
candidates.push_back(
{connection_parameters.port,
connection_parameters.security,
hosts_and_ports[attempted_address_index].address,
{}});
}
/// Names a candidate the way the messages below refer to it.
auto describe = [&](const Candidate & candidate)
{
return fmt::format(
"{}:{}{}",
connection_parameters.host,
candidate.port,
candidate.security == Protocol::Secure::Enable ? " with TLS" : "");
};
/// The failure of the candidate that was tried first, when the connection moved on to the next.
std::exception_ptr first_error;
size_t first_error_index = 0;
for (size_t candidate_index = 0; candidate_index < candidates.size(); ++candidate_index)
{
const auto & candidate = candidates[candidate_index];
connection_parameters.port = candidate.port;
connection_parameters.security = candidate.security;
connection_parameters.preferred_address = candidate.address;
connection_parameters.adopted_socket = candidate.socket;
const bool secure_auto_detected = secure_unspecified && candidate.security == Protocol::Secure::Enable;
if (is_interactive)
{
const auto announcement = fmt::format(
"Connecting to {}{}:{}{}{}.",
connection_parameters.default_database.empty()
? ""
: "database " + connection_parameters.default_database + " at ",
connection_parameters.host,
connection_parameters.port,
secure_auto_detected ? " (secure)" : "",
connection_parameters.user.empty() ? "" : " as user " + connection_parameters.user);
/// The same endpoint can be attempted more than once before the connection is
/// established: a server that requires a password rejects the first attempt, and the
/// client prompts for the password and attempts the very same endpoint again. Repeating
/// the announcement tells the user nothing and reads as if the client had connected
/// twice, so announce an endpoint only when it differs from the one announced last.
if (announcement != announced_endpoint)
{
announced_endpoint = announcement;
output_stream << announcement << std::endl;
}
}
try
{
connection = Connection::createConnection(connection_parameters, client_context);
/// The connection has taken the probed socket over; do not keep a handle to it here.
connection_parameters.adopted_socket.reset();
if (max_client_network_bandwidth)
{
ThrottlerPtr throttler = std::make_shared<Throttler>(max_client_network_bandwidth, 0, "");
connection->setThrottler(throttler);
}
connection->getServerVersion(
connection_parameters.timeouts,
server_name,
server_version_major,
server_version_minor,
server_version_patch,
server_revision);
break;
}
catch (Exception & e)
{
/// The port accepted the TCP connection, but the connection itself failed: e.g. a proxy
/// in front of the server accepts TCP on the plain port but only serves TLS there, or
/// the certificate of the automatically chosen secure port is not trusted. Try the other
/// port before giving up, but only for connection-level failures.
///
/// A TLS-only listener on the plain port answers the native `Hello` with a TLS
/// alert record, whose first byte the client reads as an unexpected packet type,
/// so `Connection::receiveHello` throws `UNEXPECTED_PACKET_FROM_SERVER`; that is
/// the normal outcome of the "plain port serves TLS" case and must be retriable.
///
/// A timeout is not retriable, in contrast: a port that accepts the connection and then
/// does not answer belongs to a server that is unresponsive rather than to a listener of
/// the wrong protocol, and the other port of the same server is not going to answer
/// either. Retrying it would double the time the client waits before it reports the
/// failure, which is exactly the delay this feature is supposed to avoid.
const bool is_connection_error = e.code() == ErrorCodes::NETWORK_ERROR
|| e.code() == ErrorCodes::ATTEMPT_TO_READ_AFTER_EOF
|| e.code() == ErrorCodes::UNKNOWN_PACKET_FROM_SERVER
|| e.code() == ErrorCodes::UNEXPECTED_PACKET_FROM_SERVER;
const bool is_transport_error = is_connection_error || e.code() == ErrorCodes::SOCKET_TIMEOUT;
if (candidate_index + 1 < candidates.size() && is_connection_error)
{
first_error = std::current_exception();
first_error_index = candidate_index;
if (is_interactive)
std::cerr << "Connection to " << describe(candidate) << " failed, trying "
<< describe(candidates[candidate_index + 1]) << "." << std::endl;
continue;
}
if (first_error && is_transport_error)
{
/// Both candidates failed at the connection level. Report the failure of the plain
/// port as the primary error, whichever order the two were tried in: that is the
/// port the client would have used if there were no automatic choice.
const auto & other = candidates[first_error_index];
auto note = [](const String & endpoint, const String & message)
{
return fmt::format("(also failed to connect to {}: {})", endpoint, message);
};
if (candidate.security == Protocol::Secure::Disable)
{
String first_message;
try
{
std::rethrow_exception(first_error);
}
catch (Exception & first_e)
{
first_message = first_e.message();
}
e.addMessage(note(describe(other), first_message));
throw;
}
const auto message = e.message();
try
{
std::rethrow_exception(first_error);
}
catch (Exception & first_e)
{
first_e.addMessage(note(describe(candidate), message));
throw;
}
}
throw;
}
}
config().setString("host", connection_parameters.host);
/// Remember the endpoint that has worked, so that a reconnect to the same address does not
/// probe the ports again. It is remembered for this address only, and not in the global
/// configuration: otherwise a failover to another address would be forced to the same port
/// and the same TLS mode, e.g. a session with `--host secure-only --host plain-only` would
/// keep connecting to the plain-only address on the secure port after the first address
/// answered on it.
hosts_and_ports[attempted_address_index].port = connection_parameters.port;
hosts_and_ports[attempted_address_index].secure = connection_parameters.security == Protocol::Secure::Enable;
if (detect_transport)
hosts_and_ports[attempted_address_index].transport_auto_detected = true;
if (hosts_and_ports[attempted_address_index].transport_auto_detected)
{
/// Remember the address that has answered as well, and not only the port and the TLS mode:
/// the ports are not probed again on a reconnect, and without the address the connection
/// would start from the first address of the host once more and pay a whole connection
/// timeout for every unresponsive address in front of the one that works.
///
/// The address is refreshed after every successful connect, and not only when the ports
/// were probed: a reconnect can fall through from the remembered address to another
/// resolved address of the same host when the old one stopped answering, and keeping
/// the dead address would make every following reconnect wait out a whole connection
/// timeout on it before falling through to the working one again.
hosts_and_ports[attempted_address_index].address = assert_cast<Connection &>(*connection).getResolvedAddress();
}
settings_from_server = assert_cast<Connection &>(*connection).settingsFromServer();
break;
}
catch (Exception & e)
{
/// Forget an automatically chosen transport after a failed connection attempt: it was only
/// valid for the endpoints this host resolved to when the ports were probed. `Connection::connect`
/// drops the `DNSResolver` cache entries for the host on a connect-level failure, so the next
/// attempt can resolve to another backend, e.g. a secure-only backend can be replaced by a
/// plain-only one; keeping the remembered port, TLS mode and address would make the client
/// retry the secure port forever and never rediscover the healthy plain port.
if (hosts_and_ports[attempted_address_index].transport_auto_detected)
{
hosts_and_ports[attempted_address_index].port.reset();
hosts_and_ports[attempted_address_index].secure.reset();
hosts_and_ports[attempted_address_index].address.reset();
hosts_and_ports[attempted_address_index].transport_auto_detected = false;
}
/// This problem can't be fixed with reconnection so it is not attempted
if (e.code() == ErrorCodes::AUTHENTICATION_FAILED || e.code() == ErrorCodes::REQUIRED_PASSWORD)
throw;
if (attempted_address_index == hosts_and_ports.size() - 1)
throw;
if (is_interactive)
{
std::cerr << "Connection attempt to database at " << connection_parameters.host << ":" << connection_parameters.port
<< " resulted in failure" << std::endl
<< getExceptionMessageForLogging(e, false) << std::endl
<< "Attempting connection to the next provided address" << std::endl;
}
}
}
server_version = toString(server_version_major) + "." + toString(server_version_minor) + "." + toString(server_version_patch);
load_suggestions
= is_interactive && (server_revision >= Suggest::MIN_SERVER_REVISION) && !config().getBool("disable_suggestion", false);
wait_for_suggestions_to_load = config().getBool("wait_for_suggestions_to_load", false);
if (load_suggestions)
{
suggestion_limit = config().getInt("suggestion_limit", 10000);
}
server_display_name = connection->getServerDisplayName(connection_parameters.timeouts);
if (server_display_name.empty())
server_display_name = config().getString("host", "localhost");
if (is_interactive)
{
output_stream << "Connected to " << server_name << " server version " << server_version << "." << std::endl << std::endl;
#if not CLICKHOUSE_CLOUD
if (!config().has("no-server-client-version-message"))
{
auto client_version_tuple = std::make_tuple(VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH);
auto server_version_tuple = std::make_tuple(server_version_major, server_version_minor, server_version_patch);
if (client_version_tuple < server_version_tuple)
{
output_stream << "ClickHouse client version is older than ClickHouse server. "
<< "It may lack support for new features." << std::endl
<< std::endl;
}
else if (client_version_tuple > server_version_tuple && server_display_name != "clickhouse-cloud")
{
output_stream << "ClickHouse server version is older than ClickHouse client. "
<< "It may indicate that the server is out of date and can be upgraded." << std::endl
<< std::endl;
}
}
#endif
}