Branch data Line data Source code
1 : : #include <base/phdr_cache.h>
2 : : #include <base/scope_guard.h>
3 : : #include <base/defines.h>
4 : :
5 : : #include <Common/EnvironmentChecks.h>
6 : : #include <Common/Exception.h>
7 : : #include <Common/StringUtils.h>
8 : : #include <Common/getHashOfLoadedBinary.h>
9 : : #include <Common/Crypto/OpenSSLInitializer.h>
10 : :
11 : :
12 : : #include "config.h"
13 : : #include "config_tools.h"
14 : :
15 : : #include <unistd.h>
16 : :
17 : : #include <filesystem>
18 : : #include <iostream>
19 : : #include <new>
20 : : #include <string>
21 : : #include <string_view>
22 : : #include <utility> /// pair
23 : : #include <vector>
24 : :
25 : : #ifdef SANITIZER
26 : : #pragma clang diagnostic push
27 : : #pragma clang diagnostic ignored "-Wreserved-identifier"
28 : : extern "C" {
29 : : #ifdef ADDRESS_SANITIZER
30 : : const char * __asan_default_options()
31 : : {
32 : : return "halt_on_error=1 abort_on_error=1";
33 : : }
34 : : const char * __lsan_default_options()
35 : : {
36 : : return "max_allocation_size_mb=32768";
37 : : }
38 : : const char * __lsan_default_suppressions()
39 : : {
40 : : /// OpenSSL intentionally does not free all global state at exit.
41 : : /// These are known false positives from OpenSSL provider and EVP initialization.
42 : : return "leak:ossl_provider_new\n"
43 : : "leak:OSSL_PROVIDER_try_load_ex\n"
44 : : "leak:ossl_rand_ctx_new\n"
45 : : "leak:OSSL_LIB_CTX_new\n"
46 : : "leak:ossl_legacy_provider_init\n"
47 : : /// OpenSSL EVP method objects are cached globally and never freed at exit.
48 : : /// Triggered when S3 client initializes HMAC (AWS SDK -> OpenSSL HMAC_Init_ex).
49 : : "leak:evp_md_new\n"
50 : : "leak:construct_evp_method\n"
51 : : "leak:CRYPTO_THREAD_lock_new\n";
52 : : }
53 : : #endif
54 : :
55 : : #ifdef MEMORY_SANITIZER
56 : : const char * __msan_default_options()
57 : : {
58 : : return "abort_on_error=1 poison_in_dtor=1 max_allocation_size_mb=32768";
59 : : }
60 : : #endif
61 : :
62 : : #ifdef THREAD_SANITIZER
63 : : const char * __tsan_default_options()
64 : : {
65 : : return "halt_on_error=1 abort_on_error=1 history_size=7 second_deadlock_stack=1 max_allocation_size_mb=32768";
66 : : }
67 : : #endif
68 : :
69 : : #ifdef UNDEFINED_BEHAVIOR_SANITIZER
70 : : const char * __ubsan_default_options()
71 : : {
72 : : return "print_stacktrace=1 max_allocation_size_mb=32768";
73 : : }
74 : : #endif
75 : : }
76 : : #pragma clang diagnostic pop
77 : : #endif
78 : :
79 : : /// Universal executable for various clickhouse applications
80 : : int mainEntryClickHouseBenchmark(int argc, char ** argv);
81 : : int mainEntryClickHouseCheckMarks(int argc, char ** argv);
82 : : int mainEntryClickHouseChecksumForCompressedBlock(int, char **);
83 : : int mainEntryClickHouseClient(int argc, char ** argv);
84 : : int mainEntryClickHouseCompressor(int argc, char ** argv);
85 : : int mainEntryClickHouseDisks(int argc, char ** argv);
86 : : int mainEntryClickHouseExtractFromConfig(int argc, char ** argv);
87 : : int mainEntryClickHouseFormat(int argc, char ** argv);
88 : : int mainEntryClickHouseFstDumpTree(int argc, char ** argv);
89 : : int mainEntryClickHouseGitImport(int argc, char ** argv);
90 : : int mainEntryClickHouseLocal(int argc, char ** argv);
91 : : int mainEntryClickHouseObfuscator(int argc, char ** argv);
92 : : int mainEntryClickHouseSU(int argc, char ** argv);
93 : : int mainEntryClickHouseDockerInit(int argc, char ** argv);
94 : : int mainEntryClickHouseServer(int argc, char ** argv);
95 : : int mainEntryClickHouseStaticFilesDiskUploader(int argc, char ** argv);
96 : : int mainEntryClickHouseZooKeeperDumpTree(int argc, char ** argv);
97 : : int mainEntryClickHouseZooKeeperRemoveByList(int argc, char ** argv);
98 : :
99 : : int mainEntryClickHouseHashBinary(int, char **)
100 : 0 : {
101 : : /// Intentionally without newline. So you can run:
102 : : /// objcopy --add-section .clickhouse.hash=<(./clickhouse hash-binary) clickhouse
103 : 0 : std::cout << getHashOfLoadedBinaryHex();
104 : 0 : return 0;
105 : 0 : }
106 : :
107 : : #if ENABLE_CLICKHOUSE_KEEPER
108 : : int mainEntryClickHouseKeeper(int argc, char ** argv);
109 : : #endif
110 : : #if ENABLE_CLICKHOUSE_KEEPER_CONVERTER
111 : : int mainEntryClickHouseKeeperConverter(int argc, char ** argv);
112 : : #endif
113 : : #if ENABLE_CLICKHOUSE_KEEPER_CLIENT
114 : : int mainEntryClickHouseKeeperClient(int argc, char ** argv);
115 : : #endif
116 : : #if USE_RAPIDJSON && USE_NURAFT
117 : : int mainEntryClickHouseKeeperBench(int argc, char ** argv);
118 : : #endif
119 : : #if USE_NURAFT
120 : : int mainEntryClickHouseKeeperDataDumper(int argc, char ** argv);
121 : : int mainEntryClickHouseKeeperUtils(int argc, char ** argv);
122 : : #endif
123 : :
124 : : #if USE_CHDIG
125 : : extern "C" int chdig_main(int argc, char ** argv);
126 : : int mainEntryClickHouseChdig(int argc, char ** argv)
127 : 4 : {
128 : 4 : return chdig_main(argc, argv);
129 : 4 : }
130 : : #endif
131 : :
132 : : // install
133 : : int mainEntryClickHouseInstall(int argc, char ** argv);
134 : : int mainEntryClickHouseStart(int argc, char ** argv);
135 : : int mainEntryClickHouseStop(int argc, char ** argv);
136 : : int mainEntryClickHouseStatus(int argc, char ** argv);
137 : : int mainEntryClickHouseRestart(int argc, char ** argv);
138 : :
139 : : namespace
140 : : {
141 : :
142 : : using MainFunc = int (*)(int, char**);
143 : :
144 : : /// Add an item here to register new application.
145 : : /// This list has a "priority" - e.g. we need to disambiguate clickhouse --format being
146 : : /// either clickouse-format or clickhouse-{local, client} --format.
147 : : /// Currently we will prefer the latter option.
148 : : std::pair<std::string_view, MainFunc> clickhouse_applications[] =
149 : : {
150 : : {"local", mainEntryClickHouseLocal},
151 : : {"client", mainEntryClickHouseClient},
152 : : #if USE_CHDIG
153 : : {"chdig", mainEntryClickHouseChdig},
154 : : {"dig", mainEntryClickHouseChdig},
155 : : #endif
156 : : {"benchmark", mainEntryClickHouseBenchmark},
157 : : {"server", mainEntryClickHouseServer},
158 : : {"extract-from-config", mainEntryClickHouseExtractFromConfig},
159 : : {"compressor", mainEntryClickHouseCompressor},
160 : : {"format", mainEntryClickHouseFormat},
161 : : {"obfuscator", mainEntryClickHouseObfuscator},
162 : : {"git-import", mainEntryClickHouseGitImport},
163 : : {"static-files-disk-uploader", mainEntryClickHouseStaticFilesDiskUploader},
164 : : {"su", mainEntryClickHouseSU},
165 : : {"docker-init", mainEntryClickHouseDockerInit},
166 : : {"hash-binary", mainEntryClickHouseHashBinary},
167 : : {"disks", mainEntryClickHouseDisks},
168 : : {"check-marks", mainEntryClickHouseCheckMarks},
169 : : {"checksum-for-compressed-block", mainEntryClickHouseChecksumForCompressedBlock},
170 : : {"zookeeper-dump-tree", mainEntryClickHouseZooKeeperDumpTree},
171 : : {"zookeeper-remove-by-list", mainEntryClickHouseZooKeeperRemoveByList},
172 : :
173 : : // keeper
174 : : #if ENABLE_CLICKHOUSE_KEEPER
175 : : {"keeper", mainEntryClickHouseKeeper},
176 : : #endif
177 : : #if ENABLE_CLICKHOUSE_KEEPER_CONVERTER
178 : : {"keeper-converter", mainEntryClickHouseKeeperConverter},
179 : : #endif
180 : : #if ENABLE_CLICKHOUSE_KEEPER_CLIENT
181 : : {"keeper-client", mainEntryClickHouseKeeperClient},
182 : : #endif
183 : : #if USE_RAPIDJSON && USE_NURAFT
184 : : {"keeper-bench", mainEntryClickHouseKeeperBench},
185 : : #endif
186 : : #if USE_NURAFT
187 : : {"keeper-data-dumper", mainEntryClickHouseKeeperDataDumper},
188 : : {"keeper-utils", mainEntryClickHouseKeeperUtils},
189 : : #endif
190 : : // install
191 : : {"install", mainEntryClickHouseInstall},
192 : : {"start", mainEntryClickHouseStart},
193 : : {"stop", mainEntryClickHouseStop},
194 : : {"status", mainEntryClickHouseStatus},
195 : : {"restart", mainEntryClickHouseRestart},
196 : : };
197 : :
198 : : int printHelp(int, char **)
199 : 20 : {
200 : 20 : std::cerr << "Use one of the following commands:" << std::endl;
201 [ + + ]: 20 : for (auto & application : clickhouse_applications)
202 : 620 : std::cerr << "clickhouse " << application.first << " [args] " << std::endl;
203 : 20 : return -1;
204 : 20 : }
205 : :
206 : : /// Add an item here to register a new short name
207 : : std::pair<std::string_view, std::string_view> clickhouse_short_names[] =
208 : : {
209 : : {"chl", "local"},
210 : : {"chc", "client"},
211 : : #if USE_CHDIG
212 : : {"chdig", "chdig"},
213 : : #endif
214 : : };
215 : :
216 : : }
217 : :
218 : : bool isClickhouseApp(std::string_view app_suffix, std::vector<char *> & argv)
219 : 850678 : {
220 [ + + ]: 850678 : for (const auto & [alias, name] : clickhouse_short_names)
221 [ + + ]: 2552034 : if (app_suffix == name
222 [ + - ][ - + ]: 2552034 : && !argv.empty() && (alias == argv[0] || endsWith(argv[0], "/" + std::string(alias))))
[ - + ]
223 : 0 : return true;
224 : :
225 : : /// Use app if the first arg 'app' is passed (the arg should be quietly removed)
226 [ + + ]: 850678 : if (argv.size() >= 2)
227 : 848332 : {
228 : 848332 : auto first_arg = argv.begin() + 1;
229 : :
230 : : /// 'clickhouse --client ...' and 'clickhouse client ...' are Ok
231 [ + + ]: 848332 : if (*first_arg == app_suffix
232 [ + + ][ - + ]: 848332 : || (std::string_view(*first_arg).starts_with("--") && std::string_view(*first_arg).substr(2) == app_suffix))
233 : 86591 : {
234 : 86591 : argv.erase(first_arg);
235 : 86591 : return true;
236 : 86591 : }
237 : 848332 : }
238 : :
239 : : /// Use app if clickhouse binary is run through symbolic link with name clickhouse-app
240 : 764087 : std::string app_name = "clickhouse-" + std::string(app_suffix);
241 [ + - ][ + + ]: 764087 : return !argv.empty() && (app_name == argv[0] || endsWith(argv[0], "/" + app_name));
[ + + ]
242 : 850678 : }
243 : :
244 : : /// Don't allow dlopen in the main ClickHouse binary, because it is harmful and insecure.
245 : : /// We don't use it. But it can be used by some libraries for implementation of "plugins".
246 : : /// We absolutely discourage the ancient technique of loading
247 : : /// 3rd-party uncontrolled dangerous libraries into the process address space,
248 : : /// because it is insane.
249 : :
250 : : #if !defined(USE_MUSL)
251 : : extern "C"
252 : : {
253 : : void * dlopen(const char *, int)
254 : 4315 : {
255 : 4315 : return nullptr;
256 : 4315 : }
257 : :
258 : : void * dlmopen(long, const char *, int) // NOLINT
259 : 0 : {
260 : 0 : return nullptr;
261 : 0 : }
262 : :
263 : : int dlclose(void *)
264 : 0 : {
265 : 0 : return 0;
266 : 0 : }
267 : :
268 : : const char * dlerror()
269 : 36 : {
270 : 36 : return "ClickHouse does not allow dynamic library loading";
271 : 36 : }
272 : : }
273 : : #endif
274 : :
275 : : /// Prevent messages from JeMalloc in the release build.
276 : : /// Some of these messages are non-actionable for the users, such as:
277 : : /// <jemalloc>: Number of CPUs detected is not deterministic. Per-CPU arena disabled.
278 : : #if USE_JEMALLOC && defined(NDEBUG) && !defined(SANITIZER)
279 : : extern "C" void (*je_malloc_message)(void *, const char *s);
280 : 195359 : __attribute__((constructor(0))) void init_je_malloc_message() { je_malloc_message = [](void *, const char *){}; }
281 : : #elif USE_JEMALLOC
282 : : #include <unordered_set>
283 : : /// Ignore messages which can be safely ignored, e.g. EAGAIN on pthread_create
284 : : extern "C" void (*je_malloc_message)(void *, const char * s);
285 : : __attribute__((constructor(0))) void init_je_malloc_message()
286 : : {
287 : : je_malloc_message = [](void *, const char * str)
288 : : {
289 : : using namespace std::literals;
290 : : static const std::unordered_set<std::string_view> ignore_messages{
291 : : "<jemalloc>: background thread creation failed (11)\n"sv};
292 : :
293 : : std::string_view message_view{str};
294 : : if (ignore_messages.contains(message_view))
295 : : return;
296 : :
297 : : # if defined(SYS_write)
298 : : syscall(SYS_write, 2 /*stderr*/, message_view.data(), message_view.size());
299 : : # else
300 : : write(STDERR_FILENO, message_view.data(), message_view.size());
301 : : # endif
302 : : };
303 : : }
304 : : #endif
305 : :
306 : : /// OpenSSL early initialization.
307 : : /// See also EnvironmentChecks.cpp for other static initializers.
308 : : /// Must be ran after EnvironmentChecks.cpp, as OpenSSL uses SSE4.1 and POPCNT.
309 : : __attribute__((constructor(202))) void init_ssl()
310 : 195359 : {
311 : 195359 : DB::OpenSSLInitializer::instance();
312 : 195359 : }
313 : :
314 : : /// This allows to implement assert to forbid initialization of a class in static constructors.
315 : : /// Usage:
316 : : ///
317 : : /// extern bool inside_main;
318 : : /// class C { C() { assert(inside_main); } };
319 : : bool inside_main = false;
320 : :
321 : : int main(int argc_, char ** argv_)
322 : 195359 : {
323 : 195359 : inside_main = true;
324 : 195359 : SCOPE_EXIT({ inside_main = false; });
325 : :
326 : : /// PHDR cache is required for query profiler to work reliably
327 : : /// It also speed up exception handling, but exceptions from dynamically loaded libraries (dlopen)
328 : : /// will work only after additional call of this function.
329 : : /// Note: we forbid dlopen in our code.
330 : 195359 : updatePHDRCache();
331 : :
332 : 195359 : #if !defined(USE_MUSL)
333 : 195359 : checkHarmfulEnvironmentVariables(argv_);
334 : 195359 : #endif
335 : :
336 : : /// This is used for testing. For example,
337 : : /// clickhouse-local should be able to run a simple query without throw/catch.
338 [ + + ]: 195359 : if (getenv("CLICKHOUSE_TERMINATE_ON_ANY_EXCEPTION")) // NOLINT(concurrency-mt-unsafe)
339 : 36 : DB::terminate_on_any_exception = true;
340 : :
341 : : /// Reset new handler to default (that throws std::bad_alloc)
342 : : /// It is needed because LLVM library clobbers it.
343 : 195359 : std::set_new_handler(nullptr);
344 : :
345 : 195359 : std::vector<char *> argv(argv_, argv_ + argc_);
346 : :
347 : : /// Print a basic help if nothing was matched
348 : 195359 : MainFunc main_func = printHelp;
349 : :
350 [ + + ]: 195359 : for (auto & application : clickhouse_applications)
351 : 850678 : {
352 [ + + ]: 850678 : if (isClickhouseApp(application.first, argv))
353 : 195230 : {
354 : 195230 : main_func = application.second;
355 : 195230 : break;
356 : 195230 : }
357 : 850678 : }
358 : :
359 : : /// If host/port arguments are passed to clickhouse/ch shortcuts,
360 : : /// interpret it as clickhouse-client invocation for usability.
361 [ + + ][ + + ]: 195359 : if (main_func == printHelp && argv.size() >= 2)
362 : 125 : {
363 [ + + ]: 306 : for (size_t i = 1, num_args = argv.size(); i < num_args; ++i)
364 : 189 : {
365 [ + + ][ + + ]: 189 : if ((i + 1 < num_args && argv[i] == std::string_view("--host")) || startsWith(argv[i], "--host=")
[ + + ][ - + ]
366 [ + + ][ - + ]: 189 : || (i + 1 < num_args && argv[i] == std::string_view("--port")) || startsWith(argv[i], "--port=")
[ - + ]
367 [ + + ]: 189 : || startsWith(argv[i], "-h"))
368 : 8 : {
369 : 8 : main_func = mainEntryClickHouseClient;
370 : 8 : break;
371 : 8 : }
372 : 189 : }
373 : 125 : }
374 : :
375 : : /// Interpret binary without argument or with arguments starts with dash
376 : : /// ('-') as clickhouse-local for better usability:
377 : : ///
378 : : /// clickhouse help # dumps help
379 : : /// clickhouse -q 'select 1' # use local
380 : : /// clickhouse # spawn local
381 : : /// clickhouse local # spawn local
382 : : /// clickhouse "select ..." # spawn local
383 : : /// clickhouse /tmp/repro --enable-analyzer
384 : : ///
385 : 195359 : std::error_code ec;
386 [ + + ][ + - ]: 195359 : if (main_func == printHelp && !argv.empty()
387 [ + + ][ + + ]: 195359 : && (argv.size() < 2 || argv[1] != std::string_view("--help"))
388 [ + + ][ + + ]: 195359 : && (argv.size() == 1 || argv[1][0] == '-' || std::string_view(argv[1]).contains(' ')
[ + + ]
389 [ + + ]: 113 : || std::filesystem::is_regular_file(std::filesystem::path{argv[1]}, ec)))
390 : 93 : {
391 : 93 : main_func = mainEntryClickHouseLocal;
392 : 93 : }
393 : :
394 : : /// If the argument looks like a file path but doesn't exist, provide a helpful error
395 : : /// instead of the generic "Use one of the following commands" message.
396 : : /// The check above routes existing files to clickhouse-local, but when the file
397 : : /// doesn't exist, we fall through to `printHelp` which is confusing:
398 : : /// $ clickhouse tests/queries/0_stateless/my_test.sql
399 : : /// Use one of the following commands: ...
400 : : /// We detect file-like arguments by the presence of `/` (path separator)
401 : : /// or `.` (file extension), which distinguishes them from mistyped subcommand
402 : : /// names like "clickhouse sever" where the generic help is appropriate.
403 [ + + ][ + - ]: 195359 : if (main_func == printHelp && argv.size() >= 2)
404 : 28 : {
405 : 28 : std::string_view arg(argv[1]);
406 [ + + ][ + + ]: 28 : if (arg.contains('/') || arg.contains('.'))
407 : 8 : {
408 : 8 : std::cerr << "Error: no such file: " << arg << std::endl;
409 : 8 : std::cerr << "If you intended to run a script, please check the path." << std::endl;
410 : 8 : return 1;
411 : 8 : }
412 : 28 : }
413 : :
414 : 195351 : int exit_code = main_func(static_cast<int>(argv.size()), argv.data());
415 : :
416 : 195351 : return exit_code;
417 : 195359 : }
|