diff --git a/clusters/uralkal/kustomization.yaml b/clusters/uralkal/kustomization.yaml index 3e91be1..feb4f73 100644 --- a/clusters/uralkal/kustomization.yaml +++ b/clusters/uralkal/kustomization.yaml @@ -18,6 +18,8 @@ resources: - ../../infrastructure/istio-config/uralkal - ../../infrastructure/s3-proxy/uralkal - ../../infrastructure/opentelemetry-collector/uralkal + # - ../../infrastructure/opentelemetry-agent/uralkal + # - ../../infrastructure/vector/uralkal - ../../infrastructure/security-audit/uralkal - ../../infrastructure/vmstack/uralkal - ../../infrastructure/local-path-provisioner/uralkal diff --git a/infrastructure/opentelemetry-agent/base/collector.yaml b/infrastructure/opentelemetry-agent/base/collector.yaml new file mode 100644 index 0000000..a73008e --- /dev/null +++ b/infrastructure/opentelemetry-agent/base/collector.yaml @@ -0,0 +1,95 @@ +extensions: + health_check: {endpoint: "0.0.0.0:13133"} + file_storage/checkpoints: + directory: /var/lib/otelcol-service-logs/checkpoints + create_directory: true + fsync: true + file_storage/queue: + directory: /var/lib/otelcol-service-logs/queue + create_directory: true + fsync: true + compaction: + on_start: true + directory: /var/lib/otelcol-service-logs/queue + +receivers: + filelog/pods: + include: [/var/log/pods/*/*/*.log] + exclude: + # Avoid collecting this pipeline's own errors, including audit S3 debug echoes. + - /var/log/pods/opentelemetry-agent_*/*/*.log + - /var/log/pods/opentelemetry-collector_*/*/*.log + - /var/log/pods/vector_*/*/*.log + - /var/log/pods/security-audit_*/*/*.log + start_at: end + include_file_path: true + storage: file_storage/checkpoints + max_log_size: 1MiB + poll_interval: 1s + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 30s + max_elapsed_time: 0s + operators: + # Detect CRI/Docker format and reassemble runtime partial records. + - {type: container, id: container-parser} + - type: json_parser + id: application-json + if: 'body matches "^\\s*\\{"' + parse_to: attributes["app"] + on_error: send + +processors: + memory_limiter: {check_interval: 1s, limit_mib: 600, spike_limit_mib: 100} + k8sattributes: + auth_type: serviceAccount + passthrough: false + filter: + node_from_env_var: K8S_NODE_NAME + extract: + metadata: + - k8s.namespace.name + - k8s.pod.name + - k8s.pod.uid + - k8s.node.name + - k8s.container.name + labels: + - {tag_name: service.name, key: app.kubernetes.io/name, from: pod} + - {tag_name: app, key: app, from: pod} + pod_association: + - sources: + - {from: resource_attribute, name: k8s.pod.uid} + - sources: + - {from: resource_attribute, name: k8s.namespace.name} + - {from: resource_attribute, name: k8s.pod.name} + +exporters: + otlp/logs: + endpoint: otel-collector.opentelemetry-collector.svc.cluster.local:4317 + tls: {insecure: true} + compression: gzip + # Vector acknowledges only after S3 upload; this must exceed its 300s batch age. + timeout: 660s + sending_queue: + enabled: true + storage: file_storage/queue + num_consumers: 8 + queue_size: 2048 + retry_on_failure: + enabled: true + initial_interval: 5s + max_interval: 30s + max_elapsed_time: 0s + +service: + extensions: [health_check, file_storage/checkpoints, file_storage/queue] + pipelines: + logs: + receivers: [filelog/pods] + # No batch processor: do not acknowledge a read before the persistent queue. + processors: [memory_limiter, k8sattributes] + exporters: [otlp/logs] + telemetry: + logs: {level: info} + metrics: {address: "0.0.0.0:8888"} diff --git a/infrastructure/opentelemetry-agent/base/daemonset.yaml b/infrastructure/opentelemetry-agent/base/daemonset.yaml new file mode 100644 index 0000000..f247066 --- /dev/null +++ b/infrastructure/opentelemetry-agent/base/daemonset.yaml @@ -0,0 +1,62 @@ +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: otel-agent +spec: + selector: + matchLabels: {app.kubernetes.io/name: otel-agent} + updateStrategy: + type: RollingUpdate + rollingUpdate: {maxUnavailable: 1} + template: + metadata: + labels: + app.kubernetes.io/name: otel-agent + sidecar.istio.io/inject: "false" + annotations: + sidecar.istio.io/inject: "false" + spec: + serviceAccountName: otel-agent + nodeSelector: {kubernetes.io/os: linux} + tolerations: + - {operator: Exists} + imagePullSecrets: + - name: regcred + terminationGracePeriodSeconds: 60 + securityContext: + runAsUser: 0 + runAsGroup: 0 + seccompProfile: {type: RuntimeDefault} + containers: + - name: otel-agent + image: cr.yandex/crp3ccidau046kdj8g9q/opentelemetry-collector/opentelemetry-collector-contrib:0.121.0-amd64 + args: ["--config=/etc/otelcol/config.yaml"] + env: + - name: K8S_NODE_NAME + valueFrom: {fieldRef: {fieldPath: spec.nodeName}} + ports: + - {name: health, containerPort: 13133} + - {name: metrics, containerPort: 8888} + readinessProbe: + httpGet: {path: /, port: health} + livenessProbe: + httpGet: {path: /, port: health} + resources: + requests: {cpu: 100m, memory: 256Mi} + limits: {cpu: "1", memory: 768Mi} + securityContext: + runAsNonRoot: false + readOnlyRootFilesystem: true + allowPrivilegeEscalation: false + capabilities: {drop: [ALL]} + volumeMounts: + - {name: config, mountPath: /etc/otelcol, readOnly: true} + - {name: pod-logs, mountPath: /var/log/pods, readOnly: true} + - {name: storage, mountPath: /var/lib/otelcol-service-logs} + volumes: + - name: config + configMap: {name: otel-agent-config} + - name: pod-logs + hostPath: {path: /var/log/pods, type: Directory} + - name: storage + hostPath: {path: /var/lib/otelcol-service-logs, type: DirectoryOrCreate} diff --git a/infrastructure/opentelemetry-agent/base/kustomization.yaml b/infrastructure/opentelemetry-agent/base/kustomization.yaml new file mode 100644 index 0000000..9323ec1 --- /dev/null +++ b/infrastructure/opentelemetry-agent/base/kustomization.yaml @@ -0,0 +1,11 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +namespace: opentelemetry-agent +resources: + - namespace.yaml + - rbac.yaml + - daemonset.yaml +configMapGenerator: + - name: otel-agent-config + files: + - config.yaml=collector.yaml diff --git a/infrastructure/opentelemetry-agent/base/namespace.yaml b/infrastructure/opentelemetry-agent/base/namespace.yaml new file mode 100644 index 0000000..c70dca7 --- /dev/null +++ b/infrastructure/opentelemetry-agent/base/namespace.yaml @@ -0,0 +1,9 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: opentelemetry-agent + labels: + istio-injection: disabled + # hostPath and root are needed to read container log files owned by root. + pod-security.kubernetes.io/enforce: privileged + pod-security.kubernetes.io/warn: baseline diff --git a/infrastructure/opentelemetry-agent/base/rbac.yaml b/infrastructure/opentelemetry-agent/base/rbac.yaml new file mode 100644 index 0000000..f5e1c7c --- /dev/null +++ b/infrastructure/opentelemetry-agent/base/rbac.yaml @@ -0,0 +1,26 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + name: otel-agent +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: otel-agent-pod-metadata +rules: + - apiGroups: [""] + resources: [pods, namespaces] + verbs: [get, list, watch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: otel-agent-pod-metadata +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: otel-agent-pod-metadata +subjects: + - kind: ServiceAccount + name: otel-agent + namespace: opentelemetry-agent diff --git a/infrastructure/opentelemetry-agent/kustomization.yaml b/infrastructure/opentelemetry-agent/kustomization.yaml new file mode 100644 index 0000000..85dcd9d --- /dev/null +++ b/infrastructure/opentelemetry-agent/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - base diff --git a/infrastructure/opentelemetry-agent/uralkal/kustomization.yaml b/infrastructure/opentelemetry-agent/uralkal/kustomization.yaml new file mode 100644 index 0000000..871f01d --- /dev/null +++ b/infrastructure/opentelemetry-agent/uralkal/kustomization.yaml @@ -0,0 +1,6 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +namespace: opentelemetry-agent +resources: + - ../base + - networkpolicy.yaml diff --git a/infrastructure/opentelemetry-agent/uralkal/networkpolicy.yaml b/infrastructure/opentelemetry-agent/uralkal/networkpolicy.yaml new file mode 100644 index 0000000..474780e --- /dev/null +++ b/infrastructure/opentelemetry-agent/uralkal/networkpolicy.yaml @@ -0,0 +1,42 @@ +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: otel-agent +spec: + podSelector: + matchLabels: {app.kubernetes.io/name: otel-agent} + policyTypes: [Ingress, Egress] + ingress: + - ports: + - {port: 13133, protocol: TCP} + - from: + - namespaceSelector: + matchLabels: {kubernetes.io/metadata.name: vmstack} + ports: + - {port: 8888, protocol: TCP} + egress: + - to: + - namespaceSelector: + matchLabels: {kubernetes.io/metadata.name: kube-system} + podSelector: + matchLabels: {k8s-app: kube-dns} + - ipBlock: {cidr: 169.254.25.10/32} + ports: + - {port: 53, protocol: UDP} + - {port: 53, protocol: TCP} + - to: + - namespaceSelector: + matchLabels: {kubernetes.io/metadata.name: opentelemetry-collector} + podSelector: + matchLabels: {telemetry/collector: traces} + ports: + - {port: 4317, protocol: TCP} + # Kubernetes service / control-plane addresses depend on the live cluster. + # Restrict to private networks; verify both service and post-DNAT API ports. + - to: + - ipBlock: {cidr: 10.0.0.0/8} + - ipBlock: {cidr: 172.16.0.0/12} + - ipBlock: {cidr: 192.168.0.0/16} + ports: + - {port: 443, protocol: TCP} + - {port: 6443, protocol: TCP} diff --git a/infrastructure/opentelemetry-collector/uralkal/networkpolicy.yaml b/infrastructure/opentelemetry-collector/uralkal/networkpolicy.yaml index 770d2be..0ba5d0d 100644 --- a/infrastructure/opentelemetry-collector/uralkal/networkpolicy.yaml +++ b/infrastructure/opentelemetry-collector/uralkal/networkpolicy.yaml @@ -1,4 +1,4 @@ -# Коллектору нужны только DNS, приём трейсов из mesh и egress в Kafka. +# Трейсы уходят в Kafka, сервисные логи — по OTLP в Vector. # По образцу security-audit/base/networkpolicy*.yaml. apiVersion: networking.k8s.io/v1 kind: NetworkPolicy @@ -33,3 +33,10 @@ spec: matchLabels: {kubernetes.io/metadata.name: kafka} ports: - {port: 9092, protocol: TCP} + - to: + - namespaceSelector: + matchLabels: {kubernetes.io/metadata.name: vector} + podSelector: + matchLabels: {app.kubernetes.io/name: vector-logs} + ports: + - {port: 4317, protocol: TCP} diff --git a/infrastructure/opentelemetry-collector/uralkal/opentelemetry-collector.yaml b/infrastructure/opentelemetry-collector/uralkal/opentelemetry-collector.yaml index 998730d..032703a 100644 --- a/infrastructure/opentelemetry-collector/uralkal/opentelemetry-collector.yaml +++ b/infrastructure/opentelemetry-collector/uralkal/opentelemetry-collector.yaml @@ -187,6 +187,15 @@ spec: - replace_pattern(span.attributes["http.target"], "[A-Za-z0-9_-]{20,}\\.[A-Za-z0-9_-]{20,}\\.[A-Za-z0-9_-]{10,}", "***jwt***") batch: {send_batch_size: 1024, send_batch_max_size: 2048, timeout: 5s} exporters: + otlp/logs: + endpoint: vector-logs.vector.svc.cluster.local:4317 + tls: {insecure: true} + compression: gzip + # Longer than Vector's 300s flush interval: S3 completion acknowledges OTLP. + timeout: 600s + # Synchronous forwarding lets the agent retain its durable queue until S3. + sending_queue: {enabled: false} + retry_on_failure: {enabled: false} kafka/traces: brokers: ["${env:KAFKA_BROKERS}"] protocol_version: 2.8.0 @@ -202,6 +211,11 @@ spec: service: extensions: [health_check] pipelines: + logs: + receivers: [otlp] + # No batch/memory queue at this hop: preserve upstream retry on failure. + processors: [memory_limiter, resource] + exporters: [otlp/logs] traces: receivers: [otlp, zipkin] processors: [memory_limiter, resource, transform/mask, batch] diff --git a/infrastructure/vector/README.md b/infrastructure/vector/README.md new file mode 100644 index 0000000..cd1a497 --- /dev/null +++ b/infrastructure/vector/README.md @@ -0,0 +1,119 @@ +# Сервисные логи УралКалия + +Поток: контейнерный stdout/stderr → OTel Agent на узле → существующий OTel gateway +→ OTLP gRPC → Vector → MinIO, Parquet/Zstd. Логи не проходят через Kafka. +Существующий pipeline трейсов продолжает работать через Kafka/audit-processor. + +## Компоненты и параметры + +| Компонент | Настройка | +|---|---| +| Agent | DaemonSet `opentelemetry-agent/otel-agent`, образ contrib `0.121.0-amd64` | +| Источник | `/var/log/pods/*/*/*.log`, CRI/Docker parser, сборка частичных записей runtime | +| Метаданные | namespace, pod/UID, container, node, service из `app.kubernetes.io/name`, fallback `app`/container | +| Gateway | `opentelemetry-collector/otel-collector`, отдельный pipeline `logs` | +| Writer | StatefulSet `vector/vector-logs`, две реплики Vector `0.56.0-debian` | +| Буфер | У каждой реплики Vector локальный `emptyDir` до `12Gi`, дисковая очередь `10Gi`; переполнение блокирует приём | +| Файлы | Фиксированная схема `base/logs.schema`, Zstd 3, 300 секунд либо 64 MiB входных событий | +| Хранилище | `http://10.133.0.245:9000/service-logs`, объекты под `logs/` | +| Retention | Lifecycle удаляет текущие объекты через 14 дней; отдельные правила для предыдущих версий и delete markers | +| Секрет | Vault KV v2 `secrets/apps/vector/minio`, поля `access_key` и `secret_key` | +| Доступ Vault | Kubernetes Auth role/policy `vector-logs`, только SA `vector-logs` в namespace `vector` | + +Пример ключа: + +```text +logs/contour=uralkal/date=2026-11-29/hour=18/-.parquet +``` + +Дата/час вычисляются из времени события в UTC. Все метки сохраняются колонками, +произвольные resource/log attributes — строкой `attributes_json`. +S3 object tags: `contour=uralkal`, `signal=logs`, `retention=14d`. +Тег сам по себе ничего не удаляет: удалением управляет lifecycle по префиксу `logs/`. +Строки времени в Parquet — RFC3339, при запросах их можно привести к TIMESTAMPTZ. + +## Перед раскаткой + +1. Зеркалировать официальный образ Vector в registry, доступный УралКалию: + + ```bash + docker pull timberio/vector:0.56.0-debian + docker tag timberio/vector:0.56.0-debian cr.yandex/crp3ccidau046kdj8g9q/vector:0.56.0-debian + docker push cr.yandex/crp3ccidau046kdj8g9q/vector:0.56.0-debian + ``` + + Новый образ нужно доставить в фактическое зеркало закрытого контура так же, + как остальные образы. Запуск не должен зависеть от доступа узлов в Docker Hub. + Vector до 0.56.0 не подходит для этого конфига без проверки наличия Parquet + в конкретной сборке. + +2. Применить конфигурацию окружения `uralkal` в репозитории `infra/terraform`. + Terraform управляет бакетом `service-logs`, lifecycle для `logs/` на 14 дней, + отдельным пользователем MinIO с правами записи, секретом + `secrets/apps/vector/minio` и policy/role Vault `vector-logs`. + Порядок применения стеков описан в README Terraform-репозитория. + +3. Распространение `regcred` в namespace `vector` и `opentelemetry-agent` + выполняется Terraform. Сами namespace объявлены в этом репозитории и + создаются Flux; в Terraform для них используется `manage: false` и + `image_pull_secret: true`. + +4. Для Vector нужны generic-узлы с доступным ephemeral storage. У каждой реплики + `emptyDir` ограничен `12Gi`; контейнер запрашивает `1Gi` ephemeral storage, + лимит — `14Gi` с учётом буфера, временных файлов и логов контейнера. + Проверить доступ Vault Agent init к Vault:8200. API egress агента сейчас + разрешён на private CIDR TCP 443/6443: после получения адресов API контура + сузить `opentelemetry-agent/uralkal/networkpolicy.yaml` до service/control-plane IP. + На узлах с Docker, если pod log files ссылаются за пределы `/var/log/pods`, + дополнительно понадобится read-only mount `/var/lib/docker/containers`. + +5. Передать изменения в GitOps обычным способом. Новые компоненты уже включены + в `clusters/uralkal/kustomization.yaml`. Временное отсутствие Vector не должно + ломать readiness gateway: приложение/трейсы и доставка логов независимы. + +## Наблюдение и ограничения + +`vmstack/uralkal` дополнен scrape jobs для OTel Agent:8888 и Vector:9598. +Контролировать `up` этих jobs, рост `otelcol_exporter_queue_size`, +`otelcol_exporter_enqueue_failed_log_records`, `component_errors_total`, +`component_discarded_events_total`, заполнение дискового буфера Vector и свободное +место на узлах. Алертинг в vmstack сейчас отключён; новые метрики доступны в +существующей Grafana, но подключение канала оповещений — отдельная настройка. + +Agent начинает читать новые файлы с конца; накопленная история при первом +подключении не импортируется. CRI partial records собираются в одно событие; +произвольные многострочные stack traces приложений требуют правил конкретного +формата (либо JSON-логирования со stack trace в одном поле). +Namespace этого конвейера и `security-audit` исключены из файлового сбора, чтобы +не собирать собственные ошибки и S3 debug echoes по кругу. + +У gateway нет batch processor/асинхронной очереди логов: upstream подтверждается +после ответа Vector, который ждёт успешной записи в S3. Поэтому таймауты gateway +600s и агента 660s больше flush interval 300s. Доставка at-least-once; это не +exactly-once. При длительной недоступности, заполнении очередей, ротации +непрочитанных файлов или потере узла возможна потеря данных. +Очередь агента ограничена числом запросов, а не байтами; hostPath требует контроля +свободного места. Буфер Vector находится в `emptyDir` на диске узла; отдельные +PV/PVC не создаются. Буфер переживает перезапуск контейнера в том же поде, +но удаляется при пересоздании пода, в том числе при rollout или переносе на другой +узел. До успешной отправки в S3 записи также остаются в очереди агента. + +Секреты подставляются Vault Agent один раз при старте. После ротации ключей +нужно перезапустить StatefulSet Vector. Текущий MinIO endpoint использует HTTP, +как существующий pipeline трейсов; TLS потребует серверного endpoint и CA. +Маскирование распространённых ключей/Bearer — дополнительная защита, не замена +запрету записи секретов приложениями. + +Expiration 14 дней считается от создания объекта, не от даты в ключе. +Удаление асинхронное. На новом бакете versioning не включается; если его +включить позднее, предыдущие версии удаляются через 14 дней после перехода в +noncurrent. Следовательно, versioning может увеличить фактический срок хранения. +Object Lock/Legal Hold могут блокировать удаление. + +## Источники + +- https://opentelemetry.io/docs/platforms/kubernetes/collector/components/ +- https://vector.dev/releases/0.56.0/ +- https://vector.dev/docs/reference/configuration/sources/opentelemetry/ +- https://vector.dev/docs/reference/configuration/sinks/aws_s3/ +- https://docs.min.io/aistor/administration/object-lifecycle-management/ diff --git a/infrastructure/vector/base/kustomization.yaml b/infrastructure/vector/base/kustomization.yaml new file mode 100644 index 0000000..fd9772c --- /dev/null +++ b/infrastructure/vector/base/kustomization.yaml @@ -0,0 +1,12 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +namespace: vector +resources: + - namespace.yaml + - statefulset.yaml + - service.yaml +configMapGenerator: + - name: vector-logs-config + files: + - vector.yaml + - logs.schema diff --git a/infrastructure/vector/base/logs.schema b/infrastructure/vector/base/logs.schema new file mode 100644 index 0000000..cdc0817 --- /dev/null +++ b/infrastructure/vector/base/logs.schema @@ -0,0 +1,19 @@ +message service_logs { + REQUIRED BINARY event_time (UTF8); + REQUIRED BINARY observed_time (UTF8); + REQUIRED BINARY contour (UTF8); + REQUIRED BINARY namespace (UTF8); + REQUIRED BINARY service_name (UTF8); + REQUIRED BINARY pod (UTF8); + REQUIRED BINARY pod_uid (UTF8); + REQUIRED BINARY container (UTF8); + REQUIRED BINARY node (UTF8); + REQUIRED BINARY severity (UTF8); + REQUIRED INT64 severity_number; + REQUIRED BINARY trace_id (UTF8); + REQUIRED BINARY span_id (UTF8); + REQUIRED BINARY message (UTF8); + REQUIRED BINARY attributes_json (UTF8); + REQUIRED BINARY partition_date (UTF8); + REQUIRED BINARY partition_hour (UTF8); +} diff --git a/infrastructure/vector/base/namespace.yaml b/infrastructure/vector/base/namespace.yaml new file mode 100644 index 0000000..8032e8b --- /dev/null +++ b/infrastructure/vector/base/namespace.yaml @@ -0,0 +1,6 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: vector + labels: + istio-injection: disabled diff --git a/infrastructure/vector/base/service.yaml b/infrastructure/vector/base/service.yaml new file mode 100644 index 0000000..45d2cb9 --- /dev/null +++ b/infrastructure/vector/base/service.yaml @@ -0,0 +1,23 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + name: vector-logs +--- +apiVersion: v1 +kind: Service +metadata: + name: vector-logs +spec: + selector: {app.kubernetes.io/name: vector-logs} + ports: + - {name: grpc-otlp, port: 4317, targetPort: otlp, appProtocol: grpc} +--- +apiVersion: v1 +kind: Service +metadata: + name: vector-logs-headless +spec: + clusterIP: None + selector: {app.kubernetes.io/name: vector-logs} + ports: + - {name: grpc-otlp, port: 4317, targetPort: otlp} diff --git a/infrastructure/vector/base/statefulset.yaml b/infrastructure/vector/base/statefulset.yaml new file mode 100644 index 0000000..ef1738d --- /dev/null +++ b/infrastructure/vector/base/statefulset.yaml @@ -0,0 +1,100 @@ +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: vector-logs +spec: + serviceName: vector-logs-headless + replicas: 2 + podManagementPolicy: Parallel + selector: + matchLabels: {app.kubernetes.io/name: vector-logs} + template: + metadata: + labels: + app.kubernetes.io/name: vector-logs + sidecar.istio.io/inject: "false" + annotations: + sidecar.istio.io/inject: "false" + vault.hashicorp.com/agent-inject: "true" + vault.hashicorp.com/agent-init-first: "true" + vault.hashicorp.com/agent-pre-populate-only: "true" + vault.hashicorp.com/auth-path: auth/kubernetes + vault.hashicorp.com/role: vector-logs + vault.hashicorp.com/agent-run-as-user: "10001" + vault.hashicorp.com/agent-run-as-group: "10001" + vault.hashicorp.com/agent-inject-secret-aws-credentials: secrets/data/apps/vector/minio + vault.hashicorp.com/agent-inject-perms-aws-credentials: "0400" + vault.hashicorp.com/agent-inject-template-aws-credentials: | + {{- with secret "secrets/data/apps/vector/minio" -}} + [default] + aws_access_key_id = {{ index .Data.data "access_key" }} + aws_secret_access_key = {{ index .Data.data "secret_key" }} + {{- end -}} + spec: + serviceAccountName: vector-logs + imagePullSecrets: + - name: regcred + terminationGracePeriodSeconds: 90 + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + fsGroup: 10001 + seccompProfile: {type: RuntimeDefault} + affinity: + podAntiAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - weight: 100 + podAffinityTerm: + topologyKey: kubernetes.io/hostname + labelSelector: + matchLabels: {app.kubernetes.io/name: vector-logs} + containers: + - name: vector + image: timberio/vector:0.56.0-debian + args: ["--config", "/etc/vector/vector.yaml", "--require-healthy"] + env: + - {name: VECTOR_LOG, value: info} + - {name: AWS_EC2_METADATA_DISABLED, value: "true"} + ports: + - {name: otlp, containerPort: 4317} + - {name: api, containerPort: 8686} + - {name: metrics, containerPort: 9598} + startupProbe: + httpGet: {path: /health, port: api} + failureThreshold: 60 + periodSeconds: 10 + readinessProbe: + httpGet: {path: /health, port: api} + livenessProbe: + httpGet: {path: /health, port: api} + periodSeconds: 20 + resources: + requests: {cpu: 250m, memory: 512Mi, ephemeral-storage: 1Gi} + limits: {cpu: "2", memory: 2Gi, ephemeral-storage: 14Gi} + securityContext: + readOnlyRootFilesystem: true + allowPrivilegeEscalation: false + capabilities: {drop: [ALL]} + volumeMounts: + - {name: config, mountPath: /etc/vector, readOnly: true} + - {name: data, mountPath: /var/lib/vector} + - {name: tmp, mountPath: /tmp} + volumes: + - name: config + configMap: {name: vector-logs-config} + - name: data + # Node disk, scoped to this pod; removed when the pod is recreated. + # Keep headroom above Vector's 10Gi buffer for disk-buffer bookkeeping. + emptyDir: {sizeLimit: 12Gi} + - name: tmp + emptyDir: {sizeLimit: 128Mi} +--- +apiVersion: policy/v1 +kind: PodDisruptionBudget +metadata: + name: vector-logs +spec: + minAvailable: 1 + selector: + matchLabels: {app.kubernetes.io/name: vector-logs} diff --git a/infrastructure/vector/base/vector.yaml b/infrastructure/vector/base/vector.yaml new file mode 100644 index 0000000..1b5b25e --- /dev/null +++ b/infrastructure/vector/base/vector.yaml @@ -0,0 +1,112 @@ +data_dir: /var/lib/vector +api: + enabled: true + address: 0.0.0.0:8686 + playground: false + +sources: + otlp: + type: opentelemetry + grpc: {address: "0.0.0.0:4317"} + http: {address: "0.0.0.0:4318"} + # Default native decoding exposes .message, .resources, .attributes. + internal_metrics: + type: internal_metrics + +transforms: + normalize_logs: + type: remap + inputs: [otlp.logs] + # A transformation failure is exported unchanged rather than silently dropped; + # all conversions below have fallbacks to keep the fixed schema valid. + source: | + resources = object(.resources) ?? {} + attributes = object(.attributes) ?? {} + app = object(attributes.app) ?? {} + text = string(.message) ?? encode_json(.message) + parsed = parse_json(text) ?? {} + if is_object(parsed) && is_empty(app) { + app = object!(parsed) + } + ts = to_timestamp(.timestamp) ?? now() + observed = to_timestamp(.observed_timestamp) ?? ts + service_name = string(resources."service.name") ?? string(resources.app) ?? string(resources."k8s.container.name") ?? "unknown" + if service_name == "" { + service_name = string(resources.app) ?? string(resources."k8s.container.name") ?? "unknown" + } + severity = upcase(string(.severity_text) ?? string(app.level) ?? string(app.levelname) ?? "UNSPECIFIED") + if severity == "" { + severity = upcase(string(app.level) ?? string(app.levelname) ?? "UNSPECIFIED") + } + trace_id = string(.trace_id) ?? "" + span_id = string(.span_id) ?? "" + if trace_id == "" || trace_id == "00000000000000000000000000000000" { + trace_id = string(app.trace_id) ?? "" + } + if span_id == "" || span_id == "0000000000000000" { + span_id = string(app.span_id) ?? "" + } + # Redact common credentials in both the original message and nested attributes. + text = replace(text, r'(?i)Bearer\s+[A-Za-z0-9._~+/-]+=*', "Bearer ***") + text = replace(text, r'(?i)"?(password|passwd|pwd|token|secret|client_secret|api[_-]?key|authorization|cookie|signature|x-amz-signature)"?\s*[:=]\s*("(\\.|[^"\\])*"|[^,;\s}]+)', "[REDACTED]") + text = replace(text, r'[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}', "***jwt***") + safe_attributes = encode_json({"resource": resources, "log": attributes}) + safe_attributes = replace(safe_attributes, r'(?i)"(password|passwd|pwd|token|secret|client_secret|api[_-]?key|authorization|cookie|signature|x-amz-signature)"\s*:\s*"(\\.|[^"\\])*"', "\"redacted\":\"***\"") + safe_attributes = replace(safe_attributes, r'(?i)Bearer\s+[A-Za-z0-9._~+/-]+=*', "Bearer ***") + safe_attributes = replace(safe_attributes, r'[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}', "***jwt***") + . = { + "event_time": format_timestamp!(ts, format: "%+"), + "observed_time": format_timestamp!(observed, format: "%+"), + "contour": "${CONTOUR}", + "namespace": string(resources."k8s.namespace.name") ?? "unknown", + "service_name": service_name, + "pod": string(resources."k8s.pod.name") ?? "", + "pod_uid": string(resources."k8s.pod.uid") ?? "", + "container": string(resources."k8s.container.name") ?? "", + "node": string(resources."k8s.node.name") ?? "", + "severity": severity, + "severity_number": to_int(.severity_number) ?? 0, + "trace_id": trace_id, + "span_id": span_id, + "message": text, + "attributes_json": safe_attributes, + "partition_date": format_timestamp!(ts, format: "%F", timezone: "UTC"), + "partition_hour": format_timestamp!(ts, format: "%H", timezone: "UTC") + } + +sinks: + minio_logs: + type: aws_s3 + inputs: [normalize_logs] + bucket: "${S3_BUCKET}" + endpoint: "${S3_ENDPOINT}" + region: us-east-1 + force_path_style: true + auth: + credentials_file: /vault/secrets/aws-credentials + key_prefix: "logs/contour={{ contour }}/date={{ partition_date }}/hour={{ partition_hour }}/" + filename_append_uuid: true + compression: none + encoding: {codec: text} + batch_encoding: + codec: parquet + schema_file: /etc/vector/logs.schema + schema_mode: strict + compression: {algorithm: zstd, level: 3} + batch: + max_bytes: 67108864 + timeout_secs: 300 + buffer: + type: disk + max_size: 10737418240 + when_full: block + # Retain the upstream agent queue until the S3 request succeeds. + acknowledgements: {enabled: true} + tags: + contour: "${CONTOUR}" + signal: logs + retention: 14d + metrics: + type: prometheus_exporter + inputs: [internal_metrics] + address: 0.0.0.0:9598 diff --git a/infrastructure/vector/kustomization.yaml b/infrastructure/vector/kustomization.yaml new file mode 100644 index 0000000..85dcd9d --- /dev/null +++ b/infrastructure/vector/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - base diff --git a/infrastructure/vector/uralkal/kustomization.yaml b/infrastructure/vector/uralkal/kustomization.yaml new file mode 100644 index 0000000..bf53e86 --- /dev/null +++ b/infrastructure/vector/uralkal/kustomization.yaml @@ -0,0 +1,12 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +namespace: vector +resources: + - ../base + - networkpolicy.yaml +images: + - name: timberio/vector + newName: cr.yandex/crp3ccidau046kdj8g9q/vector + newTag: 0.56.0-debian +patches: + - path: statefulset.yaml diff --git a/infrastructure/vector/uralkal/networkpolicy.yaml b/infrastructure/vector/uralkal/networkpolicy.yaml new file mode 100644 index 0000000..9a63b24 --- /dev/null +++ b/infrastructure/vector/uralkal/networkpolicy.yaml @@ -0,0 +1,43 @@ +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: vector-logs +spec: + podSelector: + matchLabels: {app.kubernetes.io/name: vector-logs} + policyTypes: [Ingress, Egress] + ingress: + - from: + - namespaceSelector: + matchLabels: {kubernetes.io/metadata.name: opentelemetry-collector} + podSelector: + matchLabels: {telemetry/collector: traces} + ports: + - {port: 4317, protocol: TCP} + # Kubelet probes originate from the node and are allowed by NetworkPolicy. + # Do not expose Vector's GraphQL/tap API (8686) to other pods. + - from: + - namespaceSelector: + matchLabels: {kubernetes.io/metadata.name: vmstack} + ports: + - {port: 9598, protocol: TCP} + egress: + - to: + - namespaceSelector: + matchLabels: {kubernetes.io/metadata.name: kube-system} + podSelector: + matchLabels: {k8s-app: kube-dns} + - ipBlock: {cidr: 169.254.25.10/32} + ports: + - {port: 53, protocol: UDP} + - {port: 53, protocol: TCP} + - to: + - ipBlock: {cidr: 10.133.0.245/32} + ports: + - {port: 9000, protocol: TCP} + # Vault Agent init container authenticates before Vector starts. + - to: + - namespaceSelector: + matchLabels: {kubernetes.io/metadata.name: vault} + ports: + - {port: 8200, protocol: TCP} diff --git a/infrastructure/vector/uralkal/statefulset.yaml b/infrastructure/vector/uralkal/statefulset.yaml new file mode 100644 index 0000000..0b49e5a --- /dev/null +++ b/infrastructure/vector/uralkal/statefulset.yaml @@ -0,0 +1,14 @@ +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: vector-logs +spec: + template: + spec: + nodeSelector: {dedicated: generic} + containers: + - name: vector + env: + - {name: CONTOUR, value: uralkal} + - {name: S3_BUCKET, value: service-logs} + - {name: S3_ENDPOINT, value: "http://10.133.0.245:9000"} diff --git a/infrastructure/vmstack/uralkal/vmstack.yaml b/infrastructure/vmstack/uralkal/vmstack.yaml index f2e22ce..c06c399 100644 --- a/infrastructure/vmstack/uralkal/vmstack.yaml +++ b/infrastructure/vmstack/uralkal/vmstack.yaml @@ -130,6 +130,36 @@ spec: remoteWrite: - url: http://vmsingle-vmstack.vmstack.svc.cluster.local.:8428/api/v1/write scrapeInterval: 30s + # The operator appends these jobs; no new CRD resources are needed at bootstrap. + inlineScrapeConfig: | + - job_name: service-logs-otel-agent + kubernetes_sd_configs: + - role: pod + namespaces: + names: [opentelemetry-agent] + relabel_configs: + - source_labels: [__meta_kubernetes_pod_label_app_kubernetes_io_name] + regex: otel-agent + action: keep + - source_labels: [__meta_kubernetes_pod_container_port_name] + regex: metrics + action: keep + - source_labels: [__meta_kubernetes_pod_node_name] + target_label: node + - job_name: service-logs-vector + kubernetes_sd_configs: + - role: pod + namespaces: + names: [vector] + relabel_configs: + - source_labels: [__meta_kubernetes_pod_label_app_kubernetes_io_name] + regex: vector-logs + action: keep + - source_labels: [__meta_kubernetes_pod_container_port_name] + regex: metrics + action: keep + - source_labels: [__meta_kubernetes_pod_name] + target_label: pod resources: requests: cpu: 50m