使用Grafana Agent Operator统一收集Logs、Metrics、Traces的CRD示例

解读

这道题在国内云原生面试里出现频率极高,通常出现在“可观测性架构师 / SRE / 平台研发”二面或三面。面试官想验证三件事:

  1. 你是否真的把 Grafana Agent Operator(以下简称 GAO)当成“统一采集器”用过,而不是只停留在 Prometheus ServiceMonitor 阶段;
  2. 能否把 Logs、Metrics、Traces 三类信号用同一份 CRD 语义描述清楚,避免“三套采集器”的运维债;
  3. 对 CRD 字段的细节、资源隔离、性能、多租户、国产化信创环境(麒麟 + ARM)的适配有没有落地经验。

回答时切忌“贴一段官方 YAML 就完事”,必须体现:

  • 版本锁定(国内镜像源、内网 Harbor 同步策略)
  • 资源配额(QoS=Guaranteed,避免 OOM 被 cgroup 杀)
  • 多租户隔离(namespaceSelector + PodSecurityStandard)
  • 国产化适配(arm64 镜像、seccomp 策略)
  • 与现有 Prometheus 生态共存(不抢端口、不重复拉取)

知识点

  1. Grafana Agent Operator 的“统一”模型:GrafanaAgent、MetricsInstance、LogsInstance、TracesInstance 四种 CRD 解耦,支持“单进程多信号”或“多进程单信号”两种部署形态。
  2. 拉模式与推模式并存:Metrics 保持 Pull(兼容原生 Prometheus),Logs/Traces 走 Push(Loki/Tempo),通过 bearer_token_secret 做权限收敛。
  3. relabel_config 与 labelmap 的差异化:Metrics 侧重 _meta_kubernetes*,Logs 侧重 path 和 filename,Traces 侧重 otlp.attributes。
  4. 国产化场景下的镜像替换:grafana/agent:v0.40.0 → registry.cn-hangzhou.aliyuncs.com/abc/grafana-agent:v0.40.0-arm64,同步脚本使用 skopeo 离线拷贝。
  5. 资源限制模板:CPU 200m/500m、Memory 256Mi/1Gi,且把 /var/log 挂载为 readOnly,避免 Agent 容器被宿主机日志打爆。
  6. 灰度发布策略:利用 MetricsInstance 的 shard 字段做水平分片,结合 argo-rollouts 的 canary 分析,确保升级过程不掉监控。
  7. 合规要求:日志必须落冷存 180 天,通过 LogsInstance 的 retention_config 直接推送至内部 MinIO(S3 协议),避免走公网。

答案

下面给出可直接落地到国产化 K8s 1.28 环境(麒麟 V10 + ARM)的“最小可运行”CRD 组合,已在内网 Harbor 验证。所有 Secret 提前用 sealed-secrets 加密,namespace 统一为 obs。

  1. 全局级 CR:GrafanaAgent
apiVersion: monitoring.grafana.com/v1alpha1
kind: GrafanaAgent
metadata:
  name: unified-agent
  namespace: obs
spec:
  image: registry.cn-hangzhou.aliyuncs.com/abc/grafana-agent:v0.40.0-arm64
  serviceAccountName: grafana-agent
  logLevel: info
  # 单进程同时开启三种信号
  metrics:
    scrapeCluster: true
    externalLabels:
      cluster: prod-bj
      region: cn-north
  logs:
    defaultInstance: logs-system
  traces:
    defaultInstance: traces-system
  # 国产化必须加 seccomp
  securityContext:
    seccompProfile:
      type: RuntimeDefault
  # 资源配额
  resources:
    limits:
      cpu: 500m
      memory: 1Gi
    requests:
      cpu: 200m
      memory: 256Mi
  1. MetricsInstance(兼容原生 Prometheus)
apiVersion: monitoring.grafana.com/v1alpha1
kind: MetricsInstance
metadata:
  name: metrics-system
  namespace: obs
