Hyperledger Fabric 1.4 特性調(diào)研之Operations Service(二)

Operations Service提供監(jiān)控管理服務(wù),主要包括:

  • 日志等級(jí)管理(/logspec):動(dòng)態(tài)獲取和設(shè)置peer和orderer的日志等級(jí)。
  • 健康檢查(/healthz ):檢查peer和orderer是否存活以及健康狀態(tài)。
  • 運(yùn)維信息監(jiān)控(/metrics ):提供運(yùn)維指標(biāo)數(shù)據(jù),支持Prometheus和StatsD統(tǒng)計(jì)數(shù)據(jù)。

適用場(chǎng)景

  • 日志等級(jí)管理:適用于聯(lián)盟鏈管理人員或者開(kāi)發(fā)人員對(duì)Fabric的日志等級(jí)進(jìn)行實(shí)時(shí)變更以定位問(wèn)題。
  • 健康檢查:可以獲知節(jié)點(diǎn)的健康狀況,兼容Kubernetes的容器檢測(cè)探針liveness probe等。
  • 運(yùn)維信息監(jiān)控:主要對(duì)外提供運(yùn)維信息數(shù)據(jù),適用于聯(lián)盟鏈管理人員對(duì)Fabric的運(yùn)行情況進(jìn)行實(shí)時(shí)監(jiān)控;可以支持第三方運(yùn)維工具的集成,對(duì)Fabric運(yùn)行狀況和性能進(jìn)行分析。

技術(shù)實(shí)現(xiàn)

Operation Service在peer或orderer啟動(dòng)的過(guò)程中,創(chuàng)建了一個(gè)http服務(wù)器處理日志等級(jí)管理、健康檢查和運(yùn)維信息獲取三類(lèi)請(qǐng)求。

1)日志等級(jí)管理

日志管理主體功能模塊位于common/flogging,主要基于高性能的zap日志庫(kù),對(duì)zapcore進(jìn)行了定制開(kāi)發(fā)。通過(guò)重寫(xiě)zapcore的Check函數(shù)(common/flogging/core.go,在Write之前調(diào)用),對(duì)將要寫(xiě)入的日志進(jìn)行等級(jí)判斷,實(shí)現(xiàn)日志等級(jí)的實(shí)時(shí)變更。

2)健康檢查

健康檢查通過(guò)查詢(xún)Docker服務(wù)的狀態(tài)來(lái)確定peer和orderer是否仍處于健康狀態(tài)。只要結(jié)構(gòu)體實(shí)現(xiàn)HealthCheck(context.Context) error(位于github.com/hyperledger/fabric-lib-go/healthz/checker.go)的健康檢查接口,并且通過(guò)RegisterChecker函數(shù)進(jìn)行注冊(cè),則可以實(shí)現(xiàn)對(duì)應(yīng)功能的健康檢查。官網(wǎng)上說(shuō)暫時(shí)只支持對(duì)docker容器的檢查,目前本文調(diào)研時(shí)使用的版本(commitID為334a66f17e91666d583ec1e5720419de38153ebd)可以支持如下檢查:

  • peer:couchdb是否可以正常連接;docker容器是否可以連接;
  • orderer:是否可以向kafka發(fā)送消息。

3)運(yùn)維信息監(jiān)控

運(yùn)維信息監(jiān)控包括Prometheus和StatsD兩種第三方組件的接入:

A. Prometheus

