Prometheus grafana windows monitoring

Monitoring a Linux/windows server using Prometheus

Why monitor?

Monitoring of a system is key to its smooth functioning. Going to the battlefield (production) without having proper monitoring setup done is like making your platform vulnerable, hence to obtain full control it becomes a must; as the popular say goes “Failing to plan, is planning to fail”. In this article, I’m going to show how you can monitor a system using Prometheus, node_exporter and the Grafana UI.

Difference between Pull and Push based monitoring architecture

Simply put, in push-based architecture each target node periodically sends metrics to a central collector. Examples of push architectures include sFlow, Ganglia, Graphite, collectd and StatsD. Whereas, in pull-based architecture the central collector periodically requests each of the target node to send metrics to it. Examples of pull architectures include SNMP, JMX, WMI, libvirt, Prometheus,etc.

Prometheus is primarily a pull-based system, however, it can act as a push-based system by using pushgateway

Installation and setup

At Kartbites, our HTTP server runs on Debian and the primary system for monitoring runs on Arch Linux, Hence I’ll assume target machine runs on Debian (or Windows as a bonus) and monitor system runs on Arch Linux (or Ubuntu).

We will install Prometheus which will pull metrics from the target server, node_exporter which will make the target system’s metrics available at an HTTP port for prometheus to pull; and Grafana is the UI for an amazing visualization.

1. Prometheus

The installation procedure is pretty simple, I’m going to show how to install on two platforms, Arch Linux and Ubuntu. For others, you can definitely follow the official docs

Arch Linux

Arch has a package for Prometheus, which is great because then you don’t need to explicitly write unit file for the service.

  1. sudo pacman -S prometheus
  2. sudo systemctl enable prometheus (to create systemlink to the unit file in the systemd directory to that the systemd can always start it at boot)
  3. sudo systemctl start prometheus to start the service right away.

Ubuntu

  1. Download wget https://github.com/prometheus/prometheus/releases/download/v2.8.0/prometheus-2.8.0.linux-amd64.tar.gz or if you want the latest version, get the download link of the latest version by right-clicking on the link and copy link address then pass it to wget . See:-

2. tar -xzf prometheus-2.8.0.linux-amd64.tar.gz

4. cd prometheus-2.8.0.linux-amd64

5. Move the prometheus binary executable to PATH mv prometheus /usr/local/bin/

6. Move promtheus configuration file i.e promethues.yml to /etc/. i.e mv prometheus.yml /etc/

Now set up the configuration of prometheus server-

Configure the Prometheus config file ( prometheus-2.8.0.linux-amd64/prometheus.yml ) with simple configurations:-

Now write a unit file to run prometheus as a systemd service (There are many benefits of running a process as systemd service instead, like running in the background, auto-restart, logging using journalctl,etc) . For more info on systemd and unit files see here.

Create the unit file

sudo nano /etc/systemd/system/prometheus.service

Add the following contents:-

Now follow these steps to start and enable the service so that it can keep running in the background and would try to restart automatically in case of any failure.

  1. sudo systemctl daemon-reload
  2. sudo systemctl start prometheus
  3. sudo systemctl enable prometheus

Now if you wish to check whether it is not or not execute systemctl status prometheus

Alternatively, you can use apt to install Prometheus as well.

Now you can visit :9090 on the browser to see Prometheus running. Kudos you’ve successfully set up Prometheus on your monitoring server. (make sure port 9090 is open for HTTP requests)

2. node_exporter

The Prometheus Node Exporter exposes a wide variety of hardware- and kernel-related data, which prometheus can scrape metrics from. Typically node_exporter is installed on the target machine which you want to monitor and prometheus is installed on a server which is primarily used as the master to monitor the target servers. (the load can be horizontally distributed as well)

Читайте также:  Windows smtp сервер для gmail

Here I will show you how you can install node_exporter on Debian and Windows server. Prometheus will keep pulling metrics from them and hence monitor.

Debian

The official docs will show to use the tarball (ref. — follow the above guide for installing Prometheus on ubuntu) but for convenience, we will use the official debian package.

1) sudo apt-get install prometheus-node-exporter

2) This by default enables and starts the node exporter service but you can cross check by systemctl status node_exporter.service

