Server.cpp 28.3 KB
Newer Older
1
#include "Server.h"
2

P
proller 已提交
3
#include <memory>
4
#include <sys/resource.h>
5
#include <errno.h>
6
#include <Poco/Version.h>
P
proller 已提交
7
#include <Poco/DirectoryIterator.h>
V
Vadim Skipin 已提交
8
#include <Poco/Net/HTTPServer.h>
9
#include <Poco/Net/NetException.h>
V
Vadim Skipin 已提交
10
#include <ext/scope_guard.h>
11
#include <common/logger_useful.h>
12
#include <common/ErrorHandlers.h>
V
Vadim Skipin 已提交
13 14
#include <common/getMemoryAmount.h>
#include <Common/ClickHouseRevision.h>
15
#include <Common/DNSResolver.h>
V
Vadim Skipin 已提交
16
#include <Common/CurrentMetrics.h>
17
#include <Common/Macros.h>
18
#include <Common/StringUtils/StringUtils.h>
V
Vadim Skipin 已提交
19 20 21
#include <Common/ZooKeeper/ZooKeeper.h>
#include <Common/ZooKeeper/ZooKeeperNodeCache.h>
#include <Common/config.h>
22 23
#include <Common/getFQDNOrHostName.h>
#include <Common/getMultipleKeysFromConfig.h>
24
#include <Common/getNumberOfPhysicalCPUCores.h>
25
#include <Common/TaskStatsInfoGetter.h>
26
#include <IO/HTTPCommon.h>
P
proller 已提交
27
#include <IO/UseSSL.h>
28
#include <Interpreters/AsynchronousMetrics.h>
V
Vadim Skipin 已提交
29
#include <Interpreters/DDLWorker.h>
30 31
#include <Interpreters/ProcessList.h>
#include <Interpreters/loadMetadata.h>
32
#include <Interpreters/DNSCacheUpdater.h>
33 34
#include <Storages/StorageReplicatedMergeTree.h>
#include <Storages/System/attachSystemTables.h>
V
Vadim Skipin 已提交
35 36 37
#include <AggregateFunctions/registerAggregateFunctions.h>
#include <Functions/registerFunctions.h>
#include <TableFunctions/registerTableFunctions.h>
38
#include <Storages/registerStorages.h>
39
#include <Common/Config/ConfigReloader.h>
V
Vadim Skipin 已提交
40
#include "HTTPHandlerFactory.h"
41
#include "MetricsTransmitter.h"
A
Alexey Milovidov 已提交
42
#include <Common/StatusFile.h>
V
Vadim Skipin 已提交
43
#include "TCPHandlerFactory.h"
44

45
#if USE_POCO_NETSSL
46 47 48
#include <Poco/Net/Context.h>
#include <Poco/Net/SecureServerSocket.h>
#endif
49

50 51 52 53 54
namespace CurrentMetrics
{
    extern const Metric Revision;
}