Prometheus是開(kāi)源的監(jiān)控框架。Fabric支持Prometheus接入,主要使用go-kit庫(kù)和Prometheus庫(kù)。
Prometheus記載的時(shí)序數(shù)據(jù)分為四種:Counter, Gauge, Histogram, Summary。Fabric僅使用了前三種,這三種類(lèi)型的簡(jiǎn)介如下:

  • Counter:?jiǎn)握{(diào)遞增的計(jì)數(shù)器,常用于記錄服務(wù)請(qǐng)求總量、任務(wù)完成數(shù)目、錯(cuò)誤總數(shù)等。
  • Gauge:一個(gè)單獨(dú)的數(shù)值,可以增加或減少,常用于記錄內(nèi)存使用率、磁盤(pán)使用率、并發(fā)請(qǐng)求數(shù)等。
  • Histogram:直方圖采樣數(shù)據(jù),對(duì)一段時(shí)間范圍內(nèi)的數(shù)據(jù)進(jìn)行采樣,按照指定區(qū)間和總數(shù)進(jìn)行統(tǒng)計(jì),會(huì)生成三個(gè)記錄數(shù)據(jù)<basename>_bucket,<basename>_count和<basename>_sum。其中bucket形式為<basename>_bucket{le="<upper inclusive bound>"};count是bucket數(shù)目,即<basename>_bucket{le="+Inf"}的值;sum是總數(shù)。
    Fabric在需要記錄信息的模塊,創(chuàng)建相應(yīng)的結(jié)構(gòu)體,比如peer endorser模塊的EndorserMetrics:
var (
    proposalDurationHistogramOpts = metrics.HistogramOpts{
        Namespace:    "endorser",
        Name:         "propsal_duration",
        Help:         "The time to complete a proposal.",
        LabelNames:   []string{"channel", "chaincode", "success"},
        StatsdFormat: "%{#fqname}.%{channel}.%{chaincode}.%{success}",
    }

    receivedProposalsCounterOpts = metrics.CounterOpts{
        Namespace: "endorser",
        Name:      "proposals_received",
        Help:      "The number of proposals received.",
    }

    successfulProposalsCounterOpts = metrics.CounterOpts{
        Namespace: "endorser",
        Name:      "successful_proposals",
        Help:      "The number of successful proposals.",
    }
    ……
)
func NewEndorserMetrics(p metrics.Provider) *EndorserMetrics {
    return &EndorserMetrics{
        ProposalDuration:         p.NewHistogram(proposalDurationHistogramOpts),
        ProposalsReceived:        p.NewCounter(receivedProposalsCounterOpts),
        SuccessfulProposals:      p.NewCounter(successfulProposalsCounterOpts),
        ProposalValidationFailed: p.NewCounter(proposalValidationFailureCounterOpts),
        ProposalACLCheckFailed:   p.NewCounter(proposalChannelACLFailureOpts),
        InitFailed:               p.NewCounter(initFailureCounterOpts),
        EndorsementsFailed:       p.NewCounter(endorsementFailureCounterOpts),
        DuplicateTxsFailure:      p.NewCounter(duplicateTxsFailureCounterOpts),
    }
}

Fabric將需要記錄的信息寫(xiě)入相應(yīng)的指標(biāo)記錄器中,代碼如下:

// ProcessProposal process the Proposal
func (e *Endorser) ProcessProposal(ctx context.Context, signedProp *pb.SignedProposal) (*pb.ProposalResponse, error) {
    // start time for computing elapsed time metric for successfully endorsed proposals
    startTime := time.Now()
    // 請(qǐng)求接收數(shù)目加1
    e.Metrics.ProposalsReceived.Add(1)
……
            meterLabels := []string{
                "channel", chainID,
                "chaincode", hdrExt.ChaincodeId.Name + ":" + hdrExt.ChaincodeId.Version,
                "success", strconv.FormatBool(success),
            }
            // 添加請(qǐng)求時(shí)長(zhǎng)值
            e.Metrics.ProposalDuration.With(meterLabels...).Observe(time.Since(startTime).Seconds())

目前Fabric統(tǒng)計(jì)的指標(biāo)具體參見(jiàn):https://hyperledger-fabric.readthedocs.io/en/release-1.4/metrics_reference.html

B. StatsD

StatsD是一個(gè)簡(jiǎn)單的網(wǎng)絡(luò)守護(hù)進(jìn)程,基于 Node.js,通過(guò) UDP 或者 TCP 方式偵聽(tīng)各種統(tǒng)計(jì)信息,并發(fā)送聚合信息到后端服務(wù),如 Graphite。Fabric支持StatsD接入,主要使用go-kit庫(kù),記載的時(shí)序數(shù)據(jù)也是分為Counter, Gauge, Histogram(實(shí)際上是StatsD中的Timer)三種,使用邏輯和Prometheus類(lèi)似,但是讀取數(shù)據(jù)的方式上看,Prometheus是從Fabric拉取數(shù)據(jù),而StatsD是Fabric向StatsD推送數(shù)據(jù)。

實(shí)際操作

Operations Service可以配置監(jiān)聽(tīng)地址和TLS,配置內(nèi)容如下:

operations:    # host and port for the operations server    listenAddress: 127.0.0.1:9443    # TLS configuration for the operations endpoint    tls:        # TLS enabled        enabled: false        # path to PEM encoded server certificate for the operations server        cert:            file:        # path to PEM encoded server key for the operations server        key:            file:        # most operations service endpoints require client authentication when TLS        # is enabled. clientAuthRequired requires client certificate authentication        # at the TLS layer to access all resources.        clientAuthRequired: false        # paths to PEM encoded ca certificates to trust for client authentication        clientRootCAs:            files: []

1)日志等級(jí)管理

查看日志等級(jí)可以使用如下命令:

curl http://127.0.0.1:9443/logspec

其中地址和端口為peer或orderer映射出的地址和端口(默認(rèn)端口是9443),獲得信息示例如下:

{"spec":"info"}

設(shè)置日志等級(jí)可以使用如下命令:

curl -i -X PUT -H "Content-Type: application/json" -d "{\"spec\":\"debug\"}" http://127.0.0.1:9443/logspec

設(shè)置以后可以查看log,實(shí)時(shí)生效。
設(shè)置日志等級(jí)時(shí)傳入?yún)?shù)的格式如下,可以支持多模塊不同日志等級(jí)。

