天天看點

Consul 使用手冊(感覺比較全了)

<!--一個部落客專欄付費入口結束-->
        <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-4a3473df85.css">
                                    <div id="content_views" class="markdown_views">
                <!-- flowchart 箭頭圖示 勿删 -->
                <svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
                    <path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path>
                </svg>
                                        <h1 id="使用consul">使用consul</h1>
           

介紹

Consul包含多個元件,但是作為一個整體,為你的基礎設施提供服務發現和服務配置的工具.他提供以下關鍵特性:

服務發現 Consul的用戶端可用提供一個服務,比如 api 或者mysql ,另外一些用戶端可用使用Consul去發現一個指定服務的提供者.通過DNS或者HTTP應用程式可用很容易的找到他所依賴的服務.

健康檢查 Consul用戶端可用提供任意數量的健康檢查,指定一個服務(比如:webserver是否傳回了200 OK 狀态碼)或者使用本地節點(比如:記憶體使用是否大于90%). 這個資訊可由operator用來監視叢集的健康.被服務發現元件用來避免将流量發送到不健康的主機.

Key/Value存儲 應用程式可用根據自己的需要使用Consul的層級的Key/Value存儲.比如動态配置,功能标記,協調,領袖選舉等等,簡單的HTTP API讓他更易于使用.

多資料中心 Consul支援開箱即用的多資料中心.這意味着使用者不需要擔心需要建立額外的抽象層讓業務擴充到多個區域.

Consul面向DevOps和應用開發者友好.是他适合現代的彈性的基礎設施.

Consul 使用手冊(感覺比較全了)

基礎架構

Consul是一個分布式高可用的系統. 這節将包含一些基礎,我們忽略掉一些細節這樣你可以快速了解Consul是如何工作的.如果要了解更多細節,請參考深入的架構描述.

每個提供服務給Consul的階段都運作了一個Consul agent . 發現服務或者設定和擷取 key/value存儲的資料不是必須運作agent.這個agent是負責對節點自身和節點上的服務進行健康檢查的.

Agent與一個和多個Consul Server 進行互動.Consul Server 用于存放和複制資料.server自行選舉一個領袖.雖然Consul可以運作在一台server , 但是建議使用3到5台來避免失敗情況下資料的丢失.每個資料中心建議配置一個server叢集.

你基礎設施中需要發現其他服務的元件可以查詢任何一個Consul 的server或者 agent.Agent會自動轉發請求到server .

每個資料中運作了一個Consul server叢集.當一個跨資料中心的服務發現和配置請求建立時.本地Consul Server轉發請求到遠端的資料中心并傳回結果.

更多介紹檢視官網點選前往

安裝Consul

安裝Consul,找到适合你系統的包下載下傳他.Consul打包為一個’Zip’檔案.前往下載下傳

下載下傳後解開壓縮包.拷貝Consul到你的PATH路徑中,在Unix系統中

~/bin

/usr/local/bin

是通常的安裝目錄.根據你是想為單個使用者安裝還是給整個系統安裝來選擇.在Windows系統中有可以安裝到

%PATH%

的路徑中.

驗證安裝

完成安裝後,通過打開一個新終端視窗檢查

consul

安裝是否成功.通過執行

consul

你應該看到類似下面的輸出

[root@dhcp-10-201-102-248 ~]# consul
usage: consul [--version] [--help] <command> [<args>]
Available commands are:
    agent          Runs a Consul agent
    configtest     Validate config file
    event          Fire a new event
    exec           Executes a command on Consul nodes
    force-leave    Forces a member of the cluster to enter the "left" state
    info           Provides debugging information for operators
    join           Tell Consul agent to join cluster
    keygen         Generates a new encryption key
    keyring        Manages gossip layer encryption keys
    kv             Interact with the key-value store
    leave          Gracefully leaves the Consul cluster and shuts down
    lock           Execute a command holding a lock
    maint          Controls node or service maintenance mode
    members        Lists the members of a Consul cluster
    monitor        Stream logs from a Consul agent
    operator       Provides cluster-level tools for Consul operators
    reload         Triggers the agent to reload configuration files
    rtt            Estimates network round trip time between nodes
    snapshot       Saves, restores and inspects snapshots of Consul server state
    version        Prints the Consul version
    watch          Watch for changes in Consul           

如果你得到一個

consul not be found

的錯誤,你的

PATH

可能沒有正确設定.請傳回檢查你的consul的安裝路徑是否包含在

PATH

中.

運作Agent

完成Consul的安裝後,必須運作agent. agent可以運作為

server

client

模式.每個資料中心至少必須擁有一台server . 建議在一個叢集中有3或者5個server.部署單一的server,在出現失敗時會不可避免的造成資料丢失.

其他的agent運作為client模式.一個client是一個非常輕量級的程序.用于注冊服務,運作健康檢查和轉發對server的查詢.agent必須在叢集中的每個主機上運作.

檢視啟動資料中心的細節請檢視這裡.

啟動 Consul Server

consul agent -server -bootstrap-expect 3 -data-dir /tmp/consul -node=s1 -bind=10.201.102.198 -ui-dir ./consul_ui/ -rejoin -config-dir=/etc/consul.d/ -client 0.0.0.0           

運作cosnul agent以

server

模式,

  • -server

    : 定義agent運作在server模式
  • -bootstrap-expect

    :在一個datacenter中期望提供的server節點數目,當該值提供的時候,consul一直等到達到指定sever數目的時候才會引導整個叢集,該标記不能和bootstrap共用
  • -bind

    :該位址用來在叢集内部的通訊,叢集内的所有節點到位址都必須是可達的,預設是0.0.0.0
  • -node

    :節點在叢集中的名稱,在一個叢集中必須是唯一的,預設是該節點的主機名
  • -ui-dir

    : 提供存放web ui資源的路徑,該目錄必須是可讀的
  • -rejoin

    :使consul忽略先前的離開,在再次啟動後仍舊嘗試加入叢集中。
  • -config-dir

    :配置檔案目錄,裡面所有以.json結尾的檔案都會被加載
  • -client

    :consul服務偵聽位址,這個位址提供HTTP、DNS、RPC等服務,預設是127.0.0.1是以不對外提供服務,如果你要對外提供服務改成0.0.0.0
[root@dhcp-10-201-102-198 consul]# consul agent -server -bootstrap-expect 1 -data-dir /tmp/consul -node=s1 -bind=10.201.102.198 -ui-dir ./consul_ui/ -rejoin -config-dir=/etc/consul.d/ -client 0.0.0.0
==> WARNING: Expect Mode enabled, expecting 3 servers
==> Starting Consul agent...
==> Starting Consul agent RPC...
==> Consul agent running!
           Version: 'v0.7.4'
           Node ID: '422ec677-74ef-8f29-2f22-01effeed6334'
         Node name: 's1'
        Datacenter: 'dc1'
            Server: true (bootstrap: false)
       Client Addr: 0.0.0.0 (HTTP: 8500, HTTPS: -1, DNS: 8600, RPC: 8400)
      Cluster Addr: 10.201.102.198 (LAN: 8301, WAN: 8302)
    Gossip encrypt: false, RPC-TLS: false, TLS-Incoming: false
             Atlas: <disabled>
==> Log data will now stream in as it occurs:
    2017/03/17 18:03:08 [INFO] raft: Restored from snapshot 139-352267-1489707086023
    2017/03/17 18:03:08 [INFO] raft: Initial configuration (index=6982): [{Suffrage:Voter ID:10.201.102.199:8300 Address:10.201.102.199:8300} {Suffrage:Voter ID:10.201.102.200:8300 Address:10.201.102.200:8300} {Suffrage:Voter ID:10.201.102.198:8300 Address:10.201.102.198:8300}]
    2017/03/17 18:03:08 [INFO] raft: Node at 10.201.102.198:8300 [Follower] entering Follower state (Leader: "")
    2017/03/17 18:03:08 [INFO] serf: EventMemberJoin: s1 10.201.102.198
    2017/03/17 18:03:08 [INFO] serf: Attempting re-join to previously known node: s2: 10.201.102.199:8301
    2017/03/17 18:03:08 [INFO] consul: Adding LAN server s1 (Addr: tcp/10.201.102.198:8300) (DC: dc1)
    2017/03/17 18:03:08 [INFO] consul: Raft data found, disabling bootstrap mode
    2017/03/17 18:03:08 [INFO] serf: EventMemberJoin: s2 10.201.102.199
    2017/03/17 18:03:08 [INFO] serf: EventMemberJoin: s3 10.201.102.200
    2017/03/17 18:03:08 [INFO] serf: Re-joined to previously known node: s2: 10.201.102.199:8301
    2017/03/17 18:03:08 [INFO] consul: Adding LAN server s2 (Addr: tcp/10.201.102.199:8300) (DC: dc1)
    2017/03/17 18:03:08 [INFO] consul: Adding LAN server s3 (Addr: tcp/10.201.102.200:8300) (DC: dc1)
    2017/03/17 18:03:08 [INFO] serf: EventMemberJoin: s1.dc1 10.201.102.198
    2017/03/17 18:03:08 [INFO] consul: Adding WAN server s1.dc1 (Addr: tcp/10.201.102.198:8300) (DC: dc1)
    2017/03/17 18:03:08 [WARN] serf: Failed to re-join any previously known node
    2017/03/17 18:03:14 [INFO] agent: Synced service 'consul'
    2017/03/17 18:03:14 [INFO] agent: Deregistered service 'consul01'
    2017/03/17 18:03:14 [INFO] agent: Deregistered service 'consul02'
    2017/03/17 18:03:14 [INFO] agent: Deregistered service 'consul03'           

檢視叢集成員

新開一個終端視窗運作

consul members

, 你可以看到Consul叢集的成員.

[root@dhcp-10-201-102-198 ~]# consul members
Node  Address              Status  Type    Build  Protocol  DC
s1    10.201.102.198:8301  alive   server  0.7.4  2         dc1
s2    10.201.102.199:8301  alive   server  0.7.4  2         dc1
s3    10.201.102.200:8301  alive   server  0.7.4  2         dc1           

啟動 Consul Client

