Kubernetes 重要组件

The OpenTelemetry Collector 支持许多不同的接收器 (receiver) 和处理器 (processor),以方便监控 Kubernetes。本节介绍对收集 Kubernetes 数据和增强数据最重要的一些组件。

本页介绍的组件

对于应用程序的 traces、metrics 或 logs,我们推荐使用 OTLP receiver,但任何适合您数据的接收器都可以。

Kubernetes Attributes Processor

部署模式可用
DaemonSet (agent)
Deployment (gateway)
Sidecar

Kubernetes Attributes Processor 会自动发现 Kubernetes Pod,提取其元数据,并将提取的元数据作为资源属性添加到 spans、metrics 和 logs 中。

Kubernetes Attributes Processor 是在 Kubernetes 中运行的 Collector 的最重要的组件之一。任何接收应用程序数据的 Collector 都应该使用它。 因为它为您的遥测数据添加了 Kubernetes 上下文,所以 Kubernetes Attributes Processor 可以让您将应用程序的 traces、metrics 和 logs 信号与您的 Kubernetes 遥测数据(如 pod 指标和 traces)相关联。

Kubernetes Attributes Processor 使用 Kubernetes API 来发现集群中运行的所有 Pod,并记录它们的 IP 地址、Pod UID 和重要元数据。默认情况下,通过处理器的数据会通过传入请求的 IP 地址与 Pod 相关联,但可以配置不同的规则。由于该处理器使用 Kubernetes API,因此需要特殊权限(参见下面的示例)。如果您使用的是 OpenTelemetry Collector Helm chart,则可以使用 kubernetesAttributes preset 来开始。

默认添加的属性

  • k8s.namespace.name
  • k8s.pod.name
  • k8s.pod.uid
  • k8s.pod.start_time
  • k8s.deployment.name
  • k8s.node.name

Kubernetes Attributes Processor 还可以使用您添加到 Pod 和命名空间中的 Kubernetes 标签和 Kubernetes 注释,为 traces、metrics 和 logs 设置自定义资源属性。

k8sattributes:
  auth_type: 'serviceAccount'
  extract:
    metadata: # extracted from the pod
      - k8s.namespace.name
      - k8s.pod.name
      - k8s.pod.start_time
      - k8s.pod.uid
      - k8s.deployment.name
      - k8s.node.name
    annotations:
      # Extracts the value of a pod annotation with key `annotation-one` and inserts it as a resource attribute with key `a1`
      - tag_name: a1
        key: annotation-one
        from: pod
      # Extracts the value of a namespaces annotation with key `annotation-two` with regexp and inserts it as a resource  with key `a2`
      - tag_name: a2
        key: annotation-two
        regex: field=(?P<value>.+)
        from: namespace
    labels:
      # Extracts the value of a namespaces label with key `label1` and inserts it as a resource attribute with key `l1`
      - tag_name: l1
        key: label1
        from: namespace
      # Extracts the value of a pod label with key `label2` with regexp and inserts it as a resource attribute with key `l2`
      - tag_name: l2
        key: label2
        regex: field=(?P<value>.+)
        from: pod
  pod_association: # How to associate the data to a pod (order matters)
    - sources: # First try to use the value of the resource attribute k8s.pod.ip
        - from: resource_attribute
          name: k8s.pod.ip
    - sources: # Then try to use the value of the resource attribute k8s.pod.uid
        - from: resource_attribute
          name: k8s.pod.uid
    - sources: # If neither of those work, use the request's connection to get the pod IP.
        - from: connection

当 Collector 部署为 Kubernetes DaemonSet (agent) 或 Kubernetes Deployment (gateway) 时,还有特殊的配置选项。有关详细信息,请参阅 部署场景

有关 Kubernetes Attributes Processor 的配置详细信息,请参阅 Kubernetes Attributes Processor

由于该处理器使用 Kubernetes API,因此需要正确的权限才能正常工作。对于大多数用例,您应该通过 ClusterRole 为运行 Collector 的服务帐户授予以下权限。