[<logger>[,<logger>...]=]<level>[:[<logger>[,<logger>...]=]<level>...]

目前,不同模塊設(shè)置不同日志等級(jí)的情況,只有官網(wǎng)提供的修改合約日志等級(jí)的參數(shù),如下所示:

{"spec":"chaincode=debug:info"}

2)健康檢查

查看健康情況可以使用如下命令:

curl http://127.0.0.1:9443/healthz

其中地址和端口為peer或orderer映射出的地址和端口(默認(rèn)端口是9443),正常情況下獲得信息示例如下:

{"status":"OK","time":"2019-06-04T09:31:39.2034071Z"}

目前peer可以檢查docker容器和couchdb是否可以正常連接;orderer可以檢查kafka是否可以向其發(fā)送消息。如果peer的couchdb容器宕機(jī)了,獲得信息如下:

{
    "status": "Service Unavailable",
    "time": "2019-06-05T03:33:58.4322205Z",
    "failed_checks": [
        {
            "component": "couchdb",
            "reason": "failed to connect to couch db [Head http://couchdb0:5984: dial tcp: lookup couchdb0 on 127.0.0.11:53: no such host]"
        }
    ]
}

3)運(yùn)維信息監(jiān)控

Prometheus

A. 安裝Prometheus

首先,從官網(wǎng)(https://prometheus.io/download/)下載Prometheus的軟件包,直接解壓到相應(yīng)目錄即可,命令如下:

tar xvfz prometheus-*.tar.gz
cd prometheus-*

B. 修改Prometheus相關(guān)配置文件

【此處使用fabric-sample中提供的first-network示例】
修改Fabric的docker-compose.yaml文件,在peer的環(huán)境變量中添加:

- CORE_METRICS_PROVIDER=prometheus

在orderer的環(huán)境變量中添加:

- CORE_METRICS_PROVIDER=prometheus

需要修改prometheus.yml文件,添加Fabric環(huán)境中的peer和orderer參數(shù),具體參照如下內(nèi)容:

# my global config
global:
  scrape_interval:     15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).

  # Attach these labels to any time series or alerts when communicating with
  # external systems (federation, remote storage, Alertmanager).
  external_labels:
    monitor: 'codelab-monitor'

# Alertmanager configuration
alerting:
  alertmanagers:
  - static_configs:
    - targets:
      # - alertmanager:9093

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  # - "second_rules.yml"

