Coverage Report

Created: 2026-09-01 18:01

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/service/doris_main.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include <arrow/flight/client.h>
19
#include <arrow/flight/sql/client.h>
20
#include <arrow/scalar.h>
21
#include <arrow/status.h>
22
#include <arrow/table.h>
23
#include <butil/macros.h>
24
// IWYU pragma: no_include <bthread/errno.h>
25
#include <errno.h> // IWYU pragma: keep
26
#include <fcntl.h>
27
#include <fmt/core.h>
28
#if !defined(__SANITIZE_ADDRESS__) && !defined(ADDRESS_SANITIZER) && !defined(LEAK_SANITIZER) && \
29
        !defined(THREAD_SANITIZER) && !defined(USE_JEMALLOC)
30
#include <gperftools/malloc_extension.h> // IWYU pragma: keep
31
#endif
32
#include <libgen.h>
33
#include <setjmp.h>
34
#include <signal.h>
35
#include <stdint.h>
36
#include <stdio.h>
37
#include <stdlib.h>
38
#include <unistd.h>
39
40
#include <cstring>
41
#include <functional>
42
#include <memory>
43
#include <ostream>
44
#include <string>
45
#include <string_view>
46
#include <thread>
47
#include <tuple>
48
#include <vector>
49
50
#include "cloud/cloud_backend_service.h"
51
#include "cloud/config.h"
52
#include "common/phdr_cache.h"
53
#include "common/stack_trace.h"
54
#if defined(__ELF__) && !defined(__FreeBSD__)
55
#include "common/symbol_index.h"
56
#endif
57
#include "runtime/memory/mem_tracker_limiter.h"
58
#include "storage/tablet/tablet_schema_cache.h"
59
#include "storage/utils.h"
60
#include "util/concurrency_stats.h"
61
62
#if defined(LEAK_SANITIZER)
63
#include <sanitizer/lsan_interface.h>
64
#endif
65
66
#include <curl/curl.h>
67
#include <thrift/TOutput.h>
68
69
#include "agent/heartbeat_server.h"
70
#include "common/config.h"
71
#include "common/daemon.h"
72
#include "common/logging.h"
73
#include "common/signal_handler.h"
74
#include "common/status.h"
75
#include "io/cache/block_file_cache_factory.h"
76
#include "load/stream_load/stream_load_recorder_manager.h"
77
#include "runtime/exec_env.h"
78
#include "runtime/user_function_cache.h"
79
#include "service/arrow_flight/flight_sql_service.h"
80
#include "service/backend_options.h"
81
#include "service/backend_service.h"
82
#include "service/http_service.h"
83
#include "service/server/be_server_starter_factory.h"
84
#include "storage/options.h"
85
#include "storage/storage_engine.h"
86
#include "udf/python/python_env.h"
87
#include "util/debug_util.h"
88
#include "util/disk_info.h"
89
#include "util/jni_plugin_registry.h"
90
#include "util/mem_info.h"
91
#include "util/string_util.h"
92
#include "util/thread.h"
93
#include "util/thrift_rpc_helper.h"
94
#include "util/thrift_server.h"
95
#include "util/uid_util.h"
96
97
namespace doris {} // namespace doris
98
99
static void help(const char*);
100
101
extern "C" {
102
void __lsan_do_leak_check();
103
int __llvm_profile_write_file();
104
}
105
106
namespace doris {
107
108
7
void signal_handler(int signal) {
109
7
    if (signal == SIGINT || signal == SIGTERM) {
110
7
        k_doris_exit = true;
111
7
    }
112
    // SIGQUIT deliberately does nothing here; see init_signals().
113
7
}
114
115
21
int install_signal(int signo, void (*handler)(int)) {
116
21
    struct sigaction sa;
117
21
    memset(&sa, 0, sizeof(struct sigaction));
118
21
    sa.sa_handler = handler;
119
    // Restartable syscalls stay restartable. It matters most for SIGQUIT: unlike the two
120
    // shutdown signals, that one is sent to a HEALTHY BE - `kill -3` is the operator's habit
121
    // for asking a running process for a thread dump, and since the handler now produces
122
    // nothing they send it again. Without SA_RESTART each of those turns whatever syscall the
123
    // receiving thread happened to be in into EINTR, in the middle of normal serving.
124
21
    sa.sa_flags = SA_RESTART;
125
21
    sigemptyset(&sa.sa_mask);
126
21
    auto ret = sigaction(signo, &sa, nullptr);
127
21
    if (ret != 0) {
128
0
        char buf[64];
129
0
        LOG(ERROR) << "install signal failed, signo=" << signo << ", errno=" << errno
130
0
                   << ", errmsg=" << strerror_r(errno, buf, sizeof(buf));
131
0
    }
132
21
    return ret;
133
21
}
134
135
7
void init_signals() {
136
7
    auto ret = install_signal(SIGINT, signal_handler);
137
7
    if (ret < 0) {
138
0
        exit(-1);
139
0
    }
140
7
    ret = install_signal(SIGTERM, signal_handler);
141
7
    if (ret < 0) {
142
0
        exit(-1);
143
0
    }
144
    // SIGQUIT is taken over even though the BE does nothing with it, because its default
145
    // action is not "nothing": it terminates the process and dumps core. `kill -3 <pid>` is
146
    // what an operator reaches for to get a thread dump out of a process that looks stuck,
147
    // and until the JVM started running with -Xrs it got one - the JVM installed a handler
148
    // for this signal along with the shutdown ones. -Xrs stops it from doing that (see
149
    // JvmLauncher::_build_options), which would leave SIGQUIT at SIG_DFL and turn that
150
    // habitual command into a crash. Handling it and ignoring it is the pre-change
151
    // behaviour minus the thread dump; jcmd and jstack, which attach rather than signal,
152
    // are how to get one now.
153
    //
154
    // Installed with a handler rather than SIG_IGN so that the disposition is inheritable
155
    // by nothing and visible to JvmLauncher's BeOwnedSignalGuard, which saves and restores
156
    // it around any VM creation it does not control.
157
7
    ret = install_signal(SIGQUIT, signal_handler);
158
7
    if (ret < 0) {
159
0
        exit(-1);
160
0
    }
161
7
}
162
163
8
static void thrift_output(const char* x) {
164
8
    LOG(WARNING) << "thrift internal message: " << x;
165
8
}
166
167
} // namespace doris
168
169
// These code is referenced from clickhouse
170
// It is used to check the SIMD instructions
171
enum class InstructionFail {
172
    NONE = 0,
173
    SSE3 = 1,
174
    SSSE3 = 2,
175
    SSE4_1 = 3,
176
    SSE4_2 = 4,
177
    POPCNT = 5,
178
    AVX = 6,
179
    AVX2 = 7,
180
    AVX512 = 8,
181
    ARM_NEON = 9
182
};
183
184
0
auto instruction_fail_to_string(InstructionFail fail) {
185
0
    switch (fail) {
186
0
#define ret(x) return std::make_tuple(STDERR_FILENO, x, ARRAY_SIZE(x) - 1)
187
0
    case InstructionFail::NONE:
188
0
        ret("NONE");
189
0
    case InstructionFail::SSE3:
190
0
        ret("SSE3");
191
0
    case InstructionFail::SSSE3:
192
0
        ret("SSSE3");
193
0
    case InstructionFail::SSE4_1:
194
0
        ret("SSE4.1");
195
0
    case InstructionFail::SSE4_2:
196
0
        ret("SSE4.2");
197
0
    case InstructionFail::POPCNT:
198
0
        ret("POPCNT");
199
0
    case InstructionFail::AVX:
200
0
        ret("AVX");
201
0
    case InstructionFail::AVX2:
202
0
        ret("AVX2");
203
0
    case InstructionFail::AVX512:
204
0
        ret("AVX512");
205
0
    case InstructionFail::ARM_NEON:
206
0
        ret("ARM_NEON");
207
0
    }
208
209
0
    LOG(ERROR) << "Unrecognized instruction fail value." << std::endl;
210
0
    exit(-1);
211
0
}
212
213
sigjmp_buf jmpbuf;
214
215
0
void sig_ill_check_handler(int, siginfo_t*, void*) {
216
0
    siglongjmp(jmpbuf, 1);
217
0
}
218
219
/// Check if necessary SSE extensions are available by trying to execute some sse instructions.
220
/// If instruction is unavailable, SIGILL will be sent by kernel.
221
7
void check_required_instructions_impl(volatile InstructionFail& fail) {
222
7
#if defined(__SSE3__)
223
7
    fail = InstructionFail::SSE3;
224
7
    __asm__ volatile("addsubpd %%xmm0, %%xmm0" : : : "xmm0");
225
7
#endif
226
227
7
#if defined(__SSSE3__)
228
7
    fail = InstructionFail::SSSE3;
229
7
    __asm__ volatile("pabsw %%xmm0, %%xmm0" : : : "xmm0");
230
231
7
#endif
232
233
7
#if defined(__SSE4_1__)
234
7
    fail = InstructionFail::SSE4_1;
235
7
    __asm__ volatile("pmaxud %%xmm0, %%xmm0" : : : "xmm0");
236
7
#endif
237
238
7
#if defined(__SSE4_2__)
239
7
    fail = InstructionFail::SSE4_2;
240
7
    __asm__ volatile("pcmpgtq %%xmm0, %%xmm0" : : : "xmm0");
241
7
#endif
242
243
    /// Defined by -msse4.2
244
7
#if defined(__POPCNT__)
245
7
    fail = InstructionFail::POPCNT;
246
7
    {
247
7
        uint64_t a = 0;
248
7
        uint64_t b = 0;
249
7
        __asm__ volatile("popcnt %1, %0" : "=r"(a) : "r"(b) :);
250
7
    }
251
7
#endif
252
253
7
#if defined(__AVX__)
254
7
    fail = InstructionFail::AVX;
255
7
    __asm__ volatile("vaddpd %%ymm0, %%ymm0, %%ymm0" : : : "ymm0");
256
7
#endif
257
258
7
#if defined(__AVX2__)
259
7
    fail = InstructionFail::AVX2;
260
7
    __asm__ volatile("vpabsw %%ymm0, %%ymm0" : : : "ymm0");
261
7
#endif
262
263
#if defined(__AVX512__)
264
    fail = InstructionFail::AVX512;
265
    __asm__ volatile("vpabsw %%zmm0, %%zmm0" : : : "zmm0");
266
#endif
267
268
#if defined(__ARM_NEON__)
269
    fail = InstructionFail::ARM_NEON;
270
#ifndef __APPLE__
271
    __asm__ volatile("vadd.i32  q8, q8, q8" : : : "q8");
272
#endif
273
#endif
274
275
7
    fail = InstructionFail::NONE;
276
7
}
277
278
0
bool write_retry(int fd, const char* data, size_t size) {
279
0
    if (!size) size = strlen(data);
280
281
0
    while (size != 0) {
282
0
        ssize_t res = ::write(fd, data, size);
283
284
0
        if ((-1 == res || 0 == res) && errno != EINTR) return false;
285
286
0
        if (res > 0) {
287
0
            data += res;
288
0
            size -= res;
289
0
        }
290
0
    }
291
292
0
    return true;
293
0
}
294
295
/// Macros to avoid using strlen(), since it may fail if SSE is not supported.
296
#define WRITE_ERROR(data)                                                      \
297
0
    do {                                                                       \
298
0
        static_assert(__builtin_constant_p(data));                             \
299
0
        if (!write_retry(STDERR_FILENO, data, ARRAY_SIZE(data) - 1)) _Exit(1); \
300
0
    } while (false)
