Branch data Line data Source code
1 : : #include <base/phdr_cache.h>
2 : : #include <base/scope_guard.h>
3 : : #include <base/defines.h>
4 : : #include <base/sanitizer_options.h>
5 : :
6 : : #include <Common/EnvironmentChecks.h>
7 : : #include <Common/Exception.h>
8 : : #include <Common/StringUtils.h>
9 : : #include <Common/getHashOfLoadedBinary.h>
10 : : #include <Common/Crypto/OpenSSLInitializer.h>
11 : :
12 : :
13 : : #include "config.h"
14 : : #include "config_tools.h"
15 : :
16 : : #include <unistd.h>
17 : :
18 : : #include <filesystem>
19 : : #include <iostream>
20 : : #include <new>
21 : : #include <string>
22 : : #include <string_view>
23 : : #include <utility> /// pair
24 : : #include <vector>
25 : :
26 : : /// Universal executable for various clickhouse applications
27 : : int mainEntryClickHouseBenchmark(int argc, char ** argv);
28 : : int mainEntryClickHouseCheckMarks(int argc, char ** argv);
29 : : int mainEntryClickHouseChecksumForCompressedBlock(int, char **);
30 : : int mainEntryClickHouseClient(int argc, char ** argv);
31 : : int mainEntryClickHouseCompressor(int argc, char ** argv);
32 : : int mainEntryClickHouseDisks(int argc, char ** argv);
33 : : int mainEntryClickHouseExtractFromConfig(int argc, char ** argv);
34 : : int mainEntryClickHouseFormat(int argc, char ** argv);
35 : : int mainEntryClickHouseFstDumpTree(int argc, char ** argv);
36 : : int mainEntryClickHouseGitImport(int argc, char ** argv);
37 : : int mainEntryClickHouseLocal(int argc, char ** argv);
38 : : int mainEntryClickHouseObfuscator(int argc, char ** argv);
39 : : int mainEntryClickHouseOomCanary(int argc, char ** argv);
40 : : int mainEntryClickHouseSU(int argc, char ** argv);
41 : : int mainEntryClickHouseDockerInit(int argc, char ** argv);
42 : : int mainEntryClickHouseServer(int argc, char ** argv);
43 : : int mainEntryClickHouseStaticFilesDiskUploader(int argc, char ** argv);
44 : : int mainEntryClickHouseZooKeeperDumpTree(int argc, char ** argv);
45 : : int mainEntryClickHouseZooKeeperRemoveByList(int argc, char ** argv);
46 : :
47 : : int mainEntryClickHouseHashBinary(int argc, char ** argv);
48 : : int mainEntryClickHouseHashBinary(int argc, char ** argv)
49 : 4 : {
50 [ + - ][ + - ]: 4 : if (argc > 1 && (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0))
[ # # ]
51 : 4 : {
52 : 4 : std::cout << "Usage: clickhouse hash-binary\n"
53 : 4 : "Prints hash of ClickHouse binary.\n"
54 : 4 : " -h, --help Print this message\n"
55 : 4 : "Result is intentionally without newline. So you can run:\n"
56 : 4 : "objcopy --add-section .clickhouse.hash=<(./clickhouse hash-binary) clickhouse\n\n"
57 : 4 : "Current binary hash: ";
58 : 4 : }
59 : 4 : std::cout << getHashOfLoadedBinaryHex();
60 : 4 : return 0;
61 : 4 : }
62 : :
63 : : #if ENABLE_CLICKHOUSE_KEEPER
64 : : int mainEntryClickHouseKeeper(int argc, char ** argv);
65 : : #endif
66 : : #if ENABLE_CLICKHOUSE_KEEPER_CONVERTER
67 : : int mainEntryClickHouseKeeperConverter(int argc, char ** argv);
68 : : #endif
69 : : #if ENABLE_CLICKHOUSE_KEEPER_CLIENT
70 : : int mainEntryClickHouseKeeperClient(int argc, char ** argv);
71 : : #endif
72 : : #if USE_RAPIDJSON && USE_NURAFT
73 : : int mainEntryClickHouseKeeperBench(int argc, char ** argv);
74 : : #endif
75 : : #if USE_NURAFT
76 : : int mainEntryClickHouseKeeperDataDumper(int argc, char ** argv);
77 : : int mainEntryClickHouseKeeperUtils(int argc, char ** argv);
78 : : #endif
79 : :
80 : : #if USE_CHDIG
81 : : extern "C" int chdig_main(int argc, char ** argv);
82 : : int mainEntryClickHouseChdig(int argc, char ** argv);
83 : : int mainEntryClickHouseChdig(int argc, char ** argv)
84 : 4 : {
85 : 4 : return chdig_main(argc, argv);
86 : 4 : }
87 : : #endif
88 : :
89 : : // install
90 : : int mainEntryClickHouseInstall(int argc, char ** argv);
91 : : int mainEntryClickHouseStart(int argc, char ** argv);
92 : : int mainEntryClickHouseStop(int argc, char ** argv);
93 : : int mainEntryClickHouseStatus(int argc, char ** argv);
94 : : int mainEntryClickHouseRestart(int argc, char ** argv);
95 : :
96 : : // packed-io: list/extract/create ClickHouse packed-format archives
97 : : int mainEntryClickHousePackedIO(int argc, char ** argv);
98 : :
99 : : /// Private-only programs
100 : : #if CLICKHOUSE_CLOUD
101 : : int mainEntryClickHouseSharedCatalogUtil(int argc, char ** argv);
102 : : #if ENABLE_DISTRIBUTED_CACHE
103 : : int mainEntryClickHouseDistributedCache(int argc, char ** argv);
104 : : #endif
105 : : int mainEntryClickHouseSharedMergeTreeGarbageCleaner(int argc, char ** argv);
106 : : int mainEntryClickHouseClearZooKeeperLocks(int argc, char ** argv);
107 : : int mainEntryClickHouseMangler(int argc, char ** argv);
108 : : #endif
109 : :
110 : : namespace
111 : : {
112 : :
113 : : using MainFunc = int (*)(int, char**);
114 : :
115 : : /// Forward declaration, since clickhouse_applications is defined after this function.
116 : : void printHelp(std::ostream & out);
117 : :
118 : : int mainEntryHelp(int, char **)
119 : 32 : {
120 : 32 : printHelp(std::cout);
121 : 32 : return 0;
122 : 32 : }
123 : :
124 : : int printHelpOnError(int, char **)
125 : 12 : {
126 : 12 : printHelp(std::cerr);
127 : 12 : return -1;
128 : 12 : }
129 : :
130 : : /// Add an item here to register new application.
131 : : /// This list has a "priority" - e.g. we need to disambiguate clickhouse --format being
132 : : /// either clickouse-format or clickhouse-{local, client} --format.
133 : : /// Currently we will prefer the latter option.
134 : : std::pair<std::string_view, MainFunc> clickhouse_applications[] =
135 : : {
136 : : {"local", mainEntryClickHouseLocal},
137 : : {"client", mainEntryClickHouseClient},
138 : : #if USE_CHDIG
139 : : {"chdig", mainEntryClickHouseChdig},
140 : : {"dig", mainEntryClickHouseChdig},
141 : : #endif
142 : : {"benchmark", mainEntryClickHouseBenchmark},
143 : : {"server", mainEntryClickHouseServer},
144 : : {"extract-from-config", mainEntryClickHouseExtractFromConfig},
145 : : {"compressor", mainEntryClickHouseCompressor},
146 : : {"format", mainEntryClickHouseFormat},
147 : : {"obfuscator", mainEntryClickHouseObfuscator},
148 : : {"oom-canary", mainEntryClickHouseOomCanary},
149 : : {"git-import", mainEntryClickHouseGitImport},
150 : : {"static-files-disk-uploader", mainEntryClickHouseStaticFilesDiskUploader},
151 : : {"su", mainEntryClickHouseSU},
152 : : {"docker-init", mainEntryClickHouseDockerInit},
153 : : {"hash-binary", mainEntryClickHouseHashBinary},
154 : : {"disks", mainEntryClickHouseDisks},
155 : : {"check-marks", mainEntryClickHouseCheckMarks},
156 : : {"checksum-for-compressed-block", mainEntryClickHouseChecksumForCompressedBlock},
157 : : {"zookeeper-dump-tree", mainEntryClickHouseZooKeeperDumpTree},
158 : : {"zookeeper-remove-by-list", mainEntryClickHouseZooKeeperRemoveByList},
159 : :
160 : : // keeper
161 : : #if ENABLE_CLICKHOUSE_KEEPER
162 : : {"keeper", mainEntryClickHouseKeeper},
163 : : #endif
164 : : #if ENABLE_CLICKHOUSE_KEEPER_CONVERTER
165 : : {"keeper-converter", mainEntryClickHouseKeeperConverter},
166 : : #endif
167 : : #if ENABLE_CLICKHOUSE_KEEPER_CLIENT
168 : : {"keeper-client", mainEntryClickHouseKeeperClient},
169 : : #endif
170 : : #if USE_RAPIDJSON && USE_NURAFT
171 : : {"keeper-bench", mainEntryClickHouseKeeperBench},
172 : : #endif
173 : : #if USE_NURAFT
174 : : {"keeper-data-dumper", mainEntryClickHouseKeeperDataDumper},
175 : : {"keeper-utils", mainEntryClickHouseKeeperUtils},
176 : : #endif
177 : : // install
178 : : {"install", mainEntryClickHouseInstall},
179 : : {"start", mainEntryClickHouseStart},
180 : : {"stop", mainEntryClickHouseStop},
181 : : {"status", mainEntryClickHouseStatus},
182 : : {"restart", mainEntryClickHouseRestart},
183 : : // help
184 : : {"help", mainEntryHelp},
185 : : {"packed-io", mainEntryClickHousePackedIO},
186 : :
187 : : /// Private-only programs
188 : : #if CLICKHOUSE_CLOUD
189 : : {"shared-merge-tree-garbage-cleaner", mainEntryClickHouseSharedMergeTreeGarbageCleaner},
190 : : {"clear-zookeeper-locks", mainEntryClickHouseClearZooKeeperLocks},
191 : : {"shared-catalog-util", mainEntryClickHouseSharedCatalogUtil},
192 : : {"mangler", mainEntryClickHouseMangler},
193 : : #if ENABLE_DISTRIBUTED_CACHE
194 : : {"distributed-cache", mainEntryClickHouseDistributedCache}
195 : : #endif
196 : : #endif
197 : : };
198 : :
199 : : void printHelp(std::ostream & out)
200 : 44 : {
201 : 44 : out << "Use one of the following commands:" << std::endl;
202 [ + + ]: 44 : for (const auto & application : clickhouse_applications)
203 : 1496 : out << "clickhouse " << application.first << " [args] " << std::endl;
204 : 44 : }
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 : : static bool isClickHouseApp(std::string_view app_suffix, std::vector<char *> & argv)
219 : 1262683 : {
220 [ + + ]: 1262683 : for (const auto & [alias, name] : clickhouse_short_names)
221 [ + + ]: 3788049 : if (app_suffix == name
222 [ + - ][ - + ]: 688391 : && !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 [ + + ]: 1262683 : if (argv.size() >= 2)
227 : 1259889 : {
228 : 1259889 : auto first_arg = argv.begin() + 1;
229 : :
230 : : /// 'clickhouse --client ...' and 'clickhouse client ...' are Ok
231 [ + + ]: 1259889 : if (*first_arg == app_suffix
232 [ + + ][ + + ]: 1128511 : || (std::string_view(*first_arg).starts_with("--") && std::string_view(*first_arg).substr(2) == app_suffix))
233 : 131390 : {
234 : 131390 : argv.erase(first_arg);
235 : 131390 : return true;
236 : 131390 : }
237 : 1259889 : }
238 : :
239 : : /// Use app if clickhouse binary is run through symbolic link with name clickhouse-app
240 : 1131293 : std::string app_name = "clickhouse-" + std::string(app_suffix);
241 [ + - ][ + + ]: 1131293 : return !argv.empty() && (app_name == argv[0] || endsWith(argv[0], "/" + app_name));
[ + + ]
242 : 1262683 : }
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 : : /// We do allow `dlopen()` in case of OpenSSL FIPS build,
251 : : /// because it requires a FIPS provider (i.e. fips.so), which is loaded dynamically.
252 : : ///
253 : : /// Not on WebAssembly: Emscripten's libc unconditionally defines `dlerror` (its own code
254 : : /// pulls it in), so the override would be a duplicate symbol at the link - and a sandbox
255 : : /// cannot load libraries in the first place.
256 : : #if !(defined(USE_MUSL) || USE_OPENSSL_FIPS || defined(OS_WASM))
257 : : extern "C"
258 : : {
259 : : void * dlopen(const char *, int);
260 : : void * dlmopen(long, const char *, int); // NOLINT
261 : : int dlclose(void *);
262 : : const char * dlerror();
263 : :
264 : : void * dlopen(const char *, int)
265 : 7453 : {
266 : 7453 : return nullptr;
267 : 7453 : }
268 : :
269 : : void * dlmopen(long, const char *, int) // NOLINT
270 : 0 : {
271 : 0 : return nullptr;
272 : 0 : }
273 : :
274 : : int dlclose(void *)
275 : 0 : {
276 : 0 : return 0;
277 : 0 : }
278 : :
279 : : const char * dlerror()
280 : 54 : {
281 : 54 : return "ClickHouse does not allow dynamic library loading";
282 : 54 : }
283 : : }
284 : : #endif
285 : :
286 : : /// Prevent messages from JeMalloc in the release build.
287 : : /// Some of these messages are non-actionable for the users, such as:
288 : : /// <jemalloc>: Number of CPUs detected is not deterministic. Per-CPU arena disabled.
289 : : #if USE_JEMALLOC && defined(NDEBUG) && !defined(SANITIZER)
290 : : extern "C" void (*je_malloc_message)(void *, const char *s);
291 : 285968 : static __attribute__((constructor(0))) void init_je_malloc_message() { je_malloc_message = [](void *, const char *){}; }
292 : : #elif USE_JEMALLOC
293 : : #include <unordered_set>
294 : : /// Ignore messages which can be safely ignored, e.g. EAGAIN on pthread_create
295 : : extern "C" void (*je_malloc_message)(void *, const char * s);
296 : : static __attribute__((constructor(0))) void init_je_malloc_message()
297 : : {
298 : : je_malloc_message = [](void *, const char * str)
299 : : {
300 : : using namespace std::literals;
301 : : static const std::unordered_set<std::string_view> ignore_messages{
302 : : "<jemalloc>: background thread creation failed (11)\n"sv};
303 : :
304 : : std::string_view message_view{str};
305 : : if (ignore_messages.contains(message_view))
306 : : return;
307 : :
308 : : # if defined(SYS_write)
309 : : syscall(SYS_write, 2 /*stderr*/, message_view.data(), message_view.size());
310 : : # else
311 : : write(STDERR_FILENO, message_view.data(), message_view.size());
312 : : # endif
313 : : };
314 : : }
315 : : #endif
316 : :
317 : : /// OpenSSL early initialization.
318 : : /// See also EnvironmentChecks.cpp for other static initializers.
319 : : /// Must be ran after EnvironmentChecks.cpp, as OpenSSL uses SSE4.1 and POPCNT.
320 : : static __attribute__((constructor(202))) void init_ssl()
321 : 285968 : {
322 : 285968 : DB::OpenSSLInitializer::instance();
323 : 285968 : }
324 : :
325 : : /// This allows to implement assert to forbid initialization of a class in static constructors.
326 : : /// Usage:
327 : : ///
328 : : /// extern bool inside_main;
329 : : /// class C { C() { assert(inside_main); } };
330 : : bool inside_main = false;
331 : :
332 : : int main(int argc_, char ** argv_)
333 : 285968 : {
334 : 285968 : inside_main = true;
335 : 285968 : SCOPE_EXIT({ inside_main = false; });
336 : :
337 : : /// PHDR cache is required for query profiler to work reliably
338 : : /// It also speed up exception handling, but exceptions from dynamically loaded libraries (dlopen)
339 : : /// will work only after additional call of this function.
340 : : /// Note: we forbid dlopen in our code.
341 : 285968 : updatePHDRCache();
342 : :
343 : 285968 : #if !defined(USE_MUSL)
344 : 285968 : checkHarmfulEnvironmentVariables(argv_);
345 : 285968 : #endif
346 : :
347 : : /// This is used for testing. For example,
348 : : /// clickhouse-local should be able to run a simple query without throw/catch.
349 [ + + ]: 285968 : if (getenv("CLICKHOUSE_TERMINATE_ON_ANY_EXCEPTION")) // NOLINT(concurrency-mt-unsafe)
350 : 36 : DB::terminate_on_any_exception = true;
351 : :
352 : : /// Reset new handler to default (that throws std::bad_alloc)
353 : : /// It is needed because LLVM library clobbers it.
354 : 285968 : std::set_new_handler(nullptr);
355 : :
356 : 285968 : std::vector<char *> argv(argv_, argv_ + argc_);
357 : :
358 : : /// Print a basic help if nothing was matched
359 : 285968 : MainFunc main_func = printHelpOnError;
360 : :
361 [ + + ]: 285968 : for (auto & application : clickhouse_applications)
362 : 1262683 : {
363 [ + + ]: 1262683 : if (isClickHouseApp(application.first, argv))
364 : 285776 : {
365 : 285776 : main_func = application.second;
366 : 285776 : break;
367 : 285776 : }
368 : 1262683 : }
369 : :
370 : : /// Top-level --help / -h / -? (as the sole argument) should show the dispatcher
371 : : /// help listing all subcommands and exit with code 0. Without this carve-out,
372 : : /// `--help` would match the `startsWith(argv[i], "-h")` rule below and be routed
373 : : /// into clickhouse-client, which treats anything starting with "-h" as a --host
374 : : /// specification and fails.
375 [ + + ][ + + ]: 285968 : if (main_func == printHelpOnError && argv.size() == 2)
376 : 140 : {
377 : 140 : std::string_view arg(argv[1]);
378 [ - + ][ + + ]: 140 : if (arg == "--help" || arg == "-h" || arg == "-?")
[ + + ]
379 : 8 : main_func = mainEntryHelp;
380 : 140 : }
381 : :
382 : : /// If host/port arguments are passed to clickhouse/ch shortcuts,
383 : : /// interpret it as clickhouse-client invocation for usability.
384 [ + + ][ + + ]: 285968 : if (main_func == printHelpOnError && argv.size() >= 2)
385 : 180 : {
386 [ + + ]: 416 : for (size_t i = 1, num_args = argv.size(); i < num_args; ++i)
387 : 244 : {
388 [ + + ][ + + ]: 244 : if ((i + 1 < num_args && argv[i] == std::string_view("--host")) || startsWith(argv[i], "--host=")
[ + + ][ - + ]
389 [ + + ][ - + ]: 240 : || (i + 1 < num_args && argv[i] == std::string_view("--port")) || startsWith(argv[i], "--port=")
[ - + ]
390 [ + + ]: 240 : || startsWith(argv[i], "-h"))
391 : 8 : {
392 : 8 : main_func = mainEntryClickHouseClient;
393 : 8 : break;
394 : 8 : }
395 : 244 : }
396 : 180 : }
397 : :
398 : : /// Interpret binary without argument or with arguments starts with dash
399 : : /// ('-') as clickhouse-local for better usability:
400 : : ///
401 : : /// clickhouse help # dumps help
402 : : /// clickhouse -q 'select 1' # use local
403 : : /// clickhouse # spawn local
404 : : /// clickhouse local # spawn local
405 : : /// clickhouse "select ..." # spawn local
406 : : /// clickhouse /tmp/repro --enable-analyzer
407 : : ///
408 : 285968 : std::error_code ec;
409 [ + + ][ + - ]: 285968 : if (main_func == printHelpOnError && !argv.empty()
410 [ + + ][ + - ]: 176 : && (argv.size() < 2 || argv[1] != std::string_view("--help"))
411 [ + + ][ + + ]: 176 : && (argv.size() == 1 || argv[1][0] == '-' || std::string_view(argv[1]).contains(' ')
[ + + ]
412 [ + + ]: 28 : || std::filesystem::is_regular_file(std::filesystem::path{argv[1]}, ec)))
413 : 156 : {
414 : 156 : main_func = mainEntryClickHouseLocal;
415 : 156 : }
416 : :
417 : : /// If the argument looks like a file path but doesn't exist, provide a helpful error
418 : : /// instead of the generic "Use one of the following commands" message.
419 : : /// The check above routes existing files to clickhouse-local, but when the file
420 : : /// doesn't exist, we fall through to `printHelp` which is confusing:
421 : : /// $ clickhouse tests/queries/0_stateless/my_test.sql
422 : : /// Use one of the following commands: ...
423 : : /// We detect file-like arguments by the presence of `/` (path separator)
424 : : /// or `.` (file extension), which distinguishes them from mistyped subcommand
425 : : /// names like "clickhouse sever" where the generic help is appropriate.
426 [ + + ][ + - ]: 285968 : if (main_func == printHelpOnError && argv.size() >= 2)
427 : 20 : {
428 : 20 : std::string_view arg(argv[1]);
429 [ + + ][ + + ]: 20 : if (arg.contains('/') || arg.contains('.'))
430 : 8 : {
431 : 8 : std::cerr << "Error: no such file: " << arg << std::endl;
432 : 8 : std::cerr << "If you intended to run a script, please check the path." << std::endl;
433 : 8 : return 1;
434 : 8 : }
435 : 20 : }
436 : :
437 : 285960 : int exit_code = main_func(static_cast<int>(argv.size()), argv.data());
438 : :
439 : 285960 : return exit_code;
440 : 285968 : }
|