Skip to content

Grafana #30

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 25 commits into
base: master
Choose a base branch
from
Open

Grafana #30

wants to merge 25 commits into from

Conversation

Antom91
Copy link

@Antom91 Antom91 commented Jun 13, 2019

Hello, I added Grafana to your project. How Its work? Grafana connects by alexanderzobnin-zabbix-app plugin to Zabbix and gets some information about server activity, then Grafana shows you dashboards to you.

Grafana worked by Pass Proxy, if you start all containers, you can view Grafana like this http://localhost/grafana

Grafans`s data storage is located by path ./data/ path.

You can debug this project by Vagrant

- /data/provisioning/dashboards:/etc/grafana/provisioning/dashboards
- /data/provisioning/datasources:/etc/grafana/provisioning/datasources
- ./scripts/zabbix_dashboards:/var/lib/grafana/dashboards
- ./scripts/grafana.ini:/etc/grafana/grafana.ini:ro
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Почему конфиг находится в каталоге со скриптами?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

исправлю.

@@ -0,0 +1,64 @@
# To troubleshoot and get more log info enable ldap debug logging in GrafanA.ini
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Как я могу сюдя кастомные значения закинуть? Только вручную, но конфиг в репозитории, будут конфликты


def grafana_configurator(self):
#DATASOURCE.YAML
yaml_file_ds = open(self.grafana_datas_yaml, 'w')
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я думаю, что может есть чучуть получшее формат создания yaml объекта. Посмотри пожалуйста и переформатируй этот блок.

Copy link
Author

@Antom91 Antom91 Jun 13, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да , есть модули для создания YAML, но они либо создают как то криво, либо не создают то что нужно. я потратил на них пол дня, но я ещё раз на свежую голову посмотрю что там есть..


#DASHBOARD.YAML
yaml_file_db = open(self.grafana_dashb_yaml, 'w')
yaml_file_db.write('apiVersion: 1\n\n')
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тоже самое ^^^

yaml_file_db.close()
#Grafana Port Checker (need for check, if server start?)
while True:
time.sleep(1)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Сколько ты будешь ждать, пока графана заработает?, Я так понимаю тут бесконечный цикл. Правильно?

Copy link
Author

@Antom91 Antom91 Jun 13, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не бесконечный цикл, тут идет порт чек. как только графана доступна цикл завершается. Иногда бывало так , что графана загружалась позже выполнения скриптов и выдавало ошибку. Допишу кое что, что бы в случаи если графана не подымится, цикл закончился через какое то время))

#Grafana Port Checker (need for check, if server start?)
while True:
time.sleep(1)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно ли избежать создание сокета при каждой итерации, можно ли использовать только sock.connect_ex при пробе конекшена?

logger.debug("Grafana Server is Started")
self.grafana_plugin_on() #Enable Plugin
self.grafana_dashboard_starred() #Add all dashboards to favorite
sock.close()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тоже самое касается закрытие сокета, желательно закрыть его в конце всей процедуры, а не при каждой итерации

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нет реакции на коментарий. по поводу закрытия порта при каждой итерации

@@ -0,0 +1,78 @@
server {
listen 80;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Почему конфиг находится в каталоге со скриптами?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

понял ошибку. исправлю

@mdihtyar mdihtyar requested a review from bilonic June 13, 2019 09:00
networks:
- zabbix_net
volumes:
- /data/grafana:/var/lib/grafana
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

точно /data а не ./data?
як по мені то краще б десь кучніше тримати данні

Copy link
Contributor

@bilonic bilonic left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

перенести конфіг файли в окрему папку з конфігами, і можливо створити файли з прикладами конфігів

readme.md Outdated
@@ -21,7 +21,7 @@ Requirements

### Preparing configuration file for server

If default options are not enough, then please use `.env.example` to create own environment configuration file.
Tou need to create configuration file `.env` from `.env.example`
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

у меня без него почему то не стартовало, связано с паролем админа от графаны, я ещё раз более тщательно проверю и сделаю исправление.

readme.md Outdated
@@ -33,7 +33,7 @@ Zabbix agent on host machine, where Zabbix server works inside the docker enviro

#### Run and configured only server components
```shell
$ docker-compose up -d
$ docker-compose up -d && docker restart $(docker ps -q)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

зачем рестартовать все контейнеры после старта?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

это нужно для того что бы графана смогла подключить все файлы, без рестарта контейнера с графаной, например yml файлы не принимало, лишь после рестарта.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

может проблема в чем-то другом, должна заработать сразу же, такой подход не очень, нужно попытаться решить проблему как-то по другому.

.travis.yml Outdated
- cp .env.example .env
- docker-compose stop -t 0 && sudo rm -f ./data/
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

я понял, почему так сделано, но docker-compose.yml должен быть разработанный таким образом, чтобы .env не был обязательным. Он должен быть опциональным.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

в .env файле хранится пароль от графаны, который тянется в саму графану и в конфигуратор. Мне показалось что вариант хранения пароля в docker-compose.yml неправильный. Но только что я придумал ещё один вариант реализации... хм... Позже внесу его.