consul agent -data-dir /tmp/consul -node=c1 -bind=10.201.102.248 -config-dir=/etc/consul.d/ -join 10.201.102.198           

運作cosnul agent以client模式,

-join

加入到已有的叢集中去。

[root@dhcp-10-201-102-248 ~]# consul agent -data-dir /tmp/consul -node=c1 -bind=10.201.102.248 -config-dir=/etc/consul.d/ -join 10.201.102.198
==> Starting Consul agent...
==> Starting Consul agent RPC...
==> Joining cluster...
    Join completed. Synced with 1 initial agents
==> Consul agent running!
           Version: 'v0.7.4'
           Node ID: '564dc0c7-7f4f-7402-a301-cebe7f024294'
         Node name: 'c1'
        Datacenter: 'dc1'
            Server: false (bootstrap: false)
       Client Addr: 127.0.0.1 (HTTP: 8500, HTTPS: -1, DNS: 8600, RPC: 8400)
      Cluster Addr: 10.201.102.248 (LAN: 8301, WAN: 8302)
    Gossip encrypt: false, RPC-TLS: false, TLS-Incoming: false
             Atlas: <disabled>
==> Log data will now stream in as it occurs:
    2017/03/17 15:35:16 [INFO] serf: EventMemberJoin: c1 10.201.102.248
    2017/03/17 15:35:16 [INFO] agent: (LAN) joining: [10.201.102.198]
    2017/03/17 15:35:16 [INFO] serf: EventMemberJoin: s2 10.201.102.199
    2017/03/17 15:35:16 [INFO] serf: EventMemberJoin: s3 10.201.102.200
    2017/03/17 15:35:16 [INFO] serf: EventMemberJoin: s1 10.201.102.198
    2017/03/17 15:35:16 [INFO] agent: (LAN) joined: 1 Err: <nil>
    2017/03/17 15:35:16 [INFO] consul: adding server s2 (Addr: tcp/10.201.102.199:8300) (DC: dc1)
    2017/03/17 15:35:16 [INFO] consul: adding server s3 (Addr: tcp/10.201.102.200:8300) (DC: dc1)
    2017/03/17 15:35:16 [INFO] consul: adding server s1 (Addr: tcp/10.201.102.198:8300) (DC: dc1)
    2017/03/17 15:35:16 [INFO] agent: Synced node info           

consul members

[root@dhcp-10-201-102-248 ~]# consul members
Node  Address              Status  Type    Build  Protocol  DC
c1    10.201.102.248:8301  alive   client  0.7.4  2         dc1
s1    10.201.102.198:8301  alive   server  0.7.4  2         dc1
s2    10.201.102.199:8301  alive   server  0.7.4  2         dc1
s3    10.201.102.200:8301  alive   server  0.7.4  2         dc1           

加入叢集

[root@dhcp-10-201-102-248 ~]# consul join 10.201.102.198
Node  Address              Status  Type    Build  Protocol  DC
c1    10.201.102.248:8301  alive   client  0.7.4  2         dc1
s1    10.201.102.198:8301  alive   server  0.7.4  2         dc1
s2    10.201.102.199:8301  alive   server  0.7.4  2         dc1
s3    10.201.102.200:8301  alive   server  0.7.4  2         dc1           

停止Agent

你可以使用

Ctrl-C

優雅的關閉Agent. 中斷Agent之後你可以看到他離開了叢集并關閉.

在退出中,Consul提醒其他叢集成員,這個節點離開了.如果你強行殺掉程序.叢集的其他成員應該能檢測到這個節點失效了.當一個成員離開,他的服務和檢測也會從目錄中移除.當一個成員失效了,他的健康狀況被簡單的标記為危險,但是不會從目錄中移除.Consul會自動嘗試對失效的節點進行重連.允許他從某些網絡條件下恢複過來.離開的節點則不會再繼續聯系.

此外,如果一個agent作為一個伺服器,一個優雅的離開是很重要的,可以避免引起潛在的可用性故障影響達成一緻性協定.

檢視這裡了解添加和移除server.

更新服務

服務定義可以通過配置檔案并發送

SIGHUP

給agent來進行更新.這樣你可以讓你在不關閉服務或者保持服務請求可用的情況下進行更新.

consul reload           

另外 HTTP API可以用來動态的添加,移除和修改服務.

注冊服務

搭建好conusl叢集後,使用者或者程式就能到consul中去查詢或者注冊服務。可以通過提供服務定義檔案或者調用HTTP API來注冊一個服務.

首先,為Consul配置建立一個目錄.Consul會載入配置檔案夾裡的所有配置檔案.在Unix系統中通常類似

/etc/consul.d

(.d 字尾意思是這個路徑包含了一組配置檔案).

mkdir /etc/consul.d           

然後,我們将編寫服務定義配置檔案.假設我們有一個名叫web的服務運作在 80端口.另外,我們将給他設定一個标簽.這樣我們可以使用他作為額外的查詢方式:

echo '{"service": {"name": "web", "tags": ["rails"], "port": 80}}' >/etc/consul.d/web.json           

現在重新開機agent , 設定配置目錄:

$ consul agent -server -bootstrap-expect 1 -data-dir /tmp/consul -node=s1 -bind=10.201.102.198 -rejoin -config-dir=/etc/consul.d/ -client 0.0.0.0
...
    [INFO] agent: Synced service 'web'
...           
  • -data-dir

    :提供一個目錄用來存放agent的狀态,所有的agent允許都需要該目錄,該目錄必須是穩定的,系統重新開機後都繼續存在

    你可能注意到了輸出了 “synced” 了 web這個服務.意思是這個agent從配置檔案中載入了服務定義,并且成功注冊到服務目錄.

如果你想注冊多個服務,你應該在Consul配置目錄建立多個服務定義檔案.

HTTP API注冊服務,curl指令或者postman 以

PUT

方式請求consul HTTP API更多細節點選檢視

curl -X PUT -d '{"Datacenter": "dc1", "Node": "c2", "Address": "10.155.0.106", "Service": {"Service": "MAC", "tags": ["lianglian", "Mac"], "Port": 22}}' http://127.0.0.1:8500/v1/catalog/register           

查詢服務

一旦agent啟動并且服務同步了.我們可以通過DNS或者HTTP的API來查詢服務.

DNS API

讓我們首先使用DNS API來查詢.在DNS API中,服務的DNS名字是

NAME.service.consul

. 雖然是可配置的,但預設的所有DNS名字會都在

consul

命名空間下.這個子域告訴Consul,我們在查詢服務,

NAME

則是服務的名稱.

對于我們上面注冊的Web服務.它的域名是

web.service.consul

:

[root@dhcp-10-201-102-198 ~]# dig @127.0.0.1 -p 8600 web.service.consul
; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6 <<>> @127.0.0.1 -p 8600 web.service.consul
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 39468
;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
;; WARNING: recursion requested but not available
;; QUESTION SECTION:
;web.service.consul.            IN      A
;; ANSWER SECTION:
web.service.consul.     0       IN      A       10.201.102.198
;; Query time: 0 msec
;; SERVER: 127.0.0.1#8600(127.0.0.1)
;; WHEN: Tue Mar 28 16:10:24 2017
;; MSG SIZE  rcvd: 52
[root@dhcp-10-201-102-198 ~]#           

如你所見,一個

A

記錄傳回了一個可用的服務所在的節點的IP位址.

A

記錄隻能設定為IP位址. 有也可用使用 DNS API 來接收包含 位址和端口的 SRV記錄:

[root@dhcp-10-201-102-198 ~]# dig @127.0.0.1 -p 8600 web.service.consul SRV
; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6 <<>> @127.0.0.1 -p 8600 web.service.consul SRV
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 13331
;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
;; WARNING: recursion requested but not available
;; QUESTION SECTION:
;web.service.consul.            IN      SRV
;; ANSWER SECTION:
web.service.consul.     0       IN      SRV     1 1 80 s1.node.dc1.consul.
;; ADDITIONAL SECTION:
s1.node.dc1.consul.     0       IN      A       10.201.102.198
;; Query time: 0 msec
;; SERVER: 127.0.0.1#8600(127.0.0.1)
;; WHEN: Tue Mar 28 16:10:56 2017
;; MSG SIZE  rcvd: 84
[root@dhcp-10-201-102-198 ~]#           

SRV

記錄告訴我們 web 這個服務運作于節點

dhcp-10-201-102-198

80

端口. DNS額外傳回了節點的A記錄.

最後,我們也可以用 DNS API 通過标簽來過濾服務.基于标簽的服務查詢格式為

TAG.NAME.service.consul

. 在下面的例子中,我們請求Consul傳回有

rails

标簽的

web

服務.我們成功擷取了我們注冊為這個标簽的服務:

[root@dhcp-10-201-102-198 ~]# dig @127.0.0.1 -p 8600 rails.web.service.consul SRV
; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6 <<>> @127.0.0.1 -p 8600 rails.web.service.consul SRV
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 37307
;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
;; WARNING: recursion requested but not available
;; QUESTION SECTION:
;rails.web.service.consul.      IN      SRV
;; ANSWER SECTION:
rails.web.service.consul. 0     IN      SRV     1 1 80 s1.node.dc1.consul.
;; ADDITIONAL SECTION:
s1.node.dc1.consul.     0       IN      A       10.201.102.198
;; Query time: 0 msec
;; SERVER: 127.0.0.1#8600(127.0.0.1)
;; WHEN: Tue Mar 28 16:11:45 2017
;; MSG SIZE  rcvd: 90
[root@dhcp-10-201-102-198 ~]#           

HTTP API

除了DNS API之外,HTTP API也可以用來進行服務查詢:

[root@dhcp-10-201-102-198 ~]# curl -s 127.0.0.1:8500/v1/catalog/service/web | python -m json.tool
[
    {
        "Address": "10.201.102.198",
        "CreateIndex": 492843,
        "ID": "422ec677-74ef-8f29-2f22-01effeed6334",
        "ModifyIndex": 492843,
        "Node": "s1",
        "NodeMeta": {},
        "ServiceAddress": "",
        "ServiceEnableTagOverride": false,
        "ServiceID": "web",
        "ServiceName": "web",
        "ServicePort": 80,
        "ServiceTags": [
            "rails"
        ],
        "TaggedAddresses": {
            "lan": "10.201.102.198",
            "wan": "10.201.102.198"
        }
    }
]           