301
302
/// Check SSE and others instructions availability. Calls exit on fail.
303
/// This function must be called as early as possible, even before main, because static initializers may use unavailable instructions.
304
7
void check_required_instructions() {
305
7
    struct sigaction sa {};
306
7
    struct sigaction sa_old {};
307
7
    sa.sa_sigaction = sig_ill_check_handler;
308
7
    sa.sa_flags = SA_SIGINFO;
309
7
    auto signal = SIGILL;
310
7
    if (sigemptyset(&sa.sa_mask) != 0 || sigaddset(&sa.sa_mask, signal) != 0 ||
311
7
        sigaction(signal, &sa, &sa_old) != 0) {
312
        /// You may wonder about strlen.
313
        /// Typical implementation of strlen is using SSE4.2 or AVX2.
314
        /// But this is not the case because it's compiler builtin and is executed at compile time.
315
316
0
        WRITE_ERROR("Can not set signal handler\n");
317
0
        _Exit(1);
318
0
    }
319
320
7
    volatile InstructionFail fail = InstructionFail::NONE;
321
322
7
    if (sigsetjmp(jmpbuf, 1)) {
323
0
        WRITE_ERROR("Instruction check fail. The CPU does not support ");
324
0
        if (!std::apply(write_retry, instruction_fail_to_string(fail))) _Exit(1);
325
0
        WRITE_ERROR(" instruction set.\n");
326
0
        WRITE_ERROR(
327
0
                "For example, if your CPU does not support AVX2, you need to rebuild the Doris BE "
328
0
                "with: USE_AVX2=0 sh build.sh --be");
329
0
        _Exit(1);
330
0
    }
331
332
7
    check_required_instructions_impl(fail);
333
334
7
    if (sigaction(signal, &sa_old, nullptr)) {
335
0
        WRITE_ERROR("Can not set signal handler\n");
336
0
        _Exit(1);
337
0
    }
338
7
}
339
340
struct Checker {
341
7
    Checker() { check_required_instructions(); }
342
} checker
343
#ifndef __APPLE__
344
        __attribute__((init_priority(101))) /// Run before other static initializers.
