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 : 1141069 : {
220 [ + + ]: 1141069 : for (const auto & [alias, name] : clickhouse_short_names)
221 [ + + ]: 3423207 : if (app_suffix == name
222 [ + - ][ - + ]: 3423207 : && !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 [ + + ]: 1141069 : if (argv.size() >= 2)
227 : 1138275 : {
228 : 1138275 : auto first_arg = argv.begin() + 1;
229 : :
230 : : /// 'clickhouse --client ...' and 'clickhouse client ...' are Ok
231 [ + + ]: 1138275 : if (*first_arg == app_suffix
232 [ + + ][ + + ]: 1138275 : || (std::string_view(*first_arg).starts_with("--") && std::string_view(*first_arg).substr(2) == app_suffix))
233 : 118280 : {
234 : 118280 : argv.erase(first_arg);
235 : 118280 : return true;
236 : 118280 : }
237 : 1138275 : }
238 : :
239 : : /// Use app if clickhouse binary is run through symbolic link with name clickhouse-app
240 : 1022789 : std::string app_name = "clickhouse-" + std::string(app_suffix);
241 [ + - ][ + + ]: 1022789 : return !argv.empty() && (app_name == argv[0] || endsWith(argv[0], "/" + app_name));
[ + + ]
242 : 1141069 : }
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 : : #if !(defined(USE_MUSL) || USE_OPENSSL_FIPS)
253 : : extern "C"
254 : : {
255 : : void * dlopen(const char *, int);
256 : : void * dlmopen(long, const char *, int); // NOLINT
257 : : int dlclose(void *);
258 : : const char * dlerror();
259 : :
260 : : void * dlopen(const char *, int)
261 : 5002 : {
262 : 5002 : return nullptr;
263 : 5002 : }
264 : :
265 : : void * dlmopen(long, const char *, int) // NOLINT
266 : 0 : {
267 : 0 : return nullptr;
268 : 0 : }
269 : :
270 : : int dlclose(void *)
271 : 0 : {
272 : 0 : return 0;
273 : 0 : }
274 : :
275 : : const char * dlerror()
276 : 54 : {
277 : 54 : return "ClickHouse does not allow dynamic library loading";
278 : 54 : }
279 : : }
280 : : #endif
281 : :
282 : : /// Prevent messages from JeMalloc in the release build.
283 : : /// Some of these messages are non-actionable for the users, such as:
284 : : /// <jemalloc>: Number of CPUs detected is not deterministic. Per-CPU arena disabled.
285 : : #if USE_JEMALLOC && defined(NDEBUG) && !defined(SANITIZER)
286 : : extern "C" void (*je_malloc_message)(void *, const char *s);
287 : 259363 : static __attribute__((constructor(0))) void init_je_malloc_message() { je_malloc_message = [](void *, const char *){}; }
288 : : #elif USE_JEMALLOC
289 : : #include <unordered_set>
290 : : /// Ignore messages which can be safely ignored, e.g. EAGAIN on pthread_create
291 : : extern "C" void (*je_malloc_message)(void *, const char * s);
292 : : static __attribute__((constructor(0))) void init_je_malloc_message()
293 : : {
294 : : je_malloc_message = [](void *, const char * str)
295 : : {
296 : : using namespace std::literals;
297 : : static const std::unordered_set<std::string_view> ignore_messages{
298 : : "<jemalloc>: background thread creation failed (11)\n"sv};
299 : :
300 : : std::string_view message_view{str};
301 : : if (ignore_messages.contains(message_view))
302 : : return;
303 : :
304 : : # if defined(SYS_write)
305 : : syscall(SYS_write, 2 /*stderr*/, message_view.data(), message_view.size());
306 : : # else
307 : : write(STDERR_FILENO, message_view.data(), message_view.size());
308 : : # endif
309 : : };
310 : : }
311 : : #endif
312 : :
313 : : /// OpenSSL early initialization.
314 : : /// See also EnvironmentChecks.cpp for other static initializers.
315 : : /// Must be ran after EnvironmentChecks.cpp, as OpenSSL uses SSE4.1 and POPCNT.
316 : : static __attribute__((constructor(202))) void init_ssl()
317 : 259363 : {
318 : 259363 : DB::OpenSSLInitializer::instance();
319 : 259363 : }
320 : :
321 : : /// This allows to implement assert to forbid initialization of a class in static constructors.
322 : : /// Usage:
323 : : ///
324 : : /// extern bool inside_main;
325 : : /// class C { C() { assert(inside_main); } };
326 : : bool inside_main = false;
327 : :
328 : : int main(int argc_, char ** argv_)
329 : 259363 : {
330 : 259363 : inside_main = true;
331 : 259363 : SCOPE_EXIT({ inside_main = false; });
332 : :
333 : : /// PHDR cache is required for query profiler to work reliably
334 : : /// It also speed up exception handling, but exceptions from dynamically loaded libraries (dlopen)
335 : : /// will work only after additional call of this function.
336 : : /// Note: we forbid dlopen in our code.
337 : 259363 : updatePHDRCache();
338 : :
339 : 259363 : #if !defined(USE_MUSL)
340 : 259363 : checkHarmfulEnvironmentVariables(argv_);
341 : 259363 : #endif
342 : :
343 : : /// This is used for testing. For example,
344 : : /// clickhouse-local should be able to run a simple query without throw/catch.
345 [ + + ]: 259363 : if (getenv("CLICKHOUSE_TERMINATE_ON_ANY_EXCEPTION")) // NOLINT(concurrency-mt-unsafe)
346 : 36 : DB::terminate_on_any_exception = true;
347 : :
348 : : /// Reset new handler to default (that throws std::bad_alloc)
349 : : /// It is needed because LLVM library clobbers it.
350 : 259363 : std::set_new_handler(nullptr);
351 : :
352 : 259363 : std::vector<char *> argv(argv_, argv_ + argc_);
353 : :
354 : : /// Print a basic help if nothing was matched
355 : 259363 : MainFunc main_func = printHelpOnError;
356 : :
357 [ + + ]: 259363 : for (auto & application : clickhouse_applications)
358 : 1141069 : {
359 [ + + ]: 1141069 : if (isClickhouseApp(application.first, argv))
360 : 259183 : {
361 : 259183 : main_func = application.second;
362 : 259183 : break;
363 : 259183 : }
364 : 1141069 : }
365 : :
366 : : /// Top-level --help / -h / -? (as the sole argument) should show the dispatcher
367 : : /// help listing all subcommands and exit with code 0. Without this carve-out,
368 : : /// `--help` would match the `startsWith(argv[i], "-h")` rule below and be routed
369 : : /// into clickhouse-client, which treats anything starting with "-h" as a --host
370 : : /// specification and fails.
371 [ + + ][ + + ]: 259363 : if (main_func == printHelpOnError && argv.size() == 2)
372 : 128 : {
373 : 128 : std::string_view arg(argv[1]);
374 [ - + ][ + + ]: 128 : if (arg == "--help" || arg == "-h" || arg == "-?")
[ + + ]
375 : 8 : main_func = mainEntryHelp;
376 : 128 : }
377 : :
378 : : /// If host/port arguments are passed to clickhouse/ch shortcuts,
379 : : /// interpret it as clickhouse-client invocation for usability.
380 [ + + ][ + + ]: 259363 : if (main_func == printHelpOnError && argv.size() >= 2)
381 : 168 : {
382 [ + + ]: 392 : for (size_t i = 1, num_args = argv.size(); i < num_args; ++i)
383 : 232 : {
384 [ + + ][ + + ]: 232 : if ((i + 1 < num_args && argv[i] == std::string_view("--host")) || startsWith(argv[i], "--host=")
[ + + ][ - + ]
385 [ + + ][ - + ]: 232 : || (i + 1 < num_args && argv[i] == std::string_view("--port")) || startsWith(argv[i], "--port=")
[ - + ]
386 [ + + ]: 232 : || startsWith(argv[i], "-h"))
387 : 8 : {
388 : 8 : main_func = mainEntryClickHouseClient;
389 : 8 : break;
390 : 8 : }
391 : 232 : }
392 : 168 : }
393 : :
394 : : /// Interpret binary without argument or with arguments starts with dash
395 : : /// ('-') as clickhouse-local for better usability:
396 : : ///
397 : : /// clickhouse help # dumps help
398 : : /// clickhouse -q 'select 1' # use local
399 : : /// clickhouse # spawn local
400 : : /// clickhouse local # spawn local
401 : : /// clickhouse "select ..." # spawn local
402 : : /// clickhouse /tmp/repro --enable-analyzer
403 : : ///
404 : 259363 : std::error_code ec;
405 [ + + ][ + - ]: 259363 : if (main_func == printHelpOnError && !argv.empty()
406 [ + + ][ + - ]: 259363 : && (argv.size() < 2 || argv[1] != std::string_view("--help"))
407 [ + + ][ + + ]: 259363 : && (argv.size() == 1 || argv[1][0] == '-' || std::string_view(argv[1]).contains(' ')
[ + + ]
408 [ + + ]: 164 : || std::filesystem::is_regular_file(std::filesystem::path{argv[1]}, ec)))
409 : 144 : {
410 : 144 : main_func = mainEntryClickHouseLocal;
411 : 144 : }
412 : :
413 : : /// If the argument looks like a file path but doesn't exist, provide a helpful error
414 : : /// instead of the generic "Use one of the following commands" message.
415 : : /// The check above routes existing files to clickhouse-local, but when the file
416 : : /// doesn't exist, we fall through to `printHelp` which is confusing:
417 : : /// $ clickhouse tests/queries/0_stateless/my_test.sql
418 : : /// Use one of the following commands: ...
419 : : /// We detect file-like arguments by the presence of `/` (path separator)
420 : : /// or `.` (file extension), which distinguishes them from mistyped subcommand
421 : : /// names like "clickhouse sever" where the generic help is appropriate.
422 [ + + ][ + - ]: 259363 : if (main_func == printHelpOnError && argv.size() >= 2)
423 : 20 : {
424 : 20 : std::string_view arg(argv[1]);
425 [ + + ][ + + ]: 20 : if (arg.contains('/') || arg.contains('.'))
426 : 8 : {
427 : 8 : std::cerr << "Error: no such file: " << arg << std::endl;
428 : 8 : std::cerr << "If you intended to run a script, please check the path." << std::endl;
429 : 8 : return 1;
430 : 8 : }
431 : 20 : }
432 : :
433 : 259355 : int exit_code = main_func(static_cast<int>(argv.size()), argv.data());
434 : :
435 : 259355 : return exit_code;
436 : 259363 : }
|