apiVersion: v1
kind: ServiceAccount
metadata:
  name: collector
  namespace: <OTEL_COL_NAMESPACE>
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: otel-collector
rules:
  - apiGroups:
      - ''
    resources:
      - 'pods'
      - 'namespaces'
    verbs:
      - 'get'
      - 'watch'
      - 'list'
  - apiGroups:
      - 'apps'
    resources:
      - 'replicasets'
    verbs:
      - 'get'
      - 'list'
      - 'watch'
  - apiGroups:
      - 'extensions'
    resources:
      - 'replicasets'
    verbs:
      - 'get'
      - 'list'
      - 'watch'
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: otel-collector
subjects:
  - kind: ServiceAccount
    name: collector
    namespace: <OTEL_COL_NAMESPACE>
roleRef:
  kind: ClusterRole
  name: otel-collector
  apiGroup: rbac.authorization.k8s.io

Kubeletstats Receiver

部署模式可用
DaemonSet (agent)首选
Deployment (gateway)是,但只能收集其部署所在节点的指标
Sidecar

每个 Kubernetes 节点都运行一个包含 API 服务器的 kubelet。Kubernetes Receiver 通过 API 服务器连接到该 kubelet,以收集有关节点和节点上运行的工作负载的指标。

存在不同的身份验证方法,但通常使用服务帐户。服务帐户还需要适当的权限才能从 Kubelet 拉取数据(见下文)。如果您使用的是 OpenTelemetry Collector Helm chart,则可以使用 kubeletMetrics preset 来开始。

默认情况下,将为 Pod 和节点收集指标,但您可以配置接收器以收集容器和卷的指标。接收器还允许配置指标的收集频率。

receivers:
  kubeletstats:
    collection_interval: 10s
    auth_type: 'serviceAccount'
    endpoint: '${env:K8S_NODE_NAME}:10250'
    insecure_skip_verify: true
    metric_groups:
      - node
      - pod
      - container

有关收集哪些指标的特定详细信息,请参阅 默认指标。有关特定配置详细信息,请参阅 Kubeletstats Receiver

由于该处理器使用 Kubernetes API,因此需要正确的权限才能正常工作。对于大多数用例,您应该通过 ClusterRole 为运行 Collector 的服务帐户授予以下权限。

---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: otel-collector
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: otel-collector
rules:
  - apiGroups: ['']
    resources: ['nodes/stats']
    verbs: ['get', 'watch', 'list']
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: otel-collector
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: otel-collector
subjects:
  - kind: ServiceAccount
    name: otel-collector
    namespace: default

Filelog Receiver

部署模式可用
DaemonSet (agent)首选
Deployment (gateway)是,但只能收集其部署所在节点的日志
Sidecar是,但这将被认为是高级配置

Filelog Receiver 会跟踪和解析文件中的日志。尽管它不是一个 Kubernetes 特定接收器,但它仍然是收集 Kubernetes 中任何日志的事实解决方案。

Filelog Receiver 由一系列运算符 (Operators) 组成,这些运算符被链接在一起以处理日志。每个运算符执行一项简单的职责,例如解析时间戳或 JSON。配置 Filelog Receiver 并非易事。如果您使用的是 OpenTelemetry Collector Helm chart,则可以使用 logsCollection preset 来开始。

由于 Kubernetes 日志通常符合一组标准格式,因此用于 Kubernetes 的典型 Filelog Receiver 配置如下所示

