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