- The Beginner ClickHouse Developer Instruction
- Creating a Repository on GitHub
- Cloning a Repository to Your Development Machine
- Working with Submodules
- Build System
- Optional External Libraries
- C++ Compiler
- The Building Process
- Running the Built Executable of ClickHouse
- IDE (Integrated Development Environment)
- Writing Code
- Test Data
- Creating Pull Request
- Как собрать ClickHouse на Mac OS X
- Установка Homebrew
- Установка Xcode и инструментов командной строки
- Установка компиляторов, инструментов и библиотек
- Просмотр исходников ClickHouse
- Сборка ClickHouse
- Предупреждения
- Установка
- Системные требования
- Доступные варианты установки
- Из DEB пакетов
- Пакеты
- Из RPM пакетов
- Из Tgz архивов
- Из Docker образа
- Из единого бинарного файла
- Из исполняемых файлов для нестандартных окружений
- Из исходного кода
- Запуск
The Beginner ClickHouse Developer Instruction
Building of ClickHouse is supported on Linux, FreeBSD and Mac OS X.
If you use Windows, you need to create a virtual machine with Ubuntu. To start working with a virtual machine please install VirtualBox. You can download Ubuntu from the website: https://www.ubuntu.com/#download. Please create a virtual machine from the downloaded image (you should reserve at least 4GB of RAM for it). To run a command-line terminal in Ubuntu, please locate a program containing the word “terminal” in its name (gnome-terminal, konsole etc.) or just press Ctrl+Alt+T.
ClickHouse cannot work or build on a 32-bit system. You should acquire access to a 64-bit system and you can continue reading.
Creating a Repository on GitHub
To start working with ClickHouse repository you will need a GitHub account.
You probably already have one, but if you do not, please register at https://github.com. In case you do not have SSH keys, you should generate them and then upload them on GitHub. It is required for sending over your patches. It is also possible to use the same SSH keys that you use with any other SSH servers — probably you already have those.
Create a fork of ClickHouse repository. To do that please click on the “fork” button in the upper right corner at https://github.com/ClickHouse/ClickHouse. It will fork your own copy of ClickHouse/ClickHouse to your account.
The development process consists of first committing the intended changes into your fork of ClickHouse and then creating a “pull request” for these changes to be accepted into the main repository (ClickHouse/ClickHouse).
To work with git repositories, please install git .
To do that in Ubuntu you would run in the command line terminal:
Cloning a Repository to Your Development Machine
Next, you need to download the source files onto your working machine. This is called “to clone a repository” because it creates a local copy of the repository on your working machine.
In the command line terminal run:
Note: please, substitute your_github_username with what is appropriate!
This command will create a directory ClickHouse containing the working copy of the project.
It is important that the path to the working directory contains no whitespaces as it may lead to problems with running the build system.
Please note that ClickHouse repository uses submodules . That is what the references to additional repositories are called (i.e. external libraries on which the project depends). It means that when cloning the repository you need to specify the —recursive flag as in the example above. If the repository has been cloned without submodules, to download them you need to run the following:
You can check the status with the command: git submodule status .
If you get the following error message:
It generally means that the SSH keys for connecting to GitHub are missing. These keys are normally located in
/.ssh . For SSH keys to be accepted you need to upload them in the settings section of GitHub UI.
You can also clone the repository via https protocol:
This, however, will not let you send your changes to the server. You can still use it temporarily and add the SSH keys later replacing the remote address of the repository with git remote command.
You can also add original ClickHouse repo’s address to your local repository to pull updates from there:
After successfully running this command you will be able to pull updates from the main ClickHouse repo by running git pull upstream master .
Working with Submodules
Working with submodules in git could be painful. Next commands will help to manage it:
The next commands would help you to reset all submodules to the initial state (!WARNING! — any changes inside will be deleted):
Build System
ClickHouse uses CMake and Ninja for building.
CMake — a meta-build system that can generate Ninja files (build tasks).
Ninja — a smaller build system with a focus on the speed used to execute those cmake generated tasks.
To install on Ubuntu, Debian or Mint run sudo apt install cmake ninja-build .
On CentOS, RedHat run sudo yum install cmake ninja-build .
If you use Arch or Gentoo, you probably know it yourself how to install CMake.
For installing CMake and Ninja on Mac OS X first install Homebrew and then install everything else via brew:
Next, check the version of CMake: cmake —version . If it is below 3.12, you should install a newer version from the website: https://cmake.org/download/.
Optional External Libraries
ClickHouse uses several external libraries for building. All of them do not need to be installed separately as they are built together with ClickHouse from the sources located in the submodules. You can check the list in contrib .
C++ Compiler
Compilers Clang starting from version 11 is supported for building ClickHouse.
Clang should be used instead of gcc. Though, our continuous integration (CI) platform runs checks for about a dozen of build combinations.
On Ubuntu/Debian you can use the automatic installation script (check official webpage)
Mac OS X build is also supported. Just run brew install llvm
The Building Process
Now that you are ready to build ClickHouse we recommend you to create a separate directory build inside ClickHouse that will contain all of the build artefacts:
You can have several different directories (build_release, build_debug, etc.) for different types of build.
While inside the build directory, configure your build by running CMake. Before the first run, you need to define environment variables that specify compiler.
The CC variable specifies the compiler for C (short for C Compiler), and CXX variable instructs which C++ compiler is to be used for building.
For a faster build, you can resort to the debug build type — a build with no optimizations. For that supply the following parameter -D CMAKE_BUILD_TYPE=Debug :
You can change the type of build by running this command in the build directory.
Run ninja to build:
Only the required binaries are going to be built in this example.
If you require to build all the binaries (utilities and tests), you should run ninja with no parameters:
Full build requires about 30GB of free disk space or 15GB to build the main binaries.
When a large amount of RAM is available on build machine you should limit the number of build tasks run in parallel with -j param:
On machines with 4GB of RAM, it is recommended to specify 1, for 8GB of RAM -j 2 is recommended.
If you get the message: ninja: error: loading ‘build.ninja’: No such file or directory , it means that generating a build configuration has failed and you need to inspect the message above.
Upon the successful start of the building process, you’ll see the build progress — the number of processed tasks and the total number of tasks.
While building messages about protobuf files in libhdfs2 library like libprotobuf WARNING may show up. They affect nothing and are safe to be ignored.
Upon successful build you get an executable file ClickHouse/ /programs/clickhouse :
Running the Built Executable of ClickHouse
To run the server under the current user you need to navigate to ClickHouse/programs/server/ (located outside of build ) and run:
In this case, ClickHouse will use config files located in the current directory. You can run clickhouse server from any directory specifying the path to a config file as a command-line parameter —config-file .
To connect to ClickHouse with clickhouse-client in another terminal navigate to ClickHouse/build/programs/ and run ./clickhouse client .
If you get Connection refused message on Mac OS X or FreeBSD, try specifying host address 127.0.0.1:
You can replace the production version of ClickHouse binary installed in your system with your custom-built ClickHouse binary. To do that install ClickHouse on your machine following the instructions from the official website. Next, run the following:
Note that clickhouse-client , clickhouse-server and others are symlinks to the commonly shared clickhouse binary.
You can also run your custom-built ClickHouse binary with the config file from the ClickHouse package installed on your system:
IDE (Integrated Development Environment)
If you do not know which IDE to use, we recommend that you use CLion. CLion is commercial software, but it offers 30 days free trial period. It is also free of charge for students. CLion can be used both on Linux and on Mac OS X.
KDevelop and QTCreator are other great alternatives of an IDE for developing ClickHouse. KDevelop comes in as a very handy IDE although unstable. If KDevelop crashes after a while upon opening project, you should click “Stop All” button as soon as it has opened the list of project’s files. After doing so KDevelop should be fine to work with.
As simple code editors, you can use Sublime Text or Visual Studio Code, or Kate (all of which are available on Linux).
Just in case, it is worth mentioning that CLion creates build path on its own, it also on its own selects debug for build type, for configuration it uses a version of CMake that is defined in CLion and not the one installed by you, and finally, CLion will use make to run build tasks instead of ninja . This is normal behaviour, just keep that in mind to avoid confusion.
Writing Code
The description of ClickHouse architecture can be found here: https://clickhouse.com/docs/en/development/architecture/
Test Data
Developing ClickHouse often requires loading realistic datasets. It is particularly important for performance testing. We have a specially prepared set of anonymized data from Yandex.Metrica. It requires additionally some 3GB of free disk space. Note that this data is not required to accomplish most of the development tasks.
Creating Pull Request
Navigate to your fork repository in GitHub’s UI. If you have been developing in a branch, you need to select that branch. There will be a “Pull request” button located on the screen. In essence, this means “create a request for accepting my changes into the main repository”.
A pull request can be created even if the work is not completed yet. In this case please put the word “WIP” (work in progress) at the beginning of the title, it can be changed later. This is useful for cooperative reviewing and discussion of changes as well as for running all of the available tests. It is important that you provide a brief description of your changes, it will later be used for generating release changelogs.
Testing will commence as soon as Yandex employees label your PR with a tag “can be tested”. The results of some first checks (e.g. code style) will come in within several minutes. Build check results will arrive within half an hour. And the main set of tests will report itself within an hour.
The system will prepare ClickHouse binary builds for your pull request individually. To retrieve these builds click the “Details” link next to “ClickHouse build check” entry in the list of checks. There you will find direct links to the built .deb packages of ClickHouse which you can deploy even on your production servers (if you have no fear).
Most probably some of the builds will fail at first times. This is due to the fact that we check builds both with gcc as well as with clang, with almost all of existing warnings (always with the -Werror flag) enabled for clang. On that same page, you can find all of the build logs so that you do not have to build ClickHouse in all of the possible ways.
Источник
Как собрать ClickHouse на Mac OS X
Сборка должна запускаться с x86_64 (Intel) на macOS версии 10.15 (Catalina) и выше в последней версии компилятора Xcode’s native AppleClang, Homebrew’s vanilla Clang или в GCC-компиляторах.
Установка Homebrew
Установка Xcode и инструментов командной строки
Установите из App Store последнюю версию Xcode.
Запустите ее, чтобы принять лицензионное соглашение. Необходимые компоненты установятся автоматически.
Затем убедитесь, что в системе выбрана последняя версия инструментов командной строки:
bash $ sudo rm -rf /Library/Developer/CommandLineTools $ sudo xcode-select —install
Установка компиляторов, инструментов и библиотек
bash $ brew update $ brew install cmake ninja libtool gettext llvm gcc
Просмотр исходников ClickHouse
bash $ git clone —recursive [email protected]:ClickHouse/ClickHouse.git # or https://github.com/ClickHouse/ClickHouse.git
Сборка ClickHouse
Чтобы запустить сборку в компиляторе Xcode’s native AppleClang:
bash $ cd ClickHouse $ rm -rf build $ mkdir build $ cd build $ cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DENABLE_JEMALLOC=OFF .. $ cmake —build . —config RelWithDebInfo $ cd ..
Чтобы запустить сборку в компиляторе Homebrew’s vanilla Clang:
bash $ cd ClickHouse $ rm -rf build $ mkdir build $ cd build $ cmake -DCMAKE_C_COMPILER=$(brew —prefix llvm)/bin/clang -DCMAKE_CXX_COMPILER==$(brew —prefix llvm)/bin/clang++ -DCMAKE_BUILD_TYPE=RelWithDebInfo -DENABLE_JEMALLOC=OFF .. $ cmake -DCMAKE_C_COMPILER=$(brew —prefix llvm)/bin/clang -DCMAKE_CXX_COMPILER=$(brew —prefix llvm)/bin/clang++ -DCMAKE_BUILD_TYPE=RelWithDebInfo -DENABLE_JEMALLOC=OFF .. $ cmake —build . —config RelWithDebInfo $ cd ..
Чтобы собрать с помощью компилятора Homebrew’s vanilla GCC:
bash $ cd ClickHouse $ rm -rf build $ mkdir build $ cd build $ cmake -DCMAKE_C_COMPILER=$(brew —prefix gcc)/bin/gcc-11 -DCMAKE_CXX_COMPILER=$(brew —prefix gcc)/bin/g++-11 -DCMAKE_BUILD_TYPE=RelWithDebInfo -DENABLE_JEMALLOC=OFF .. $ cmake —build . —config RelWithDebInfo $ cd ..
Предупреждения
Если будете запускать clickhouse-server , убедитесь, что увеличили системную переменную maxfiles .
Вам понадобится команда sudo .
- Создайте файл /Library/LaunchDaemons/limit.maxfiles.plist и поместите в него следующее:
bash $ sudo chown root:wheel /Library/LaunchDaemons/limit.maxfiles.plist
Чтобы проверить, как это работает, выполните команду ulimit -n .
Источник
Установка
Системные требования
ClickHouse может работать на любой операционной системе Linux, FreeBSD или Mac OS X с архитектурой процессора x86_64, AArch64 или PowerPC64LE.
Предварительно собранные пакеты компилируются для x86_64 и используют набор инструкций SSE 4.2, поэтому, если не указано иное, его поддержка в используемом процессоре, становится дополнительным требованием к системе. Вот команда, чтобы проверить, поддерживает ли текущий процессор SSE 4.2:
Чтобы запустить ClickHouse на процессорах, которые не поддерживают SSE 4.2, либо имеют архитектуру AArch64 или PowerPC64LE, необходимо самостоятельно собрать ClickHouse из исходного кода с соответствующими настройками конфигурации.
Доступные варианты установки
Из DEB пакетов
Яндекс рекомендует использовать официальные скомпилированные deb пакеты для Debian или Ubuntu. Для установки пакетов выполните:
Также эти пакеты можно скачать и установить вручную отсюда: https://repo.clickhouse.com/deb/stable/main/.
Если вы хотите использовать наиболее свежую версию, замените stable на testing (рекомендуется для тестовых окружений).
Также вы можете вручную скачать и установить пакеты из репозитория.
Пакеты
- clickhouse-common-static — Устанавливает исполняемые файлы ClickHouse.
- clickhouse-server — Создает символические ссылки для clickhouse-server и устанавливает конфигурационные файлы.
- clickhouse-client — Создает символические ссылки для clickhouse-client и других клиентских инструментов и устанавливает конфигурационные файлы clickhouse-client .
- clickhouse-common-static-dbg — Устанавливает исполняемые файлы ClickHouse собранные с отладочной информацией.
Если вам нужно установить ClickHouse определенной версии, вы должны установить все пакеты одной версии:
sudo apt-get install clickhouse-server=21.8.5.7 clickhouse-client=21.8.5.7 clickhouse-common-static=21.8.5.7
Из RPM пакетов
Команда ClickHouse в Яндексе рекомендует использовать официальные предкомпилированные rpm пакеты для CentOS, RedHat и всех остальных дистрибутивов Linux, основанных на rpm.
Сначала нужно подключить официальный репозиторий:
Для использования наиболее свежих версий нужно заменить stable на testing (рекомендуется для тестовых окружений). Также иногда доступен prestable .
Для, собственно, установки пакетов необходимо выполнить следующие команды:
Также есть возможность установить пакеты вручную, скачав отсюда: https://repo.clickhouse.com/rpm/stable/x86_64.
Из Tgz архивов
Команда ClickHouse в Яндексе рекомендует использовать предкомпилированные бинарники из tgz архивов для всех дистрибутивов, где невозможна установка deb и rpm пакетов.
Интересующую версию архивов можно скачать вручную с помощью curl или wget из репозитория https://repo.clickhouse.com/tgz/.
После этого архивы нужно распаковать и воспользоваться скриптами установки. Пример установки самой свежей версии:
Для production окружений рекомендуется использовать последнюю stable -версию. Её номер также можно найти на github с на вкладке https://github.com/ClickHouse/ClickHouse/tags c постфиксом -stable .
Из Docker образа
Для запуска ClickHouse в Docker нужно следовать инструкции на Docker Hub. Внутри образов используются официальные deb пакеты.
Из единого бинарного файла
Для установки ClickHouse под Linux можно использовать единый переносимый бинарный файл из последнего коммита ветки master : [https://builds.clickhouse.com/master/amd64/clickhouse].
Из исполняемых файлов для нестандартных окружений
Для других операционных систем и архитектуры AArch64 сборки ClickHouse предоставляются в виде кросс-компилированного бинарного файла из последнего коммита ветки master (с задержкой в несколько часов).
- macOS — curl -O ‘https://builds.clickhouse.com/master/macos/clickhouse’ && chmod a+x ./clickhouse
- FreeBSD — curl -O ‘https://builds.clickhouse.com/master/freebsd/clickhouse’ && chmod a+x ./clickhouse
- AArch64 — curl -O ‘https://builds.clickhouse.com/master/aarch64/clickhouse’ && chmod a+x ./clickhouse
После скачивания можно воспользоваться clickhouse client для подключения к серверу или clickhouse local для обработки локальных данных.
Чтобы установить ClickHouse в рамках всей системы (с необходимыми конфигурационными файлами, настройками пользователей и т.д.), выполните sudo ./clickhouse install . Затем выполните команды clickhouse start (чтобы запустить сервер) и clickhouse-client (чтобы подключиться к нему).
Данные сборки не рекомендуются для использования в рабочей среде, так как они недостаточно тщательно протестированы. Также в них присутствуют не все возможности ClickHouse.
Из исходного кода
Для компиляции ClickHouse вручную, используйте инструкцию для Linux или Mac OS X.
Можно скомпилировать пакеты и установить их, либо использовать программы без установки пакетов. Также при ручой сборке можно отключить необходимость поддержки набора инструкций SSE 4.2 или собрать под процессоры архитектуры AArch64.
Для работы собранного вручную сервера необходимо создать директории для данных и метаданных, а также сделать их chown для желаемого пользователя. Пути к этим директориям могут быть изменены в конфигурационном файле сервера (src/programs/server/config.xml), по умолчанию используются следующие:
На Gentoo для установки ClickHouse из исходного кода можно использовать просто emerge clickhouse .
Запуск
Для запуска сервера в качестве демона, выполните:
Смотрите логи в директории /var/log/clickhouse-server/ .
Если сервер не стартует, проверьте корректность конфигурации в файле /etc/clickhouse-server/config.xml
Также можно запустить сервер вручную из консоли:
При этом, лог будет выводиться в консоль, что удобно для разработки.
Если конфигурационный файл лежит в текущей директории, то указывать параметр —config-file не требуется, по умолчанию будет использован файл ./config.xml .
После запуска сервера, соединиться с ним можно с помощью клиента командной строки:
По умолчанию он соединяется с localhost:9000, от имени пользователя default без пароля. Также клиент может быть использован для соединения с удалённым сервером с помощью аргумента —host .
Терминал должен использовать кодировку UTF-8.
Более подробная информация о клиенте располагается в разделе «Клиент командной строки».
Пример проверки работоспособности системы:
Поздравляем, система работает!
Для дальнейших экспериментов можно попробовать загрузить один из тестовых наборов данных или пройти пошаговое руководство для начинающих.
Источник