BaseDaemon.cpp 33.4 KB
Newer Older
1
#include <daemon/BaseDaemon.h>
2

3
#include <Common/ConfigProcessor/ConfigProcessor.h>
4 5 6 7 8 9 10 11 12 13

#include <sys/stat.h>
#include <sys/types.h>
#include <sys/fcntl.h>
#include <sys/time.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <cxxabi.h>
#include <execinfo.h>
14

15 16 17 18
#if USE_UNWIND
    #define UNW_LOCAL_ONLY
    #include <libunwind.h>
#endif
19

V
Vladimir Smirnov 已提交
20 21 22 23
#ifdef __APPLE__
// ucontext is not available without _XOPEN_SOURCE
#define _XOPEN_SOURCE
#endif
24
#include <ucontext.h>
25

26 27 28 29 30 31
#include <typeinfo>
#include <common/logger_useful.h>
#include <common/ErrorHandlers.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <iostream>
32
#include <fstream>
33
#include <sstream>
34
#include <memory>
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
#include <Poco/Observer.h>
#include <Poco/Logger.h>
#include <Poco/AutoPtr.h>
#include <Poco/SplitterChannel.h>
#include <Poco/Ext/LevelFilterChannel.h>
#include <Poco/Ext/ThreadNumber.h>
#include <Poco/FormattingChannel.h>
#include <Poco/PatternFormatter.h>
#include <Poco/ConsoleChannel.h>
#include <Poco/TaskManager.h>
#include <Poco/File.h>
#include <Poco/Path.h>
#include <Poco/Message.h>
#include <Poco/Util/AbstractConfiguration.h>
#include <Poco/Util/XMLConfiguration.h>
50 51
#include <Poco/Util/MapConfiguration.h>
#include <Poco/Util/Application.h>
52 53 54 55 56 57
#include <Poco/ScopedLock.h>
#include <Poco/Exception.h>
#include <Poco/ErrorHandler.h>
#include <Poco/NumberFormatter.h>
#include <Poco/Condition.h>
#include <Poco/SyslogChannel.h>
58 59 60 61 62 63 64
#include <Common/Exception.h>
#include <IO/WriteBufferFromFileDescriptor.h>
#include <IO/ReadBufferFromFileDescriptor.h>
#include <IO/ReadHelpers.h>
#include <IO/WriteHelpers.h>
#include <Common/getMultipleKeysFromConfig.h>
#include <Common/ClickHouseRevision.h>
65
#include <daemon/OwnPatternFormatter.h>
66 67 68 69 70 71 72 73 74 75 76 77 78

using Poco::Logger;
using Poco::AutoPtr;
using Poco::Observer;
using Poco::FormattingChannel;
using Poco::SplitterChannel;
using Poco::ConsoleChannel;
using Poco::FileChannel;
using Poco::Path;
using Poco::Message;
using Poco::Util::AbstractConfiguration;


79 80
constexpr char BaseDaemon::DEFAULT_GRAPHITE_CONFIG_NAME[];

81 82 83 84 85
/** For transferring information from signal handler to a separate thread.
  * If you need to do something serious in case of a signal (example: write a message to the log),
  *  then sending information to a separate thread through pipe and doing all the stuff asynchronously
  *  - is probably the only safe method for doing it.
  * (Because it's only safe to use reentrant functions in signal handlers.)
86 87 88
  */
struct Pipe
{
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    union
    {
        int fds[2];
        struct
        {
            int read_fd;
            int write_fd;
        };
    };

    Pipe()
    {
        read_fd = -1;
        write_fd = -1;

        if (0 != pipe(fds))
            DB::throwFromErrno("Cannot create pipe");
    }

    void close()
    {
        if (-1 != read_fd)
        {
            ::close(read_fd);
            read_fd = -1;
        }

        if (-1 != write_fd)
        {
            ::close(write_fd);
            write_fd = -1;
        }
    }

    ~Pipe()
    {
        close();
    }
127 128 129 130 131 132
};


Pipe signal_pipe;


133 134
/** Reset signal handler to the default and send signal to itself.
  * It's called from user signal handler to write core dump.
135 136 137
  */
static void call_default_signal_handler(int sig)
{
138 139
    signal(sig, SIG_DFL);
    kill(getpid(), sig);
140 141 142
}


143
using ThreadNumber = decltype(Poco::ThreadNumber::get());
144 145
static const size_t buf_size = sizeof(int) + sizeof(siginfo_t) + sizeof(ucontext_t) + sizeof(ThreadNumber);

146
using signal_function = void(int, siginfo_t*, void*);
147

148
static void writeSignalIDtoSignalPipe(int sig)
149
{
150 151 152 153
    char buf[buf_size];
    DB::WriteBufferFromFileDescriptor out(signal_pipe.write_fd, buf_size, buf);
    DB::writeBinary(sig, out);
    out.next();
154 155
}