filelog:
  include:
    - /var/log/pods/*/*/*.log
  exclude:
    # Exclude logs from all containers named otel-collector
    - /var/log/pods/*/otel-collector/*.log
  start_at: end
  include_file_path: true
  include_file_name: false
  operators:
    # parse container logs
    - type: container
      id: container-parser

有关 Filelog Receiver 的配置详细信息,请参阅 Filelog Receiver

除了 Filelog Receiver 的配置之外,您在 Kubernetes 中的 OpenTelemetry Collector 安装还需要访问其要收集的日志。这通常意味着在您的 collector manifest 中添加一些 volumes 和 volumeMounts

---
apiVersion: apps/v1
kind: DaemonSet
...
spec:
  ...
  template:
    ...
    spec:
      ...
      containers:
        - name: opentelemetry-collector
          ...
          volumeMounts:
            ...
            # Mount the volumes to the collector container
            - name: varlogpods
              mountPath: /var/log/pods
              readOnly: true
            - name: varlibdockercontainers
              mountPath: /var/lib/docker/containers
              readOnly: true
            ...
      volumes:
        ...
        # Typically the collector will want access to pod logs and container logs
        - name: varlogpods
          hostPath:
            path: /var/log/pods
        - name: varlibdockercontainers
          hostPath:
            path: /var/lib/docker/containers
        ...

Kubernetes Cluster Receiver

部署模式可用
DaemonSet (agent)是,但会导致数据重复
Deployment (gateway)是,但多个副本会导致数据重复
Sidecar

Kubernetes Cluster Receiver 使用 Kubernetes API 服务器收集有关整个集群的指标和实体事件。使用此接收器可以回答有关 Pod 状态、节点条件和其他集群范围的问题。由于该接收器收集整个集群的遥测数据,因此在集群中只需要一个接收器实例即可收集所有数据。

存在不同的身份验证方法,但通常使用服务帐户。服务帐户还需要适当的权限才能从 Kubernetes API 服务器拉取数据(见下文)。如果您使用的是 OpenTelemetry Collector Helm chart,则可以使用 clusterMetrics preset 来开始。

对于节点条件,默认情况下接收器仅收集 Ready,但可以配置以收集更多。接收器还可以配置为报告一组可分配资源,例如 cpumemory

k8s_cluster:
  auth_type: serviceAccount
  node_conditions_to_report:
    - Ready
    - MemoryPressure
  allocatable_types_to_report:
    - cpu
    - memory

要了解收集的指标,请参阅 默认指标。有关配置详细信息,请参阅 Kubernetes Cluster Receiver

由于该处理器使用 Kubernetes API,因此需要正确的权限才能正常工作。对于大多数用例,您应该通过 ClusterRole 为运行 Collector 的服务帐户授予以下权限。

---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: otel-collector-opentelemetry-collector
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: otel-collector-opentelemetry-collector
rules:
  - apiGroups:
      - ''
    resources:
      - events
      - namespaces
      - namespaces/status
      - nodes
      - nodes/spec
      - pods
      - pods/status
      - replicationcontrollers
      - replicationcontrollers/status
      - resourcequotas
      - services
    verbs:
      - get
      - list
      - watch
  - apiGroups:
      - apps
    resources:
      - daemonsets
      - deployments
      - replicasets
      - statefulsets
    verbs:
      - get
      - list
      - watch
  - apiGroups:
      - extensions
    resources:
      - daemonsets
      - deployments
      - replicasets
    verbs:
      - get
      - list
      - watch
  - apiGroups:
      - batch
    resources:
      - jobs
      - cronjobs
    verbs:
      - get
      - list
      - watch
  - apiGroups:
      - autoscaling
    resources:
      - horizontalpodautoscalers
    verbs:
      - get
      - list
      - watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: otel-collector-opentelemetry-collector
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: otel-collector-opentelemetry-collector
subjects:
  - kind: ServiceAccount
    name: otel-collector-opentelemetry-collector
    namespace: default

Kubernetes Objects Receiver

部署模式可用
DaemonSet (agent)是,但会导致数据重复
Deployment (gateway)是,但多个副本会导致数据重复
Sidecar

Kubernetes Objects receiver 通过拉取或监视方式从 Kubernetes API 服务器收集对象。此接收器最常见的用例是监视 Kubernetes 事件,但也可用于收集任何类型的 Kubernetes 对象。由于该接收器收集整个集群的遥测数据,因此在集群中只需要一个接收器实例即可收集所有数据。

目前只能使用服务帐户进行身份验证。服务帐户还需要适当的权限才能从 Kubernetes API 服务器拉取数据(见下文)。如果您使用的是 OpenTelemetry Collector Helm chart 并希望摄入事件,则可以使用 kubernetesEvents preset 来开始。

对于配置为拉取的对象,接收器将使用 Kubernetes API 定期列出集群中的所有对象。每个对象将被转换为自己的日志。对于配置为监视的对象,接收器会创建一个与 Kubernetes API 的流,并接收对象更改时的更新。

要查看集群中可用于收集的对象,请运行 kubectl api-resources

kubectl api-resources
NAME                              SHORTNAMES   APIVERSION                             NAMESPACED   KIND
bindings                                       v1                                     true         Binding
componentstatuses                 cs           v1                                     false        ComponentStatus
configmaps                        cm           v1                                     true         ConfigMap
endpoints                         ep           v1                                     true         Endpoints
events                            ev           v1                                     true         Event
limitranges                       limits       v1                                     true         LimitRange
namespaces                        ns           v1                                     false        Namespace
nodes                             no           v1                                     false        Node
persistentvolumeclaims            pvc          v1                                     true         PersistentVolumeClaim
persistentvolumes                 pv           v1                                     false        PersistentVolume
pods                              po           v1                                     true         Pod
podtemplates                                   v1                                     true         PodTemplate
replicationcontrollers            rc           v1                                     true         ReplicationController
resourcequotas                    quota        v1                                     true         ResourceQuota
secrets                                        v1                                     true         Secret
serviceaccounts                   sa           v1                                     true         ServiceAccount
services                          svc          v1                                     true         Service
mutatingwebhookconfigurations                  admissionregistration.k8s.io/v1        false        MutatingWebhookConfiguration
validatingwebhookconfigurations                admissionregistration.k8s.io/v1        false        ValidatingWebhookConfiguration
customresourcedefinitions         crd,crds     apiextensions.k8s.io/v1                false        CustomResourceDefinition
apiservices                                    apiregistration.k8s.io/v1              false        APIService
controllerrevisions                            apps/v1                                true         ControllerRevision
daemonsets                        ds           apps/v1                                true         DaemonSet
deployments                       deploy       apps/v1                                true         Deployment
replicasets                       rs           apps/v1                                true         ReplicaSet
statefulsets                      sts          apps/v1                                true         StatefulSet
tokenreviews                                   authentication.k8s.io/v1               false        TokenReview
localsubjectaccessreviews                      authorization.k8s.io/v1                true         LocalSubjectAccessReview
selfsubjectaccessreviews                       authorization.k8s.io/v1                false        SelfSubjectAccessReview
selfsubjectrulesreviews                        authorization.k8s.io/v1                false        SelfSubjectRulesReview
subjectaccessreviews                           authorization.k8s.io/v1                false        SubjectAccessReview
horizontalpodautoscalers          hpa          autoscaling/v2                         true         HorizontalPodAutoscaler
cronjobs                          cj           batch/v1                               true         CronJob
jobs                                           batch/v1                               true         Job
certificatesigningrequests        csr          certificates.k8s.io/v1                 false        CertificateSigningRequest
leases                                         coordination.k8s.io/v1                 true         Lease
endpointslices                                 discovery.k8s.io/v1                    true         EndpointSlice
events                            ev           events.k8s.io/v1                       true         Event
flowschemas                                    flowcontrol.apiserver.k8s.io/v1beta2   false        FlowSchema
prioritylevelconfigurations                    flowcontrol.apiserver.k8s.io/v1beta2   false        PriorityLevelConfiguration
ingressclasses                                 networking.k8s.io/v1                   false        IngressClass
ingresses                         ing          networking.k8s.io/v1                   true         Ingress
networkpolicies                   netpol       networking.k8s.io/v1                   true         NetworkPolicy
runtimeclasses                                 node.k8s.io/v1                         false        RuntimeClass
poddisruptionbudgets              pdb          policy/v1                              true         PodDisruptionBudget
clusterrolebindings                            rbac.authorization.k8s.io/v1           false        ClusterRoleBinding
clusterroles                                   rbac.authorization.k8s.io/v1           false        ClusterRole
rolebindings                                   rbac.authorization.k8s.io/v1           true         RoleBinding
roles                                          rbac.authorization.k8s.io/v1           true         Role
priorityclasses                   pc           scheduling.k8s.io/v1                   false        PriorityClass
csidrivers                                     storage.k8s.io/v1                      false        CSIDriver
csinodes                                       storage.k8s.io/v1                      false        CSINode
csistoragecapacities                           storage.k8s.io/v1                      true         CSIStorageCapacity
storageclasses                    sc           storage.k8s.io/v1                      false        StorageClass
volumeattachments                              storage.k8s.io/v1                      false        VolumeAttachment

有关特定配置详细信息,请参阅 Kubernetes Objects Receiver

由于该处理器使用 Kubernetes API,因此需要正确的权限才能正常工作。由于服务帐户是唯一的身份验证选项,因此您必须为服务帐户提供适当的访问权限。对于您要收集的任何对象,都需要确保将名称添加到 ClusterRole 中。例如,如果您想收集 Pod,那么 ClusterRole 将如下所示

---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: otel-collector-opentelemetry-collector
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: otel-collector-opentelemetry-collector
rules:
  - apiGroups:
      - ''
    resources:
      - pods
    verbs:
      - get
      - list
      - watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: otel-collector-opentelemetry-collector
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: otel-collector-opentelemetry-collector
subjects:
  - kind: ServiceAccount
    name: otel-collector-opentelemetry-collector
    namespace: default

Prometheus Receiver

部署模式可用
DaemonSet (agent)
Deployment (gateway)
Sidecar

Prometheus 是 Kubernetes 和在 Kubernetes 上运行的服务的常见指标格式。Prometheus Receiver 是收集这些指标的最小替代品。它支持 Prometheus scrape_config 选项的全部功能。

接收器不支持一些高级 Prometheus 功能。如果配置 YAML/代码包含以下任何内容,接收器将返回错误

  • alert_config.alertmanagers
  • alert_config.relabel_configs
  • remote_read
  • remote_write
  • rule_files

有关特定配置详细信息,请参阅 Prometheus Receiver

Prometheus receiver 是 Stateful 的,这意味着在使用它时需要考虑重要细节

  • 当运行 Collector 的多个副本时,Collector 无法自动扩展抓取过程。
  • 当使用相同配置运行 Collector 的多个副本时,它将多次抓取目标。
  • 如果用户想手动分片抓取过程,则需要为每个副本配置不同的抓取配置。

为了简化 Prometheus receiver 的配置,OpenTelemetry Operator 包含一个名为 Target Allocator 的可选组件。此组件可用于告诉 Collector 应该抓取哪些 Prometheus 端点。

有关接收器设计的更多信息,请参阅 设计

Host Metrics Receiver

部署模式可用
DaemonSet (agent)首选
Deployment (gateway)是,但只收集其部署所在节点的指标
Sidecar

Host Metrics Receiver 使用各种抓取器 (scrapers) 从主机收集指标。与 Kubeletstats Receiver 有一些重叠,因此如果您决定同时使用两者,禁用这些重复的指标可能会有所帮助。

在 Kubernetes 中,接收器需要访问 hostfs volume 才能正常工作。如果您使用的是 OpenTelemetry Collector Helm chart,则可以使用 hostMetrics preset 来开始。

可用的抓取器是

抓取器支持的操作系统描述
cpu除 macOS 外所有1CPU 利用率指标
disk除 macOS 外所有1磁盘 I/O 指标
loadAllCPU 负载指标
filesystemAll文件系统利用率指标
memoryAll内存利用率指标
networkAll网络接口 I/O 指标和 TCP 连接指标
pagingAll分页/Swap 空间利用率和 I/O 指标
processesLinux, macOS进程计数指标
processLinux, macOS, Windows每个进程的 CPU、内存和磁盘 I/O 指标

有关收集的指标的具体详细信息和配置详细信息,请参阅 Host Metrics Receiver

如果您需要自己配置组件,请确保挂载 hostfs volume,如果您想收集节点而不是容器的指标。

---
apiVersion: apps/v1
kind: DaemonSet
...
spec:
  ...
  template:
    ...
    spec:
      ...
      containers:
        - name: opentelemetry-collector
          ...
          volumeMounts:
            ...
            - name: hostfs
              mountPath: /hostfs
              readOnly: true
              mountPropagation: HostToContainer
      volumes:
        ...
        - name: hostfs
          hostPath:
            path: /
      ...

然后配置 Host Metrics Receiver 使用 volumeMount

receivers:
  hostmetrics:
    root_path: /hostfs
    collection_interval: 10s
    scrapers:
      cpu:
      load:
      memory:
      disk:
      filesystem:
      network:

有关在容器中使用接收器的更多详细信息,请参阅 从容器内部收集主机指标(仅限 Linux)


  1. 在未编译 cgo 的情况下,macOS 不支持此功能,这是 Collector SIG 发布镜像的默认设置。↩︎ ↩︎