345
#endif
346
        ;
347
348
// A startup failure that happens after ExecEnv::init() has run must terminate the
349
// process the same way normal shutdown does (see the _exit(0) at the end of main):
350
// in the default mode we _exit() immediately, skipping global destructors and the
351
// LeakSanitizer atexit check. Init-time singletons (e.g. the internal workload
352
// group's task scheduler) intentionally live for the whole process lifetime, so
353
// running the leak check on this abnormal-exit path reports them as false-positive
354
// leaks. enable_graceful_exit_check is honored so memleak-check mode still runs LSAN.
355
0
[[noreturn]] static void exit_on_startup_failure() {
356
0
    google::FlushLogFiles(google::GLOG_INFO);
357
0
    if (!doris::config::enable_graceful_exit_check) {
358
0
        _exit(1);
359
0
    }
360
0
    exit(1);
361
0
}
362
363
7
int main(int argc, char** argv) {
364
7
    doris::signal::InstallFailureSignalHandler();
365
    // create StackTraceCache Instance, at the beginning, other static destructors may use.
366
7
    StackTrace::createCache();
367
    // extern doris::ErrorCode::ErrorCodeInitializer error_code_init;
368
    // Some developers will modify status.h and we use a very ticky logic to init error_states
369
    // and it maybe not inited. So add a check here.
370
7
    doris::ErrorCode::error_code_init.check_init();
371
    // check if print version or help
372
7
    if (argc > 1) {
373
0
        if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0) {
374
0
            puts(doris::get_build_version(false).c_str());
375
0
            exit(0);
376
0
        } else if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0) {
377
0
            help(basename(argv[0]));
378
0
            exit(0);
379
0
        }
