diff --git a/clusters/uralkal/kustomization.yaml b/clusters/uralkal/kustomization.yaml index 44832c1..4a0ff6c 100644 --- a/clusters/uralkal/kustomization.yaml +++ b/clusters/uralkal/kustomization.yaml @@ -17,6 +17,7 @@ resources: - ../../infrastructure/trino/uralkal - ../../infrastructure/istio-config/uralkal - ../../infrastructure/s3-proxy/uralkal + - ../../infrastructure/opentelemetry-collector/uralkal - ../../infrastructure/security-audit/uralkal - ../../apps/reviews/uralkal diff --git a/infrastructure/istio-config/uralkal/istio-config.yaml b/infrastructure/istio-config/uralkal/istio-config.yaml index a4952e6..2ebdda8 100644 --- a/infrastructure/istio-config/uralkal/istio-config.yaml +++ b/infrastructure/istio-config/uralkal/istio-config.yaml @@ -22,6 +22,45 @@ spec: environments: uralkal: istio: + # traceparent из b3-заголовков sidecar'а для приложений (W3C), см. чарт istio-config-contour. + add-traceparent-filter: + - attachments + - auth-flow + - bi + - bim + - cde + - checklists + - comparisons + - contracts + - control-interface + - cross-section + - django + - document-link + - documentations + - drawings + - eav + - faas + - flows + - gateway + - iam + - inspections + - issues + - mapper + - measurements + - message-hub + - notes + - pm + - prescriptions + - processing + - projects + - remarks + - reviews + - rfi + - stamp-verification + - subscriptions + - system-log + - transmittal + - workspaces gateways: platform: name: platform-gateway diff --git a/infrastructure/istio-pilot/uralkal/istio-pilot.yaml b/infrastructure/istio-pilot/uralkal/istio-pilot.yaml index f2a0646..04d7065 100644 --- a/infrastructure/istio-pilot/uralkal/istio-pilot.yaml +++ b/infrastructure/istio-pilot/uralkal/istio-pilot.yaml @@ -9,13 +9,31 @@ spec: dependsOn: - name: istio-base namespace: istio-system + - name: opentelemetry-collector + namespace: opentelemetry-collector values: global: imagePullSecrets: - regcred - # Провайдер журнала доступа для security-audit (access-collector). Сам по себе ничего не включает: - # работает только для workload'ов, на которые ссылается Telemetry (infrastructure/security-audit/mesh). + # Трейсы sidecar'ов и шлюза: zipkin в otel-collector (infrastructure/opentelemetry-collector/uralkal), + # дальше коллектор пишет в S3 (MinIO контура). + traceSampling: 100 meshConfig: + enableTracing: true + defaultConfig: + tracing: + sampling: 100 + custom_tags: + client_ip: + header: + name: x-forwarded-for + user.id: + header: + name: x-user-id + zipkin: + address: otel-collector.opentelemetry-collector.svc.cluster.local:9411 + # Провайдер журнала доступа для security-audit (access-collector). Сам по себе ничего не включает: + # работает только для workload'ов, на которые ссылается Telemetry (infrastructure/security-audit/mesh). extensionProviders: - name: audit-access envoyOtelAls: diff --git a/infrastructure/opentelemetry-collector/uralkal/kustomization.yaml b/infrastructure/opentelemetry-collector/uralkal/kustomization.yaml new file mode 100644 index 0000000..ce41389 --- /dev/null +++ b/infrastructure/opentelemetry-collector/uralkal/kustomization.yaml @@ -0,0 +1,7 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../base + - networkpolicy.yaml +patches: + - path: opentelemetry-collector.yaml diff --git a/infrastructure/opentelemetry-collector/uralkal/networkpolicy.yaml b/infrastructure/opentelemetry-collector/uralkal/networkpolicy.yaml new file mode 100644 index 0000000..b38cf16 --- /dev/null +++ b/infrastructure/opentelemetry-collector/uralkal/networkpolicy.yaml @@ -0,0 +1,35 @@ +# Коллектору нужны только DNS, приём трейсов из mesh и egress во внешний MinIO. +# По образцу security-audit/base/networkpolicy*.yaml. +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: otel-collector +spec: + podSelector: + matchLabels: + telemetry/collector: traces # podLabels HelmRelease opentelemetry-collector + policyTypes: [Ingress, Egress] + ingress: + # Трейсы принимаются от всех workload'ов mesh (sidecar'ы приложений, ingress-шлюз): + # список namespace-источников — весь контур, поэтому ограничение только по портам. + - ports: + - {port: 4317, protocol: TCP} # OTLP gRPC (приложения) + - {port: 4318, protocol: TCP} # OTLP HTTP (приложения) + - {port: 9411, protocol: TCP} # zipkin от sidecar'ов (meshConfig.defaultConfig.tracing) + - {port: 13133, protocol: TCP} # health_check (liveness/readiness kubelet) + egress: + - to: + - namespaceSelector: + matchLabels: {kubernetes.io/metadata.name: kube-system} + podSelector: + matchLabels: {k8s-app: kube-dns} + - ipBlock: {cidr: 169.254.25.10/32} # nodelocaldns kubespray; TODO(verify): enable_nodelocaldns в контуре + ports: + - {port: 53, protocol: UDP} + - {port: 53, protocol: TCP} + # Внешний MinIO контура (ServiceEntry minio.uralkal.external → 10.133.0.245), тот же адрес + # задан у audit-processor (K8S_AUDIT_MINIO_ENDPOINT) в security-audit. + - to: + - ipBlock: {cidr: 10.133.0.245/32} + ports: + - {port: 9000, protocol: TCP} diff --git a/infrastructure/opentelemetry-collector/uralkal/opentelemetry-collector.yaml b/infrastructure/opentelemetry-collector/uralkal/opentelemetry-collector.yaml new file mode 100644 index 0000000..f5b1f66 --- /dev/null +++ b/infrastructure/opentelemetry-collector/uralkal/opentelemetry-collector.yaml @@ -0,0 +1,177 @@ +# Трейсы → S3 (внешний MinIO контура): zipkin от sidecar'ов Istio (провайдер задаётся в +# istio-pilot/uralkal) и OTLP от приложений, дальше экспортёр awss3 пишет OTLP-proto в MinIO. +# Предусловия создаёт terraform контура (infra/terraform, ветка contour, env uralkal): +# - Secret regcred (фан-аут по image_pull_secret) и otel-collector-minio в namespace +# opentelemetry-collector — креды те же, что у security-audit-minio (бакет security-audit); +# - lifecycle бакета security-audit: префикс traces/ — 30 дней. +# Порядок раскатки: сначала этот оверлей (создаст namespace), потом terragrunt apply. +apiVersion: helm.toolkit.fluxcd.io/v2 +kind: HelmRelease +metadata: + name: opentelemetry-collector + namespace: opentelemetry-collector +spec: + interval: 5m + timeout: 10m + install: + disableWait: true + remediation: + retries: 3 + upgrade: + disableWait: true + remediation: + retries: 3 + values: + mode: deployment + replicaCount: 2 + fullnameOverride: otel-collector + + podDisruptionBudget: + enabled: true + minAvailable: 1 + # Мягкая: при одном доступном узле вторая реплика всё равно встанет. + affinity: + podAntiAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - weight: 100 + podAffinityTerm: + topologyKey: kubernetes.io/hostname + labelSelector: + matchLabels: + telemetry/collector: traces + + # Дефолт чарта 0.117.1 — тот же contrib-образ (зеркало в registry контура); задан явно, как в security-audit. + image: + repository: cr.yandex/crp3ccidau046kdj8g9q/opentelemetry-collector/opentelemetry-collector-contrib + tag: "0.121.0-amd64" + command: + name: otelcol-contrib + imagePullSecrets: + - name: regcred + + # Доступ к Kubernetes API коллектору не нужен (k8sattributes/hostMetrics не используются). + clusterRole: + create: false + serviceAccount: + create: true + name: otel-collector + presets: + logsCollection: {enabled: false} + hostMetrics: {enabled: false} + kubernetesAttributes: {enabled: false} + kubeletMetrics: {enabled: false} + kubernetesEvents: {enabled: false} + clusterMetrics: {enabled: false} + + ports: + otlp: + enabled: true + containerPort: 4317 + servicePort: 4317 + protocol: TCP + appProtocol: grpc # Istio выбирает протокол по appProtocol + otlp-http: + enabled: true + containerPort: 4318 + servicePort: 4318 + protocol: TCP + appProtocol: http + zipkin: + enabled: true + containerPort: 9411 + servicePort: 9411 + protocol: TCP + appProtocol: http + jaeger-compact: {enabled: false} + jaeger-thrift: {enabled: false} + jaeger-grpc: {enabled: false} + metrics: {enabled: false} + service: + enabled: true + + podSecurityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + seccompProfile: {type: RuntimeDefault} + securityContext: + runAsNonRoot: true + runAsUser: 10001 + readOnlyRootFilesystem: true + allowPrivilegeEscalation: false + privileged: false + capabilities: + drop: [ALL] + + resources: + requests: {cpu: 100m, memory: 256Mi} + limits: {cpu: 1000m, memory: 1Gi} + + # Без sidecar, как audit-processor/audit-collector в security-audit: во внешний MinIO — напрямую + # по IP мимо mesh. Sidecar сломал бы egress: ServiceEntry minio.uralkal.external держит HTTP-листенер + # на :9000, и запросы с Host=10.133.0.245:9000 получили бы 404 от Envoy (поэтому в security-audit + # все, кто ходит в MinIO, без sidecar). Приём из mesh — plaintext (PeerAuthentication нет, PERMISSIVE). + # AuthorizationPolicy не добавляем: отправители трейсов — все workload'ы mesh, allowlist невыразим; + # транспорт ограничен NetworkPolicy (networkpolicy.yaml). + podLabels: + telemetry/collector: traces # селектор NetworkPolicy и anti-affinity + sidecar.istio.io/inject: "false" + podAnnotations: + sidecar.istio.io/inject: "false" + + # Ключи MinIO — статический Secret namespace (как security-audit-minio), в env AWS SDK. + extraEnvs: + - name: AWS_ACCESS_KEY_ID + valueFrom: + secretKeyRef: {name: otel-collector-minio, key: access_key} + - name: AWS_SECRET_ACCESS_KEY + valueFrom: + secretKeyRef: {name: otel-collector-minio, key: secret_key} + + # Полный конфиг вместо мержа с дефолтами чарта (как в security-audit). + alternateConfig: + extensions: + health_check: {endpoint: "${env:MY_POD_IP}:13133"} + receivers: + otlp: + protocols: + grpc: {endpoint: "${env:MY_POD_IP}:4317"} + http: {endpoint: "${env:MY_POD_IP}:4318"} + zipkin: + endpoint: "${env:MY_POD_IP}:9411" + processors: + memory_limiter: {check_interval: 1s, limit_mib: 800, spike_limit_mib: 200} + resource: + attributes: + - {action: insert, key: k8s.cluster.name, value: uralkal} + - {action: insert, key: deployment.environment, value: uralkal} + batch: {send_batch_size: 1024, send_batch_max_size: 2048, timeout: 5s} + exporters: + awss3/traces: + s3uploader: + region: us-east-1 # MinIO игнорирует, но поле обязательно для AWS SDK + endpoint: http://10.133.0.245:9000 # внешний MinIO контура (ServiceEntry minio.uralkal.external) + # Общий бакет с security-audit: ключи per-bucket пользователя (security-audit-minio) + # привязаны политикой к этому бакету, в другой не запишешь. Трейсы — под префиксом + # uralkal/traces/ (конвенция раскладки аудита: uralkal/<поток>/, см. ILM бакета). + s3_bucket: security-audit + s3_prefix: uralkal/traces + # Партиции по часам (strftime), дефолт — по минутам: меньше мелких объектов в MinIO. + s3_partition_format: "year=%Y/month=%m/day=%d/hour=%H" + s3_force_path_style: true + disable_ssl: true + compression: gzip + marshaler: otlp_proto + # Очередь в памяти (диска у Deployment нет): при падении пода неотправленные батчи теряются. + sending_queue: {enabled: true, queue_size: 5000, num_consumers: 4} + retry_on_failure: {enabled: true, initial_interval: 5s, max_interval: 60s, max_elapsed_time: 0} + service: + extensions: [health_check] + pipelines: + traces: + receivers: [otlp, zipkin] + processors: [memory_limiter, resource, batch] + exporters: [awss3/traces] + telemetry: + logs: {level: info} + metrics: {address: "${env:MY_POD_IP}:8888"}