# A scrape configuration containing exactly one endpoint to scrape:
scrape_configs:
  - job_name:       'fabric'

    # Override the global default and scrape targets from this job every 5 seconds.
    scrape_interval: 5s

    static_configs:
      - targets: ['localhost:9443']
        labels:
          group: 'peer0_org1'

      - targets: ['localhost:10443']
        labels:
          group: 'peer1_org1'

      - targets: ['localhost:11443']
        labels:
          group: 'peer0_org2'

      - targets: ['localhost:12443']
        labels:
          group: 'peer1_org2'

      - targets: ['localhost:8443']
        labels:
          group: 'orderer'

主要關(guān)注scrape_configs,其中添加了名字為fabric的job,其中static_configs中添加需要監(jiān)控的節(jié)點(diǎn),targets中填寫(xiě)operations服務(wù)的地址和監(jiān)聽(tīng)端口(默認(rèn)是9443),labels.group中填寫(xiě)分組的名稱(chēng)。以上示例把peer分成不同的組,也可以根據(jù)組織合并為一個(gè)組,如下所示:

static_configs:
      - targets: ['localhost:9443', 'localhost:10443']
        labels:
          group: 'peers_org1'

      - targets: ['localhost:11443', 'localhost:12443']
        labels:
          group: 'peers_org2'

C. 啟動(dòng)Prometheus

首先啟動(dòng)Fabric環(huán)境,待Fabric環(huán)境啟動(dòng)完成后,運(yùn)行如下命令啟動(dòng)Prometheus:

./prometheus --config.file=prometheus.yml

使用瀏覽器訪問(wèn)http://localhost:9090即可查看Prometheus監(jiān)控面板,可以選擇指標(biāo)或者寫(xiě)入查詢(xún)語(yǔ)句,點(diǎn)擊execute查看圖表,如下圖所示:

image.png

D. 可以配置Grafana可視化工具

參照官網(wǎng)說(shuō)明(https://grafana.com/grafana/download)下載Grafana軟件后,使用瀏覽器訪問(wèn)http://localhost:3000(默認(rèn)用戶(hù)名admin,密碼admin),配置數(shù)據(jù)源為Prometheus,即可定制可視化監(jiān)控界面。具體流程可參照https://prometheus.io/docs/visualization/grafana/。界面如下圖所示:

image.png

StatsD

A. 下載StatsD + Graphite + Grafana的docker鏡像

Graphite主要由監(jiān)聽(tīng)器carbon,時(shí)序數(shù)據(jù)庫(kù)whisper和圖形展示django-webapp三個(gè)組件構(gòu)成。一般使用StatsD + Graphite + Grafana這三個(gè)框架搭建運(yùn)維可視化界面。該鏡像集成了StatsD + Graphite + Grafana 4 + Kamon(https://hub.docker.com/r/kamon/grafana_graphite)。使用如下命令拉取鏡像:

docker pull kamon/grafana_graphite

B. 啟動(dòng)docker容器

使用如下命令啟動(dòng)容器:

docker run -d\
 --name graphite\
 --restart=always\
 -p 80:80\
 -p 81:81\
 -p 2003:2003\
 -p 8125:8125/udp\
 -p 8126:8126\
 kamon/grafana_graphite

C. 修改Fabric配置文件

【此處使用fabric-sample中提供的first-network示例】
修改Fabric的docker-compose.yaml文件,在peer的環(huán)境變量中添加:

- CORE_METRICS_PROVIDER= statsd
- CORE_METRICS_STATSD_PREFIX=peer0_org1
- CORE_METRICS_STATSD_ADDRESS=192.168.101.76:8125

在orderer的環(huán)境變量中添加:

- ORDERER_METRICS_PROVIDER=statsd
- ORDERER_METRICS_STATSD_PREFIX=orderer
- ORDERER_METRICS_STATSD_ADDRESS=192.168.101.76:8125

如上所示,需要配置prefix用于區(qū)分節(jié)點(diǎn),配置address是StatsD的地址和端口,即docker容器映射的地址和端口。

D. 查看界面

訪問(wèn)http://localhost:81可以查看Graphite界面,如下:

image.png

訪問(wèn)http://localhost可以查看Grafana界面,具體配置方法見(jiàn)前面Prometheus的描述。界面如下:

image.png

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容