def grafana_configurator(self):
#Datasource.yaml Template generation
tmpl = Template(u'''\
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно этот шаблон вынести в отдельный файл, чтобы в конфигураторе не было такого типа описания?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

имеется введу вынести код генерации YAML файлов в отдельный файл?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да, вынести код шаблона во внешний файл. К примеру в каталог configuration и обозвать файлы <name>.yaml.tmpl

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

понял, занимаюсь

ds_file.close()

#Dashboard.yaml Template generation
tmpl = Template(u'''\
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тоже самое касается и этого шаблона

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • вопрос, если у тебя нет сложных конструкций, типа циклов и т.п, можно ли воспользоваться стандартнымы средствами python для генерации таких простых шаблонов?
    к примеру https://pyformat.info/

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да, можно, такой вариант тоже должен работать хорошо

logger.debug("Grafana Server is Started")
self.grafana_plugin_on() #Enable Plugin
self.grafana_dashboard_starred() #Add all dashboards to favorite
sock.close()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нет реакции на коментарий. по поводу закрытия порта при каждой итерации

x-setup-agent.sh Outdated
@@ -189,3 +190,7 @@ echo "Done."
printf "Removing dangling data. "
rm -f /tmp/zabbix-release.deb
echo "Done."

printf "Restarting All Containers"
docker restart $(docker ps -q) > /dev/null
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Зачем перезапускать все контейнеры? они должны запуститься и работать сразу.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

установка агента производится на сервере, где возможно не будет еще контейнеров, есть подозрение, что на этом месте скрипт упадет.

readme.md Outdated
@@ -33,7 +33,7 @@ Zabbix agent on host machine, where Zabbix server works inside the docker enviro

#### Run and configured only server components
```shell
$ docker-compose up -d
$ docker-compose up -d && docker restart $(docker ps -q)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

может проблема в чем-то другом, должна заработать сразу же, такой подход не очень, нужно попытаться решить проблему как-то по другому.

- GF_AUTH_LDAP_CONFIG_FILE=${GF_AUTH_LDAP_CONFIG_FILE:-/etc/grafana/ldap_custom.toml}
- GF_AUTH_LDAP_ALLOW_SIGN_UP=${GF_AUTH_LDAP_ALLOW_SIGN_UP:-true}
##########LDAP CONFIG ENVIROMENTS##########
- LDAP_GF_HOST=${LDAP_GF_HOST:-172.17.0.1}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

какой вариант можно предложить, если я не хочу LDAP подключать, имею ли я право выбора. К примеру у деплоя забикса есть такая возможность, хочешь используй внутреннюю аутентификаци, а хочешь LDAP. Твои предложения?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я этот момент учел, у графаны по стандартному работает как и внутренняя аутентификация так и параллельно авторизация через LDAP, то есть, если LDAP упадет то внутренняя работать будет, поэтому сделал возможность включения и отключения LDAP через GF_AUTH_LDAP_ENABLED=true, Даже если LDAP упал или ещё что то, всё продолжает работать хорошо кроме авторизации через LDAP, логи выведут определенную ошибку.

- ./data/provisioning/datasources:/etc/grafana/provisioning/datasources
- ./scripts/zabbix_dashboards:/var/lib/grafana/dashboards
- ./configuration/grafana.ini:/etc/grafana/grafana.ini:ro
restart: unless-stopped
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

вижу повтор restart: опции в сервисе, убери пожалуйста дубликат

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

уже и сам заметил... видимо случайно добавил, исправил...

restart: unless-stopped
environment:
- GF_SECURITY_ADMIN_PASSWORD=${GF_SECURITY_ADMIN_PASSWORD:-grafana}
- GF_AUTH_LDAP_ENABLED=${GF_AUTH_LDAP_ENABLED:-true}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

получается по-умолчанию предлагается всегда LDAP аутентификация. Можно ли здесь поставить false по умолчанию? Что будет?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да, если поставим false то будет работать внутренняя авторизация, LDAP будет отключен. Сейчас же, если развернуть всё это дело и не подключать LDAP но там будет стоять true, ничего критического не произойдет, логи выведут сообщение о том что нет коннекта с LDAP и продолжит работать на внутренней авторизации.
С замечанием согласен, я думаю лучше что бы здесь было false изначально

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а можно сделать, если будет false, вообще убрать раздел касающий LDAP?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Раздел касающийся LDAP это что ? там по сути к LDAP относятся только переменные, которые нужны для генерации конфига, не более. Ну и часть кода, которая относится к созданию конфигурационного файла, но она в run.sh

@@ -9,6 +9,7 @@ RUN apt-get update && \
libssl-dev \
python-pip && \
pip install \
jinja2 \
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Может есть вариант избежать установки jinja2, если не нужно обрабатывать сложные шаблоны?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Например .format()

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

да, как вариант

@@ -0,0 +1,11 @@
FROM grafana/grafana:latest
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Всегда фиксируем версию базового образа, никогда не привязываемся к latest

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Сделал

.env.example Outdated
@@ -18,3 +18,34 @@ DEFAULT_HOST_SECRET=8201e33f60093f2ce49f1abe6be8*****
URL_LIST=[{"name":"localhost","url":"http://localhost","priority":4},{"name":"github.com","url":"https://github.com","priority":4}]
ZBX_CONFIG={"authentication_type":0,"ok_period":"1d"}
ZBX_ADMIN_USERS=[{"name":"user","password":"password"},{"name":"user1","password":"password"}]
GF_SECURITY_ADMIN_PASSWORD=grafana
GF_AUTH_LDAP_ENABLED=true
GF_AUTH_LDAP_CONFIG_FILE=/etc/grafana/ldap_custom.toml
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

если есть какой-то статический конфиг, не нужно его оглашать в общем конфиги, можно сделать это или в Dockerfile или же в docker-compose. В конфиг выносим, только все очень важное

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

понял, сделал

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants