# 使用Heapster獲取集群對象的metric數據
Heapster作為kubernetes安裝過程中默認安裝的一個插件,見[安裝heapster插件](../practice/heapster-addon-installation.md)。這對于集群監控十分有用,同時在[Horizontal Pod Autoscaling](../concepts/horizontal-pod-autoscaling.md)中也用到了,HPA將Heapster作為`Resource Metrics API`,向其獲取metric,做法是在`kube-controller-manager` 中配置`--api-server`指向[kube-aggregator](https://github.com/kubernetes/kube-aggregator),也可以使用heapster來實現,通過在啟動heapster的時候指定`--api-server=true`。
Heapster可以收集Node節點上的cAdvisor數據,還可以按照kubernetes的資源類型來集合資源,比如Pod、Namespace域,可以分別獲取它們的CPU、內存、網絡和磁盤的metric。默認的metric數據聚合時間間隔是1分鐘。
## 架構
下面是Heapster架構圖:

[Heapser](https://github.com/kubernetes/heapster)是用Go語言開發Kubernetes集群計算資源使用情況的數據采集工具,編譯后可以直接以一個二進制文件運行,通過向heapster傳遞的參數來指定數據采集行為,這些數據可以選擇多種sink方式,例如Graphite、influxDB、OpenTSDB、ElasticSearch、Kafka等。
## 使用案例
Heapster使用起來很簡單,本身就是二進制文件,直接使用命令行啟動,也可以放在容器里運行,在作為kubernetes插件運行時,我們是直接放在容器中的,見[安裝heapster插件](../practice/heapster-addon-installation.md)。
### 運行
下面是heapster的啟動參數:
| **Flag** | **Description** |
| ------------------------------------------------------- | ------------------------------------------------------------ |
| --allowed-users string | comma-separated list of allowed users |
| --alsologtostderr | log to standard error as well as files |
| --api-server | Enable API server for the Metrics API. If set, the Metrics API will be served on --insecure-port (internally) and --secure-port (externally). |
| --authentication-kubeconfig string | kubeconfig file pointing at the 'core' kubernetes server with enough rights to create tokenaccessreviews.authentication.k8s.io. |
| --authentication-token-webhook-cache-ttl duration | The duration to cache responses from the webhook token authenticator. (default 10s) |
| --authorization-kubeconfig string | kubeconfig file pointing at the ‘core' kubernetes server with enough rights to create subjectaccessreviews.authorization.k8s.io |
| --authorization-webhook-cache-authorized-ttl duration | The duration to cache 'authorized' responses from the webhook authorizer. (default 10s) |
| --authorization-webhook-cache-unauthorized-ttl duration | The duration to cache 'unauthorized' responses from the webhook authorizer. (default 10s) |
| --bind-address ip | The IP address on which to listen for the --secure-port port. The associated interface(s) must be reachable by the rest of the cluster, and by CLI/web clients. If blank, all interfaces will be used (0.0.0.0). (default 0.0.0.0) |
| --cert-dir string | The directory where the TLS certs are located (by default /var/run/kubernetes). If --tls-cert-file and --tls-private-key-file are provided, this flag will be ignored. (default "/var/run/kubernetes") |
| --client-ca-file string | If set, any request presenting a client certificate signed by one of the authorities in the client-ca-file is authenticated with an identity corresponding to the CommonName of the client certificate. |
| --contention-profiling | Enable contention profiling. Requires --profiling to be set to work. |
| --disable-export | Disable exporting metrics in api/v1/metric-export |
| --enable-swagger-ui | Enables swagger ui on the apiserver at /swagger-ui |
| --heapster-port int | port used by the Heapster-specific APIs (default 8082) |
| --historical-source string | which source type to use for the historical API (should be exactly the same as one of the sink URIs), or empty to disable the historical API |
| --label-seperator string | seperator used for joining labels (default ",") |
| --listen-ip string | IP to listen on, defaults to all IPs |
| --log-backtrace-at traceLocation | when logging hits line file:N, emit a stack trace (default :0) |
| --log-dir string | If non-empty, write log files in this directory |
| --log-flush-frequency duration | Maximum number of seconds between log flushes (default 5s) |
| --logtostderr | log to standard error instead of files (default true) |
| --max-procs int | max number of CPUs that can be used simultaneously. Less than 1 for default (number of cores) |
| --metric-resolution duration | The resolution at which heapster will retain metrics. (default 1m0s) |
| --profiling | Enable profiling via web interface host:port/debug/pprof/ (default true) |
| --requestheader-allowed-names stringSlice | List of client certificate common names to allow to provide usernames in headers specified by --requestheader-username-headers. If empty, any client certificate validated by the authorities in --requestheader-client-ca-file is allowed. |
| --requestheader-client-ca-file string | Root certificate bundle to use to verify client certificates on incoming requests before trusting usernames in headers specified by --requestheader-username-headers |
| --requestheader-extra-headers-prefix stringSlice | List of request header prefixes to inspect. X-Remote-Extra- is suggested. (default [x-remote-extra-]) |
| --requestheader-group-headers stringSlice | List of request headers to inspect for groups. X-Remote-Group is suggested. (default [x-remote-group]) |
| --requestheader-username-headers stringSlice | List of request headers to inspect for usernames. X-Remote-User is common. (default [x-remote-user]) |
| --secure-port int | The port on which to serve HTTPS with authentication and authorization. If 0, don't serve HTTPS at all. (default 6443) |
| --sink *flags.Uris | external sink(s) that receive data (default []) |
| --source *flags.Uris | source(s) to watch (default []) |
| --stderrthreshold severity | logs at or above this threshold go to stderr (default 2) |
| --tls-ca-file string | If set, this certificate authority will used for secure access from Admission Controllers. This must be a valid PEM-encoded CA bundle. Altneratively, the certificate authority can be appended to the certificate provided by --tls-cert-file. |
| --tls-cert string | file containing TLS certificate |
| --tls-cert-file string | File containing the default x509 Certificate for HTTPS. (CA cert, if any, concatenated after server cert). If HTTPS serving is enabled, and --tls-cert-file and --tls-private-key-file are not provided, a self-signed certificate and key are generated for the public address and saved to /var/run/kubernetes. |
| --tls-client-ca string | file containing TLS client CA for client cert validation |
| --tls-key string | file containing TLS key |
| --tls-private-key-file string | File containing the default x509 private key matching --tls-cert-file. |
| --tls-sni-cert-key namedCertKey | A pair of x509 certificate and private key file paths, optionally suffixed with a list of domain patterns which are fully qualified domain names, possibly with prefixed wildcard segments. If no domain patterns are provided, the names of the certificate are extracted. Non-wildcard matches trump over wildcard matches, explicit domain patterns trump over extracted names. For multiple key/certificate pairs, use the --tls-sni-cert-key multiple times. Examples: "example.key,example.crt" or "*.foo.com,foo.com:foo.key,foo.crt". (default []) |
| --v Level | log level for V logs |
| --version | print version info and exit |
| --vmodule moduleSpec | comma-separated list of pattern=N settings for file-filtered logging |
**Version**
version: v1.4.0
commit: 546ab66f
### API使用
Heapster提供RESTful API接口,下面以獲取`spark-cluster` namespace的memory usage為例講解Heapster API的使用。
**構造URL地址**
https://172.20.0.113:6443/api/v1/proxy/namespaces/kube-system/services/heapster/api/v1/model/namespaces/spark-cluster/metrics/memory/usage?start=2017-10-16T09:14:00Z&end=2017-10-16T09:16:00Z
**結果**
訪問該地址獲取的結果是這樣的:
```json
{
"metrics": [
{
"timestamp": "2017-10-16T09:14:00Z",
"value": 322592768
},
{
"timestamp": "2017-10-16T09:15:00Z",
"value": 322592768
},
{
"timestamp": "2017-10-16T09:16:00Z",
"value": 322592768
}
],
"latestTimestamp": "2017-10-16T09:16:00Z"
}
```
注意:Heapster中查詢的所有值都是以最小單位為單位,比如CPU為1milicore,內存為B。
**第一部分:Heapster API地址**
`https://172.20.0.113:6443/api/v1/proxy/namespaces/kube-system/services/heapster/`
可以使用下面的命令獲取:
```bash
$ kubectl cluster-info
Heapster is running at https://172.20.0.113:6443/api/v1/proxy/namespaces/kube-system/services/heapster
...
```
**第二部分:Heapster API參數**
`/api/v1/model/namespaces/spark-cluster/metrics/memory/usage`
表示查詢的是`spark-cluster` namespace中的`memory/usage`的metrics。
**第三部分:時間片**
`?start=2017-10-16T09:14:00Z&end=2017-10-16T09:16:00Z`
查詢參數為時間片:包括start和end。使用`RFC-3339`時間格式,在Linux系統中可以這樣獲取:
```bash
$ date --rfc-3339="seconds"
2017-10-16 17:23:20+08:00
```
該時間中的空格替換成T,最后的`+08:00`替換成Z代表時區。可以只指定start時間,end時間自動設置為當前時間。
## 參考
- [kubernetes metrics](https://github.com/kubernetes/metrics)
- [Heapster metric model](https://github.com/kubernetes/heapster/blob/master/docs/model.md)
- [Heapster storage schema](https://github.com/kubernetes/heapster/blob/master/docs/storage-schema.md)
- 序言
- 云原生
- 云原生(Cloud Native)的定義
- CNCF - 云原生計算基金會簡介
- CNCF章程
- 云原生的設計哲學
- Play with Kubernetes
- 快速部署一個云原生本地實驗環境
- Kubernetes與云原生應用概覽
- 云原生應用之路——從Kubernetes到Cloud Native
- 云原生編程語言
- 云原生編程語言Ballerina
- 云原生編程語言Pulumi
- 云原生的未來
- Kubernetes架構
- 設計理念
- Etcd解析
- 開放接口
- CRI - Container Runtime Interface(容器運行時接口)
- CNI - Container Network Interface(容器網絡接口)
- CSI - Container Storage Interface(容器存儲接口)
- Kubernetes中的網絡
- Kubernetes中的網絡解析——以flannel為例
- Kubernetes中的網絡解析——以calico為例
- 具備API感知的網絡和安全性管理開源軟件Cilium
- Cilium架構設計與概念解析
- 資源對象與基本概念解析
- Pod狀態與生命周期管理
- Pod概覽
- Pod解析
- Init容器
- Pause容器
- Pod安全策略
- Pod的生命周期
- Pod Hook
- Pod Preset
- Pod中斷與PDB(Pod中斷預算)
- 集群資源管理
- Node
- Namespace
- Label
- Annotation
- Taint和Toleration(污點和容忍)
- 垃圾收集
- 控制器
- Deployment
- StatefulSet
- DaemonSet
- ReplicationController和ReplicaSet
- Job
- CronJob
- Horizontal Pod Autoscaling
- 自定義指標HPA
- 準入控制器(Admission Controller)
- 服務發現
- Service
- Ingress
- Traefik Ingress Controller
- 身份與權限控制
- ServiceAccount
- RBAC——基于角色的訪問控制
- NetworkPolicy
- 存儲
- Secret
- ConfigMap
- ConfigMap的熱更新
- Volume
- Persistent Volume(持久化卷)
- Storage Class
- 本地持久化存儲
- 集群擴展
- 使用自定義資源擴展API
- 使用CRD擴展Kubernetes API
- Aggregated API Server
- APIService
- Service Catalog
- 資源調度
- QoS(服務質量等級)
- 用戶指南
- 資源對象配置
- 配置Pod的liveness和readiness探針
- 配置Pod的Service Account
- Secret配置
- 管理namespace中的資源配額
- 命令使用
- Docker用戶過度到kubectl命令行指南
- kubectl命令概覽
- kubectl命令技巧大全
- 使用etcdctl訪問kubernetes數據
- 集群安全性管理
- 管理集群中的TLS
- kubelet的認證授權
- TLS bootstrap
- 創建用戶認證授權的kubeconfig文件
- IP偽裝代理
- 使用kubeconfig或token進行用戶身份認證
- Kubernetes中的用戶與身份認證授權
- Kubernetes集群安全性配置最佳實踐
- 訪問Kubernetes集群
- 訪問集群
- 使用kubeconfig文件配置跨集群認證
- 通過端口轉發訪問集群中的應用程序
- 使用service訪問群集中的應用程序
- 從外部訪問Kubernetes中的Pod
- Cabin - Kubernetes手機客戶端
- Kubernetic - Kubernetes桌面客戶端
- Kubernator - 更底層的Kubernetes UI
- 在Kubernetes中開發部署應用
- 適用于kubernetes的應用開發部署流程
- 遷移傳統應用到Kubernetes中——以Hadoop YARN為例
- 最佳實踐概覽
- 在CentOS上部署Kubernetes集群
- 創建TLS證書和秘鑰
- 創建kubeconfig文件
- 創建高可用etcd集群
- 安裝kubectl命令行工具
- 部署master節點
- 安裝flannel網絡插件
- 部署node節點
- 安裝kubedns插件
- 安裝dashboard插件
- 安裝heapster插件
- 安裝EFK插件
- 生產級的Kubernetes簡化管理工具kubeadm
- 使用kubeadm在Ubuntu Server 16.04上快速構建測試集群
- 服務發現與負載均衡
- 安裝Traefik ingress
- 分布式負載測試
- 網絡和集群性能測試
- 邊緣節點配置
- 安裝Nginx ingress
- 安裝配置DNS
- 安裝配置Kube-dns
- 安裝配置CoreDNS
- 運維管理
- Master節點高可用
- 服務滾動升級
- 應用日志收集
- 配置最佳實踐
- 集群及應用監控
- 數據持久化問題
- 管理容器的計算資源
- 集群聯邦
- 存儲管理
- GlusterFS
- 使用GlusterFS做持久化存儲
- 使用Heketi作為Kubernetes的持久存儲GlusterFS的external provisioner
- 在OpenShift中使用GlusterFS做持久化存儲
- GlusterD-2.0
- Ceph
- 用Helm托管安裝Ceph集群并提供后端存儲
- 使用Ceph做持久化存儲
- 使用rbd-provisioner提供rbd持久化存儲
- OpenEBS
- 使用OpenEBS做持久化存儲
- Rook
- NFS
- 利用NFS動態提供Kubernetes后端存儲卷
- 集群與應用監控
- Heapster
- 使用Heapster獲取集群和對象的metric數據
- Prometheus
- 使用Prometheus監控kubernetes集群
- Prometheus查詢語言PromQL使用說明
- 使用Vistio監控Istio服務網格中的流量
- 分布式跟蹤
- OpenTracing
- 服務編排管理
- 使用Helm管理Kubernetes應用
- 構建私有Chart倉庫
- 持續集成與發布
- 使用Jenkins進行持續集成與發布
- 使用Drone進行持續集成與發布
- 更新與升級
- 手動升級Kubernetes集群
- 升級dashboard
- 領域應用概覽
- 微服務架構
- 微服務中的服務發現
- 使用Java構建微服務并發布到Kubernetes平臺
- Spring Boot快速開始指南
- Service Mesh 服務網格
- 企業級服務網格架構
- Service Mesh基礎
- Service Mesh技術對比
- 采納和演進
- 定制和集成
- 總結
- Istio
- 安裝并試用Istio service mesh
- 配置請求的路由規則
- 安裝和拓展Istio service mesh
- 集成虛擬機
- Istio中sidecar的注入規范及示例
- 如何參與Istio社區及注意事項
- Istio教程
- Istio免費學習資源匯總
- 深入理解Istio Service Mesh中的Envoy Sidecar注入與流量劫持
- 深入理解Istio Service Mesh中的Envoy Sidecar代理的路由轉發
- Linkerd
- Linkerd 使用指南
- Conduit
- Condiut概覽
- 安裝Conduit
- Envoy
- Envoy的架構與基本術語
- Envoy作為前端代理
- Envoy mesh教程
- SOFAMesh
- SOFAMesh中的Dubbo on x-protocol
- SOFAMosn
- 使用 SOFAMosn 構建 SOFAMesh
- 大數據
- Spark standalone on Kubernetes
- 運行支持Kubernetes原生調度的Spark程序
- Serverless架構
- 理解Serverless
- FaaS-函數即服務
- OpenFaaS快速入門指南
- 邊緣計算
- 人工智能