目錄API給出所有節點提供的服務.稍後我們會像通常的那樣帶上健康檢查進行查詢.就像DNS内部處理的那樣.這是隻檢視健康的執行個體的查詢方法:

[root@dhcp-10-201-102-198 ~]# curl -s 127.0.0.1:8500/v1/catalog/service/web?passing | python -m json.tool
[
    {
        "Address": "10.201.102.198",
        "CreateIndex": 492843,
        "ID": "422ec677-74ef-8f29-2f22-01effeed6334",
        "ModifyIndex": 492843,
        "Node": "s1",
        "NodeMeta": {},
        "ServiceAddress": "",
        "ServiceEnableTagOverride": false,
        "ServiceID": "web",
        "ServiceName": "web",
        "ServicePort": 80,
        "ServiceTags": [
            "rails"
        ],
        "TaggedAddresses": {
            "lan": "10.201.102.198",
            "wan": "10.201.102.198"
        }
    }
]           

WEB管理界面

Consul同時提供了一個漂亮的功能齊全的WEB界面,開箱即用.界面可以用來檢視所有的節點,可以檢視健康檢查和他們的目前狀态.可以讀取和設定K/V 存儲的資料.UI自動支援多資料中心.點選前往下載下傳

Consul 使用手冊(感覺比較全了)

下載下傳完後上傳至伺服器,建議所有server角色都使用WebUI,。

consul agent -server -bootstrap-expect 1 -data-dir /tmp/consul -node=s1 -bind=10.201.102.198 -ui-dir ./consul_ui/ -rejoin -config-dir=/etc/consul.d/ -client 0.0.0.0           
  • -ui-dir

    : 提供存放web ui資源的路徑,指向該目錄必須是可讀的
  • -client

    :consul服務偵聽位址,這個位址提供HTTP、DNS、RPC等服務,預設是127.0.0.1是以不對外提供服務,如果你要對外提供服務改成0.0.0.0

    可通過http://10.201.102.198:8500通路WEB管理界面。

Consul 使用手冊(感覺比較全了)

健康檢查

我們現在看到Consul運作時如此簡單.添加節點和服務,查詢節點和服務.在這一節.我們将繼續添加健康檢查到節點和服務.健康檢查是服務發現的關鍵元件.預防使用到不健康的服務.

這一步建立在前一節的Consul叢集建立之上.目前你應該有一個包含多個節點的Consul叢集.

自定義檢查

和服務注冊類似,一個檢查可以通過檢查定義或HTTP API請求來注冊.

我們将使用和檢查定義來注冊檢查.和服務類似,因為這是建立檢查最常用的方式.

在第二個節點的配置目錄建立定義檔案:

/etc/consul.d/web.json           
{"service": {
    "name": "Faceid",
    "tags": ["extract", "verify", "compare", "idcard"],
    "address": "10.201.102.198",
    "port": 9000,
    "check": {
        "name": "ping",
        "script": "curl -s localhost:9000",
        "interval": "3s"
        }
    }
}           

or

/etc/consul.d/web.json           
{"service": {
    "name": "Faceid",
    "tags": ["extract", "verify", "compare", "idcard"],
    "address": "10.201.102.199",
    "port": 9000,
    "check": {
        "id": "api",
           "name": "HTTP API on port 9000",
        "http": "http://localhost:9000",
        "interval": "10s",
        "timeout": "1s"
        }
   }
}           

more

檢查健康狀态

我們能适應HTTP API來檢查他們.首先我們檢查有哪些失敗的檢查.使用這個指令(注意:這個指令可以運作在任何節點)

[root@dhcp-10-201-102-198 ~]# curl -s http://localhost:8500/v1/health/state/critical | python -m json.tool
[
    {
        "CheckID": "service:Faceid",
        "CreateIndex": 493398,
        "ModifyIndex": 493846,
        "Name": "Service 'Faceid' check",
        "Node": "s1",
        "Notes": "",
        "Output": "",
        "ServiceID": "Faceid",
        "ServiceName": "Faceid",
        "Status": "critical"
    }
]           

我們可以看到,隻有一個檢查我們的

web

服務在

critical

狀态

另外,我們可以嘗試用DNS查詢web服務,Consul将不會傳回結果.因為服務不健康.

[root@dhcp-10-201-102-198 ~]# dig @127.0.0.1 -p 8600 Faceid.service.consul SRV
; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6 <<>> @127.0.0.1 -p 8600 Faceid.service.consul SRV
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 40884
;; flags: qr aa rd; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 3
;; WARNING: recursion requested but not available
;; QUESTION SECTION:
;Faceid.service.consul.         IN      SRV
;; ANSWER SECTION:
Faceid.service.consul.  0       IN      SRV     1 1 9000 s3.node.dc1.consul.
Faceid.service.consul.  0       IN      SRV     1 1 9000 s1.node.dc1.consul.
Faceid.service.consul.  0       IN      SRV     1 1 9000 s2.node.dc1.consul.
;; ADDITIONAL SECTION:
s3.node.dc1.consul.     0       IN      A       10.201.102.200
s1.node.dc1.consul.     0       IN      A       10.201.102.198
s2.node.dc1.consul.     0       IN      A       10.201.102.199
;; Query time: 0 msec
;; SERVER: 127.0.0.1#8600(127.0.0.1)
;; WHEN: Tue Mar 28 18:20:15 2017
;; MSG SIZE  rcvd: 165           

K /V

除了提供服務發現和健康檢查的內建.Consul提供了一個易用的鍵/值存儲.這可以用來保持動态配置,協助服務協調,領袖選舉,做開發者可以想到的任何事情.