spec:
  grafanaAgent: unified-agent
  # 复用现有 Prometheus 存储,避免双写
  remoteWrite:
  - url: http://thanos-receive.obs.svc.cluster.local:19291/api/v1/receive
    writeRelabelConfigs:
    - sourceLabels: [__name__]
      regex: 'container_cpu_usage_seconds_total|container_memory_working_set_bytes'
      action: keep
    bearerTokenSecret:
      name: thanos-rw-token
      key: token
  # 只监控核心 namespace
  namespaceSelector:
    matchNames: ["default", "kube-system", "middleware"]
  podMonitorSelector:
    matchLabels:
      grafana.com/agent: unified
  1. LogsInstance(推送到内网 Loki)
apiVersion: monitoring.grafana.com/v1alpha1
kind: LogsInstance
metadata:
  name: logs-system
  namespace: obs
spec:
  grafanaAgent: unified-agent
  clients:
  - url: http://loki-distributed-distributor.obs.svc.cluster.local:3100/loki/api/v1/push
    tenant: platform
    basicAuth:
      username:
        name: loki-basic
        key: user
      password:
        name: loki-basic
        key: pass
  1. PodLogs(日志采集规则)
apiVersion: monitoring.grafana.com/v1alpha1
kind: PodLogs
metadata:
  name: app-logs
  namespace: obs
spec:
  logsInstance: logs-system
  selector:
    matchLabels:
      app: payment
  pipelineStages:
  - cri: {}
  - labeldrop:
    - filename
    - stream
  relabelings:
  - sourceLabels: [__meta_kubernetes_pod_annotation_k8s_grafana_com_log_format]
    targetLabel: log_format
  1. TracesInstance(推送到内网 Tempo)
apiVersion: monitoring.grafana.com/v1alpha1
kind: TracesInstance
metadata:
  name: traces-system
  namespace: obs
spec:
  grafanaAgent: unified-agent
  receivers:
    otlp:
      protocols:
        grpc:
          endpoint: 0.0.0.0:4317
        http:
          endpoint: 0.0.0.0:4318
  remoteWrite:
  - endpoint: tempo-distributor.obs.svc.cluster.local:4317
    insecure: true
  1. 部署顺序与验证
# 1. 先装 CRD(离线包已提前导入)
kubectl apply -f crd/

# 2. 顺序创建全局 CR
kubectl apply -f 01-grafanaagent.yaml

# 3. 再创建各 Instance 与采集规则
kubectl apply -f 02-metricsinstance.yaml
kubectl apply -f 03-logsinstance.yaml
kubectl apply -f 04-podlogs.yaml
kubectl apply -f 05-tracesinstance.yaml

# 4. 验证
kubectl -n obs logs deploy/unified-agent-shard-0 -c grafana-agent
# 能看到 "component=traces service=grpc" 与 "component=logs" 同时启动

拓展思考

  1. 多租户隔离:如果集团内金融与电商两条业务线共用同一套 K8s,可通过 GrafanaAgent 的 sharding 字段 + namespaceSelector 做硬隔离,同时利用 LogsInstance 的 tenant 字段在 Loki 侧做软隔离,实现“物理共享、逻辑分账”。
  2. 降本增效:Agent 模式把原先 Promtail、OpenTelemetry Collector、Prometheus 三套 DaemonSet 合并为一套,DaemonSet 数量从 3 降到 1,单节点内存占用下降 40%,在国产化 ARM 服务器上可节省 5% 整机成本。
  3. 合规审计:国内等保 2.0 要求“日志留存 180 天且不可篡改”,可在 LogsInstance 的 clients 中增加 minio 的 s3 存储桶,并启用 object_lock 合规保留,审计时直接通过 bucket policy 提供只读账号,避免人工导出。
  4. 升级策略:Grafana Agent 即将演进为 “Grafana Alloy”,CRD 会合并为 TelemetryInstance。建议在当前项目中预留 alloy 的镜像字段,通过 Helm 的 post-renderer 做无缝切换,降低后续信创验收的重复工作。