> For the complete documentation index, see [llms.txt](https://utm-1.gitbook.io/utm-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://utm-1.gitbook.io/utm-docs/dokumentaciya/utm-it/resheniya/kubernetes/prilozheniya/monitoring/grafana.md).

# Grafana

## Ссылки

grafana / helm-charts: <https://github.com/grafana/helm-charts>

Развертывание Grafana с использованием Helm Charts: [grafana.com](https://grafana.com/docs/grafana/latest/setup-grafana/installation/helm/)

Deploy Grafana on Kubernetes: [grafana.com](https://grafana.com/docs/grafana/latest/setup-grafana/installation/kubernetes/)

Настроить Grafana: [grafana.com](https://grafana.com/docs/grafana/latest/setup-grafana/configure-grafana/)

Миграция базы данных Grafana: от внутреннего хранилища к PostgreSQL: [habr.com](https://habr.com/ru/articles/897400/)

Миграция Grafana из SQLite в PostgreSQL: [etogeek.dev](https://etogeek.dev/posts/grafana-migration-to-postgresql/)

## Подготовка базы для Grafana в Postgres

Предполагается подключение Grafana к базе Postgres.

По умолчанию Grafana развертывание на основе базы sqlite, но это приводит к ошибке если включать режим persistence.enabled=true

```
Error: ✗ migration failed (id = create migration_log table): database is locked
```

Поэтому вместо sqlite необходимо использовать Postgres.

Для подключения базы Postgres к Grafana необходимо:

* Работающий сервер Postgres
* База на сервере Postgres для Grafana
* Пользователь на сервере Postgres с полными правами к базе для Grafana

На сервере Postgres необходимо выполнить:

```plsql
CREATE DATABASE k8s_grafana;
CREATE USER grafana_user WITH PASSWORD '****';
GRANT ALL PRIVILEGES ON DATABASE k8s_grafana TO grafana_user;
GRANT ALL PRIVILEGES ON SCHEMA public TO grafana_user;
```

## Развертывание Grafana

### Установка через Argo CD

В github в репозитории argocd в каталоге `env-prod\apps` создать подкаталог `monitoring\grafana` в котором создать файл `app.yaml` следующего содержания:

```yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name     : k8s-grafana
  namespace: argocd
spec:
  project: default
  destination:
    name     : in-cluster
    namespace: monitoring
  sources:
  - repoURL: git@github.com:<user-code>/argocd.git
    targetRevision: HEAD
    ref: values
  - repoURL: git@github.com:<user-code>/argocd.git
    targetRevision: HEAD
    path: "env-prod/apps/monitoring/grafana/manifests_before"
  - chart: grafana
    repoURL: https://grafana.github.io/helm-charts
    targetRevision: 10.2.0
    helm:
      releaseName: k8s-grafana
      valueFiles:
      - $values/env-prod/apps/monitoring/grafana/values.yaml
  syncPolicy:
    automated:
      prune   : true
      selfHeal: true
    syncOptions:
      - CreateNamespace=true
      - ServerSideApply=true
```

В каталоге `monitoring\grafana` создать подкаталог `manifests_before` в котором создать следующие файлы:

**grafana-cred.yaml**

```yaml
apiVersion: v1
kind: Secret
metadata:
  name: grafana-cred
  namespace: monitoring
type: Opaque
data:
  admin-user: <имя пользователя в base64>
  admin-password: <пароль в base64>
  # example
  # echo -n "<data>" | base64
```

В каталоге `monitoring\grafana` внести изменения в файл `values.yaml` (базовый файл взять [отсюда](https://github.com/grafana/helm-charts/blob/main/charts/grafana/values.yaml))

{% hint style="info" %}
Всё что необходимо изменить в файле `values.yaml` смотри в репозитории argocd в реальном файле. Все изменения помечены меткой `!!!TEST`
{% endhint %}

Подключение базы Postgres в файле `values.yaml`:

```yaml
grafana.ini:
...
  database:
    type: postgres
    host: 192.168.4.9:5432
    name: k8s_grafana
    user: grafana_user
    password: <пароль>
    migration_locking: false
    log_queries: true
    ssl_mode: disable
```

Сделать коммит в github. После этого Argo CD развернет Grafana в связанном кластере Kubernetes.

В Grafana заходить под логином и паролем, указанном в файле `monitoring\grafana\manifests_before\grafana-cred.yaml`

## Информация

#### Прокси <a href="#command-line-proxy" id="command-line-proxy"></a>

**prometheus:**

**grafana:**

```bash
kubectl -n monitoring port-forward svc/k8s-grafana 80:80

export POD_NAME=$(kubectl get pods --namespace monitoring -l "app.kubernetes.io/name=grafana,app.kubernetes.io/instance=k8s-grafana" -o jsonpath="{.items[0].metadata.name}")
kubectl --namespace monitoring port-forward $POD_NAME 80
```

<http://localhost:80>

#### Пароль администратора

```bash
kubectl get secret --namespace monitoring k8s-grafana -o jsonpath="{.data.admin-password}" | base64 --decode ; echo
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://utm-1.gitbook.io/utm-docs/dokumentaciya/utm-it/resheniya/kubernetes/prilozheniya/monitoring/grafana.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