Windows

Unfortunately node_exporter is not well-supported on windows and hence we will use an alternative

2) I would recommend to download and run the .msi as can setup most of the things for you. By default, the service will start running on port 9182 so make sure to open that port to Prometheus server.

Now, make this newly created exporter a target for Prometheus to pull. Add the following lines to Prometheus configuration file i.e prometheus.yml :-

For the above mentioned debian target server:-

Similar, for the above-mentioned windows target server but change the port address to 9182 since wmi-exporter runs on this port by default. These ports are the default values and can be changed according to need by making necessary changes to the configuration file of the exporters.

For the new target to get ready to be configured we need to restart the prometheus service so that it read the updated configuration i.e prometheus.yml . Run sudo systemctl restart prometheus.service . The downside to this restart is that this will cause downtime during the restart process. To get around this downtime follow this neat trick. The idea is to send a hang-up single to the prometheus service which will make it reload the configuration. For that first, we need to know the PID (process ID) of the process. Run ps aux | grep prome*

So now we know that the PID of the prometheus service is 29915 .

Now we need the hang-up signal to it. Run sudo kill -s HUP 29115

This will make Prometheus reload the configuration as evident in the below logs:-

Now visit the Status —> Targets on the Prometheus address in the browser and your target server will appear there. Now you can query for basic metrics and see the corresponding graph on the dashboard. But Grafana makes it cooler. Let’s grab it now.

3. Grafana

Now it’s time to give our our monitoring solution a beautiful UI and for that what can be a better option than Grafana! Let’s dive quickly into installing it.

Debian

1) wget https://dl.grafana.com/oss/release/grafana_6.0.2_amd64.deb

2) sudo dpkg -i grafana_6.0.2_amd64.deb

3) sudo systemctl start grafana-server.service

4) sudo systemctl enable grafana-server.service

Or, you can use the package manager (in this case APT) to install the same. For that, I would recommend you to follow this link

However while installing via dpkg or apt I faced an issue that some of it’s dependencies coulld not be installed. If you are also facing this issue run the following command-

sudo apt —fix-broken install

Arch Linux

On arch, you can use the package manager as well for the installation.

sudo pacman -S grafana

Now that installation is successful, you need to enable and start the grafana systemd service. For that you need to execute the following commands:-

sudo systemctl enable grafana

sudo systemctl start grafana

Now open port 3000 in server’s firewall policy because by default Grafana listens on port 3000. Now hit port 3000 and you can see Grafana running. The default username and password is admin and admin respectively.

Congratulations, your pretty dashboard is now setup correctly!

Now we need to configure Grafana to set prometheus as a data source.

2) Click on Add data source

3) Select prometheus

4) Let the defaults be. Check if the address the alright.

5) Import a pre-built dashboard but clicking on + icon.

Читайте также:  Windows 10 arm mediatek

6) Import 1860 and 405 as Dashboard ID. (personal choice, you can import any)

Мониторинг с помощью Prometheus

Мониторинг приложений и серверов приложений — важная часть DevOps-культуры. Вы наверняка хотите постоянно мониторить состояние приложения и серверов, загрузку центрального процессора, потребление памяти, дисковую утилизацию и т.д. Также вы наверняка хотите получать уведомления, если у сервера заканчивается доступная память или приложение перестает отвечать на запросы, что позволит предотвратить проблемы.

Для мониторинга есть ряд бесплатных и платных инструментов, таких как Amazon CloudWatch, Nagios, New Relic, Prometheus, Zabbix и другие. В этом посте мы рассмотрим Prometheus — инструмент для одновременного мониторинга десятков тысяч служб.

Что такое Prometheus и чем он отличается от других систем мониторинга?

Prometheus — популярный CNCF-проект с открытым исходных кодом, большая часть компонентов которого написана на Golang, а часть — на Ruby. Это означает, что у вас будет всего один бинарный файл, который нужно скачать и запустить вместе с компонентами Prometheus. Prometheus полностью совместим с Docker и доступен на Docker Hub. Для начала давайте рассмотрим основные компоненты Prometheus.

Компоненты Prometheus

Сервер Prometheus

Prometheus имеет центральный компонент, называемый Prometheus Server. Его основная задача — хранить и мониторить определенные объекты. Объектом может стать что угодно: Linux-сервер, сервер Apache, один из процессов, сервер базы данных или любой другой компонент системы, которую вы хотите контролировать. В терминах Prometheus главная служба мониторинга называется сервером Prometheus, а объекты мониторинга — целевыми объектами. Как я сказал ранее, целевым объектом может быть один сервер, или целевые объекты для проверки конечных точек через HTTP, HTTPS, DNS, TCP и ICMP (*Black-Box Exporter), или простая конечная точка HTTP, которую выдает приложение. Через конечную точку HTTP сервер Prometheus проверяет статус приложения.

Каждый элемент целевого объекта, который вы хотите мониторить (статус центрального процессора, память или любой другой элемент), называется метрикой. Таким образом, Prometheus собирает через HTTP метрики целевых объектов, хранит их локально или удаленно и отображает.

Сервер Prometheus считывает целевые объекты с интервалом, который вы определяете на сбор метрик, и хранит их в базе данных временных рядов. Целевые объекты и временной интервал считывания метрик вы задаете в конфигурационном файле prometheus.yml .

Вы запрашиваете у базы данных временных рядов Prometheus информацию о месте хранения метрик, используя язык запросов PromQL. Другими словами, с помощью PromQL вы просите сервер Prometheus показать статус конкретного целевого объекта в данный момент времени и получаете метрики.

Prometheus предоставляет клиентские библиотеки на нескольких языках, которые вы можете использовать для обеспечения работоспособности приложения. Но Prometheus — это не только мониторинг приложений. Вы можете использовать экспортеры (exporters) для мониторинга сторонних систем (таких как сервер Linux, демон MySQL и т.д.). Экспортер — часть программного обеспечения, которое получает существующие метрики от сторонней системы и экспортирует их в формат, понятный серверу Prometheus.

Примерной метрикой с сервера Prometheus может быть текущее использование свободной памяти или файловой системы через Node Exporter на сервере Prometheus.

Важно знать, что Prometheus использует стандартную модель данных с метрикой на основе ключа, которая может не совпадать с моделью сторонней системы Именно поэтому вы используете экспортеры для преобразования метрик. Я не буду вдаваться в подробности каждого синтаксиса показателей Prometheus и того, как они отличаются.

Уровень визуализации с Grafana

Вы можете использовать Grafana в качестве стороннего компонента для визуализации метрик, хранящихся в базе данных временных рядов Prometheus. Вместо того чтобы писать запросы PromQL непосредственно на сервер Prometheus, вы используете доски графического интерфейса Grafana для запроса метрик с сервера Prometheus и визуализации их на панели мониторинга Grafana.

Управление оповещениями с Prometheus Alert Manager

Prometheus имеет компонент управления оповещениями, называемый AlertManager. Он служит для запуска оповещений через Email, Slack или другие клиентские уведомления.

Вы определяете правила оповещения в файле под названием alert.rules . Например, если сервер Prometheus найдет значение метрики, превышающее порог, который вы определили в файле alert.rules , Alert Manager разошлет оповещения. Как Alert Manager работает с Prometheus и как его установить в стеке Prometheus, я расскажу в следующем посте.

Prometheus, Grafana и Node Exporter являются основой системы мониторинга Prometheus. Вам нужен центральный сервер Prometheus, целевой объект и слой визуализации. Давайте посмотрим, как настроить минимальный стек Prometheus для мониторинга простого сервера Ubuntu 16.04 с помощью docker-compose .

Читайте также:  Родительский контроль mac os big sur

Настройка Prometheus в контейнерах Docker

Время настроить Prometheus-стек на сервере с Linux. Вы настроите сервер Prometheus для сбора метрик, Grafana для визуализации и Node Exporter для мониторинга хост-системы на Ubuntu 16.04. Используйте docker-compose для развертывания сервера Prometheus, Grafana и Node Exporter, но сначала разверните автономный сервер Prometheus с помощью файла docker-compose , приведенного ниже:

Мы используем официальный образ prom/prometheus . Он сохраняет данные Prometheus (временные данные) в именованный volume и получает файл YAML конфигурации Prometheus из файловой системы хоста, который мы определили в секции command файла compose. Флаг —storage.tsdb.retention=200h важен, так как он чистит TSDB каждые 15 дней, что экономит дисковое пространство. Вы предоставляете порты сервиса, чтобы иметь возможность получения доступа к портам через Интернет.

Compose-файл будет разворачивать сервер Prometheus без Exporter или приложения. С автономным сервером Prometheus, запущенным внутри docker-контейнера, вы можете мониторить сам сервер Prometheus, поскольку он считывает данные, определенные в файле prometheus.yml . Например, можно увидеть, сколько оповещений дали сбой с тех пор, как сервер Prometheus запущен и работает с другими типами метрик. Теперь добавим службу Node Exporter в указанный выше compose-файл.

Добавление Node Exporter

Следующее, что нужно сделать, — развернуть контейнер Node Exporter и прикрепить его к серверу Prometheus, как показано в следующем файле YAML:

Здесь вы добавили еще один сервис docker-compose под названием nodexporter. Как упоминалось выше, экспортер – часть программного обеспечения, которая переводит метрики из сторонней системы в метрический формат, понятняй Prometheus. Node Exporter экспортирует метрики ОС на сервер Prometheus, который получает и хранит их в базе данных временных рядов. Вы монтируете тома хост-системы и передаете пару флагов службе Node Exporter, чтобы помочь обнаружить информацию о хост-системе, используя точки монтирования procfs и sysfs. procfs и sysfs – файловые системы в Unix-подобных операционных системах, которые показывают в иерархической файловой структуре и каталогах информацию о процессах и другую системную информацию, такую как хранилище и т. д. Структура варьируется от дистрибутива к дистрибутиву. Вы монтируете эти каталоги хоста в виде volumes в сервис Node Exporter, чтобы Node Exporter мог видеть системную информацию узла и вы могли передавать некоторые флаги командной строки со значением местоположения этих каталогов в контейнер Node Exporter.

При запуске сервера Prometheus вы должны увидеть или выполнить запросы PromQL с префиксом node_ на сервере Prometheus. Запуск PromQL-запросов в Prometheus покажет информацию о процессах хоста, хранении и другие метрики.

Добавление визуализации с Grafana

Grafana — средство визуализации и мониторинга данных с поддержкой нескольких баз данных, включая TSDB Prometheus. С помощью Grafana вы можете создать графический пользовательский интерфейс для метрик, которые собираете на сервере Prometheus, как показано ниже:

Вы пишете запросы PromQL в элементах панели Grafana, а не на сервере Prometheus. Но Grafana вытаскивает метрики с сервера Prometheus с интервалом, который вы выбираете в верхнем правом углу панели мониторинга Grafana, и графически отображает их в своей панели мониторинга. Grafana запускается в контейнере Docker, поэтому добавьте службу Grafana в файл compose. Окончательный docker-compose файл выглядит так:

Скопируйте содержимое файла docker-compose и запустите docker-compose up -d , чтобы развернуть сервер Promtheus, контейнеры Node Exporter и Grafana, а также запустите docker-compose ps для проверки состояния контейнеров. В файле compose вы также монтируете файловую систему хоста в сервис Grafana, чтобы Grafana могла получить доступ к Json-панели мониторинга из хост-системы.

Перейдите на публичный IP-адрес системы с портом 3000 и вбейте admin: admin в качестве имени пользователя и пароля, чтобы увидеть статистику сервера в панели Grafana. Вы увидите что-то подобное:

Заключение

Вы увидели простейший пример того, как настроить сервер Prometheus с Node Exporter и Grafana для визуализации статистики сервера на Ubuntu 16.0. Вы можете хранить данные временного ряда Prometheus в стороннем хранилище, таком как InfluxDB, а не в локальной файловой системе. Важно отметить, что Prometheus не связан с логированием и трассировкой. Мы рассмотрели, как добавить компонент Prometheus Alert Manager в вышеуказанный стек для отправки оповещений по электронной почте или в Slack, если что-то идет не так, и как использовать service discovery в Prometheus.

Здесь вы можете найти полный исходный код. Также рекомендую прочитать документациюPrometheus, чтобы узнать больше о его компонентах и архитектуре.

Оцените статью