[root@dhcp-10-201-102-198 ~]# curl -v http://localhost:8500/v1/kv/?recurse
* About to connect() to localhost port 8500 (#0)
*   Trying ::1... 拒絕連接配接
*   Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 8500 (#0)
> GET /v1/kv/?recurse HTTP/1.1
> User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.21 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2
> Host: localhost:8500
> Accept: */*
>
< HTTP/1.1 404 Not Found
< X-Consul-Index: 1
< X-Consul-Knownleader: true
< X-Consul-Lastcontact: 0
< Date: Thu, 18 Aug 2016 08:21:39 GMT
< Content-Length: 0
< Content-Type: text/plain; charset=utf-8
<
* Connection #0 to host localhost left intact
* Closing connection #0           

因為沒有key是以我們得到了一個404響應.現在我們

PUT

一些示例的Key:

[root@dhcp-10-201-102-198 ~]# curl -X PUT -d 'test' http://localhost:8500/v1/kv/web/key1
[root@dhcp-10-201-102-198 ~]# curl -X PUT -d 'test' http://localhost:8500/v1/kv/web/key2?flags=42
[root@dhcp-10-201-102-198 ~]# curl -X PUT -d 'test'  http://localhost:8500/v1/kv/web/sub/key3           

我們建立了值為”test”的3個Key,注意傳回的值是經過了

base64

編碼的.用來支援非UTF8編碼字元.對Key

web/key2

我們設定了一個标志值為

42

.所有的key支援設定一個64位的整形數字标志.Consul内部不适用這個值.但是他可以被用戶端适用來做一些中繼資料.

完成設定後,我們發起了一個

GET

請求來接收多個key的值,使用

?recurse

參數.

[root@dhcp-10-201-102-198 ~]# curl -s http://localhost:8500/v1/kv/web/?recurse | python -m json.tool
[
    {
        "CreateIndex": 502660,
        "Flags": 0,
        "Key": "web/key1",
        "LockIndex": 0,
        "ModifyIndex": 502660,
        "Value": "dGVzdA=="
    },
    {
        "CreateIndex": 502663,
        "Flags": 42,
        "Key": "web/key2",
        "LockIndex": 0,
        "ModifyIndex": 502663,
        "Value": "dGVzdA=="
    },
    {
        "CreateIndex": 502665,
        "Flags": 0,
        "Key": "web/sub/key3",
        "LockIndex": 0,
        "ModifyIndex": 502665,
        "Value": "dGVzdA=="
    }
]           

你可以擷取單個的key

[root@dhcp-10-201-102-198 ~]# curl -s http://localhost:8500/v1/kv/web/key1 | python -m json.tool
[
    {
        "CreateIndex": 502660,
        "Flags": 0,
        "Key": "web/key1",
        "LockIndex": 0,
        "ModifyIndex": 502660,
        "Value": "dGVzdA=="
    }
]           

删除key也很簡單.通過

DELETE

動作來完成.我們可以通過指定完整路徑來删除一個單獨的key.或者我們可以使用

?recurse

遞歸的删除主路徑下所有key.

[root@dhcp-10-201-102-198 ~]# curl -X DELETE http://localhost:8500/v1/kv/web/sub?recurse
true           

可以通過發送相同的URL并提供不同的消息體的

PUT

請求去修改一個Key.另外,Consul提供一個檢查并設定的操作,實作原子的Key修改.通過

?cas=參數

加上

GET

中最近的

ModifyIndex

來達到. 例如我們想修改 “web/key1”:

curl -X PUT -d 'newval' http://localhost:8500/v1/kv/web/key1?cas=502660
true
curl -X PUT -d 'newval' http://localhost:8500/v1/kv/web/key1?cas=502660
false           

在這種情況下,第一次

CAS

更新成功因為

ModifyIndex

502660

.而第二次失敗是因為

ModifyIndex

在第一次更新後已經不是

502660

了 .

我們也可以使用

ModifyIndex

來等待key值的改變.例如我們想等待

key2

被修改:

[root@dhcp-10-201-102-198 ~]# curl "http://localhost:8500/v1/kv/web/key2"
[{"LockIndex":0,"Key":"web/key2","Flags":42,"Value":"dGVzdA==","CreateIndex":502663,"ModifyIndex":502663}]
[root@dhcp-10-201-102-198 ~]# curl "http://localhost:8500/v1/kv/web/key2?index=502663&wait=5s"
[{"LockIndex":0,"Key":"web/key2","Flags":42,"Value":"dGVzdA==","CreateIndex":502663,"ModifyIndex":502663}]           

通過提供

?index=

,我們請求等待key值有一個比

502663

更大的

ModifyIndex

.雖然

?wait=5s

參數限制了這個請求最多5秒,否則傳回目前的未改變的值. 這樣可以有效的等待key的改變.另外,這個功能可以用于等待一組key.直到其中的某個key有修改.

Conusl 指令行

見識了consul的強大,consul可以通過一個簡單的CLI來控制,consul隻有一個指令行應用,就是consul指令,consul指令可以包含agent、members等參數進行使用,這一篇來具體看看consul CLI的具體用法,consul -h即可看到consul cli所支援的參數,而每個參數裡面又支援其他參數,下面我們就來具體看看。

[root@dhcp-10-201-102-198 ~]# consul
usage: consul [--version] [--help] <command> [<args>]
Available commands are:
    agent          Runs a Consul agent  運作一個consul agent
    configtest     Validate config file
    event          Fire a new event
    exec           Executes a command on Consul nodes  在consul節點上執行一個指令
    force-leave    Forces a member of the cluster to enter the "left" state   強制節點成員在叢集中的狀态轉換到left狀态
    info           Provides debugging information for operators  提供操作的debug級别的資訊
    join           Tell Consul agent to join cluster   加入consul節點到叢集中
    keygen         Generates a new encryption key  生成一個新的加密key
    keyring        Manages gossip layer encryption keys
    kv             Interact with the key-value store
    leave          Gracefully leaves the Consul cluster and shuts down
    lock           Execute a command holding a lock
    maint          Controls node or service maintenance mode
    members        Lists the members of a Consul cluster    列出叢集中成員
    monitor        Stream logs from a Consul agent  列印consul節點的日志資訊
    operator       Provides cluster-level tools for Consul operators
    reload         Triggers the agent to reload configuration files   觸發節點重新加載配置檔案
    rtt            Estimates network round trip time between nodes
    snapshot       Saves, restores and inspects snapshots of Consul server state
    version        Prints the Consul version    列印consul的版本資訊
    watch          Watch for changes in Consul   監控consul的改變           

更詳細見官網

Agent

agent

指令是consul的核心,它運作agent來維護成員的重要資訊、運作檢查、服務宣布、查詢處理等等。

==> Usage: consul agent [options]
  Starts the Consul agent and runs until an interrupt is received. The
  agent represents a single node in a cluster.
Options:
  -advertise=addr                  Sets the advertise address to use
  -advertise-wan=addr              Sets address to advertise on wan instead of
                                   advertise addr
  -bootstrap                       Sets server to bootstrap mode
  -bind=0.0.0.0                    Sets the bind address for cluster
                                   communication
  -http-port=8500                  Sets the HTTP API port to listen on
  -bootstrap-expect=0              Sets server to expect bootstrap mode.
  -client=127.0.0.1                Sets the address to bind for client access.
                                   This includes RPC, DNS, HTTP and HTTPS (if
                                   configured)
  -config-file=foo                 Path to a JSON file to read configuration
                                   from. This can be specified multiple times.
  -config-dir=foo                  Path to a directory to read configuration
                                   files from. This will read every file ending
                                   in ".json" as configuration in this
                                   directory in alphabetical order. This can be
                                   specified multiple times.
  -data-dir=path                   Path to a data directory to store agent
                                   state
  -dev                             Starts the agent in development mode.
  -recursor=1.2.3.4                Address of an upstream DNS server.
                                   Can be specified multiple times.
  -dc=east-aws                     Datacenter of the agent (deprecated: use
                                   'datacenter' instead).
  -datacenter=east-aws             Datacenter of the agent.
  -encrypt=key                     Provides the gossip encryption key
  -join=1.2.3.4                    Address of an agent to join at start time.
                                   Can be specified multiple times.
  -join-wan=1.2.3.4                Address of an agent to join -wan at start
                                   time. Can be specified multiple times.
  -retry-join=1.2.3.4              Address of an agent to join at start time
                                   with retries enabled. Can be specified
                                   multiple times.
  -retry-interval=30s              Time to wait between join attempts.
  -retry-max=0                     Maximum number of join attempts. Defaults to
                                   0, which will retry indefinitely.
  -retry-join-ec2-region           EC2 Region to use for discovering servers to
                                   join.
  -retry-join-ec2-tag-key          EC2 tag key to filter on for server
                                   discovery
  -retry-join-ec2-tag-value        EC2 tag value to filter on for server
                                   discovery
  -retry-join-gce-project-name     Google Compute Engine project to discover
                                   servers in
  -retry-join-gce-zone-pattern     Google Compute Engine region or zone to
                                   discover servers in (regex pattern)
  -retry-join-gce-tag-value        Google Compute Engine tag value to filter
                                   for server discovery
  -retry-join-gce-credentials-file Path to credentials JSON file to use with
                                   Google Compute Engine
  -retry-join-wan=1.2.3.4          Address of an agent to join -wan at start
                                   time with retries enabled. Can be specified
                                   multiple times.
  -retry-interval-wan=30s          Time to wait between join -wan attempts.
  -retry-max-wan=0                 Maximum number of join -wan attempts.
                                   Defaults to 0, which will retry
                                   indefinitely.
  -log-level=info                  Log level of the agent.
  -node=hostname                   Name of this node. Must be unique in the
                                   cluster
  -node-meta=key:value             An arbitrary metadata key/value pair for
                                   this node.
                                   This can be specified multiple times.
  -protocol=N                      Sets the protocol version. Defaults to
                                   latest.
  -rejoin                          Ignores a previous leave and attempts to
                                   rejoin the cluster.
  -server                          Switches agent to server mode.
  -syslog                          Enables logging to syslog
  -ui                              Enables the built-in static web UI server
  -ui-dir=path                     Path to directory containing the Web UI
                                   resources
  -pid-file=path                   Path to file to store agent PID           

event

event

指令提供了一種機制,用來fire自定義的使用者事件,這些事件對consul來說是不透明的,但它們可以用來建構自動部署、重新開機服務或者其他行動的腳本。

-http-addr:http服務的位址,agent可以連結上來發送指令,如果沒有設定,則預設是127.0.0.1:8500。
-datacenter:資料中心。
-name:事件的名稱
-node:一個正規表達式,用來過濾節點
-service:一個正規表達式,用來過濾節點上比對的服務
-tag:一個正規表達式,用來過濾節點上符合tag的服務,必須和-service一起使用。           

exec

exec

指令提供了一種遠端執行機制,比如你要在所有的機器上執行uptime指令,遠端執行的工作通過job來指定,存儲在KV中,agent使用event系統可以快速的知道有新的job産生,消息是通過gossip協定來傳遞的,是以消息傳遞是最佳的,但是并不保證指令的執行。事件通過gossip來驅動,遠端執行依賴KV存儲系統(就像消息代理一樣)。

-http-addr:http服務的位址,agent可以連結上來發送指令,如果沒有設定,則預設是127.0.0.1:8500。
-datacenter:資料中心。
-prefix:key在KV系統中的字首,用來存儲請求資料,預設是_rexec
-node:一個正規表達式,用來過濾節點,評估事件
-service:一個正規表達式,用來過濾節點上比對的服務
-tag:一個正規表達式,用來過濾節點上符合tag的服務,必須和-service一起使用。
-wait:在節點多長時間沒有響應後,認為job已經完成。
-wait-repl:
-verbose:輸出更多資訊           

force-leave

force-leave

治療可以強制consul叢集中的成員進入left狀态(空閑狀态),記住,即使一個成員處于活躍狀态,它仍舊可以再次加入叢集中,這個方法的真實目的是強制移除failed的節點。如果failed的節點還是網絡的一部分,則consul會周期性的重新連結failed的節點,如果經過一段時間後(預設是72小時),consul則會宣布停止嘗試連結failed的節點。force-leave指令可以快速的把failed節點轉換到left狀态。

-rpc-addr:一個rpc位址,agent可以連結上來發送指令,如果沒有指定,預設是127.0.0.1:8400。           

info

info

指令提供了各種操作時可以用到的debug資訊,對于client和server,info有傳回不同的子系統資訊,目前有以下幾個KV資訊:agent(提供agent資訊),consul(提供consul庫的資訊),raft(提供raft庫的資訊),serf_lan(提供LAN gossip pool),serf_wan(提供WAN gossip pool)

-rpc-addr:一個rpc位址,agent可以連結上來發送指令,如果沒有指定,預設是127.0.0.1:8400           

join

join

指令告訴consul agent加入一個已經存在的叢集中,一個新的consul agent必須加入一個已經有至少一個成員的叢集中,這樣它才能加入已經存在的叢集中,如果你不加入一個已經存在的叢集,則agent是它自身叢集的一部分,其他agent則可以加入進來。agents可以加入其他agent多次。consul join [options] address。如果你想加入多個叢集,則可以寫多個位址,consul會加入所有的位址。

-wan:agent運作在server模式,xxxxxxx
-rpc-addr:一個rpc位址,agent可以連結上來發送指令,如果沒有指定,預設是127.0.0.1:8400。           

keygen

keygen

指令生成加密的密鑰,可以用在consul agent通訊加密

生成一個key

leave

leave

指令觸發一個優雅的離開動作并關閉agent,節點離開後不會嘗試重新加入叢集中。運作在server狀态的節點,節點會被優雅的删除,這是很嚴重的,在某些情況下一個不優雅的離開會影響到叢集的可用性。

-rpc-addr:一個rpc位址,agent可以連結上來發送指令,如果沒有指定,預設是127.0.0.1:8400。           

members

members

指令輸出consul agent目前所知道的所有的成員以及它們的狀态,節點的狀态隻有alive、left、failed三種狀态。

-detailed:輸出每個節點更詳細的資訊。
-rpc-addr:一個rpc位址,agent可以連結上來發送指令,如果沒有指定,預設是127.0.0.1:8400。
-status:過濾出符合正則規則的節點
-wan:xxxxxx           

monitor

monitor

指令用來連結運作的agent,并顯示日志。monitor會顯示最近的日志,并持續的顯示日志流,不會自動退出,除非你手動或者遠端agent自己退出。

-log-level:顯示哪個級别的日志,預設是info
-rpc-addr:一個rpc位址,agent可以連結上來發送指令,如果沒有指定,預設是127.0.0.1:8400           

reload

reload

指令可以重新加載agent的配置檔案。SIGHUP指令在重新加載配置檔案時使用,任何重新加載的錯誤都會寫在agent的log檔案中,并不會列印到螢幕。

-rpc-addr:一個rpc位址,agent可以連結上來發送指令,如果沒有指定,預設是127.0.0.1:8400           

version

列印consul的版本

watch

watch

指令提供了一個機制,用來監視實際資料視圖的改變(節點清單、成員服務、KV),如果沒有指定程序,目前值會被dump出來

-http-addr:http服務的位址,agent可以連結上來發送指令,如果沒有設定,則預設是127.0.0.1:8500。
-datacenter:資料中心查詢。
-token:ACL token
-key:監視key,隻針對key類型
-name:監視event,隻針對event類型
-prefix:監視key prefix,隻針對keyprefix類型
-service:監控service,隻針對service類型
-state:過略check state
-tag:過濾service tag
-type:監控類型,一般有key、keyprefix、service、nodes、checks、event           

Consul 配置

agent有各種各樣的配置項可以在指令行或者配置檔案進行定義,所有的配置項都是可選擇的,當加載配置檔案的時候,consul從配置檔案或者配置目錄加載配置。後面定義的配置會合并前面定義的配置,但是大多數情況下,合并的意思是後面定義的配置會覆寫前面定義的配置,但是有些情況,例如event句柄,合并僅僅是添加到前面定義的句柄後面。consul重新加載配置檔案也支援以信号的方式接收update信号。

下面看看指令行參數:

-advertise:通知展現位址用來改變我們給叢集中的其他節點展現的位址,一般情況下-bind位址就是展現位址
-bootstrap:用來控制一個server是否在bootstrap模式,在一個datacenter中隻能有一個server處于bootstrap模式,當一個server處于bootstrap模式時,可以自己選舉為raft leader。
-bootstrap-expect:在一個datacenter中期望提供的server節點數目,當該值提供的時候,consul一直等到達到指定sever數目的時候才會引導整個叢集,該标記不能和bootstrap公用
-bind:該位址用來在叢集内部的通訊,叢集内的所有節點到位址都必須是可達的,預設是0.0.0.0
-client:consul綁定在哪個client位址上,這個位址提供HTTP、DNS、RPC等服務,預設是127.0.0.1
-config-file:明确的指定要加載哪個配置檔案
-config-dir:配置檔案目錄,裡面所有以.json結尾的檔案都會被加載
-data-dir:提供一個目錄用來存放agent的狀态,所有的agent允許都需要該目錄,該目錄必須是穩定的,系統重新開機後都繼續存在
-dc:該标記控制agent允許的datacenter的名稱,預設是dc1
-encrypt:指定secret key,使consul在通訊時進行加密,key可以通過consul keygen生成,同一個叢集中的節點必須使用相同的key
-join:加入一個已經啟動的agent的ip位址,可以多次指定多個agent的位址。如果consul不能加入任何指定的位址中,則agent會啟動失敗,預設agent啟動時不會加入任何節點。
-retry-join:和join類似,但是允許你在第一次失敗後進行嘗試。
-retry-interval:兩次join之間的時間間隔,預設是30s
-retry-max:嘗試重複join的次數,預設是0,也就是無限次嘗試
-log-level:consul agent啟動後顯示的日志資訊級别。預設是info,可選:trace、debug、info、warn、err。
-node:節點在叢集中的名稱,在一個叢集中必須是唯一的,預設是該節點的主機名
-protocol:consul使用的協定版本
-rejoin:使consul忽略先前的離開,在再次啟動後仍舊嘗試加入叢集中。
-server:定義agent運作在server模式,每個叢集至少有一個server,建議每個叢集的server不要超過5個
-syslog:開啟系統日志功能,隻在linux/osx上生效
-ui-dir:提供存放web ui資源的路徑,該目錄必須是可讀的
-pid-file:提供一個路徑來存放pid檔案,可以使用該檔案進行SIGINT/SIGHUP(關閉/更新)agent           

除了指令行參數外,配置也可以寫入檔案中,在某些情況下配置檔案會更簡單一些,例如:利用consul被用來管理系統。配置檔案是json格式的,很容易編寫。配置檔案不僅被用來設定agent的啟動,也可以用來提供健康檢測和服務發現的定義。配置檔案的一般樣例如下:

{
  "datacenter": "dc1",
  "data_dir": "/opt/consul",
  "log_level": "INFO",
  "node_name": "s1",
  "server": true,
  "bootstrap_expect": 3,
  "bind_addr": "10.201.102.198",
  "client_addr": "0.0.0.0",
  "ui_dir": "/root/consul_ui",
  "retry_join": ["10.201.102.198","10.201.102.199","10.201.102.200","10.201.102.248"],
  "retry_interval": "30s",
  "enable_debug": false,
  "rejoin_after_leave": true,
  "start_join": ["10.201.102.198","10.201.102.199","10.201.102.200","10.201.102.248"],
  "enable_syslog": true,
  "syslog_facility": "local5"
}           

下面看看詳細的配置檔案參數:

acl_datacenter:隻用于server,指定的datacenter的權威ACL資訊,所有的servers和datacenter必須同意ACL datacenter
acl_default_policy:預設是allow
acl_down_policy:
acl_master_token:
acl_token:agent會使用這個token和consul server進行請求
acl_ttl:控制TTL的cache,預設是30s
addresses:一個嵌套對象,可以設定以下key:dns、http、rpc
advertise_addr:等同于-advertise
bootstrap:等同于-bootstrap
bootstrap_expect:等同于-bootstrap-expect
bind_addr:等同于-bind
ca_file:提供CA檔案路徑,用來檢查用戶端或者服務端的連結
cert_file:必須和key_file一起
check_update_interval:
client_addr:等同于-client
datacenter:等同于-dc
data_dir:等同于-data-dir
disable_anonymous_signature:在進行更新檢查時禁止匿名簽名
disable_remote_exec:禁止支援遠端執行,設定為true,agent會忽視所有進入的遠端執行請求
disable_update_check:禁止自動檢查安全公告和新版本資訊
dns_config:是一個嵌套對象,可以設定以下參數:allow_stale、max_stale、node_ttl 、service_ttl、enable_truncate
domain:預設情況下consul在進行DNS查詢時,查詢的是consul域,可以通過該參數進行修改
enable_debug:開啟debug模式
enable_syslog:等同于-syslog
encrypt:等同于-encrypt
key_file:提供私鑰的路徑
leave_on_terminate:預設是false,如果為true,當agent收到一個TERM信号的時候,它會發送leave資訊到叢集中的其他節點上。
log_level:等同于-log-level
node_name:等同于-node
ports:這是一個嵌套對象,可以設定以下key:dns(dns位址:8600)、http(http api位址:8500)、rpc(rpc:8400)、serf_lan(lan port:8301)、serf_wan(wan port:8302)、server(server rpc:8300)
protocol:等同于-protocol
recursor:
rejoin_after_leave:等同于-rejoin
retry_join:等同于-retry-join
retry_interval:等同于-retry-interval
server:等同于-server
server_name:會覆寫TLS CA的node_name,可以用來确認CA name和hostname相比對
skip_leave_on_interrupt:和leave_on_terminate比較類似,不過隻影響目前句柄
start_join:一個字元數組提供的節點位址會在啟動時被加入
statsd_addr:
statsite_addr:
syslog_facility:當enable_syslog被提供後,該參數控制哪個級别的資訊被發送,預設Local0
ui_dir:等同于-ui-dir
verify_incoming:預設false,如果為true,則所有進傳入連結接都需要使用TLS,需要用戶端使用ca_file提供ca檔案,隻用于consul server端,因為client從來沒有進入的連結
verify_outgoing:預設false,如果為true,則所有出去連結都需要使用TLS,需要服務端使用ca_file提供ca檔案,consul server和client都需要使用,因為兩者都有出去的連結
watches:watch一個詳細名單           

HTTP API

consul的主要接口是RESTful HTTP API,該API可以用來增删查改nodes、services、checks、configguration。所有的endpoints主要分為以下類别:

kv - Key/Value存儲
agent - Agent控制
catalog - 管理nodes和services
health - 管理健康監測
session - Session操作
acl - ACL建立和管理
event - 使用者Events
status - Consul系統狀态           

下面我們就單獨看看每個子產品的具體内容。

agent

agent endpoints用來和本地agent進行互動,一般用來服務注冊和檢查注冊,支援以下接口

/v1/agent/checks : 傳回本地agent注冊的所有檢查(包括配置檔案和HTTP接口)
/v1/agent/services : 傳回本地agent注冊的所有 服務
/v1/agent/members : 傳回agent在叢集的gossip pool中看到的成員
/v1/agent/self : 傳回本地agent的配置和成員資訊
/v1/agent/join/<address> : 觸發本地agent加入node
/v1/agent/force-leave/<node>>: 強制删除node
/v1/agent/check/register : 在本地agent增加一個檢查項,使用PUT方法傳輸一個json格式的資料
/v1/agent/check/deregister/<checkID> : 登出一個本地agent的檢查項
/v1/agent/check/pass/<checkID> : 設定一個本地檢查項的狀态為passing
/v1/agent/check/warn/<checkID> : 設定一個本地檢查項的狀态為warning
/v1/agent/check/fail/<checkID> : 設定一個本地檢查項的狀态為critical
/v1/agent/service/register : 在本地agent增加一個新的服務項,使用PUT方法傳輸一個json格式的資料
/v1/agent/service/deregister/<serviceID> : 登出一個本地agent的服務項           

catalog

catalog endpoints用來注冊/登出nodes、services、checks

/v1/catalog/register : Registers a new node, service, or check
/v1/catalog/deregister : Deregisters a node, service, or check
/v1/catalog/datacenters : Lists known datacenters
/v1/catalog/nodes : Lists nodes in a given DC
/v1/catalog/services : Lists services in a given DC
/v1/catalog/service/<service> : Lists the nodes in a given service
/v1/catalog/node/<node> : Lists the services provided by a node           

health

health endpoints用來查詢健康狀況相關資訊,該功能從catalog中單獨分離出來

/v1/healt/node/<node>: 傳回node所定義的檢查,可用參數?dc=
/v1/health/checks/<service>: 傳回和服務相關聯的檢查,可用參數?dc=
/v1/health/service/<service>: 傳回給定datacenter中給定node中service
/v1/health/state/<state>: 傳回給定datacenter中指定狀态的服務,state可以是"any", "unknown", "passing", "warning", or "critical",可用參數?dc=           

session

session endpoints用來create、update、destory、query sessions

/v1/session/create: Creates a new session
/v1/session/destroy/<session>: Destroys a given session
/v1/session/info/<session>: Queries a given session
/v1/session/node/<node>: Lists sessions belonging to a node
/v1/session/list: Lists all the active sessions           

acl

acl endpoints用來create、update、destory、query acl

/v1/acl/create: Creates a new token with policy
/v1/acl/update: Update the policy of a token
/v1/acl/destroy/<id>: Destroys a given token
/v1/acl/info/<id>: Queries the policy of a given token
/v1/acl/clone/<id>: Creates a new token by cloning an existing token
/v1/acl/list: Lists all the active tokens           

event endpoints用來fire新的events、查詢已有的events

/v1/event/fire/<name>: 觸發一個新的event,使用者event需要name和其他可選的參數,使用PUT方法
/v1/event/list: 傳回agent知道的events           

status

status endpoints用來或者consul 叢集的資訊

/v1/status/leader : 傳回目前叢集的Raft leader
/v1/status/peers : 傳回目前叢集中同僚           

Consul-Template

在consul-template沒出現之前,大家建構服務發現系統,大多采用的是zookeeper、etcd+confd這樣類似的系統,之前寫過一篇consul+confd的文,講的是如何動态生成配置檔案的,如今consul官方推出了自己的模闆系統,就是consul-template,這樣的話動态的配置系統可以分化為etcd+confd和consul+consul-template兩大陣營。consul是一個和etcd類似但又強于etcd的系統,關于etcd和consul可以翻閱以前的文章,consul-template的定位就和confd差不多一樣了,confd的後端可以是etcd或者consul,相信consul搭配consul-template能發揮更大的效果。consul-template提供了一個便捷的方式從consul中擷取存儲的值,consul-template守護程序會查詢consul執行個體,來更新系統上指定的任何模闆,當更新完成後,模闆可以選擇運作一些任意的指令。

consul template的使用場景:consul template可以查詢consul中的服務目錄、key、key-values等。這種強大的抽象功能和查詢語言模闆可以使consul template特别适合動态的建立配置檔案。例如:建立apache/nginx proxy balancers、haproxy backends、varnish servers、application configurations。           

consul template的特性:

quiescence:consul template内制靜止平衡功能,可以智能的發現consul執行個體中的更改資訊。這個功能可以防止頻繁的更新模闆而引起系統的波動。
    dry mode:不确定目前架構的狀态?擔心模闆的變化會破壞子系統?無須擔心,因為consul template還有-dry模式。在dry模式,consul template會将結果呈現在STDOUT,是以操作員可以檢查輸出是否正常,以決定更換模闆是否安全
    CLI and Config:如果你喜歡在指令行上指定一切,consul template都可以hold住。随着内置HCL的支援,consul template接收一個配置檔案,指令行參數,或者兩者的混合。通過這種方式你可以繼續使用你現在已有的配置管理工具和consul template來配合。
    verbose debugging:即使每件事你都做的近乎完美,但是有時候還是會有失敗發生。consul template可以提供更詳細的debug日志資訊。           

安裝

你可以在釋出頁下載下傳釋出包.如果你希望自己編譯請檢視說明文檔.

使用

-auth=<user[:pass]>      設定基本的認證使用者名和密碼
  -consul-addr=<address>   設定Consul執行個體的位址
  -max-stale=<duration>    查詢過期的最大頻率,預設是1s
  -dedup                   啟用重複資料删除,當許多consul template執行個體渲染一個模闆的時候可以降低consul的負載
  -ssl                     使用https連接配接Consul使用SSL
  -ssl-verify              通過SSL連接配接的時候檢查證書
  -ssl-cert                SSL用戶端證書發送給伺服器
  -ssl-key                 用戶端認證時使用的SSL/TLS私鑰
  -ssl-ca-cert             驗證伺服器的CA憑證清單
  -token=<token>           設定Consul API的token
  -syslog                  把标準輸出和标準錯誤重定向到syslog,syslog的預設級别是local0。
  -syslog-facility=<f>     設定syslog級别,預設是local0,必須和-syslog配合使用
  -template=<template>     增加一個需要監控的模闆,格式是:'templatePath:outputPath(:command)',多個模闆則可以設定多次
  -wait=<duration>         當呈現一個新的模闆到系統和觸發一個指令的時候,等待的最大最小時間。如果最大值被忽略,預設是最小值的4倍。
  -retry=<duration>        當在和consul api互動的傳回值是error的時候,等待的時間,預設是5s。
  -config=<path>           配置檔案或者配置目錄的路徑
  -pid-file=<path>         PID檔案的路徑
  -log-level=<level>       設定日志級别,可以是"debug","info", "warn" (default), and "err"
  -dry                     Dump生成的模闆到标準輸出,不會生成到磁盤
  -once                    運作consul-template一次後退出,不以守護程序運作
  -reap                    子程序自動收割           

檢視全部選項,使用以下指令

consul-template -h           

指令行

1、查詢本地consl執行個體,生成模闆後重新開機nginx,如果consul不可用,如果api故障則每30s嘗試檢測一次值,consul-template運作一次後退出

consul-template -retry 30s -once -consul-addr=10.201.102.198:8500 -template "test.ctmpl:test.out"           

test.ctmpl

{{range service "Faceid"}}
{{.ID}} {{.Address}}:{{.Port}} check inter 5000 fall 1 rise 2 weight 2{{end}}           

test.out

Faceid 10.201.102.198:9000 check inter 5000 fall 1 rise 2 weight 2
Faceid 10.201.102.199:9000 check inter 5000 fall 1 rise 2 weight 2
Faceid 10.201.102.200:9000 check inter 5000 fall 1 rise 2 weight 2           

2、運作consul-temple作為一個服務

consul-template -consul-addr=10.201.102.198:8500 -template "test.ctmpl:test.out"           

3、查詢一個執行個體,渲染多個模闆,然後重新開機相關服務

consul-template -retry 30s -once -consul-addr=10.201.102.198:8500 -template "test.ctmpl:test.out"\
 -template "/tmp/redis.ctmpl:/var/redis/redis.conf:service redis restart" \
 -template "/tmp/haproxy.ctmpl:/var/haproxy/haproxy.conf"           

4、查詢一個執行個體,dump模闆到标準輸出,參數中的-template則會被忽略

consul-template -dry -consul-addr=10.201.102.198:8500 -template "test.ctmpl:test.out"           

以上參數除了在指令行使用,也可以直接配置在檔案中,下面看看Consul-Template的配置檔案,簡稱HCL(HashiCorp Configuration Language),它是和JSON相容的,下面看個例子:

#### 配置檔案
​```Consul-Template```配置檔案是使用[HashiCorp Configuration Language (HCL)](https://github.com/hashicorp/hcl)編寫的.這意味着```Consul Template```是和JSON相容的,檢視更多資訊請檢視 [HCL 規範](https://github.com/hashicorp/hcl)
配置檔案文法支援上面的所有的選項,除非在表格中進行标明.
​```json
// 這是要連接配接的Consul Agent的位址.預設為127.0.0.1:8500.這是Consul的預設綁定位址和端口.
// 不建議你直接與 Consul的 Server直接進行互動,請與本地的Consul Agent進行互動.這樣做是有一些原因
// 最重要的是本地agent可以複用與server的連接配接.減少HTTP的連接配接數.另外這個位址更好記.
consul = "127.0.0.1:8500"
// 這是用于連接配接Consul的ACL token. 如果你的叢集未啟用就不需要設定.
//
// 這個選項也可以通過環境變量 CONSUL_TOKEN 來進行設定
token = "abcd1234"
// 這是監聽出發reload事件的信号,預設值如下所示.将這個值設定為空将引起 CT ,進而不監聽reload事件
reload_signal = "SIGHUP"
// 這是監聽出發core dump事件的信号,預設值如下所示.将這個值設定為空将引起 CT ,進而不監聽core dump信号
dump_signal = "SIGQUIT"
// 這是監聽出發graceful stop事件的信号,預設值如下所示.将這個值設定為空将引起 CT ,進而不監聽graceful stop信号
kill_signal = "SIGINT"
// 這是連接配接Consul的重試時間.Consul Template是高容錯的設計.這意味着,出現失敗他不會退出.而按照
// 分布式系統的慣例進行指數補償和重試來等待叢集恢複.
retry = "10s"
// This is the maximum interval to allow "stale" data. By default, only the
// Consul leader will respond to queries; any requests to a follower will
// forward to the leader. In large clusters with many requests, this is not as
// scalable, so this option allows any follower to respond to a query, so long
// as the last-replicated data is within these bounds. Higher values result in
// less cluster load, but are more likely to have outdated data.
// 這是允許陳舊資料的最大時間.Consul預設隻有領袖對請求進行相應.所有對追随者的請求将被轉發給領袖.
// 在有大量請求的大型叢集中,這顯得不夠有擴充性.是以這個選項允許任何追随者響應查詢,隻要最後複制的資料
// 在這個範圍内.數值越高,越減少叢集負載,但是更容易接受到過期資料.
max_stale = "10m"
// 這是log的等級,如果你找到了bug,請打開debug 日志,這樣我們可以更好的定位問題.這個選項也可用在指令行.
log_level = "warn"
// 這是存放Consul Template 程序的PID檔案的路徑,如果你計劃發送定制的信号到這個程序這會比較有用.
pid_file = "/path/to/pid"
// 這是一個靜止定時器,他定義了在模闆渲染之前等待叢集達到一緻狀态的最小和最大時間.
// 這對于一些變化較大的系統中比較有用,可以減少模闆渲染的次數
wait = "5s:10s"
// 這是 Vault配置的開始
// Vault是HashiCorp的另外一個産品
vault {
  // This is the address of the Vault leader. The protocol (http(s)) portion
  // of the address is required.
  address = "https://vault.service.consul:8200"
  // This is the token to use when communicating with the Vault server.
  // Like other tools that integrate with Vault, Consul Template makes the
  // assumption that you provide it with a Vault token; it does not have the
  // incorporated logic to generate tokens via Vault's auth methods.
  //
  // This value can also be specified via the environment variable VAULT_TOKEN.
  token = "abcd1234"
  // This option tells Consul Template to automatically renew the Vault token
  // given. If you are unfamiliar with Vault's architecture, Vault requires
  // tokens be renewed at some regular interval or they will be revoked. Consul
  // Template will automatically renew the token at half the lease duration of
  // the token. The default value is true, but this option can be disabled if
  // you want to renew the Vault token using an out-of-band process.
  //
  // Note that secrets specified in a template (using {{secret}} for example)
  // are always renewed, even if this option is set to false. This option only
  // applies to the top-level Vault token itself.
  renew = true
  // This section details the SSL options for connecting to the Vault server.
  // Please see the SSL options below for more information (they are the same).
  ssl {
    // ...
  }
}
// 這部配置設定置請求的基本的權限驗證資訊
auth {
  enabled  = true
  username = "test"
  password = "test"
}
// 這部配置設定置連接配接到Consul伺服器的SSL資訊.
ssl {
  // 使用SSL需要先打開這個開關
  enabled = true
  // This enables SSL peer verification. The default value is "true", which
  // will check the global CA chain to make sure the given certificates are
  // valid. If you are using a self-signed certificate that you have not added
  // to the CA chain, you may want to disable SSL verification. However, please
  // understand this is a potential security vulnerability.
  verify = false
  // This is the path to the certificate to use to authenticate. If just a
  // certificate is provided, it is assumed to contain both the certificate and
  // the key to convert to an X509 certificate. If both the certificate and
  // key are specified, Consul Template will automatically combine them into an
  // X509 certificate for you.
  cert = "/path/to/client/cert"
  key = "/path/to/client/key"
  // This is the path to the certificate authority to use as a CA. This is
  // useful for self-signed certificates or for organizations using their own
  // internal certificate authority.
  ca_cert = "/path/to/ca"
}
// 設定連接配接到syslog伺服器的配置
// 用于進行日志記錄syslog {
  // 打開開關
  enabled = true
  // 裝置名稱
  facility = "LOCAL5"
}
// This block defines the configuration for de-duplication mode. Please see the
// de-duplication mode documentation later in the README for more information
// on how de-duplication mode operates.
deduplicate {
  // This enables de-duplication mode. Specifying any other options also enables
  // de-duplication mode.
  enabled = true
  // This is the prefix to the path in Consul's KV store where de-duplication
  // templates will be pre-rendered and stored.
  prefix = "consul-template/dedup/"
}
// This block defines the configuration for exec mode. Please see the exec mode
// documentation at the bottom of this README for more information on how exec
// mode operates and the caveats of this mode.
exec {
  // This is the command to exec as a child process. There can be only one
  // command per Consul Template process.
  command = "/usr/bin/app"
  // This is a random splay to wait before killing the command. The default
  // value is 0 (no wait), but large clusters should consider setting a splay
  // value to prevent all child processes from reloading at the same time when
  // data changes occur. When this value is set to non-zero, Consul Template
  // will wait a random period of time up to the splay value before reloading
  // or killing the child process. This can be used to prevent the thundering
  // herd problem on applications that do not gracefully reload.
  splay = "5s"
  // This defines the signal that will be sent to the child process when a
  // change occurs in a watched template. The signal will only be sent after
  // the process is started, and the process will only be started after all
  // dependent templates have been rendered at least once. The default value
  // is "" (empty or nil), which tells Consul Template to restart the child
  // process instead of sending it a signal. This is useful for legacy
  // applications or applications that cannot properly reload their
  // configuration without a full reload.
  reload_signal = "SIGUSR1"
  // This defines the signal sent to the child process when Consul Template is
  // gracefully shutting down. The application should begin a graceful cleanup.
  // If the application does not terminate before the `kill_timeout`, it will
  // be terminated (effectively "kill -9"). The default value is "SIGTERM".
  kill_signal = "SIGINT"
  // This defines the amount of time to wait for the child process to gracefully
  // terminate when Consul Template exits. After this specified time, the child
  // process will be force-killed (effectively "kill -9"). The default value is
  // "30s".
  kill_timeout = "2s"
}
// 這部分定義了對模闆的配置,和其他配置塊不同.這部分可以針對不同模闆配置多次.也可以在CLI指令
// 直接進行配置
template {
  // 這是輸入模闆的配置檔案路徑,必選項
  source = "/path/on/disk/to/template.ctmpl"
  // 這是源模闆渲染之後存放的路徑,如果父目錄不存在Consul Template會嘗試進行建立
  destination = "/path/on/disk/where/template/will/render.txt"
  // This is the optional command to run when the template is rendered. The
  // command will only run if the resulting template changes. The command must
  // return within 30s (configurable), and it must have a successful exit code.
  // Consul Template is not a replacement for a process monitor or init system.
  // 這是當模闆渲染完成後可選的要執行的指令.這個指令隻會在模闆發生改變後才會運作.這個指令必須要在30秒
  // 内進行傳回(可配置),必須傳回一個成功的退出碼.Consul Template不能替代程序監視或者init 系統
  // 的功能
  command = "restart service foo"
  // 這是最大的等待指令傳回的時間,預設是30秒
  command_timeout = "60s"
  // 這是渲染後的檔案的權限,如果不設定,Consul Template将去比對之前已經存在的檔案的權限.
  // 如果檔案不存在,權限會被設定為 0644
  perms = 0600
  // 這個選項對渲染之前的檔案進行備份.他保持一個備份.
  // 這個選項在發生意外更高時,有一個復原政策.
  backup = true
  // 模闆的分隔符,預設是 "{{"和"}}".但是對于一些模闆用其他的分隔符可能更好
  // 可以避免與本身的沖突
  left_delimiter  = "{{"
  right_delimiter = "}}"
  // 這是最小和最大等待渲染一個新模闆和執行指令的時間.使用 分号 個号.如果忽略最大值,最大
  // 值會被設定為最小值的4倍.這個選項沒有預設值.這個值相對全局是以的等待時間有最高優先級
  wait = "2s:6s"
}           

注意: 不是所有的選項都是必選的.例如: 如果你沒有使用Vault你不用設定這一塊. 類似的你沒有使用syslog系統你也不需要指定syslog配置.

為了更加安全,

token

也可以從環境變量裡讀取,使用

CONSUL_TOKEN

VAULT_TOKEN

.強烈建議你不要把token放到未加密的文本配置檔案中.

模版文法

Consul Template 使用了Go的模闆文法.如果你對他的文法不熟悉建議你讀下文檔.他的文法看起來與 Mustache, Handlebars, 或者 Liquid 類似.

在Go 提供的模闆函數之外,Consul Template暴露了以下的函數:

API 函數

datacenters

查詢目錄中的所有資料中心.使用以下文法:

{{datacenters}}           

file

讀取并輸出磁盤上的本地檔案,如果無法讀取産生一個錯誤.使用如下文法

{{file "/path/to/local/file"}}           

這個例子将輸出

/path/to/local/file

檔案内容到模闆. 注意:這不會在嵌套模闆中被處理

key

查詢Consul指定key的值,如果key的值不能轉換為字元串,将産生錯誤.使用如下文法:

{{key "service/redis/maxconns@east-aws"}}           

上面的例子查詢了在

east-aws

資料中心的

service/redis/maxconns

的值.如果忽略資料中心參數,将會查詢本地資料中心的值:

{{key "service/redis/maxconns"}}           

Consul鍵值結構的美妙在于,這完全取決于你!

key_or_default

查詢Consul中指定的key的值,如果key不存在,則傳回預設值.使用方式如下

{{key_or_default "service/redis/maxconns@east-aws" "5"}}           

注意Consul Template使用了多個階段的運算.在第一階段的運算如果Consul沒有傳回值,則會一直使用預設值.後續模闆解析中如果值存在了則會讀取真實的值.這很重要,運維Consul Templae不會因為

key_or_default

沒找到key而阻塞模闆的的渲染.即使key存在如果Consul沒有按時傳回這個資料,也會使用預設值來進行替代.

ls

檢視Consul的所有以指定字首開頭的key-value對.如果有值無法轉換成字元串則會産生一個錯誤:

{{range ls "service/redis@east-aws"}}
{{.Key}} {{.Value}}{{end}}           

如果Consul執行個體在

east-aws

資料中心存在這個結構

service/redis

,渲染後的模闆應該類似這樣:

minconns 2
maxconns 12           

如果你忽略資料中心屬性,則會傳回本地資料中心的查詢結果.

node

查詢目錄中的一個節點資訊

{{node "node1"}}           

如果未指定任何參數,則目前agent所在節點将會被傳回:

{{node}}           

你可以指定一個可選的參數來指定資料中心:

{{node "node1" "@east-aws"}}           

如果指定的節點沒有找到則會傳回

nil

.如果節點存在就會列出節點的資訊和節點提供的服務.

{{with node}}{{.Node.Node}} ({{.Node.Address}}){{range .Services}}
  {{.Service}} {{.Port}} ({{.Tags | join ","}}){{end}}
{{end}}           

nodes

查詢目錄中的全部節點,使用如下文法

{{nodes}}           

這個例子會查詢Consul的預設資料中心.你可以使用可選參數指定一個可選參數來指定資料中心:

{{nodes "@east-aws"}}           

這個例子會查詢east-aws資料中心的所有幾點.

secret

查詢

Vault

中指定路徑的密匙.如果指定的路徑不存在或者

Vault

Token

沒有足夠權限去讀取指定的路徑,将會産生一個錯誤.如果路徑存在但是key不存在則傳回“.

{{with secret "secret/passwords"}}{{.Data.password}}{{end}}           

可以使用如下字段:

LeaseID - the unique lease identifier
LeaseDuration - the number of seconds the lease is valid
Renewable - if the secret is renewable
Data - the raw data - this is a map[string]interface{}, so it can be queried using Go's templating "dot notation"
If the map key has dots "." in it, you need to access the value using the index function:
{{index .Data "my.key.with.dots"}}
If additional arguments are passed to the function, then the operation is assumed to be a write operation instead of a read operation. The write operation must return data in order to be valid. This is especially useful for the PKI secret backend, for example.
{{ with secret "pki/issue/my-domain-dot-com" "common_name=foo.example.com" }}
{{ .Data.certificate }}
{{ end }}
The parameters must be key=value pairs, and each pair must be its own argument to the function:
{{ secret "path/" "a=b" "c=d" "e=f" }}
Please always consider the security implications of having the contents of a secret in plain-text on disk. If an attacker is able to get access to the file, they will have access to plain-text secrets.           

Please note that Vault does not support blocking queries. As a result, Consul Template will not immediately reload in the event a secret is changed as it does with Consul’s key-value store. Consul Template will fetch a new secret at half the lease duration of the original secret. For example, most items in Vault’s generic secret backend have a default 30 day lease. This means Consul Template will renew the secret every 15 days. As such, it is recommended that a smaller lease duration be used when generating the initial secret to force Consul Template to renew more often.

secrets

Query Vault to list the secrets at the given path. Please note this requires Vault 0.5+ and the endpoint you want to list secrets must support listing. Not all endpoints support listing. The result is the list of secret names as strings.

{{range secrets "secret/"}}{{.}}{{end}}           

The trailing slash is optional in the template, but the generated secret dependency will always have a trailing slash in log output.

To iterate and list over every secret in the generic secret backend in Vault, for example, you would need to do something like this:

{{range secrets "secret/"}}
{{with secret (printf "secret/%s" .)}}
{{range $k, $v := .Data}}
{{$k}}: {{$v}}
{{end}}
{{end}}
{{end}}           

You should probably never do this. Please also note that Vault does not support blocking queries. To understand the implications, please read the note at the end of the secret function.

service

查詢Consul中比對表達式的服務.文法如下:

{{service "release.web@east-aws"}}           

上面的例子查詢Consul中,在

east-aws

資料中心存在的健康的

web

服務.tag和資料中心參數是可選的.從目前資料中心查詢所有節點的

web

服務而不管tag,查詢文法如下:

{{service "web"}}           

這個函數傳回

[]*HealthService

結構.可按照如下方式應用到模闆:

{{range service "web@data center"}}
server {{.Name}} {{.Address}}:{{.Port}}{{end}}           

産生如下輸出:

server nyc_web_01 123.456.789.10:8080
server nyc_web_02 456.789.101.213:8080           

預設值會傳回健康的服務,如果你想擷取所有服務,可以增加

any

選項,如下:

{{service "web" "any"}}           

這樣就會傳回注冊過的所有服務,而不論他的狀态如何.

如果你想過濾指定的一個或者多個健康狀态,你可以通過逗号隔開多個健康狀态:

{{service "web" "passing, warning"}}           

這樣将會傳回被他們的節點和服務級别的檢查定義标記為 “passing” 或者 “warning”的服務. 請注意逗号是

OR

而不是

AND

的意思.

指定了超過一個狀态過濾,并包含

any

将會傳回一個錯誤.因為

any

是比所有狀态更進階的過濾.

後面這2種方式有些架構上的不同:

{{service "web"}}
{{service "web" "passing"}}           

前者會傳回Consul認為

healthy

passing

的所有服務.後者将傳回所有已經在Consul注冊的服務.然後會執行一個用戶端的過濾.通常如果你想擷取健康的服務,你應該不要使用

passing

參數,直接忽略第三個參數即可.然而第三個參數在你想查詢 passing或者

warning

的服務會比較有用,如下:

{{service "web" "passing, warning"}}           

服務的狀态也是可見的,如果你想自己做一些額外的過濾,文法如下:

{{range service "web" "any"}}
{{if eq .Status "critical"}}
// Critical state!{{end}}
{{if eq .Status "passing"}}
// Ok{{end}}           

執行指令時,在Consul将服務設定為維護模式,隻需要在你的指令上包上Consul的

maint

調用:

#!/bin/sh
set -e
consul maint -enable -service web -reason "Consul Template updated"
service nginx reload
consul maint -disable -service web           

另外如果你沒有安裝Consul agent,你可以直接調用API請求:

#!/bin/sh
set -e
curl -X PUT "http://$CONSUL_HTTP_ADDR/v1/agent/service/maintenance/web?enable=true&reason=Consul+Template+Updated"
service nginx reload
curl -X PUT "http://$CONSUL_HTTP_ADDR/v1/agent/service/maintenance/web?enable=false"           

services

查詢Consul目錄中的所有服務,使用如下文法:

{{services}}           

這個例子将查詢Consul的預設資料中心,你可以指定一個可選參數來指定資料中心:

{{services "@east-aws"}}           

請注意: services函數與service是不同的,service接受更多參數并且查詢監控的服務清單.這個查詢Consul目錄并傳回一個服務的tag的Map,如下:

{{range services}}
{{.Name}}
{{range .Tags}}
  {{.}}{{end}}
{{end}}           

tree

查詢所有指定字首的key-value值對,如果其中的值有無法轉換為字元串的則引發錯誤:

{{range tree "service/redis@east-aws"}}
{{.Key}} {{.Value}}{{end}}           

east-aws

資料中心有一個

service/redis

結構,模闆的渲染結果類似下面:

minconns 2
maxconns 12
nested/config/value "value"           

ls

不同,

tree

傳回字首下的所有key.和Unix的tree指令比較像.如果忽略資料中心參數,則會使用本地資料中心

檢視更多

項目Github位址

Haproxy 執行個體

根據haproxy服務的配置檔案建立一個consul-template模版渲染檔案:

haproxy.ctmpl

# Consul Haproxy configured
global
        maxconn         20480
        ulimit-n        65535
        log             127.0.0.1 local5
        uid             200
        gid             200
        chroot          /usr/local/haproxy
        nbproc          1
        daemon
        pidfile         /usr/local/haproxy/logs/haproxy.pid
defaults
        log             global
        mode            http
        option          httplog
        option          dontlognull
        option          forwardfor
        option          abortonclose
        retries         3
        maxconn         3000
        stats           enable
        stats           hide-version
        stats   uri     /admin
        stats   auth    admin:admin
        stats   refresh 10s
        balance         roundrobin
        timeout connect 5000ms
        timeout client 50000ms
        timeout server 50000ms
        timeout check 2000ms
listen web_haproxy
        bind 0.0.0.0:8080
        mode http
        log     127.0.0.1 local5 err
        stats   refresh 5s
        stats   uri /admin
        stats   realm liang lian
        stats   auth admin:admin
        stats   hide-version
        stats   admin if TRUE
frontend consul
        bind    0.0.0.0:8500
        mode    http
        log     global
        default_backend consul-cluster
backend consul-cluster
        mode http
        {{range service "Faceid"}}
        server {{.ID}} {{.Address}}:{{.Port}} check inter 5000 fall 1 rise 2 weight 2{{end}}           

運作consul-template作為一個服務,通過上面的渲染模版渲染一個haproxy.cfg的配置檔案,然後重新開機haproxy服務

consul-template -consul-addr=10.201.102.185:8500 -template "/root/haproxy.ctmpl:/etc/haproxy.cfg:service haproxy restart"           

10.201.102.185 看我上篇文章Haproxy,這是consul叢集的VIP,為了避免單獨調某一台伺服器伺服器出現故障後consul-template無法工作。

渲染後的

haproxy.cfg

# Consul Haproxy configured
global
        maxconn         20480
        ulimit-n        65535
        log             127.0.0.1 local5
        uid             200
        gid             200
        chroot          /usr/local/haproxy
        nbproc          1
        daemon
        pidfile         /usr/local/haproxy/logs/haproxy.pid
defaults
        log             global
        mode            http
        option          httplog
        option          dontlognull
        option          forwardfor
        option          abortonclose
        retries         3
        maxconn         3000
        stats           enable
        stats           hide-version
        stats   uri     /admin
        stats   auth    admin:admin
        stats   refresh 10s
        balance         roundrobin
        timeout connect 5000ms
        timeout client 50000ms
        timeout server 50000ms
        timeout check 2000ms
listen web_haproxy
        bind 0.0.0.0:8080
        mode http
        log     127.0.0.1 local5 err
        stats   refresh 5s
        stats   uri /admin
        stats   realm liang lian
        stats   auth admin:admin
        stats   hide-version
        stats   admin if TRUE
frontend consul
        bind    0.0.0.0:8500
        mode    http
        log     global
        default_backend consul-cluster
backend consul-cluster
        mode http
        server Faceid 10.201.102.198:9000 check inter 5000 fall 1 rise 2 weight 2
        server Faceid 10.201.102.199:9000 check inter 5000 fall 1 rise 2 weight 2
        server Faceid 10.201.102.200:9000 check inter 5000 fall 1 rise 2 weight 2           

整個就是搭建consul叢集,平台中的服務會注冊到consul叢集中,haproxy避免consul-template調consul時出現單點故障consul-template無法工作做的高可用,Consul-template就是能在整個平台的各個系統和應用中使用,查詢consul叢集來擷取平台上各個應用的存活狀态和IP。

整套下來實作了兩個重點:

實作了中心服務注冊查詢

平台中其他節點的查詢服務和配置檔案自動更新

參考資料

https://my.oschina.net/guol/blog/675281

https://www.consul.io/docs/guides/index.html

https://www.gitbook.com/book/vincentmi/consul-guide/details

https://my.oschina.net/abcfy2/blog/675665

下載下傳

點選下載下傳PDF檔案

本文标題:Consul 使用手冊

文章作者:梁先森

釋出時間:2017-04-06, 19:25:40

最後更新:2017-08-02, 14:15:20

原始連結:http://www.liangxiansen.cn/2017/04/06/consul/

許可協定: “署名-非商用-相同方式共享 4.0” 轉載請保留原文連結及作者。

原文位址:https://blog.csdn.net/liuzhuchen/article/details/81913562

繼續閱讀