156
/** Signal handler for HUP / USR1 */
157 158
static void closeLogsSignalHandler(int sig, siginfo_t * info, void * context)
{
159
    writeSignalIDtoSignalPipe(sig);
160 161 162 163
}

static void terminateRequestedSignalHandler(int sig, siginfo_t * info, void * context)
{
164
    writeSignalIDtoSignalPipe(sig);
165 166
}

167

168 169
thread_local bool already_signal_handled = false;

170
/** Handler for "fault" signals. Send data about fault to separate thread to write into log.
171
  */
172
static void faultSignalHandler(int sig, siginfo_t * info, void * context)
173
{
174 175 176 177
    if (already_signal_handled)
        return;
    already_signal_handled = true;

178 179
    char buf[buf_size];
    DB::WriteBufferFromFileDescriptor out(signal_pipe.write_fd, buf_size, buf);
180

181 182 183 184
    DB::writeBinary(sig, out);
    DB::writePODBinary(*info, out);
    DB::writePODBinary(*reinterpret_cast<const ucontext_t *>(context), out);
    DB::writeBinary(Poco::ThreadNumber::get(), out);
185

186
    out.next();
187

188
    /// The time that is usually enough for separate thread to print info into log.
189
    ::sleep(10);
190

191
    call_default_signal_handler(sig);
192 193 194 195 196
}


static bool already_printed_stack_trace = false;

197
#if USE_UNWIND
198 199 200 201 202 203 204
size_t backtraceLibUnwind(void ** out_frames, size_t max_frames, ucontext_t & context)
{
    if (already_printed_stack_trace)
        return 0;

    unw_cursor_t cursor;

205
    if (unw_init_local2(&cursor, &context, UNW_INIT_SIGNAL_FRAME) < 0)
206 207 208 209 210 211 212 213
        return 0;

    size_t i = 0;
    for (; i < max_frames; ++i)
    {
        unw_word_t ip;
        unw_get_reg(&cursor, UNW_REG_IP, &ip);
        out_frames[i] = reinterpret_cast<void*>(ip);
214 215 216

        /// NOTE This triggers "AddressSanitizer: stack-buffer-overflow". Looks like false positive.
        /// It's Ok, because we use this method if the program is crashed nevertheless.
217 218 219 220 221 222
        if (!unw_step(&cursor))
            break;
    }

    return i;
}
223
#endif
224

225 226 227 228 229

/** The thread that read info about signal or std::terminate from pipe.
  * On HUP / USR1, close log files (for new files to be opened later).
  * On information about std::terminate, write it to log.
  * On other signals, write info to log.
230 231 232 233
  */
class SignalListener : public Poco::Runnable
{
public:
234 235 236 237 238 239
    enum Signals : int
    {
        StdTerminate = -1,
        StopThread = -2
    };

240 241 242
    explicit SignalListener(BaseDaemon & daemon_)
        : log(&Logger::get("BaseDaemon"))
        , daemon(daemon_)
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
    {
    }

    void run()
    {
        char buf[buf_size];
        DB::ReadBufferFromFileDescriptor in(signal_pipe.read_fd, buf_size, buf);

        while (!in.eof())
        {
            int sig = 0;
            DB::readBinary(sig, in);

            if (sig == Signals::StopThread)
            {
                LOG_INFO(log, "Stop SignalListener thread");
                break;
            }
            else if (sig == SIGHUP || sig == SIGUSR1)
            {
                LOG_DEBUG(log, "Received signal to close logs.");
                BaseDaemon::instance().closeLogs();
                LOG_INFO(log, "Opened new log file after received signal.");
            }
            else if (sig == Signals::StdTerminate)
            {
                ThreadNumber thread_num;
                std::string message;

                DB::readBinary(thread_num, in);
                DB::readBinary(message, in);

                onTerminate(message, thread_num);
            }
            else if (sig == SIGINT ||
                sig == SIGQUIT ||
                sig == SIGTERM)
            {
                daemon.handleSignal(sig);
            }
            else
            {
                siginfo_t info;
                ucontext_t context;
                ThreadNumber thread_num;

                DB::readPODBinary(info, in);
                DB::readPODBinary(context, in);
                DB::readBinary(thread_num, in);

                onFault(sig, info, context, thread_num);
            }
        }
    }
297 298

private:
299 300
    Logger * log;
    BaseDaemon & daemon;
301

302
private:
303 304 305 306 307 308 309 310 311 312 313 314 315
    void onTerminate(const std::string & message, ThreadNumber thread_num) const
    {
        LOG_ERROR(log, "(from thread " << thread_num << ") " << message);
    }