380
0
    }
381
382
7
    if (getenv("DORIS_HOME") == nullptr) {
383
0
        fprintf(stderr, "you need set DORIS_HOME environment variable.\n");
384
0
        exit(-1);
385
0
    }
386
7
    if (getenv("PID_DIR") == nullptr) {
387
0
        fprintf(stderr, "you need set PID_DIR environment variable.\n");
388
0
        exit(-1);
389
0
    }
390
391
7
    SCOPED_INIT_THREAD_CONTEXT();
392
393
7
    using doris::Status;
394
7
    using std::string;
395
396
    // open pid file, obtain file lock and save pid
397
7
    string pid_file = string(getenv("PID_DIR")) + "/be.pid";
398
7
    int fd = open(pid_file.c_str(), O_RDWR | O_CREAT,
399
7
                  S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
400
7
    if (fd < 0) {
401
0
        fprintf(stderr, "fail to create pid file.");
402
0
        exit(-1);
403
0
    }
404
405
7
    string pid = std::to_string((long)getpid());
406
7
    pid += "\n";
407
7
    size_t length = write(fd, pid.c_str(), pid.size());
408
7
    if (length != pid.size()) {
409
0
        fprintf(stderr, "fail to save pid into pid file.");
410
0
        exit(-1);
411
0
    }
412
413
    // descriptor will be leaked when failing to close fd
414
7
    if (::close(fd) < 0) {
415
0
        fprintf(stderr, "failed to close fd of pidfile.");
416
0
        exit(-1);
417
0
    }
418
419
    // init config.
420
    // the config in be_custom.conf will overwrite the config in be.conf
421
    // Must init custom config after init config, separately.
422
    // Because the path of custom config file is defined in be.conf
423
7
    string conffile = string(getenv("DORIS_HOME")) + "/conf/be.conf";
424
7
    if (!doris::config::init(conffile.c_str(), true, true, true)) {
425
0
        fprintf(stderr, "error read config file. \n");
426
0
        return -1;
427
0
    }
428
429
7
    string custom_conffile = doris::config::custom_config_dir + "/be_custom.conf";
430
7
    if (!doris::config::init(custom_conffile.c_str(), true, false, false)) {
431
0
        fprintf(stderr, "error read custom config file. \n");
432
0
        return -1;
433
0
    }
434
435
    // ATTN: Callers that want to override default gflags variables should do so before calling this method
436
7
    google::ParseCommandLineFlags(&argc, &argv, true);
437
    // ATTN: MUST init before LOG
438
7
    doris::init_glog("be");
439
440
7
    LOG(INFO) << doris::get_version_string(false);
441
442
7
    doris::init_thrift_logging();
443
444
7
    if (doris::config::enable_fuzzy_mode) {
445
7
        Status status = doris::config::set_fuzzy_configs();
446
7
        if (!status.ok()) {
447
0
            LOG(WARNING) << "Failed to initialize fuzzy config: " << status;
448
0
            exit(1);
449
0
        }
450
7
    }
451
452
#if !defined(__SANITIZE_ADDRESS__) && !defined(ADDRESS_SANITIZER) && !defined(LEAK_SANITIZER) && \
453
        !defined(THREAD_SANITIZER) && !defined(USE_JEMALLOC)
454
    // Change the total TCMalloc thread cache size if necessary.
455
    const size_t kDefaultTotalThreadCacheBytes = 1024 * 1024 * 1024;
456
    if (!MallocExtension::instance()->SetNumericProperty("tcmalloc.max_total_thread_cache_bytes",
457
                                                         kDefaultTotalThreadCacheBytes)) {
458
        fprintf(stderr, "Failed to change TCMalloc total thread cache size.\n");
459
        return -1;
460
    }
461
#endif
462
463
7
    std::vector<doris::StorePath> paths;
464
7
    auto olap_res = doris::parse_conf_store_paths(doris::config::storage_root_path, &paths);
465
7
    if (!olap_res) {
466
0
        LOG(ERROR) << "parse config storage path failed, path=" << doris::config::storage_root_path;
467
0
        exit(-1);
468
0
    }
469
470
7
    std::vector<doris::StorePath> spill_paths;
471
7
    if (doris::config::spill_storage_root_path.empty()) {
472
7
        doris::config::spill_storage_root_path = doris::config::storage_root_path;
473
7
    }
474
7
    olap_res = doris::parse_conf_store_paths(doris::config::spill_storage_root_path, &spill_paths);
475
7
    if (!olap_res) {
476
0
        LOG(ERROR) << "parse config spill storage path failed, path="
477
0
                   << doris::config::spill_storage_root_path;
478
0
        exit(-1);
479
0
    }
480
7
    std::set<std::string> broken_paths;
481
7
    doris::parse_conf_broken_store_paths(doris::config::broken_storage_path, &broken_paths);
482
483
7
    auto it = paths.begin();
484
18
    for (; it != paths.end();) {
485
11
        if (broken_paths.count(it->path) > 0) {
486
0
            if (doris::config::ignore_broken_disk) {
487
0
                LOG(WARNING) << "ignore broken disk, path = " << it->path;
488
0
                it = paths.erase(it);
489
0
            } else {
490
0
                LOG(ERROR) << "a broken disk is found " << it->path;
491
0
                exit(-1);
492
0
            }
493
11
        } else if (!doris::check_datapath_rw(it->path)) {
494
0
            if (doris::config::ignore_broken_disk) {
495
0
                LOG(WARNING) << "read write test file failed, path=" << it->path;
496
0
                it = paths.erase(it);
497
0
            } else {
498
0
                LOG(ERROR) << "read write test file failed, path=" << it->path;
499
                // if only one disk and the disk is full, also need exit because rocksdb will open failed
500
0
                exit(-1);
501
0
            }
502
11
        } else {
503
11
            ++it;
504
11
        }
505
11
    }
506
507
7
    if (paths.empty()) {
508
0
        LOG(ERROR) << "All disks are broken, exit.";
509
0
        exit(-1);
510
0
    }
511
512
7
    it = spill_paths.begin();
513
18
    for (; it != spill_paths.end();) {
514
11
        if (!doris::check_datapath_rw(it->path)) {
515
0
            if (doris::config::ignore_broken_disk) {
516
0
                LOG(WARNING) << "read write test file failed, path=" << it->path;
517
0
                it = spill_paths.erase(it);
518
0
            } else {
519
0
                LOG(ERROR) << "read write test file failed, path=" << it->path;
520
0
                exit(-1);
521
0
            }
522
11
        } else {
523
11
            ++it;
524
11
        }
525
11
    }
526
7
    if (spill_paths.empty()) {
527
0
        LOG(ERROR) << "All spill disks are broken, exit.";
528
0
        exit(-1);
529
0
    }
530
531
    // initialize libcurl here to avoid concurrent initialization
532
7
    auto curl_ret = curl_global_init(CURL_GLOBAL_ALL);
533
7
    if (curl_ret != 0) {
534
0
        LOG(ERROR) << "fail to initialize libcurl, curl_ret=" << curl_ret;
535
0
        exit(-1);
536
0
    }
537
    // add logger for thrift internal
538
7
    apache::thrift::TOutput::instance().setOutputFunction(doris::thrift_output);
539
540
7
    Status status = Status::OK();
541
    // No JVM is started here on purpose. It is created by the first Java feature that asks
542
    // for it - a JNI table format, a Java UDF, an hdfs access - and a BE that uses none of
543
    // them runs without one. See Jni::JvmLauncher.
544
545
7
    if (doris::config::enable_python_udf_support) {
546
7
        if (std::string python_udf_root_path =
547
7
                    fmt::format("{}/lib/udf/python", std::getenv("DORIS_HOME"));
548
7
            !std::filesystem::exists(python_udf_root_path)) {
549
1
            std::filesystem::create_directories(python_udf_root_path);
550
1
        }
551
552
        // Normalize and trim all Python-related config parameters
553
7
        std::string python_env_mode =
554
7
                std::string(doris::trim(doris::to_lower(doris::config::python_env_mode)));
555
7
        std::string python_conda_root_path =
556
7
                std::string(doris::trim(doris::config::python_conda_root_path));
557
7
        std::string python_venv_root_path =
558
7
                std::string(doris::trim(doris::config::python_venv_root_path));
559
7
        std::string python_venv_interpreter_paths =
560
7
                std::string(doris::trim(doris::config::python_venv_interpreter_paths));
561
562
7
        if (python_env_mode == "conda") {
563
1
            if (python_conda_root_path.empty()) {
564
0
                LOG(ERROR)
565
0
                        << "Python conda root path is empty, please set `python_conda_root_path` "
566
0
                           "or set `enable_python_udf_support` to `false`";
567
0
                exit(1);
568
0
            }
569
1
            LOG(INFO) << "Doris backend python version manager is initialized. Python conda "
570
1
                         "root path: "
571
1
                      << python_conda_root_path;
572
1
            status = doris::PythonVersionManager::instance().init(doris::PythonEnvType::CONDA,
573
1
                                                                  python_conda_root_path, "");
574
6
        } else if (python_env_mode == "venv") {
575
6
            if (python_venv_root_path.empty()) {
576
0
                LOG(ERROR)
577
0
                        << "Python venv root path is empty, please set `python_venv_root_path` or "
578
0
                           "set `enable_python_udf_support` to `false`";
579
0
                exit(1);
580
0
            }
581
6
            if (python_venv_interpreter_paths.empty()) {
582
0
                LOG(ERROR)
583
0
                        << "Python interpreter paths is empty, please set "
584
0
                           "`python_venv_interpreter_paths` or set `enable_python_udf_support` to "
585
0
                           "`false`";
586
0
                exit(1);
587
0
            }
588
6
            LOG(INFO) << "Doris backend python version manager is initialized. Python venv "
589
6
                         "root path: "
590
6
                      << python_venv_root_path
591
6
                      << ", python interpreter paths: " << python_venv_interpreter_paths;
592
6
            status = doris::PythonVersionManager::instance().init(doris::PythonEnvType::VENV,
593
6
                                                                  python_venv_root_path,
594
6
                                                                  python_venv_interpreter_paths);
595
6
        } else {
596
0
            status = Status::InvalidArgument(
597
0
                    "Python env mode is invalid, should be `conda` or `venv`. If you don't want to "
598
0
                    "enable the Python UDF function, please set `enable_python_udf_support` to "
599
0
                    "`false`");
600
0
        }
601
602
7
        if (!status.ok()) {
603
0
            LOG(ERROR) << "Failed to initialize python version manager: " << status;
604
0
            exit(1);
605
0
        }
606
7
        LOG(INFO) << doris::PythonVersionManager::instance().to_string();
607
7
    }
608
609
    // SIGINT and SIGTERM are how the BE is asked to shut down, and the handler installed
610
    // here does nothing but raise the flag the loop at the end of main() waits on, so the
611
    // shutdown stays orderly. SIGQUIT is claimed here as well, so that it does nothing at
612
    // all rather than killing the BE with a core dump. A JVM would rather turn the first
613
    // two into a Java Shutdown.exit() and answer the third with a thread dump, and it
614
    // installs handlers of its own for all three when it starts. The JVM used to be created
615
    // a few lines above this call, which is what left these handlers on top; now that it is
616
    // created on demand, Jni::JvmLauncher::_bootstrap() is what puts them back once the JVM
617
    // has had its way with them.
618
    // https://www.oracle.com/java/technologies/javase/signals.html
619
7
    doris::init_signals();
620
    // ATTN: MUST init before `ExecEnv`, `StorageEngine` and other daemon services
621
    //
622
    //       Daemon ───┬──► StorageEngine ──► ExecEnv ──► Disk/Mem/CpuInfo
623
    //                 │
624
    //                 │
625
    // BackendService ─┘
626
7
    doris::CpuInfo::init();
627
7
    doris::DiskInfo::init();
628
7
    doris::MemInfo::init();
629
630
7
    LOG(INFO) << doris::CpuInfo::debug_string();
631
7
    LOG(INFO) << doris::DiskInfo::debug_string();
632
7
    LOG(INFO) << doris::MemInfo::debug_string();
633
634
    // Doris-patched GNU libunwind reads PHDR metadata from our lock-free snapshot instead of
635
    // entering glibc dl_iterate_phdr while jemalloc profiling or signal-context unwinding may
636
    // already be involved in loader-lock-sensitive code. Configure libunwind before daemon threads
637
    // start so all later heap-profile and stack-trace unwinds use the same lock-safe policy.
638
7
    configureLibunwindPHDRCache();
639
7
    updatePHDRCache();
640
7
    LOG(INFO) << "PHDR cache enabled: " << hasPHDRCache();
641
7
#if defined(__ELF__) && !defined(__FreeBSD__)
642
7
    auto symbol_index = doris::SymbolIndex::instance();
643
7
    LOG(INFO) << "SymbolIndex preloaded: objects=" << symbol_index->objects().size()
644
7
              << " symbols=" << symbol_index->symbols().size();
645
7
#endif
646
7
    if (!doris::BackendOptions::init()) {
647
0
        exit(-1);
648
0
    }
649
650
    // init exec env
651
7
    auto* exec_env(doris::ExecEnv::GetInstance());
652
7
    status = doris::ExecEnv::init(doris::ExecEnv::GetInstance(), paths, spill_paths, broken_paths);
653
7
    if (status != Status::OK()) {
654
0
        std::cerr << "failed to init doris storage engine, res=" << status;
655
0
        exit_on_startup_failure();
656
0
    }
657
658
    // Start concurrency stats manager
659
7
    doris::ConcurrencyStatsManager::instance().start();
660
661
    // begin to start services
662
7
    doris::ThriftRpcHelper::setup(exec_env);
663
    // 1. thrift server with be_port
664
7
    std::shared_ptr<doris::BaseBackendService> service;
665
7
    std::function<void(Status&, std::string_view)> stop_work_if_error = [&](Status& status,
666
42
                                                                            std::string_view msg) {
667
42
        if (!status.ok()) {
668
0
            std::cerr << msg << '\n';
669
0
            service->stop_works();
670
0
            exit_on_startup_failure();
671
0
        }
672
42
    };
673
674
7
    if (doris::config::is_cloud_mode()) {
675
1
        service = std::make_shared<doris::CloudBackendService>(
676
1
                exec_env->storage_engine().to_cloud(), exec_env);
677
6
    } else {
678
6
        service = std::make_shared<doris::BackendService>(exec_env->storage_engine().to_local(),
679
6
                                                          exec_env);
680
6
    }
681
682
7
    std::unique_ptr<doris::server::IServerStarter> backend_thrift_starter;
683
7
    EXIT_IF_ERROR(doris::server::create_backend_thrift_starter(exec_env, doris::config::be_port,
684
7
                                                               service, &backend_thrift_starter));
685
7
    status = backend_thrift_starter->start();
686
7
    stop_work_if_error(status, "Doris BE server did not start correctly, exiting");
687
688
    // 2. brpc service
689
7
    std::unique_ptr<doris::server::IServerStarter> brpc_starter;
690
7
    EXIT_IF_ERROR(doris::server::create_brpc_starter(
691
7
            exec_env, doris::config::brpc_port, doris::config::brpc_num_threads, &brpc_starter));
692
7
    status = brpc_starter->start();
693
7
    stop_work_if_error(status, "BRPC service did not start correctly, exiting");
694
695
    // 3. http service
696
7
    std::unique_ptr<doris::server::IServerStarter> http_starter;
697
7
    EXIT_IF_ERROR(doris::server::create_http_starter(exec_env, doris::config::webserver_port,
698
7
                                                     doris::config::webserver_num_workers,
699
7
                                                     &http_starter));
700
7
    status = http_starter->start();
701
7
    stop_work_if_error(status, "Doris Be http service did not start correctly, exiting");
702
703
    // 4. heart beat server
704
7
    doris::ClusterInfo* cluster_info = exec_env->cluster_info();
705
7
    std::unique_ptr<doris::server::IServerStarter> heartbeat_thrift_starter;
706
7
    status = doris::server::create_heartbeat_thrift_starter(
707
7
            exec_env, doris::config::heartbeat_service_port,
708
7
            doris::config::heartbeat_service_thread_count, cluster_info, &heartbeat_thrift_starter);
709
7
    stop_work_if_error(status, "Heartbeat services did not start correctly, exiting");
710
711
7
    status = heartbeat_thrift_starter->start();
712
7
    stop_work_if_error(status, "Doris BE HeartBeat Service did not start correctly, exiting: " +
713
7
                                       status.to_string());
714
715
    // 5. arrow flight service
716
7
    std::unique_ptr<doris::server::IServerStarter> flight_starter;
717
7
    EXIT_IF_ERROR(doris::server::create_flight_starter(doris::config::arrow_flight_sql_port,
718
7
                                                       &flight_starter));
719
7
    status = flight_starter->start();
720
7
    stop_work_if_error(
721
7
            status, "Arrow Flight Service did not start correctly, exiting, " + status.to_string());
722
723
    // 6. start daemon thread to do clean or gc jobs
724
7
    doris::Daemon daemon;
725
7
    daemon.start();
726
727
7
    exec_env->storage_engine().notify_listeners();
728
729
7
    doris::k_is_server_ready = true;
730
731
    // 7. load the deployed Java plugins, once the BE is otherwise serving.
732
    //
733
    // On its own thread and non-fatal on purpose: the point is that a plugin broken by a bad
734
    // deployment shows up in the log now instead of inside the first user query that needs
735
    // it, and a plugin that cannot load must not hold up or take down everything else. When
736
    // no plugin is deployed this starts no JVM and returns immediately.
737
    //
738
    // Joined on the way out rather than detached, so that a stop arriving while plugins are
739
    // still loading waits for them instead of running the global destructors underneath a
740
    // thread that is inside the JVM. Warming up is bounded - one JVM start plus one pass over
741
    // the plugin directory - and the Java side of it is a single call, so there is nothing to
742
    // interrupt halfway.
743
7
    std::shared_ptr<doris::Thread> plugin_warmup_thread;
744
7
    if (doris::config::enable_java_support && doris::config::java_plugin_warmup) {
745
0
        EXIT_IF_ERROR(doris::Thread::create(
746
0
                "Jni", "java_plugin_warmup",
747
0
                []() {
748
                    // Named background thread with a thread context of its own: everything it
749
                    // allocates would otherwise be orphan memory, and the try/catch is what
750
                    // keeps a directory that becomes unreadable mid-iteration from reaching
751
                    // std::terminate (directory_iterator::operator++ throws).
752
0
                    SCOPED_INIT_THREAD_CONTEXT();
753
0
                    try {
754
0
                        if (Status status = doris::Jni::PluginRegistry::warmup(); !status.ok()) {
755
0
                            LOG(WARNING) << "failed to warm up Java plugins: " << status;
756
0
                        }
757
0
                    } catch (const std::exception& e) {
758
0
                        LOG(WARNING) << "failed to warm up Java plugins: " << e.what();
759
0
                    } catch (...) {
760
0
                        LOG(WARNING) << "failed to warm up Java plugins: unknown exception";
761
0
                    }
762
0
                },
763
0
                &plugin_warmup_thread));
764
0
    }
765
766
1.57k
    while (!doris::k_doris_exit) {
767
#if defined(LEAK_SANITIZER)
768
        __lsan_do_leak_check();
769
#endif
770
1.56k
        sleep(3);
771
1.56k
    }
772
7
    doris::k_is_server_ready = false;
773
7
    LOG(INFO) << "Doris main exiting.";
774
7
#if defined(LLVM_PROFILE)
775
7
    __llvm_profile_write_file();
776
7
    LOG(INFO) << "Flush profile file.";
777
7
#endif
778
    // For graceful shutdown, need to wait for all running queries to stop
779
7
    exec_env->wait_for_all_tasks_done();
780
781
7
    if (!doris::config::enable_graceful_exit_check) {
782
        // If not in memleak check mode, no need to wait all objects de-constructed normally, just exit.
783
        // It will make sure that graceful shutdown can be done definitely.
784
0
        LOG(INFO) << "Doris main exited.";
785
0
        google::FlushLogFiles(google::GLOG_INFO);
786
0
        _exit(0); // Do not call exit(0), it will wait for all objects de-constructed normally
787
0
        return 0;
788
0
    }
789
    // Before anything is torn down: the warmup thread may still be inside the JVM, and it
790
    // reaches BE state that the destructors below free. The fast path above does not need
791
    // this - _exit() runs no destructor at all.
792
7
    if (plugin_warmup_thread != nullptr) {
793
0
        plugin_warmup_thread->join();
794
0
        LOG(INFO) << "Java plugin warmup stopped";
795
0
    }
796
7
    daemon.stop();
797
7
    flight_starter->stop();
798
7
    flight_starter->join();
799
7
    LOG(INFO) << "Flight server stopped.";
800
7
    heartbeat_thrift_starter->stop();
801
7
    heartbeat_thrift_starter->join();
802
7
    LOG(INFO) << "Heartbeat server stopped";
803
    // The stream load recorder manager writes its audit records through this BE's own http
804
    // service, so it has to be stopped while that service is still up. Otherwise an audit
805
    // load that is in flight here can never be answered, and it blocks the join() done by
806
    // SAFE_STOP(_stream_load_recorder_manager) in ExecEnv::destroy() for up to the stream
807
    // load timeout, which is longer than the grace period of stop_be.sh --grace.
808
7
    if (auto* recorder_manager = exec_env->stream_load_recorder_manager();
809
7
        recorder_manager != nullptr) {
810
3
        recorder_manager->stop();
811
3
    }
812
    // TODO(zhiqiang): http_service
813
7
    http_starter->stop();
814
7
    http_starter->join();
815
7
    LOG(INFO) << "Http service stopped";
816
7
    backend_thrift_starter->stop();
817
7
    backend_thrift_starter->join();
818
7
    LOG(INFO) << "Be server stopped";
819
7
    brpc_starter->stop();
820
7
    brpc_starter->join();
821
7
    LOG(INFO) << "Brpc service stopped";
822
7
    service.reset();
823
7
    LOG(INFO) << "Backend Service stopped";
824
7
    exec_env->destroy();
825
7
    LOG(INFO) << "All service stopped, doris main exited.";
826
7
    return 0;
827
7
}
828
829
0
static void help(const char* progname) {
830
0
    printf("%s is the Doris backend server.\n\n", progname);
831
0
    printf("Usage:\n  %s [OPTION]...\n\n", progname);
832
0
    printf("Options:\n");
833
0
    printf("  -v, --version      output version information, then exit\n");
834
0
    printf("  -?, --help         show this help, then exit\n");
835
0
}