55 56
namespace DB
{
57

58 59 60 61
namespace ErrorCodes
{
    extern const int NO_ELEMENTS_IN_CONFIG;
    extern const int SUPPORT_IS_DISABLED;
62
    extern const int ARGUMENT_OUT_OF_BOUND;
63
    extern const int EXCESSIVE_ELEMENT_IN_CONFIG;
64 65 66
}


67
static std::string getCanonicalPath(std::string && path)
68
{
69 70 71 72 73
    Poco::trimInPlace(path);
    if (path.empty())
        throw Exception("path configuration parameter is empty");
    if (path.back() != '/')
        path += '/';
74
    return std::move(path);
75 76
}

77 78 79 80 81 82 83 84 85 86 87 88
void Server::uninitialize()
{
    logger().information("shutting down");
    BaseDaemon::uninitialize();
}

void Server::initialize(Poco::Util::Application & self)
{
    BaseDaemon::initialize(self);
    logger().information("starting up");
}

89 90
std::string Server::getDefaultCorePath() const
{
91
    return getCanonicalPath(config().getString("path")) + "cores";
92
}
93

A
Alexey Milovidov 已提交
94
int Server::main(const std::vector<std::string> & /*args*/)
95
{
96 97
    Logger * log = &logger();

P
proller 已提交
98 99
    UseSSL use_ssl;

P
proller 已提交
100
    registerFunctions();
101
    registerAggregateFunctions();
102
    registerTableFunctions();
103
    registerStorages();
P
proller 已提交
104

105 106
    CurrentMetrics::set(CurrentMetrics::Revision, ClickHouseRevision::get());

107 108 109
    /** Context contains all that query execution is dependent:
      *  settings, available functions, data types, aggregate functions, databases...
      */
110
    global_context = std::make_unique<Context>(Context::createGlobal());
111 112 113
    global_context->setGlobalContext(*global_context);
    global_context->setApplicationType(Context::ApplicationType::SERVER);

114
    bool has_zookeeper = config().has("zookeeper");
115 116 117 118 119

    zkutil::ZooKeeperNodeCache main_config_zk_node_cache([&] { return global_context->getZooKeeper(); });
    if (loaded_config.has_zk_includes)
    {
        auto old_configuration = loaded_config.configuration;
120 121 122 123
        ConfigProcessor config_processor(config_path);
        loaded_config = config_processor.loadConfigWithZooKeeperIncludes(
            main_config_zk_node_cache, /* fallback_to_preprocessed = */ true);
        config_processor.savePreprocessedConfig(loaded_config);
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
        config().removeConfiguration(old_configuration.get());
        config().add(loaded_config.configuration.duplicate(), PRIO_DEFAULT, false);
    }

    std::string path = getCanonicalPath(config().getString("path"));
    std::string default_database = config().getString("default_database", "default");

    global_context->setPath(path);

    /// Create directories for 'path' and for default database, if not exist.
    Poco::File(path + "data/" + default_database).createDirectories();
    Poco::File(path + "metadata/" + default_database).createDirectories();

    StatusFile status{path + "status"};

139 140 141 142 143 144 145 146 147
    SCOPE_EXIT({
        /** Explicitly destroy Context. It is more convenient than in destructor of Server, because logger is still available.
          * At this moment, no one could own shared part of Context.
          */
        global_context.reset();

        LOG_DEBUG(log, "Destroyed global context.");
    });

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
    /// Try to increase limit on number of open files.
    {
        rlimit rlim;
        if (getrlimit(RLIMIT_NOFILE, &rlim))
            throw Poco::Exception("Cannot getrlimit");

        if (rlim.rlim_cur == rlim.rlim_max)
        {
            LOG_DEBUG(log, "rlimit on number of file descriptors is " << rlim.rlim_cur);
        }
        else
        {
            rlim_t old = rlim.rlim_cur;
            rlim.rlim_cur = config().getUInt("max_open_files", rlim.rlim_max);
            int rc = setrlimit(RLIMIT_NOFILE, &rlim);
            if (rc != 0)
                LOG_WARNING(log,
165 166 167
                    "Cannot set max number of file descriptors to " << rlim.rlim_cur
                        << ". Try to specify max_open_files according to your system limits. error: "
                        << strerror(errno));
168 169 170 171 172 173 174 175 176 177 178 179 180
            else
                LOG_DEBUG(log, "Set max number of file descriptors to " << rlim.rlim_cur << " (was " << old << ").");
        }
    }

    static ServerErrorHandler error_handler;
    Poco::ErrorHandler::set(&error_handler);

    /// Initialize DateLUT early, to not interfere with running time of first query.
    LOG_DEBUG(log, "Initializing DateLUT.");
    DateLUT::instance();
    LOG_TRACE(log, "Initialized DateLUT with time zone `" << DateLUT::instance().getTimeZone() << "'.");

181
    /// Directory with temporary data for processing of heavy queries.
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
    {
        std::string tmp_path = config().getString("tmp_path", path + "tmp/");
        global_context->setTemporaryPath(tmp_path);
        Poco::File(tmp_path).createDirectories();

        /// Clearing old temporary files.
        Poco::DirectoryIterator dir_end;
        for (Poco::DirectoryIterator it(tmp_path); it != dir_end; ++it)
        {
            if (it->isFile() && startsWith(it.name(), "tmp"))
            {
                LOG_DEBUG(log, "Removing old temporary file " << it->path());
                it->remove();
            }
        }
    }

    /** Directory with 'flags': files indicating temporary settings for the server set by system administrator.
      * Flags may be cleared automatically after being applied by the server.
      * Examples: do repair of local data; clone all replicated tables from replica.
      */
203 204 205 206 207 208 209 210 211 212 213 214 215
    {
        Poco::File(path + "flags/").createDirectories();
        global_context->setFlagsPath(path + "flags/");
    }

    /** Directory with user provided files that are usable by 'file' table function.
      */
    {

        std::string user_files_path = config().getString("user_files_path", path + "user_files/");
        global_context->setUserFilesPath(user_files_path);
        Poco::File(user_files_path).createDirectories();
    }
216

217 218 219 220
    if (config().has("interserver_http_port") && config().has("interserver_https_port"))
        throw Exception("Both http and https interserver ports are specified", ErrorCodes::EXCESSIVE_ELEMENT_IN_CONFIG);

    static const auto interserver_tags =
221
    {
222 223 224
        std::make_tuple("interserver_http_host", "interserver_http_port", "http"),
        std::make_tuple("interserver_https_host", "interserver_https_port", "https")
    };
225

226 227 228
    for (auto [host_tag, port_tag, scheme] : interserver_tags)
    {
        if (config().has(port_tag))
229
        {
230 231 232 233 234 235 236 237 238
            String this_host = config().getString(host_tag, "");

            if (this_host.empty())
            {
                this_host = getFQDNOrHostName();
                LOG_DEBUG(log,
                    "Configuration parameter '" + String(host_tag) + "' doesn't exist or exists and empty. Will use '" + this_host
                        + "' as replica host.");
            }
239

240 241
            String port_str = config().getString(port_tag);
            int port = parse<int>(port_str);
242

243 244
            if (port < 0 || port > 0xFFFF)
                throw Exception("Out of range '" + String(port_tag) + "': " + toString(port), ErrorCodes::ARGUMENT_OUT_OF_BOUND);
245

246 247
            global_context->setInterserverIOAddress(this_host, port);
            global_context->setInterserverScheme(scheme);
248 249 250
        }
    }

251
    if (config().has("interserver_http_credentials"))
252 253 254
    {
        String user = config().getString("interserver_http_credentials.user", "");
        String password = config().getString("interserver_http_credentials.password", "");
255

256
        if (user.empty())
A
alesapin 已提交
257
            throw Exception("Configuration parameter interserver_http_credentials user can't be empty", ErrorCodes::NO_ELEMENTS_IN_CONFIG);
258

259
        global_context->setInterserverCredentials(user, password);
260 261 262
    }

    if (config().has("macros"))
A
Alexey Milovidov 已提交
263
        global_context->setMacros(std::make_unique<Macros>(config(), "macros"));
264 265 266 267 268 269

    /// Initialize main config reloader.
    std::string include_from_path = config().getString("include_from", "/etc/metrika.xml");
    auto main_config_reloader = std::make_unique<ConfigReloader>(config_path,
        include_from_path,
        std::move(main_config_zk_node_cache),
270 271
        [&](ConfigurationPtr config)
        {
272
            buildLoggers(*config);
273
            global_context->setClustersConfig(config);
A
Alexey Milovidov 已提交
274
            global_context->setMacros(std::make_unique<Macros>(*config, "macros"));
275
        },
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
        /* already_loaded = */ true);

    /// Initialize users config reloader.
    std::string users_config_path = config().getString("users_config", config_path);
    /// If path to users' config isn't absolute, try guess its root (current) dir.
    /// At first, try to find it in dir of main config, after will use current dir.
    if (users_config_path.empty() || users_config_path[0] != '/')
    {
        std::string config_dir = Poco::Path(config_path).parent().toString();
        if (Poco::File(config_dir + users_config_path).exists())
            users_config_path = config_dir + users_config_path;
    }
    auto users_config_reloader = std::make_unique<ConfigReloader>(users_config_path,
        include_from_path,
        zkutil::ZooKeeperNodeCache([&] { return global_context->getZooKeeper(); }),
        [&](ConfigurationPtr config) { global_context->setUsersConfig(config); },
        /* already_loaded = */ false);

294
    /// Reload config in SYSTEM RELOAD CONFIG query.
295 296
    global_context->setConfigReloadCallback([&]()
    {
297 298 299 300
        main_config_reloader->reload();
        users_config_reloader->reload();
    });

A
Alexey Milovidov 已提交
301
    /// Limit on total number of concurrently executed queries.
302 303 304 305 306 307
    global_context->getProcessList().setMaxSize(config().getInt("max_concurrent_queries", 0));

    /// Setup protection to avoid accidental DROP for big tables (that are greater than 50 GB by default)
    if (config().has("max_table_size_to_drop"))
        global_context->setMaxTableSizeToDrop(config().getUInt64("max_table_size_to_drop"));

308
    if (config().has("max_partition_size_to_drop"))
309
        global_context->setMaxPartitionSizeToDrop(config().getUInt64("max_partition_size_to_drop"));
310

311
    /// Size of cache for uncompressed blocks. Zero means disabled.
312
    size_t uncompressed_cache_size = config().getUInt64("uncompressed_cache_size", 0);
313 314 315
    if (uncompressed_cache_size)
        global_context->setUncompressedCache(uncompressed_cache_size);

316 317
    /// Load global settings from default_profile and system_profile.
    global_context->setDefaultProfiles(config());
318 319
    Settings & settings = global_context->getSettingsRef();

320 321 322 323 324
    /// Size of cache for marks (index of MergeTree family of tables). It is necessary.
    size_t mark_cache_size = config().getUInt64("mark_cache_size");
    if (mark_cache_size)
        global_context->setMarkCache(mark_cache_size);

A
alesapin 已提交
325
#if USE_EMBEDDED_COMPILER
326 327
    size_t compiled_expression_cache_size = config().getUInt64("compiled_expression_cache_size", std::numeric_limits<UInt64>::max());
    if (compiled_expression_cache_size)
A
alesapin 已提交
328
        global_context->setCompiledExpressionCache(compiled_expression_cache_size);
A
alesapin 已提交
329
#endif
330

331 332 333 334 335
    /// Set path for format schema files
    auto format_schema_path = Poco::File(config().getString("format_schema_path", path + "format_schemas/"));
    global_context->setFormatSchemaPath(format_schema_path.path() + "/");
    format_schema_path.createDirectories();

336
    LOG_INFO(log, "Loading metadata.");
337
    loadMetadataSystem(*global_context);
338 339
    /// After attaching system databases we can initialize system log.
    global_context->initializeSystemLogs();
340 341 342
    /// After the system database is created, attach virtual system tables (in addition to query_log and part_log)
    attachSystemTablesServer(*global_context->getDatabase("system"), has_zookeeper);
    /// Then, load remaining databases
343 344 345 346 347
    loadMetadata(*global_context);
    LOG_DEBUG(log, "Loaded metadata.");

    global_context->setCurrentDatabase(default_database);

348 349 350 351 352 353 354 355 356 357 358
    SCOPE_EXIT({
        /** Ask to cancel background jobs all table engines,
          *  and also query_log.
          * It is important to do early, not in destructor of Context, because
          *  table engines could use Context on destroy.
          */
        LOG_INFO(log, "Shutting down storages.");
        global_context->shutdown();
        LOG_DEBUG(log, "Shutted down storages.");
    });

359 360
    if (has_zookeeper && config().has("distributed_ddl"))
    {
361
        /// DDL worker should be started after all tables were loaded
362
        String ddl_zookeeper_path = config().getString("distributed_ddl.path", "/clickhouse/task_queue/ddl/");
363
        global_context->setDDLWorker(std::make_shared<DDLWorker>(ddl_zookeeper_path, *global_context, &config(), "distributed_ddl"));
364 365
    }

366 367 368 369
    std::unique_ptr<DNSCacheUpdater> dns_cache_updater;
    if (config().has("disable_internal_dns_cache") && config().getInt("disable_internal_dns_cache"))
    {
        /// Disable DNS caching at all
370
        DNSResolver::instance().setDisableCacheFlag();
371 372 373 374 375 376
    }
    else
    {
        /// Initialize a watcher updating DNS cache in case of network errors
        dns_cache_updater = std::make_unique<DNSCacheUpdater>(*global_context);
    }
377

378
#if defined(__linux__)
A
Alexey Milovidov 已提交
379
    if (!TaskStatsInfoGetter::checkPermissions())
380
    {
A
Alexey Milovidov 已提交
381
        LOG_INFO(log, "It looks like the process has no CAP_NET_ADMIN capability, 'taskstats' performance statistics will be disabled."
A
Alexey Milovidov 已提交
382
                      " It could happen due to incorrect ClickHouse package installation."
A
Alexey Milovidov 已提交
383 384 385
                      " You could resolve the problem manually with 'sudo setcap cap_net_admin=+ep /usr/bin/clickhouse'."
                      " Note that it will not work on 'nosuid' mounted filesystems."
                      " It also doesn't work if you run clickhouse-server inside network namespace as it happens in some containers.");
386
    }
387 388 389
#else
    LOG_INFO(log, "TaskStats is not implemented for this OS. IO accounting will be disabled.");
#endif
390

391
    {
392
        Poco::Timespan keep_alive_timeout(config().getUInt("keep_alive_timeout", 10), 0);
393

394
        Poco::ThreadPool server_pool(3, config().getUInt("max_connections", 1024));
395
        Poco::Net::HTTPServerParams::Ptr http_params = new Poco::Net::HTTPServerParams;
396
        http_params->setTimeout(settings.http_receive_timeout);
397 398 399 400
        http_params->setKeepAliveTimeout(keep_alive_timeout);

        std::vector<std::unique_ptr<Poco::Net::TCPServer>> servers;

401
        std::vector<std::string> listen_hosts = DB::getMultipleValuesFromConfig(config(), "", "listen_host");
402

403
        bool listen_try = config().getBool("listen_try", false);
404 405 406 407
        if (listen_hosts.empty())
        {
            listen_hosts.emplace_back("::1");
            listen_hosts.emplace_back("127.0.0.1");
P
proller 已提交
408
            listen_try = true;
409 410
        }

411 412
        auto make_socket_address = [&](const std::string & host, UInt16 port)
        {
413 414 415 416 417 418 419
            Poco::Net::SocketAddress socket_address;
            try
            {
                socket_address = Poco::Net::SocketAddress(host, port);
            }
            catch (const Poco::Net::DNSException & e)
            {
P
proller 已提交
420 421
                const auto code = e.code();
                if (code == EAI_FAMILY
P
proller 已提交
422
#if defined(EAI_ADDRFAMILY)
P
proller 已提交
423
                    || code == EAI_ADDRFAMILY
P
proller 已提交
424
#endif
425 426 427
                    )
                {
                    LOG_ERROR(log,
P
proller 已提交
428
                        "Cannot resolve listen_host (" << host << "), error " << e.code() << ": " << e.message() << ". "
A
alexey-milovidov 已提交
429 430 431
                        "If it is an IPv6 address and your host has disabled IPv6, then consider to "
                        "specify IPv4 address to listen in <listen_host> element of configuration "
                        "file. Example: <listen_host>0.0.0.0</listen_host>");
432 433 434 435 436 437 438
                }

                throw;
            }
            return socket_address;
        };

439 440 441 442 443 444 445
        auto socket_bind_listen = [&](auto & socket, const std::string & host, UInt16 port, bool secure = 0)
        {
               auto address = make_socket_address(host, port);
#if !POCO_CLICKHOUSE_PATCH || POCO_VERSION <= 0x02000000 // TODO: fill correct version
               if (secure)
                   /// Bug in old poco, listen() after bind() with reusePort param will fail because have no implementation in SecureServerSocketImpl
                   /// https://github.com/pocoproject/poco/pull/2257
P
proller 已提交
446
                   socket.bind(address, /* reuseAddress = */ true);
447 448
               else
#endif
P
proller 已提交
449 450 451
#if POCO_VERSION < 0x01080000
                   socket.bind(address, /* reuseAddress = */ true);
#else
452
                   socket.bind(address, /* reuseAddress = */ true, /* reusePort = */ config().getBool("listen_reuse_port", false));
P
proller 已提交
453
#endif
454 455 456 457 458 459

               socket.listen(/* backlog = */ config().getUInt("listen_backlog", 64));

               return address;
        };

460 461 462
        for (const auto & listen_host : listen_hosts)
        {
            /// For testing purposes, user may omit tcp_port or http_port or https_port in configuration file.
463
            try
464
            {
465 466 467
                /// HTTP
                if (config().has("http_port"))
                {
468 469 470 471
                    Poco::Net::ServerSocket socket;
                    auto address = socket_bind_listen(socket, listen_host, config().getInt("http_port"));
                    socket.setReceiveTimeout(settings.http_receive_timeout);
                    socket.setSendTimeout(settings.http_send_timeout);
472
                    servers.emplace_back(new Poco::Net::HTTPServer(
V
Vadim Skipin 已提交
473 474
                        new HTTPHandlerFactory(*this, "HTTPHandler-factory"),
                        server_pool,
475
                        socket,
V
Vadim Skipin 已提交
476
                        http_params));
477

478
                    LOG_INFO(log, "Listening http://" + address.toString());
479
                }
480

481 482 483
                /// HTTPS
                if (config().has("https_port"))
                {
484
#if USE_POCO_NETSSL
485 486 487 488
                    Poco::Net::SecureServerSocket socket;
                    auto address = socket_bind_listen(socket, listen_host, config().getInt("https_port"), /* secure = */ true);
                    socket.setReceiveTimeout(settings.http_receive_timeout);
                    socket.setSendTimeout(settings.http_send_timeout);
489
                    servers.emplace_back(new Poco::Net::HTTPServer(
P
proller 已提交
490
                        new HTTPHandlerFactory(*this, "HTTPSHandler-factory"),
V
Vadim Skipin 已提交
491
                        server_pool,
492
                        socket,
V
Vadim Skipin 已提交
493
                        http_params));
494

495
                    LOG_INFO(log, "Listening https://" + address.toString());
V
Vadim Skipin 已提交
496
#else
A
Alexey Milovidov 已提交
497
                    throw Exception{"HTTPS protocol is disabled because Poco library was built without NetSSL support.",
498
                        ErrorCodes::SUPPORT_IS_DISABLED};
V
Vadim Skipin 已提交
499
#endif
500
                }
501

502 503 504
                /// TCP
                if (config().has("tcp_port"))
                {
505 506 507 508
                    Poco::Net::ServerSocket socket;
                    auto address = socket_bind_listen(socket, listen_host, config().getInt("tcp_port"));
                    socket.setReceiveTimeout(settings.receive_timeout);
                    socket.setSendTimeout(settings.send_timeout);
V
Vadim Skipin 已提交
509 510 511
                    servers.emplace_back(new Poco::Net::TCPServer(
                        new TCPHandlerFactory(*this),
                        server_pool,
512
                        socket,
V
Vadim Skipin 已提交
513
                        new Poco::Net::TCPServerParams));
514

515
                    LOG_INFO(log, "Listening tcp: " + address.toString());
516
                }
517

A
alexey-milovidov 已提交
518
                /// TCP with SSL
519
                if (config().has("tcp_port_secure"))
P
proller 已提交
520
                {
521
#if USE_POCO_NETSSL
522 523 524 525
                    Poco::Net::SecureServerSocket socket;
                    auto address = socket_bind_listen(socket, listen_host, config().getInt("tcp_port_secure"), /* secure = */ true);
                    socket.setReceiveTimeout(settings.receive_timeout);
                    socket.setSendTimeout(settings.send_timeout);
P
proller 已提交
526
                    servers.emplace_back(new Poco::Net::TCPServer(
P
proller 已提交
527
                        new TCPHandlerFactory(*this, /* secure= */ true ),
P
proller 已提交
528
                                                                  server_pool,
529
                                                                  socket,
P
proller 已提交
530
                                                                  new Poco::Net::TCPServerParams));
531
                    LOG_INFO(log, "Listening tcp_secure: " + address.toString());
P
proller 已提交
532
#else
A
Alexey Milovidov 已提交
533
                    throw Exception{"SSL support for TCP protocol is disabled because Poco library was built without NetSSL support.",
P
proller 已提交
534 535 536 537
                        ErrorCodes::SUPPORT_IS_DISABLED};
#endif
                }

538 539 540
                /// At least one of TCP and HTTP servers must be created.
                if (servers.empty())
                    throw Exception("No 'tcp_port' and 'http_port' is specified in configuration file.", ErrorCodes::NO_ELEMENTS_IN_CONFIG);
541

542 543 544
                /// Interserver IO HTTP
                if (config().has("interserver_http_port"))
                {
545 546 547 548
                    Poco::Net::ServerSocket socket;
                    auto address = socket_bind_listen(socket, listen_host, config().getInt("interserver_http_port"));
                    socket.setReceiveTimeout(settings.http_receive_timeout);
                    socket.setSendTimeout(settings.http_send_timeout);
549
                    servers.emplace_back(new Poco::Net::HTTPServer(
V
Vadim Skipin 已提交
550
                        new InterserverIOHTTPHandlerFactory(*this, "InterserverIOHTTPHandler-factory"),
551
                        server_pool,
552
                        socket,
553 554
                        http_params));

555
                    LOG_INFO(log, "Listening interserver http: " + address.toString());
556
                }
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576

                if (config().has("interserver_https_port"))
                {
#if USE_POCO_NETSSL
                    Poco::Net::SecureServerSocket socket;
                    auto address = socket_bind_listen(socket, listen_host, config().getInt("interserver_https_port"), /* secure = */ true);
                    socket.setReceiveTimeout(settings.http_receive_timeout);
                    socket.setSendTimeout(settings.http_send_timeout);
                    servers.emplace_back(new Poco::Net::HTTPServer(
                        new InterserverIOHTTPHandlerFactory(*this, "InterserverIOHTTPHandler-factory"),
                        server_pool,
                        socket,
                        http_params));

                    LOG_INFO(log, "Listening interserver https: " + address.toString());
#else
                    throw Exception{"SSL support for TCP protocol is disabled because Poco library was built without NetSSL support.",
                            ErrorCodes::SUPPORT_IS_DISABLED};
#endif
                }
577 578
            }
            catch (const Poco::Net::NetException & e)
579
            {
580
                if (listen_try)
P
proller 已提交
581
                    LOG_ERROR(log, "Listen [" << listen_host << "]: " << e.code() << ": " << e.what() << ": " << e.message()
A
alexey-milovidov 已提交
582 583 584 585
                        << "  If it is an IPv6 or IPv4 address and your host has disabled IPv6 or IPv4, then consider to "
                        "specify not disabled IPv4 or IPv6 address to listen in <listen_host> element of configuration "
                        "file. Example for disabled IPv6: <listen_host>0.0.0.0</listen_host> ."
                        " Example for disabled IPv4: <listen_host>::</listen_host>");
586 587
                else
                    throw;
588 589 590
            }
        }

591 592 593
        if (servers.empty())
             throw Exception("No servers started (add valid listen_host and 'tcp_port' or 'http_port' to configuration file.)", ErrorCodes::NO_ELEMENTS_IN_CONFIG);

594 595 596
        for (auto & server : servers)
            server->start();

597 598 599
        main_config_reloader->start();
        users_config_reloader->start();

600 601
        {
            std::stringstream message;
602
            message << "Available RAM = " << formatReadableSizeWithBinarySuffix(getMemoryAmount()) << ";"
603 604
                << " physical cores = " << getNumberOfPhysicalCPUCores() << ";"
                // on ARM processors it can show only enabled at current moment cores
605
                << " threads = " <<  std::thread::hardware_concurrency() << ".";
606 607 608
            LOG_INFO(log, message.str());
        }

609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
        LOG_INFO(log, "Ready for connections.");

        SCOPE_EXIT({
            LOG_DEBUG(log, "Received termination signal.");
            LOG_DEBUG(log, "Waiting for current connections to close.");

            is_cancelled = true;

            int current_connections = 0;
            for (auto & server : servers)
            {
                server->stop();
                current_connections += server->currentConnections();
            }

            LOG_DEBUG(log,
                "Closed all listening sockets."
626
                    << (current_connections ? " Waiting for " + toString(current_connections) + " outstanding connections." : ""));
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645

            if (current_connections)
            {
                const int sleep_max_ms = 1000 * config().getInt("shutdown_wait_unfinished", 5);
                const int sleep_one_ms = 100;
                int sleep_current_ms = 0;
                while (sleep_current_ms < sleep_max_ms)
                {
                    current_connections = 0;
                    for (auto & server : servers)
                        current_connections += server->currentConnections();
                    if (!current_connections)
                        break;
                    sleep_current_ms += sleep_one_ms;
                    std::this_thread::sleep_for(std::chrono::milliseconds(sleep_one_ms));
                }
            }

            LOG_DEBUG(
646
                log, "Closed connections." << (current_connections ? " But " + toString(current_connections) + " remains."
647
                    " Tip: To increase wait time add to config: <shutdown_wait_unfinished>60</shutdown_wait_unfinished>" : ""));
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669

            main_config_reloader.reset();
            users_config_reloader.reset();
        });

        /// try to load dictionaries immediately, throw on error and die
        try
        {
            if (!config().getBool("dictionaries_lazy_load", true))
            {
                global_context->tryCreateEmbeddedDictionaries();
                global_context->tryCreateExternalDictionaries();
            }
        }
        catch (...)
        {
            LOG_ERROR(log, "Caught exception while loading dictionaries.");
            throw;
        }

        /// This object will periodically calculate some metrics.
        AsynchronousMetrics async_metrics(*global_context);
670
        attachSystemTablesAsync(*global_context->getDatabase("system"), async_metrics);
671 672 673 674

        std::vector<std::unique_ptr<MetricsTransmitter>> metrics_transmitters;
        for (const auto & graphite_key : DB::getMultipleKeysFromConfig(config(), "", "graphite"))
        {
675 676
            metrics_transmitters.emplace_back(std::make_unique<MetricsTransmitter>(
                *global_context, async_metrics, graphite_key));
677 678
        }

679 680
        SessionCleaner session_cleaner(*global_context);

681 682 683 684
        waitForTerminationRequest();
    }

    return Application::EXIT_OK;
685 686
}
}
687

A
Alexey Milovidov 已提交
688 689 690 691 692 693 694 695 696 697 698 699 700 701
int mainEntryClickHouseServer(int argc, char ** argv)
{
    DB::Server app;
    try
    {
        return app.run(argc, argv);
    }
    catch (...)
    {
        std::cerr << DB::getCurrentExceptionMessage(true) << "\n";
        auto code = DB::getCurrentExceptionCode();
        return code ? code : 1;
    }
}