    void onFault(int sig, siginfo_t & info, ucontext_t & context, ThreadNumber thread_num) const
    {
        LOG_ERROR(log, "########################################");
        LOG_ERROR(log, "(from thread " << thread_num << ") "
            << "Received signal " << strsignal(sig) << " (" << sig << ")" << ".");

        if (sig == SIGSEGV)
        {
316
            /// Print info about address and reason.
317 318 319 320 321 322 323 324 325 326 327
            if (nullptr == info.si_addr)
                LOG_ERROR(log, "Address: NULL pointer.");
            else
                LOG_ERROR(log, "Address: " << info.si_addr
                    << (info.si_code == SEGV_ACCERR ? ". Attempted access has violated the permissions assigned to the memory area." : ""));
        }

        if (already_printed_stack_trace)
            return;

        void * caller_address = nullptr;
328

329
#if defined(__x86_64__)
330 331 332 333 334 335 336 337
        /// Get the address at the time the signal was raised from the RIP (x86-64)
        #if defined(__FreeBSD__)
        caller_address = reinterpret_cast<void *>(context.uc_mcontext.mc_rip);
        #elif defined(__APPLE__)
        caller_address = reinterpret_cast<void *>(context.uc_mcontext->__ss.__rip);
        #else
        caller_address = reinterpret_cast<void *>(context.uc_mcontext.gregs[REG_RIP]);
        #endif
338
#elif defined(__aarch64__)
339
        caller_address = reinterpret_cast<void *>(context.uc_mcontext.pc);
340
#endif
341

342 343
        static const int max_frames = 50;
        void * frames[max_frames];
344 345

#if USE_UNWIND
346
        int frames_size = backtraceLibUnwind(frames, max_frames, context);
347

348
        if (frames_size)
349
        {
350
#else
351 352 353
        /// No libunwind means no backtrace, because we are in a different thread from the one where the signal happened.
        /// So at least print the function where the signal happened.
        if (caller_address)
354
        {
355 356
            frames[0] = caller_address;
            int frames_size = 1;
357 358
#endif

359 360 361 362 363 364 365 366 367
            char ** symbols = backtrace_symbols(frames, frames_size);

            if (!symbols)
            {
                if (caller_address)
                    LOG_ERROR(log, "Caller address: " << caller_address);
            }
            else
            {
368
                for (int i = 0; i < frames_size; ++i)
369
                {
370
                    /// Perform demangling of names. Name is in parentheses, before '+' character.
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402

                    char * name_start = nullptr;
                    char * name_end = nullptr;
                    char * demangled_name = nullptr;
                    int status = 0;

                    if (nullptr != (name_start = strchr(symbols[i], '('))
                        && nullptr != (name_end = strchr(name_start, '+')))
                    {
                        ++name_start;
                        *name_end = '\0';
                        demangled_name = abi::__cxa_demangle(name_start, 0, 0, &status);
                        *name_end = '+';
                    }

                    std::stringstream res;

                    res << i << ". ";

                    if (nullptr != demangled_name && 0 == status)
                    {
                        res.write(symbols[i], name_start - symbols[i]);
                        res << demangled_name << name_end;
                    }
                    else
                        res << symbols[i];

                    LOG_ERROR(log, res.rdbuf());
                }
            }
        }
    }
403 404 405
};


406 407 408 409
/** To use with std::set_terminate.
  * Collects slightly more info than __gnu_cxx::__verbose_terminate_handler,
  *  and send it to pipe. Other thread will read this info from pipe and asynchronously write it to log.
  * Look at libstdc++-v3/libsupc++/vterminate.cc for example.
410 411 412
  */
static void terminate_handler()
{
413
    static thread_local bool terminating = false;
414 415 416
    if (terminating)
    {
        abort();
417
        return; /// Just for convenience.
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
    }

    terminating = true;

    std::stringstream log;

    std::type_info * t = abi::__cxa_current_exception_type();
    if (t)
    {
        /// Note that "name" is the mangled name.
        char const * name = t->name();
        {
            int status = -1;
            char * dem = 0;

            dem = abi::__cxa_demangle(name, 0, 0, &status);

            log << "Terminate called after throwing an instance of " << (status == 0 ? dem : name) << std::endl;

            if (status == 0)
                free(dem);
        }

        already_printed_stack_trace = true;

        /// If the exception is derived from std::exception, we can give more information.
        try
        {
            throw;
        }
        catch (DB::Exception & e)
        {
            log << "Code: " << e.code() << ", e.displayText() = " << e.displayText() << ", e.what() = " << e.what() << std::endl;
        }
        catch (Poco::Exception & e)
        {
            log << "Code: " << e.code() << ", e.displayText() = " << e.displayText() << ", e.what() = " << e.what() << std::endl;
        }
        catch (const std::exception & e)
        {
            log << "what(): " << e.what() << std::endl;
        }
        catch (...)
        {
        }

        log << "Stack trace:\n\n" << StackTrace().toString() << std::endl;
    }
    else
    {
        log << "Terminate called without an active exception" << std::endl;
    }

    static const size_t buf_size = 1024;

    std::string log_message = log.str();
    if (log_message.size() > buf_size - 16)
        log_message.resize(buf_size - 16);

    char buf[buf_size];
    DB::WriteBufferFromFileDescriptor out(signal_pipe.write_fd, buf_size, buf);

    DB::writeBinary(static_cast<int>(SignalListener::StdTerminate), out);
    DB::writeBinary(Poco::ThreadNumber::get(), out);
    DB::writeBinary(log_message, out);
    out.next();
484 485 486 487 488

    abort();
}


P
proller 已提交
489
static std::string createDirectory(const std::string & file)
490
{
P
proller 已提交
491 492 493
    auto path = Poco::Path(file).makeParent();
    if (path.toString().empty())
        return "";
494 495
    Poco::File(path).createDirectories();
    return path.toString();
496 497
};

498 499
static bool tryCreateDirectories(Poco::Logger * logger, const std::string & path)
{
500 501 502 503 504 505 506 507 508 509
    try
    {
        Poco::File(path).createDirectories();
        return true;
    }
    catch (...)
    {
        LOG_WARNING(logger, __PRETTY_FUNCTION__ << ": when creating " << path << ", " << DB::getCurrentExceptionMessage(true));
    }
    return false;
510 511
}

512

513
void BaseDaemon::reloadConfiguration()
514
{
515 516 517 518 519
    /** If the program is not run in daemon mode and 'config-file' is not specified,
      *  then we use config from 'config.xml' file in current directory,
      *  but will log to console (or use parameters --log-file, --errorlog-file from command line)
      *  instead of using files specified in config.xml.
      * (It's convenient to log in console when you start server without any command line parameters.)
520 521
      */
    config_path = config().getString("config-file", "config.xml");
522
    loaded_config = ConfigProcessor(config_path, false, true).loadConfig(/* allow_zk_includes = */ true);
523 524 525 526
    if (last_configuration != nullptr)
        config().removeConfiguration(last_configuration);
    last_configuration = loaded_config.configuration.duplicate();
    config().add(last_configuration, PRIO_DEFAULT, false);
527 528 529
}


530
/// For creating and destroying unique_ptr of incomplete type.
531
BaseDaemon::BaseDaemon() = default;
532 533 534 535


BaseDaemon::~BaseDaemon()
{
536 537 538
    writeSignalIDtoSignalPipe(SignalListener::StopThread);
    signal_listener_thread.join();
    signal_pipe.close();
539
}
540 541


542
void BaseDaemon::terminate()
543
{
544 545 546 547 548
    getTaskManager().cancelAll();
    if (::kill(Poco::Process::id(), SIGTERM) != 0)
    {
        throw Poco::SystemException("cannot terminate process");
    }
549 550
}

551
void BaseDaemon::kill()
552
{
553 554
    pid.clear();
    Poco::Process::kill(getpid());
555 556
}

557
void BaseDaemon::sleep(double seconds)
558
{
559 560
    wakeup_event.reset();
    wakeup_event.tryWait(seconds * 1000);
561 562
}

563
void BaseDaemon::wakeup()
564
{
565
    wakeup_event.set();
566 567 568
}


569
void BaseDaemon::buildLoggers()
570
{
571 572
    bool is_daemon = config().getBool("application.runAsDaemon", false);

573
    /// Change path for logging.
574
    if (config().hasProperty("logger.log"))
575 576
    {
        std::string path = createDirectory(config().getString("logger.log"));
577
        if (is_daemon
578 579 580 581 582
            && chdir(path.c_str()) != 0)
            throw Poco::Exception("Cannot change directory to " + path);
    }
    else
    {
583
        if (is_daemon
584 585 586 587
            && chdir("/tmp") != 0)
            throw Poco::Exception("Cannot change directory to /tmp");
    }

588 589
    // Split log and error log.
    Poco::AutoPtr<SplitterChannel> split = new SplitterChannel;
590

591
    if (config().hasProperty("logger.log"))
592
    {
593
        createDirectory(config().getString("logger.log"));
A
Alexey Milovidov 已提交
594
        std::cerr << "Logging to " << config().getString("logger.log") << std::endl;
595

596
        // Set up two channel chains.
597 598 599 600
        Poco::AutoPtr<OwnPatternFormatter> pf = new OwnPatternFormatter(this);
        pf->setProperty("times", "local");
        Poco::AutoPtr<FormattingChannel> log = new FormattingChannel(pf);
        log_file = new FileChannel;
601 602 603 604 605 606 607
        log_file->setProperty(Poco::FileChannel::PROP_PATH, Poco::Path(config().getString("logger.log")).absolute().toString());
        log_file->setProperty(Poco::FileChannel::PROP_ROTATION, config().getRawString("logger.size", "100M"));
        log_file->setProperty(Poco::FileChannel::PROP_ARCHIVE, "number");
        log_file->setProperty(Poco::FileChannel::PROP_COMPRESS, config().getRawString("logger.compress", "true"));
        log_file->setProperty(Poco::FileChannel::PROP_PURGECOUNT, config().getRawString("logger.count", "1"));
        log_file->setProperty(Poco::FileChannel::PROP_FLUSH, config().getRawString("logger.flush", "true"));
        log_file->setProperty(Poco::FileChannel::PROP_ROTATEONOPEN, config().getRawString("logger.rotateOnOpen", "false"));
608 609 610
        log->setChannel(log_file);
        split->addChannel(log);
        log_file->open();
611
    }
612

613 614 615
    if (config().hasProperty("logger.errorlog"))
    {
        createDirectory(config().getString("logger.errorlog"));
A
Alexey Milovidov 已提交
616
        std::cerr << "Logging errors to " << config().getString("logger.errorlog") << std::endl;
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
        Poco::AutoPtr<Poco::LevelFilterChannel> level = new Poco::LevelFilterChannel;
        level->setLevel(Message::PRIO_NOTICE);
        Poco::AutoPtr<OwnPatternFormatter> pf = new OwnPatternFormatter(this);
        pf->setProperty("times", "local");
        Poco::AutoPtr<FormattingChannel> errorlog = new FormattingChannel(pf);
        error_log_file = new FileChannel;
        error_log_file->setProperty(Poco::FileChannel::PROP_PATH, Poco::Path(config().getString("logger.errorlog")).absolute().toString());
        error_log_file->setProperty(Poco::FileChannel::PROP_ROTATION, config().getRawString("logger.size", "100M"));
        error_log_file->setProperty(Poco::FileChannel::PROP_ARCHIVE, "number");
        error_log_file->setProperty(Poco::FileChannel::PROP_COMPRESS, config().getRawString("logger.compress", "true"));
        error_log_file->setProperty(Poco::FileChannel::PROP_PURGECOUNT, config().getRawString("logger.count", "1"));
        error_log_file->setProperty(Poco::FileChannel::PROP_FLUSH, config().getRawString("logger.flush", "true"));
        error_log_file->setProperty(Poco::FileChannel::PROP_ROTATEONOPEN, config().getRawString("logger.rotateOnOpen", "false"));
        errorlog->setChannel(error_log_file);
        level->setChannel(errorlog);
        split->addChannel(level);
        errorlog->open();
    }
635

636 637
    /// "dynamic_layer_selection" is needed only for Yandex.Metrika, that share part of ClickHouse code.
    /// We don't need this configuration parameter.
638

639 640 641 642 643 644 645 646 647
    if (config().getBool("logger.use_syslog", false) || config().getBool("dynamic_layer_selection", false))
    {
        Poco::AutoPtr<OwnPatternFormatter> pf = new OwnPatternFormatter(this, OwnPatternFormatter::ADD_LAYER_TAG);
        pf->setProperty("times", "local");
        Poco::AutoPtr<FormattingChannel> log = new FormattingChannel(pf);
        syslog_channel = new Poco::SyslogChannel(commandName(), Poco::SyslogChannel::SYSLOG_CONS | Poco::SyslogChannel::SYSLOG_PID, Poco::SyslogChannel::SYSLOG_DAEMON);
        log->setChannel(syslog_channel);
        split->addChannel(log);
        syslog_channel->open();
648
    }
649 650

    if (config().getBool("logger.console", false) || (!config().hasProperty("logger.console") && !is_daemon && (isatty(STDIN_FILENO) || isatty(STDERR_FILENO))))
651 652 653 654 655 656 657
    {
        Poco::AutoPtr<ConsoleChannel> file = new ConsoleChannel;
        Poco::AutoPtr<OwnPatternFormatter> pf = new OwnPatternFormatter(this);
        pf->setProperty("times", "local");
        Poco::AutoPtr<FormattingChannel> log = new FormattingChannel(pf);
        log->setChannel(file);
        logger().warning("Logging to console");
658
        split->addChannel(log);
659 660
    }

661 662 663 664
    split->open();
    logger().close();
    logger().setChannel(split);

665
    // Global logging level (it can be overridden for specific loggers).
666 667
    logger().setLevel(config().getString("logger.level", "trace"));

668
    // Attach to the root logger.
669 670 671
    Logger::root().setLevel(logger().getLevel());
    Logger::root().setChannel(logger().getChannel());

672
    // Explicitly specified log levels for specific loggers.
673 674 675 676 677 678
    AbstractConfiguration::Keys levels;
    config().keys("logger.levels", levels);

    if(!levels.empty())
        for(AbstractConfiguration::Keys::iterator it = levels.begin(); it != levels.end(); ++it)
            Logger::get(*it).setLevel(config().getString("logger.levels." + *it, "trace"));
679 680 681
}


682
void BaseDaemon::closeLogs()
683
{
684 685 686 687
    if (log_file)
        log_file->close();
    if (error_log_file)
        error_log_file->close();
688

689 690
    if (!log_file)
        logger().warning("Logging to console but received signal to close log file (ignoring).");
691 692
}

A
Alexey Milovidov 已提交
693
std::string BaseDaemon::getDefaultCorePath() const
694
{
695
    return "/opt/cores/";
696 697
}

698
void BaseDaemon::initialize(Application & self)
699
{
700 701 702
    task_manager.reset(new Poco::TaskManager);
    ServerApplication::initialize(self);

703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
    {
        /// Parsing all args and converting to config layer
        /// Test: -- --1=1 --1=2 --3 5 7 8 -9 10 -11=12 14= 15== --16==17 --=18 --19= --20 21 22 --23 --24 25 --26 -27 28 ---29=30 -- ----31 32 --33 3-4
        Poco::AutoPtr<Poco::Util::MapConfiguration> map_config = new Poco::Util::MapConfiguration;
        std::string key;
        for(auto & arg : argv())
        {
            auto key_start = arg.find_first_not_of('-');
            auto pos_minus = arg.find('-');
            auto pos_eq = arg.find('=');

            // old saved '--key', will set to some true value "1"
            if (!key.empty() && pos_minus != std::string::npos && pos_minus < key_start)
            {
                map_config->setString(key, "1");
                key = "";
            }

            if (pos_eq == std::string::npos)
            {
                if (!key.empty())
                {
                    if (pos_minus == std::string::npos || pos_minus > key_start)
                    {
                        map_config->setString(key, arg);
                    }
                    key = "";
                }
                if (pos_minus != std::string::npos && key_start != std::string::npos && pos_minus < key_start)
                    key = arg.substr(key_start);
                continue;
            }
            else
            {
                key = "";
            }

            if (key_start == std::string::npos)
                continue;

            if (pos_minus > key_start)
                continue;

            key = arg.substr(key_start, pos_eq - key_start);
            if (key.empty())
                continue;
            std::string value;
            if (arg.size() > pos_eq)
                value = arg.substr(pos_eq+1);

            map_config->setString(key, value);
            key = "";
        }
        /// now highest priority (lowest value) is PRIO_APPLICATION = -100, we want higher!
        config().add(map_config, PRIO_APPLICATION - 100);
    }

760 761 762 763
    bool is_daemon = config().getBool("application.runAsDaemon", false);

    if (is_daemon)
    {
764
        /** When creating pid file and looking for config, will search for paths relative to the working path of the program when started.
765 766 767 768 769 770 771 772
          */
        std::string path = Poco::Path(config().getString("application.path")).setFileName("").toString();
        if (0 != chdir(path.c_str()))
            throw Poco::Exception("Cannot change directory to " + path);
    }

    reloadConfiguration();

773 774 775 776 777 778 779 780 781 782 783 784 785 786
    /// This must be done before creation of any files (including logs).
    if (config().has("umask"))
    {
        std::string umask_str = config().getString("umask");
        mode_t umask_num = 0;
        std::stringstream stream;
        stream << umask_str;
        stream >> std::oct >> umask_num;

        umask(umask_num);
    }

    ConfigProcessor(config_path).savePreprocessedConfig(loaded_config);

787
    /// Write core dump on crash.
788 789 790 791
    {
        struct rlimit rlim;
        if (getrlimit(RLIMIT_CORE, &rlim))
            throw Poco::Exception("Cannot getrlimit");
792
        /// 1 GiB by default. If more - it writes to disk too long.
793 794 795 796 797 798 799 800
        rlim.rlim_cur = config().getUInt64("core_dump.size_limit", 1024 * 1024 * 1024);

        if (setrlimit(RLIMIT_CORE, &rlim))
        {
            std::string message = "Cannot set max size of core file to " + std::to_string(rlim.rlim_cur);
        #if !defined(ADDRESS_SANITIZER) && !defined(THREAD_SANITIZER)
            throw Poco::Exception(message);
        #else
801
            /// It doesn't work under address/thread sanitizer. http://lists.llvm.org/pipermail/llvm-bugs/2013-April/027880.html
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
            std::cerr << message << std::endl;
        #endif
        }
    }

    /// This must be done before any usage of DateLUT. In particular, before any logging.
    if (config().has("timezone"))
    {
        if (0 != setenv("TZ", config().getString("timezone").data(), 1))
            throw Poco::Exception("Cannot setenv TZ variable");

        tzset();
    }

    std::string log_path = config().getString("logger.log", "");
    if (!log_path.empty())
        log_path = Poco::Path(log_path).setFileName("").toString();

    if (is_daemon)
    {
822 823 824 825
        /** Redirect stdout, stderr to separate files in the log directory.
          * Some libraries write to stderr in case of errors in debug mode,
          *  and this output makes sense even if the program is run in daemon mode.
          * We have to do it before buildLoggers, for errors on logger initialization will be written to these files.
826 827 828 829 830 831 832 833 834 835 836 837
          */
        if (!log_path.empty())
        {
            std::string stdout_path = log_path + "/stdout";
            if (!freopen(stdout_path.c_str(), "a+", stdout))
                throw Poco::OpenFileException("Cannot attach stdout to " + stdout_path);

            std::string stderr_path = log_path + "/stderr";
            if (!freopen(stderr_path.c_str(), "a+", stderr))
                throw Poco::OpenFileException("Cannot attach stderr to " + stderr_path);
        }

838
        /// Create pid file.
839 840 841 842 843 844 845 846
        if (is_daemon && config().has("pid"))
            pid.seed(config().getString("pid"));
    }

    buildLoggers();

    if (is_daemon)
    {
847 848
        /** Change working directory to the directory to write core dumps.
          * We have to do it after buildLoggers, because there is the case when config files was in current directory.
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
          */

        std::string core_path = config().getString("core_path", "");
        if (core_path.empty())
            core_path = getDefaultCorePath();

        tryCreateDirectories(&logger(), core_path);

        Poco::File cores = core_path;
        if (!(cores.exists() && cores.isDirectory()))
        {
            core_path = !log_path.empty() ? log_path : "/opt/";
            tryCreateDirectories(&logger(), core_path);
        }

        if (0 != chdir(core_path.c_str()))
            throw Poco::Exception("Cannot change directory to " + core_path);
    }

    std::set_terminate(terminate_handler);

870 871 872 873 874 875 876
    /// We want to avoid SIGPIPE when working with sockets and pipes, and just handle return value/errno instead.
    {
        sigset_t sig_set;
        if (sigemptyset(&sig_set) || sigaddset(&sig_set, SIGPIPE) || pthread_sigmask(SIG_BLOCK, &sig_set, nullptr))
            throw Poco::Exception("Cannot block signal.");
    }

877
    /// Setup signal handlers.
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
    auto add_signal_handler =
        [](const std::vector<int> & signals, signal_function handler)
        {
            struct sigaction sa;
            memset(&sa, 0, sizeof(sa));
            sa.sa_sigaction = handler;
            sa.sa_flags = SA_SIGINFO;

            {
                if (sigemptyset(&sa.sa_mask))
                    throw Poco::Exception("Cannot set signal handler.");

                for (auto signal : signals)
                    if (sigaddset(&sa.sa_mask, signal))
                        throw Poco::Exception("Cannot set signal handler.");

                for (auto signal : signals)
                    if (sigaction(signal, &sa, 0))
                        throw Poco::Exception("Cannot set signal handler.");
            }
        };

    add_signal_handler({SIGABRT, SIGSEGV, SIGILL, SIGBUS, SIGSYS, SIGFPE, SIGPIPE}, faultSignalHandler);
    add_signal_handler({SIGHUP, SIGUSR1}, closeLogsSignalHandler);
    add_signal_handler({SIGINT, SIGQUIT, SIGTERM}, terminateRequestedSignalHandler);

904
    /// Set up Poco ErrorHandler for Poco Threads.
905 906 907 908 909 910 911 912 913 914 915 916
    static KillingErrorHandler killing_error_handler;
    Poco::ErrorHandler::set(&killing_error_handler);

    logRevision();

    signal_listener.reset(new SignalListener(*this));
    signal_listener_thread.start(*signal_listener);

    for (const auto & key : DB::getMultipleKeysFromConfig(config(), "", "graphite"))
    {
        graphite_writers.emplace(key, std::make_unique<GraphiteWriter>(key));
    }
917 918
}

919
void BaseDaemon::logRevision() const
920
{
921
    Logger::root().information("Starting daemon with revision " + Poco::NumberFormatter::format(ClickHouseRevision::get()));
922
}
923

924
/// Makes server shutdown if at least one Poco::Task have failed.
925
void BaseDaemon::exitOnTaskError()
926
{
927 928
    Observer<BaseDaemon, Poco::TaskFailedNotification> obs(*this, &BaseDaemon::handleNotification);
    getTaskManager().addObserver(obs);
929 930
}

931
/// Used for exitOnTaskError()
932
void BaseDaemon::handleNotification(Poco::TaskFailedNotification *_tfn)
933
{
934 935 936 937 938
    task_failed = true;
    AutoPtr<Poco::TaskFailedNotification> fn(_tfn);
    Logger *lg = &(logger());
    LOG_ERROR(lg, "Task '" << fn->task()->name() << "' failed. Daemon is shutting down. Reason - " << fn->reason().displayText());
    ServerApplication::terminate();
939 940
}

941
void BaseDaemon::defineOptions(Poco::Util::OptionSet& _options)
942
{
943 944 945
    Poco::Util::ServerApplication::defineOptions (_options);

    _options.addOption(
A
Alexey Milovidov 已提交
946 947 948 949 950
        Poco::Util::Option("config-file", "C", "load configuration from a given file")
            .required(false)
            .repeatable(false)
            .argument("<file>")
            .binding("config-file"));
951 952

    _options.addOption(
A
Alexey Milovidov 已提交
953 954 955 956 957
        Poco::Util::Option("log-file", "L", "use given log file")
            .required(false)
            .repeatable(false)
            .argument("<file>")
            .binding("logger.log"));
958 959

    _options.addOption(
A
Alexey Milovidov 已提交
960 961 962 963 964
        Poco::Util::Option("errorlog-file", "E", "use given log file for errors only")
            .required(false)
            .repeatable(false)
            .argument("<file>")
            .binding("logger.errorlog"));
965 966

    _options.addOption(
A
Alexey Milovidov 已提交
967 968 969 970 971
        Poco::Util::Option("pid-file", "P", "use given pidfile")
            .required(false)
            .repeatable(false)
            .argument("<file>")
            .binding("pid"));
972 973
}

974 975 976 977 978 979
bool isPidRunning(pid_t pid)
{
    if (getpgid(pid) >= 0)
        return 1;
    return 0;
}
980

981
void BaseDaemon::PID::seed(const std::string & file_)
982
{
983
    file = Poco::Path(file_).absolute().toString();
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
    Poco::File poco_file(file);

    if (poco_file.exists())
    {
        pid_t pid_read = 0;
        {
            std::ifstream in(file);
            if (in.good())
            {
                in >> pid_read;
                if (pid_read && isPidRunning(pid_read))
                    throw Poco::Exception("Pid file exists and program running with pid = " + std::to_string(pid_read) + ", should not start daemon.");
            }
        }
        std::cerr << "Old pid file exists (with pid = " << pid_read << "), removing." << std::endl;
        poco_file.remove();
    }
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027

    int fd = open(file.c_str(),
        O_CREAT | O_EXCL | O_WRONLY,
        S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);

    if (-1 == fd)
    {
        file.clear();
        if (EEXIST == errno)
            throw Poco::Exception("Pid file exists, should not start daemon.");
        throw Poco::CreateFileException("Cannot create pid file.");
    }

    try
    {
        std::stringstream s;
        s << getpid();
        if (static_cast<ssize_t>(s.str().size()) != write(fd, s.str().c_str(), s.str().size()))
            throw Poco::Exception("Cannot write to pid file.");
    }
    catch (...)
    {
        close(fd);
        throw;
    }

    close(fd);
1028 1029
}

1030
void BaseDaemon::PID::clear()
1031
{
1032 1033 1034 1035 1036
    if (!file.empty())
    {
        Poco::File(file).remove();
        file.clear();
    }
1037
}
1038 1039 1040

void BaseDaemon::handleSignal(int signal_id)
{
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
    if (signal_id == SIGINT ||
        signal_id == SIGQUIT ||
        signal_id == SIGTERM)
    {
        std::unique_lock<std::mutex> lock(signal_handler_mutex);
        {
            ++terminate_signals_counter;
            sigint_signals_counter += signal_id == SIGINT;
            signal_event.notify_all();
        }

        onInterruptSignals(signal_id);
    }
    else
        throw DB::Exception(std::string("Unsupported signal: ") + strsignal(signal_id));
1056 1057 1058 1059
}

void BaseDaemon::onInterruptSignals(int signal_id)
{
1060 1061 1062 1063 1064 1065 1066 1067
    is_cancelled = true;
    LOG_INFO(&logger(), "Received termination signal (" << strsignal(signal_id) << ")");

    if (sigint_signals_counter >= 2)
    {
        LOG_INFO(&logger(), "Received second signal Interrupt. Immediately terminate.");
        kill();
    }
1068 1069 1070 1071 1072
}


void BaseDaemon::waitForTerminationRequest()
{
1073 1074
    std::unique_lock<std::mutex> lock(signal_handler_mutex);
    signal_event.wait(lock, [this](){ return terminate_signals_counter > 0; });
1075 1076
}