Consul 使用手冊

http://www.liangxiansen.cn/2017/04/06/consul/

使用consul

介紹

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

  • 服務發現 Consul的客戶端可用提供一個服務,比如 api 或者mysql ,另外一些客戶端可用使用Consul去發現一個指定服務的提供者.通過DNS或者HTTP應用程序可用很容易的找到他所依賴的服務.
  • 健康檢查 Consul客戶端可用提供任意數量的健康檢查,指定一個服務(比如:webserver是否返回了200 OK 狀態碼)或者使用本地節點(比如:內存使用是否大於90%). 這個信息可由operator用來監視集羣的健康.被服務發現組件用來避免將流量發送到不健康的主機.
  • Key/Value存儲 應用程序可用根據自己的需要使用Consul的層級的Key/Value存儲.比如動態配置,功能標記,協調,領袖選舉等等,簡單的HTTP API讓他更易於使用.
  • 多數據中心: Consul支持開箱即用的多數據中心.這意味着用戶不需要擔心需要建立額外的抽象層讓業務擴展到多個區域.

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

consul-cluster

基礎架構

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你應該看到類似下面的輸出


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

如果你得到一個consul not be found的錯誤,你的PATH可能沒有正確設置.請返回檢查你的consul的安裝路徑是否包含在PATH中.

運行Agent

完成Consul的安裝後,必須運行agent. agent可以運行爲serverclient模式.每個數據中心至少必須擁有一臺server . 建議在一個集羣中有3或者5個server.部署單一的server,在出現失敗時會不可避免的造成數據丟失.

其他的agent運行爲client模式.一個client是一個非常輕量級的進程.用於註冊服務,運行健康檢查和轉發對server的查詢.agent必須在集羣中的每個主機上運行.

查看啓動數據中心的細節請查看這裏.

啓動 Consul Server


 
  1. 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

 
  1. [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
  2. ==> WARNING: Expect Mode enabled, expecting 3 servers
  3. ==> Starting Consul agent...
  4. ==> Starting Consul agent RPC...
  5. ==> Consul agent running!
  6. Version: 'v0.7.4'
  7. Node ID: '422ec677-74ef-8f29-2f22-01effeed6334'
  8. Node name: 's1'
  9. Datacenter: 'dc1'
  10. Server: true (bootstrap: false)
  11. Client Addr: 0.0.0.0 (HTTP: 8500, HTTPS: -1, DNS: 8600, RPC: 8400)
  12. Cluster Addr: 10.201.102.198 (LAN: 8301, WAN: 8302)
  13. Gossip encrypt: false, RPC-TLS: false, TLS-Incoming: false
  14. Atlas: <disabled>
  15.  
  16. ==> Log data will now stream in as it occurs:
  17.  
  18. 2017/03/17 18:03:08 [INFO] raft: Restored from snapshot 139-352267-1489707086023
  19. 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}]
  20. 2017/03/17 18:03:08 [INFO] raft: Node at 10.201.102.198:8300 [Follower] entering Follower state (Leader: "")
  21. 2017/03/17 18:03:08 [INFO] serf: EventMemberJoin: s1 10.201.102.198
  22. 2017/03/17 18:03:08 [INFO] serf: Attempting re-join to previously known node: s2: 10.201.102.199:8301
  23. 2017/03/17 18:03:08 [INFO] consul: Adding LAN server s1 (Addr: tcp/10.201.102.198:8300) (DC: dc1)
  24. 2017/03/17 18:03:08 [INFO] consul: Raft data found, disabling bootstrap mode
  25. 2017/03/17 18:03:08 [INFO] serf: EventMemberJoin: s2 10.201.102.199
  26. 2017/03/17 18:03:08 [INFO] serf: EventMemberJoin: s3 10.201.102.200
  27. 2017/03/17 18:03:08 [INFO] serf: Re-joined to previously known node: s2: 10.201.102.199:8301
  28. 2017/03/17 18:03:08 [INFO] consul: Adding LAN server s2 (Addr: tcp/10.201.102.199:8300) (DC: dc1)
  29. 2017/03/17 18:03:08 [INFO] consul: Adding LAN server s3 (Addr: tcp/10.201.102.200:8300) (DC: dc1)
  30. 2017/03/17 18:03:08 [INFO] serf: EventMemberJoin: s1.dc1 10.201.102.198
  31. 2017/03/17 18:03:08 [INFO] consul: Adding WAN server s1.dc1 (Addr: tcp/10.201.102.198:8300) (DC: dc1)
  32. 2017/03/17 18:03:08 [WARN] serf: Failed to re-join any previously known node
  33. 2017/03/17 18:03:14 [INFO] agent: Synced service 'consul'
  34. 2017/03/17 18:03:14 [INFO] agent: Deregistered service 'consul01'
  35. 2017/03/17 18:03:14 [INFO] agent: Deregistered service 'consul02'
  36. 2017/03/17 18:03:14 [INFO] agent: Deregistered service 'consul03'
  • 查看集羣成員

新開一個終端窗口運行consul members, 你可以看到Consul集羣的成員.


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

啓動 Consul Client


 
  1. 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 加入到已有的集羣中去。


 
  1. [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
  2. ==> Starting Consul agent...
  3. ==> Starting Consul agent RPC...
  4. ==> Joining cluster...
  5. Join completed. Synced with 1 initial agents
  6. ==> Consul agent running!
  7. Version: 'v0.7.4'
  8. Node ID: '564dc0c7-7f4f-7402-a301-cebe7f024294'
  9. Node name: 'c1'
  10. Datacenter: 'dc1'
  11. Server: false (bootstrap: false)
  12. Client Addr: 127.0.0.1 (HTTP: 8500, HTTPS: -1, DNS: 8600, RPC: 8400)
  13. Cluster Addr: 10.201.102.248 (LAN: 8301, WAN: 8302)
  14. Gossip encrypt: false, RPC-TLS: false, TLS-Incoming: false
  15. Atlas: <disabled>
  16.  
  17. ==> Log data will now stream in as it occurs:
  18.  
  19. 2017/03/17 15:35:16 [INFO] serf: EventMemberJoin: c1 10.201.102.248
  20. 2017/03/17 15:35:16 [INFO] agent: (LAN) joining: [10.201.102.198]
  21. 2017/03/17 15:35:16 [INFO] serf: EventMemberJoin: s2 10.201.102.199
  22. 2017/03/17 15:35:16 [INFO] serf: EventMemberJoin: s3 10.201.102.200
  23. 2017/03/17 15:35:16 [INFO] serf: EventMemberJoin: s1 10.201.102.198
  24. 2017/03/17 15:35:16 [INFO] agent: (LAN) joined: 1 Err: <nil>
  25. 2017/03/17 15:35:16 [INFO] consul: adding server s2 (Addr: tcp/10.201.102.199:8300) (DC: dc1)
  26. 2017/03/17 15:35:16 [INFO] consul: adding server s3 (Addr: tcp/10.201.102.200:8300) (DC: dc1)
  27. 2017/03/17 15:35:16 [INFO] consul: adding server s1 (Addr: tcp/10.201.102.198:8300) (DC: dc1)
  28. 2017/03/17 15:35:16 [INFO] agent: Synced node info
  • 查看集羣成員

新開一個終端窗口運行consul members, 你可以看到Consul集羣的成員.


 
  1. [root@dhcp-10-201-102-248 ~]# consul members
  2. Node Address Status Type Build Protocol DC
  3. c1 10.201.102.248:8301 alive client 0.7.4 2 dc1
  4. s1 10.201.102.198:8301 alive server 0.7.4 2 dc1
  5. s2 10.201.102.199:8301 alive server 0.7.4 2 dc1
  6. s3 10.201.102.200:8301 alive server 0.7.4 2 dc1
  • 加入集羣

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

停止Agent

你可以使用Ctrl-C 優雅的關閉Agent. 中斷Agent之後你可以看到他離開了集羣並關閉.

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

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

查看這裏瞭解添加和移除server.

更新服務

服務定義可以通過配置文件併發送SIGHUP給agent來進行更新.這樣你可以讓你在不關閉服務或者保持服務請求可用的情況下進行更新.


 
  1. consul reload

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

註冊服務

搭建好conusl集羣后,用戶或者程序就能到consul中去查詢或者註冊服務。可以通過提供服務定義文件或者調用HTTP API來註冊一個服務.

首先,爲Consul配置創建一個目錄.Consul會載入配置文件夾裏的所有配置文件.在Unix系統中通常類似 /etc/consul.d (.d 後綴意思是這個路徑包含了一組配置文件).


 
  1. mkdir /etc/consul.d

然後,我們將編寫服務定義配置文件.假設我們有一個名叫web的服務運行在 80端口.另外,我們將給他設置一個標籤.這樣我們可以使用他作爲額外的查詢方式:


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

現在重啓agent , 設置配置目錄:


 
  1. $ 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
  2.  
  3. ...
  4. [INFO] agent: Synced service 'web'
  5. ...
  • -data-dir:提供一個目錄用來存放agent的狀態,所有的agent允許都需要該目錄,該目錄必須是穩定的,系統重啓後都繼續存在

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

如果你想註冊多個服務,你應該在Consul配置目錄創建多個服務定義文件.

HTTP API註冊服務,curl命令或者postman 以PUT方式請求consul HTTP API更多細節點擊查看


 
  1. 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 :


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

如你所見,一個A記錄返回了一個可用的服務所在的節點的IP地址.A`記錄只能設置爲IP地址. 有也可用使用 DNS API 來接收包含 地址和端口的 SRV記錄:


 
  1. [root@dhcp-10-201-102-198 ~]# dig @127.0.0.1 -p 8600 web.service.consul SRV
  2.  
  3. ; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6 <<>> @127.0.0.1 -p 8600 web.service.consul SRV
  4. ; (1 server found)
  5. ;; global options: +cmd
  6. ;; Got answer:
  7. ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 13331
  8. ;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
  9. ;; WARNING: recursion requested but not available
  10.  
  11. ;; QUESTION SECTION:
  12. ;web.service.consul. IN SRV
  13.  
  14. ;; ANSWER SECTION:
  15. web.service.consul. 0 IN SRV 1 1 80 s1.node.dc1.consul.
  16.  
  17. ;; ADDITIONAL SECTION:
  18. s1.node.dc1.consul. 0 IN A 10.201.102.198
  19.  
  20. ;; Query time: 0 msec
  21. ;; SERVER: 127.0.0.1#8600(127.0.0.1)
  22. ;; WHEN: Tue Mar 28 16:10:56 2017
  23. ;; MSG SIZE rcvd: 84
  24.  
  25. [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服務.我們成功獲取了我們註冊爲這個標籤的服務:


 
  1. [root@dhcp-10-201-102-198 ~]# dig @127.0.0.1 -p 8600 rails.web.service.consul SRV
  2.  
  3. ; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6 <<>> @127.0.0.1 -p 8600 rails.web.service.consul SRV
  4. ; (1 server found)
  5. ;; global options: +cmd
  6. ;; Got answer:
  7. ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 37307
  8. ;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
  9. ;; WARNING: recursion requested but not available
  10.  
  11. ;; QUESTION SECTION:
  12. ;rails.web.service.consul. IN SRV
  13.  
  14. ;; ANSWER SECTION:
  15. rails.web.service.consul. 0 IN SRV 1 1 80 s1.node.dc1.consul.
  16.  
  17. ;; ADDITIONAL SECTION:
  18. s1.node.dc1.consul. 0 IN A 10.201.102.198
  19.  
  20. ;; Query time: 0 msec
  21. ;; SERVER: 127.0.0.1#8600(127.0.0.1)
  22. ;; WHEN: Tue Mar 28 16:11:45 2017
  23. ;; MSG SIZE rcvd: 90
  24.  
  25. [root@dhcp-10-201-102-198 ~]#
  • HTTP API

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


 
  1. [root@dhcp-10-201-102-198 ~]# curl -s 127.0.0.1:8500/v1/catalog/service/web | python -m json.tool
  2. [
  3. {
  4. "Address": "10.201.102.198",
  5. "CreateIndex": 492843,
  6. "ID": "422ec677-74ef-8f29-2f22-01effeed6334",
  7. "ModifyIndex": 492843,
  8. "Node": "s1",
  9. "NodeMeta": {},
  10. "ServiceAddress": "",
  11. "ServiceEnableTagOverride": false,
  12. "ServiceID": "web",
  13. "ServiceName": "web",
  14. "ServicePort": 80,
  15. "ServiceTags": [
  16. "rails"
  17. ],
  18. "TaggedAddresses": {
  19. "lan": "10.201.102.198",
  20. "wan": "10.201.102.198"
  21. }
  22. }
  23. ]

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


 
  1. [root@dhcp-10-201-102-198 ~]# curl -s 127.0.0.1:8500/v1/catalog/service/web?passing | python -m json.tool
  2. [
  3. {
  4. "Address": "10.201.102.198",
  5. "CreateIndex": 492843,
  6. "ID": "422ec677-74ef-8f29-2f22-01effeed6334",
  7. "ModifyIndex": 492843,
  8. "Node": "s1",
  9. "NodeMeta": {},
  10. "ServiceAddress": "",
  11. "ServiceEnableTagOverride": false,
  12. "ServiceID": "web",
  13. "ServiceName": "web",
  14. "ServicePort": 80,
  15. "ServiceTags": [
  16. "rails"
  17. ],
  18. "TaggedAddresses": {
  19. "lan": "10.201.102.198",
  20. "wan": "10.201.102.198"
  21. }
  22. }
  23. ]

WEB管理界面

Consul同時提供了一個漂亮的功能齊全的WEB界面,開箱即用.界面可以用來查看所有的節點,可以查看健康檢查和他們的當前狀態.可以讀取和設置K/V 存儲的數據.UI自動支持多數據中心.點擊前往下載

UI_Download

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


 
  1. 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管理界面。

UI_Download

健康檢查

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

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

  • 自定義檢查

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

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

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

/etc/consul.d/web.json


 
  1. {"service": {
  2. "name": "Faceid",
  3. "tags": ["extract", "verify", "compare", "idcard"],
  4. "address": "10.201.102.198",
  5. "port": 9000,
  6. "check": {
  7. "name": "ping",
  8. "script": "curl -s localhost:9000",
  9. "interval": "3s"
  10. }
  11. }
  12. }

or

/etc/consul.d/web.json


 
  1. {"service": {
  2. "name": "Faceid",
  3. "tags": ["extract", "verify", "compare", "idcard"],
  4. "address": "10.201.102.199",
  5. "port": 9000,
  6. "check": {
  7. "id": "api",
  8. "name": "HTTP API on port 9000",
  9. "http": "http://localhost:9000",
  10. "interval": "10s",
  11. "timeout": "1s"
  12. }
  13. }
  14. }

more

檢查健康狀態

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


 
  1. [root@dhcp-10-201-102-198 ~]# curl -s http://localhost:8500/v1/health/state/critical | python -m json.tool
  2. [
  3. {
  4. "CheckID": "service:Faceid",
  5. "CreateIndex": 493398,
  6. "ModifyIndex": 493846,
  7. "Name": "Service 'Faceid' check",
  8. "Node": "s1",
  9. "Notes": "",
  10. "Output": "",
  11. "ServiceID": "Faceid",
  12. "ServiceName": "Faceid",
  13. "Status": "critical"
  14. }
  15. ]

我們可以看到,只有一個檢查我們的web服務在critical狀態

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


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

K /V

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


 
  1. [root@dhcp-10-201-102-198 ~]# curl -v http://localhost:8500/v1/kv/?recurse
  2. * About to connect() to localhost port 8500 (#0)
  3. * Trying ::1... 拒絕連接
  4. * Trying 127.0.0.1... connected
  5. * Connected to localhost (127.0.0.1) port 8500 (#0)
  6. > GET /v1/kv/?recurse HTTP/1.1
  7. > 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
  8. > Host: localhost:8500
  9. > Accept: */*
  10. >
  11. < HTTP/1.1 404 Not Found
  12. < X-Consul-Index: 1
  13. < X-Consul-Knownleader: true
  14. < X-Consul-Lastcontact: 0
  15. < Date: Thu, 18 Aug 2016 08:21:39 GMT
  16. < Content-Length: 0
  17. < Content-Type: text/plain; charset=utf-8
  18. <
  19. * Connection #0 to host localhost left intact
  20. * Closing connection #0

因爲沒有key所以我們得到了一個404響應.現在我們PUT`一些示例的Key:


 
  1. [root@dhcp-10-201-102-198 ~]# curl -X PUT -d 'test' http://localhost:8500/v1/kv/web/key1
  2. [root@dhcp-10-201-102-198 ~]# curl -X PUT -d 'test' http://localhost:8500/v1/kv/web/key2?flags=42
  3. [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參數.


 
  1. [root@dhcp-10-201-102-198 ~]# curl -s http://localhost:8500/v1/kv/web/?recurse | python -m json.tool
  2. [
  3. {
  4. "CreateIndex": 502660,
  5. "Flags": 0,
  6. "Key": "web/key1",
  7. "LockIndex": 0,
  8. "ModifyIndex": 502660,
  9. "Value": "dGVzdA=="
  10. },
  11. {
  12. "CreateIndex": 502663,
  13. "Flags": 42,
  14. "Key": "web/key2",
  15. "LockIndex": 0,
  16. "ModifyIndex": 502663,
  17. "Value": "dGVzdA=="
  18. },
  19. {
  20. "CreateIndex": 502665,
  21. "Flags": 0,
  22. "Key": "web/sub/key3",
  23. "LockIndex": 0,
  24. "ModifyIndex": 502665,
  25. "Value": "dGVzdA=="
  26. }
  27. ]

你可以獲取單個的key


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

刪除key也很簡單.通過DELETE動作來完成.我們可以通過指定完整路徑來刪除一個單獨的key.或者我們可以使用?recurse遞歸的刪除主路徑下所有key.


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

可以通過發送相同的URL並提供不同的消息體的PUT請求去修改一個Key.另外,Consul提供一個檢查並設置的操作,實現原子的Key修改.通過?cas=參數加上GET中最近的ModifyIndex來達到. 例如我們想修改 “web/key1”:


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

在這種情況下,第一次CAS 更新成功因爲ModifyIndex502660.而第二次失敗是因爲ModifyIndex在第一次更新後已經不是502660了 .

我們也可以使用ModifyIndex來等待key值的改變.例如我們想等待key2被修改:


 
  1. [root@dhcp-10-201-102-198 ~]# curl "http://localhost:8500/v1/kv/web/key2"
  2. [{"LockIndex":0,"Key":"web/key2","Flags":42,"Value":"dGVzdA==","CreateIndex":502663,"ModifyIndex":502663}]
  3. [root@dhcp-10-201-102-198 ~]# curl "http://localhost:8500/v1/kv/web/key2?index=502663&wait=5s"
  4. [{"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所支持的參數,而每個參數裏面又支持其他參數,下面我們就來具體看看。


 
  1. [root@dhcp-10-201-102-198 ~]# consul
  2. usage: consul [--version] [--help] <command> [<args>]
  3.  
  4. Available commands are:
  5. agent Runs a Consul agent 運行一個consul agent
  6. configtest Validate config file
  7. event Fire a new event
  8. exec Executes a command on Consul nodes 在consul節點上執行一個命令
  9. force-leave Forces a member of the cluster to enter the "left" state 強制節點成員在集羣中的狀態轉換到left狀態
  10. info Provides debugging information for operators 提供操作的debug級別的信息
  11. join Tell Consul agent to join cluster 加入consul節點到集羣中
  12. keygen Generates a new encryption key 生成一個新的加密key
  13. keyring Manages gossip layer encryption keys
  14. kv Interact with the key-value store
  15. leave Gracefully leaves the Consul cluster and shuts down
  16. lock Execute a command holding a lock
  17. maint Controls node or service maintenance mode
  18. members Lists the members of a Consul cluster 列出集羣中成員
  19. monitor Stream logs from a Consul agent 打印consul節點的日誌信息
  20. operator Provides cluster-level tools for Consul operators
  21. reload Triggers the agent to reload configuration files 觸發節點重新加載配置文件
  22. rtt Estimates network round trip time between nodes
  23. snapshot Saves, restores and inspects snapshots of Consul server state
  24. version Prints the Consul version 打印consul的版本信息
  25. watch Watch for changes in Consul 監控consul的改變
  26.  

更詳細見官網

Agent

agent指令是consul的核心,它運行agent來維護成員的重要信息、運行檢查、服務宣佈、查詢處理等等。


 
  1. ==> Usage: consul agent [options]
  2.  
  3. Starts the Consul agent and runs until an interrupt is received. The
  4. agent represents a single node in a cluster.
  5.  
  6. Options:
  7.  
  8. -advertise=addr Sets the advertise address to use
  9. -advertise-wan=addr Sets address to advertise on wan instead of
  10. advertise addr
  11. -bootstrap Sets server to bootstrap mode
  12. -bind=0.0.0.0 Sets the bind address for cluster
  13. communication
  14. -http-port=8500 Sets the HTTP API port to listen on
  15. -bootstrap-expect=0 Sets server to expect bootstrap mode.
  16. -client=127.0.0.1 Sets the address to bind for client access.
  17. This includes RPC, DNS, HTTP and HTTPS (if
  18. configured)
  19. -config-file=foo Path to a JSON file to read configuration
  20. from. This can be specified multiple times.
  21. -config-dir=foo Path to a directory to read configuration
  22. files from. This will read every file ending
  23. in ".json" as configuration in this
  24. directory in alphabetical order. This can be
  25. specified multiple times.
  26. -data-dir=path Path to a data directory to store agent
  27. state
  28. -dev Starts the agent in development mode.
  29. -recursor=1.2.3.4 Address of an upstream DNS server.
  30. Can be specified multiple times.
  31. -dc=east-aws Datacenter of the agent (deprecated: use
  32. 'datacenter' instead).
  33. -datacenter=east-aws Datacenter of the agent.
  34. -encrypt=key Provides the gossip encryption key
  35. -join=1.2.3.4 Address of an agent to join at start time.
  36. Can be specified multiple times.
  37. -join-wan=1.2.3.4 Address of an agent to join -wan at start
  38. time. Can be specified multiple times.
  39. -retry-join=1.2.3.4 Address of an agent to join at start time
  40. with retries enabled. Can be specified
  41. multiple times.
  42. -retry-interval=30s Time to wait between join attempts.
  43. -retry-max=0 Maximum number of join attempts. Defaults to
  44. 0, which will retry indefinitely.
  45. -retry-join-ec2-region EC2 Region to use for discovering servers to
  46. join.
  47. -retry-join-ec2-tag-key EC2 tag key to filter on for server
  48. discovery
  49. -retry-join-ec2-tag-value EC2 tag value to filter on for server
  50. discovery
  51. -retry-join-gce-project-name Google Compute Engine project to discover
  52. servers in
  53. -retry-join-gce-zone-pattern Google Compute Engine region or zone to
  54. discover servers in (regex pattern)
  55. -retry-join-gce-tag-value Google Compute Engine tag value to filter
  56. for server discovery
  57. -retry-join-gce-credentials-file Path to credentials JSON file to use with
  58. Google Compute Engine
  59. -retry-join-wan=1.2.3.4 Address of an agent to join -wan at start
  60. time with retries enabled. Can be specified
  61. multiple times.
  62. -retry-interval-wan=30s Time to wait between join -wan attempts.
  63. -retry-max-wan=0 Maximum number of join -wan attempts.
  64. Defaults to 0, which will retry
  65. indefinitely.
  66. -log-level=info Log level of the agent.
  67. -node=hostname Name of this node. Must be unique in the
  68. cluster
  69. -node-meta=key:value An arbitrary metadata key/value pair for
  70. this node.
  71. This can be specified multiple times.
  72. -protocol=N Sets the protocol version. Defaults to
  73. latest.
  74. -rejoin Ignores a previous leave and attempts to
  75. rejoin the cluster.
  76. -server Switches agent to server mode.
  77. -syslog Enables logging to syslog
  78. -ui Enables the built-in static web UI server
  79. -ui-dir=path Path to directory containing the Web UI
  80. resources
  81. -pid-file=path Path to file to store agent PID

event

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


 
  1. -http-addr:http服務的地址,agent可以鏈接上來發送命令,如果沒有設置,則默認是127.0.0.1:8500。
  2. -datacenter:數據中心。
  3. -name:事件的名稱
  4. -node:一個正則表達式,用來過濾節點
  5. -service:一個正則表達式,用來過濾節點上匹配的服務
  6. -tag:一個正則表達式,用來過濾節點上符合tag的服務,必須和-service一起使用。

exec

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


 
  1. -http-addr:http服務的地址,agent可以鏈接上來發送命令,如果沒有設置,則默認是127.0.0.1:8500。
  2. -datacenter:數據中心。
  3. -prefix:key在KV系統中的前綴,用來存儲請求數據,默認是_rexec
  4. -node:一個正則表達式,用來過濾節點,評估事件
  5. -service:一個正則表達式,用來過濾節點上匹配的服務
  6. -tag:一個正則表達式,用來過濾節點上符合tag的服務,必須和-service一起使用。
  7. -wait:在節點多長時間沒有響應後,認爲job已經完成。
  8. -wait-repl:
  9. -verbose:輸出更多信息

force-leave

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


 
  1. -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)


 
  1. -rpc-addr:一個rpc地址,agent可以鏈接上來發送命令,如果沒有指定,默認是127.0.0.1:8400

join

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


 
  1. -wan:agent運行在server模式,xxxxxxx
  2. -rpc-addr:一個rpc地址,agent可以鏈接上來發送命令,如果沒有指定,默認是127.0.0.1:8400。

keygen

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


 
  1. 生成一個key

leave

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


 
  1. -rpc-addr:一個rpc地址,agent可以鏈接上來發送命令,如果沒有指定,默認是127.0.0.1:8400。

members

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


 
  1. -detailed:輸出每個節點更詳細的信息。
  2. -rpc-addr:一個rpc地址,agent可以鏈接上來發送命令,如果沒有指定,默認是127.0.0.1:8400。
  3. -status:過濾出符合正則規則的節點
  4. -wan:xxxxxx

monitor

monitor指令用來鏈接運行的agent,並顯示日誌。monitor會顯示最近的日誌,並持續的顯示日誌流,不會自動退出,除非你手動或者遠程agent自己退出。


 
  1. -log-level:顯示哪個級別的日誌,默認是info
  2. -rpc-addr:一個rpc地址,agent可以鏈接上來發送命令,如果沒有指定,默認是127.0.0.1:8400

reload

reload指令可以重新加載agent的配置文件。SIGHUP指令在重新加載配置文件時使用,任何重新加載的錯誤都會寫在agent的log文件中,並不會打印到屏幕。


 
  1. -rpc-addr:一個rpc地址,agent可以鏈接上來發送命令,如果沒有指定,默認是127.0.0.1:8400

version

打印consul的版本

watch

watch指令提供了一個機制,用來監視實際數據視圖的改變(節點列表、成員服務、KV),如果沒有指定進程,當前值會被dump出來


 
  1. -http-addr:http服務的地址,agent可以鏈接上來發送命令,如果沒有設置,則默認是127.0.0.1:8500。
  2. -datacenter:數據中心查詢。
  3. -token:ACL token
  4. -key:監視key,只針對key類型
  5. -name:監視event,只針對event類型
  6. -prefix:監視key prefix,只針對keyprefix類型
  7. -service:監控service,只針對service類型
  8. -state:過略check state
  9. -tag:過濾service tag
  10. -type:監控類型,一般有key、keyprefix、service、nodes、checks、event

Consul 配置

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

下面看看命令行參數:


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

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


 
  1. {
  2. "datacenter": "dc1",
  3. "data_dir": "/opt/consul",
  4. "log_level": "INFO",
  5. "node_name": "s1",
  6. "server": true,
  7. "bootstrap_expect": 3,
  8. "bind_addr": "10.201.102.198",
  9. "client_addr": "0.0.0.0",
  10. "ui_dir": "/root/consul_ui",
  11. "retry_join": ["10.201.102.198","10.201.102.199","10.201.102.200","10.201.102.248"],
  12. "retry_interval": "30s",
  13. "enable_debug": false,
  14. "rejoin_after_leave": true,
  15. "start_join": ["10.201.102.198","10.201.102.199","10.201.102.200","10.201.102.248"],
  16. "enable_syslog": true,
  17. "syslog_facility": "local5"
  18. }

下面看看詳細的配置文件參數:


 
  1. acl_datacenter:只用於server,指定的datacenter的權威ACL信息,所有的servers和datacenter必須同意ACL datacenter
  2. acl_default_policy:默認是allow
  3. acl_down_policy:
  4. acl_master_token:
  5. acl_token:agent會使用這個token和consul server進行請求
  6. acl_ttl:控制TTL的cache,默認是30s
  7. addresses:一個嵌套對象,可以設置以下key:dns、http、rpc
  8. advertise_addr:等同於-advertise
  9. bootstrap:等同於-bootstrap
  10. bootstrap_expect:等同於-bootstrap-expect
  11. bind_addr:等同於-bind
  12. ca_file:提供CA文件路徑,用來檢查客戶端或者服務端的鏈接
  13. cert_file:必須和key_file一起
  14. check_update_interval:
  15. client_addr:等同於-client
  16. datacenter:等同於-dc
  17. data_dir:等同於-data-dir
  18. disable_anonymous_signature:在進行更新檢查時禁止匿名簽名
  19. disable_remote_exec:禁止支持遠程執行,設置爲true,agent會忽視所有進入的遠程執行請求
  20. disable_update_check:禁止自動檢查安全公告和新版本信息
  21. dns_config:是一個嵌套對象,可以設置以下參數:allow_stale、max_stale、node_ttl 、service_ttl、enable_truncate
  22. domain:默認情況下consul在進行DNS查詢時,查詢的是consul域,可以通過該參數進行修改
  23. enable_debug:開啓debug模式
  24. enable_syslog:等同於-syslog
  25. encrypt:等同於-encrypt
  26. key_file:提供私鑰的路徑
  27. leave_on_terminate:默認是false,如果爲true,當agent收到一個TERM信號的時候,它會發送leave信息到集羣中的其他節點上。
  28. log_level:等同於-log-level
  29. node_name:等同於-node
  30. 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)
  31. protocol:等同於-protocol
  32. recursor:
  33. rejoin_after_leave:等同於-rejoin
  34. retry_join:等同於-retry-join
  35. retry_interval:等同於-retry-interval
  36. server:等同於-server
  37. server_name:會覆蓋TLS CA的node_name,可以用來確認CA name和hostname相匹配
  38. skip_leave_on_interrupt:和leave_on_terminate比較類似,不過隻影響當前句柄
  39. start_join:一個字符數組提供的節點地址會在啓動時被加入
  40. statsd_addr:
  41. statsite_addr:
  42. syslog_facility:當enable_syslog被提供後,該參數控制哪個級別的信息被髮送,默認Local0
  43. ui_dir:等同於-ui-dir
  44. verify_incoming:默認false,如果爲true,則所有進入鏈接都需要使用TLS,需要客戶端使用ca_file提供ca文件,只用於consul server端,因爲client從來沒有進入的鏈接
  45. verify_outgoing:默認false,如果爲true,則所有出去鏈接都需要使用TLS,需要服務端使用ca_file提供ca文件,consul server和client都需要使用,因爲兩者都有出去的鏈接
  46. watches:watch一個詳細名單

HTTP API

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


 
  1. kv - Key/Value存儲
  2. agent - Agent控制
  3. catalog - 管理nodes和services
  4. health - 管理健康監測
  5. session - Session操作
  6. acl - ACL創建和管理
  7. event - 用戶Events
  8. status - Consul系統狀態

下面我們就單獨看看每個模塊的具體內容。

agent

agent endpoints用來和本地agent進行交互,一般用來服務註冊和檢查註冊,支持以下接口


 
  1. /v1/agent/checks : 返回本地agent註冊的所有檢查(包括配置文件和HTTP接口)
  2. /v1/agent/services : 返回本地agent註冊的所有 服務
  3. /v1/agent/members : 返回agent在集羣的gossip pool中看到的成員
  4. /v1/agent/self : 返回本地agent的配置和成員信息
  5. /v1/agent/join/<address> : 觸發本地agent加入node
  6. /v1/agent/force-leave/<node>>: 強制刪除node
  7. /v1/agent/check/register : 在本地agent增加一個檢查項,使用PUT方法傳輸一個json格式的數據
  8. /v1/agent/check/deregister/<checkID> : 註銷一個本地agent的檢查項
  9. /v1/agent/check/pass/<checkID> : 設置一個本地檢查項的狀態爲passing
  10. /v1/agent/check/warn/<checkID> : 設置一個本地檢查項的狀態爲warning
  11. /v1/agent/check/fail/<checkID> : 設置一個本地檢查項的狀態爲critical
  12. /v1/agent/service/register : 在本地agent增加一個新的服務項,使用PUT方法傳輸一個json格式的數據
  13. /v1/agent/service/deregister/<serviceID> : 註銷一個本地agent的服務項

catalog

catalog endpoints用來註冊/註銷nodes、services、checks


 
  1. /v1/catalog/register : Registers a new node, service, or check
  2. /v1/catalog/deregister : Deregisters a node, service, or check
  3. /v1/catalog/datacenters : Lists known datacenters
  4. /v1/catalog/nodes : Lists nodes in a given DC
  5. /v1/catalog/services : Lists services in a given DC
  6. /v1/catalog/service/<service> : Lists the nodes in a given service
  7. /v1/catalog/node/<node> : Lists the services provided by a node

health

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


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

session

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


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

acl

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


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

event

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


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

status

status endpoints用來或者consul 集羣的信息


 
  1. /v1/status/leader : 返回當前集羣的Raft leader
  2. /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實例,來更新系統上指定的任何模板,當更新完成後,模板可以選擇運行一些任意的命令。


 
  1. consul template的使用場景:consul template可以查詢consul中的服務目錄、key、key-values等。這種強大的抽象功能和查詢語言模板可以使consul template特別適合動態的創建配置文件。例如:創建apache/nginx proxy balancers、haproxy backends、varnish servers、application configurations。

consul template的特性:


 
  1. quiescence:consul template內製靜止平衡功能,可以智能的發現consul實例中的更改信息。這個功能可以防止頻繁的更新模板而引起系統的波動。
  2. dry mode:不確定當前架構的狀態?擔心模板的變化會破壞子系統?無須擔心,因爲consul template還有-dry模式。在dry模式,consul template會將結果呈現在STDOUT,所以操作員可以檢查輸出是否正常,以決定更換模板是否安全
  3. CLI and Config:如果你喜歡在命令行上指定一切,consul template都可以hold住。隨着內置HCL的支持,consul template接收一個配置文件,命令行參數,或者兩者的混合。通過這種方式你可以繼續使用你現在已有的配置管理工具和consul template來配合。
  4. verbose debugging:即使每件事你都做的近乎完美,但是有時候還是會有失敗發生。consul template可以提供更詳細的debug日誌信息。

安裝

你可以在發佈頁下載發佈包.如果你希望自己編譯請查看說明文檔.

使用


 
  1. -auth=<user[:pass]> 設置基本的認證用戶名和密碼
  2. -consul-addr=<address> 設置Consul實例的地址
  3. -max-stale=<duration> 查詢過期的最大頻率,默認是1s
  4. -dedup 啓用重複數據刪除,當許多consul template實例渲染一個模板的時候可以降低consul的負載
  5. -ssl 使用https連接Consul使用SSL
  6. -ssl-verify 通過SSL連接的時候檢查證書
  7. -ssl-cert SSL客戶端證書發送給服務器
  8. -ssl-key 客戶端認證時使用的SSL/TLS私鑰
  9. -ssl-ca-cert 驗證服務器的CA證書列表
  10. -token=<token> 設置Consul API的token
  11. -syslog 把標準輸出和標準錯誤重定向到syslog,syslog的默認級別是local0。
  12. -syslog-facility=<f> 設置syslog級別,默認是local0,必須和-syslog配合使用
  13. -template=<template> 增加一個需要監控的模板,格式是:'templatePath:outputPath(:command)',多個模板則可以設置多次
  14. -wait=<duration> 當呈現一個新的模板到系統和觸發一個命令的時候,等待的最大最小時間。如果最大值被忽略,默認是最小值的4倍。
  15. -retry=<duration> 當在和consul api交互的返回值是error的時候,等待的時間,默認是5s。
  16. -config=<path> 配置文件或者配置目錄的路徑
  17. -pid-file=<path> PID文件的路徑
  18. -log-level=<level> 設置日誌級別,可以是"debug","info", "warn" (default), and "err"
  19. -dry Dump生成的模板到標準輸出,不會生成到磁盤
  20. -once 運行consul-template一次後退出,不以守護進程運行
  21. -reap 子進程自動收割

查看全部選項,使用以下命令


 
  1. consul-template -h

命令行

1、查詢本地consl實例,生成模板後重啓nginx,如果consul不可用,如果api故障則每30s嘗試檢測一次值,consul-template運行一次後退出


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

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

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

2、運行consul-temple作爲一個服務


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

3、查詢一個實例,渲染多個模板,然後重啓相關服務


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

4、查詢一個實例,dump模板到標準輸出,參數中的-template則會被忽略


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

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

 
  1. #### 配置文件
  2.  
  3. ​```Consul-Template```配置文件是使用[HashiCorp Configuration Language (HCL)](https://github.com/hashicorp/hcl)編寫的.這意味着```Consul Template```是和JSON兼容的,查看更多信息請查看 [HCL 規範](https://github.com/hashicorp/hcl)
  4.  
  5. 配置文件語法支持上面的所有的選項,除非在表格中進行標明.
  6.  
  7. ​```json
  8.  
  9. // 這是要連接的Consul Agent的地址.默認爲127.0.0.1:8500.這是Consul的默認綁定地址和端口.
  10. // 不建議你直接與 Consul的 Server直接進行交互,請與本地的Consul Agent進行交互.這樣做是有一些原因
  11. // 最重要的是本地agent可以複用與server的連接.減少HTTP的連接數.另外這個地址更好記.
  12. consul = "127.0.0.1:8500"
  13.  
  14. // 這是用於連接Consul的ACL token. 如果你的集羣未啓用就不需要設置.
  15. //
  16. // 這個選項也可以通過環境變量 CONSUL_TOKEN 來進行設置
  17. token = "abcd1234"
  18.  
  19. // 這是監聽出發reload事件的信號,默認值如下所示.將這個值設置爲空將引起 CT ,從而不監聽reload事件
  20. reload_signal = "SIGHUP"
  21.  
  22. // 這是監聽出發core dump事件的信號,默認值如下所示.將這個值設置爲空將引起 CT ,從而不監聽core dump信號
  23. dump_signal = "SIGQUIT"
  24.  
  25. // 這是監聽出發graceful stop事件的信號,默認值如下所示.將這個值設置爲空將引起 CT ,從而不監聽graceful stop信號
  26. kill_signal = "SIGINT"
  27.  
  28. // 這是連接Consul的重試時間.Consul Template是高容錯的設計.這意味着,出現失敗他不會退出.而按照
  29. // 分佈式系統的慣例進行指數補償和重試來等待集羣恢復.
  30. retry = "10s"
  31.  
  32. // This is the maximum interval to allow "stale" data. By default, only the
  33. // Consul leader will respond to queries; any requests to a follower will
  34. // forward to the leader. In large clusters with many requests, this is not as
  35. // scalable, so this option allows any follower to respond to a query, so long
  36. // as the last-replicated data is within these bounds. Higher values result in
  37. // less cluster load, but are more likely to have outdated data.
  38. // 這是允許陳舊數據的最大時間.Consul默認只有領袖對請求進行相應.所有對追隨者的請求將被轉發給領袖.
  39. // 在有大量請求的大型集羣中,這顯得不夠有擴展性.所以這個選項允許任何追隨者響應查詢,只要最後複製的數據
  40. // 在這個範圍內.數值越高,越減少集羣負載,但是更容易接受到過期數據.
  41. max_stale = "10m"
  42.  
  43. // 這是log的等級,如果你找到了bug,請打開debug 日誌,這樣我們可以更好的定位問題.這個選項也可用在命令行.
  44. log_level = "warn"
  45.  
  46. // 這是存放Consul Template 進程的PID文件的路徑,如果你計劃發送定製的信號到這個進程這會比較有用.
  47. pid_file = "/path/to/pid"
  48.  
  49. // 這是一個靜止定時器,他定義了在模板渲染之前等待集羣達到一致狀態的最小和最大時間.
  50. // 這對於一些變化較大的系統中比較有用,可以減少模板渲染的次數
  51. wait = "5s:10s"
  52.  
  53.  
  54. // 這是 Vault配置的開始
  55. // Vault是HashiCorp的另外一個產品
  56. vault {
  57. // This is the address of the Vault leader. The protocol (http(s)) portion
  58. // of the address is required.
  59. address = "https://vault.service.consul:8200"
  60.  
  61. // This is the token to use when communicating with the Vault server.
  62. // Like other tools that integrate with Vault, Consul Template makes the
  63. // assumption that you provide it with a Vault token; it does not have the
  64. // incorporated logic to generate tokens via Vault's auth methods.
  65. //
  66. // This value can also be specified via the environment variable VAULT_TOKEN.
  67. token = "abcd1234"
  68.  
  69. // This option tells Consul Template to automatically renew the Vault token
  70. // given. If you are unfamiliar with Vault's architecture, Vault requires
  71. // tokens be renewed at some regular interval or they will be revoked. Consul
  72. // Template will automatically renew the token at half the lease duration of
  73. // the token. The default value is true, but this option can be disabled if
  74. // you want to renew the Vault token using an out-of-band process.
  75. //
  76. // Note that secrets specified in a template (using {{secret}} for example)
  77. // are always renewed, even if this option is set to false. This option only
  78. // applies to the top-level Vault token itself.
  79. renew = true
  80.  
  81. // This section details the SSL options for connecting to the Vault server.
  82. // Please see the SSL options below for more information (they are the same).
  83. ssl {
  84. // ...
  85. }
  86. }
  87.  
  88. // 這部分配置請求的基本的權限驗證信息
  89. auth {
  90. enabled = true
  91. username = "test"
  92. password = "test"
  93. }
  94.  
  95. // 這部分配置連接到Consul服務器的SSL信息.
  96. ssl {
  97. // 使用SSL需要先打開這個開關
  98. enabled = true
  99.  
  100. // This enables SSL peer verification. The default value is "true", which
  101. // will check the global CA chain to make sure the given certificates are
  102. // valid. If you are using a self-signed certificate that you have not added
  103. // to the CA chain, you may want to disable SSL verification. However, please
  104. // understand this is a potential security vulnerability.
  105. verify = false
  106.  
  107. // This is the path to the certificate to use to authenticate. If just a
  108. // certificate is provided, it is assumed to contain both the certificate and
  109. // the key to convert to an X509 certificate. If both the certificate and
  110. // key are specified, Consul Template will automatically combine them into an
  111. // X509 certificate for you.
  112. cert = "/path/to/client/cert"
  113. key = "/path/to/client/key"
  114.  
  115. // This is the path to the certificate authority to use as a CA. This is
  116. // useful for self-signed certificates or for organizations using their own
  117. // internal certificate authority.
  118. ca_cert = "/path/to/ca"
  119. }
  120.  
  121. // 設置連接到syslog服務器的配置
  122. // 用於進行日誌記錄syslog {
  123. // 打開開關
  124. enabled = true
  125.  
  126. // 設備名稱
  127. facility = "LOCAL5"
  128. }
  129.  
  130. // This block defines the configuration for de-duplication mode. Please see the
  131. // de-duplication mode documentation later in the README for more information
  132. // on how de-duplication mode operates.
  133. deduplicate {
  134. // This enables de-duplication mode. Specifying any other options also enables
  135. // de-duplication mode.
  136. enabled = true
  137.  
  138. // This is the prefix to the path in Consul's KV store where de-duplication
  139. // templates will be pre-rendered and stored.
  140. prefix = "consul-template/dedup/"
  141. }
  142.  
  143. // This block defines the configuration for exec mode. Please see the exec mode
  144. // documentation at the bottom of this README for more information on how exec
  145. // mode operates and the caveats of this mode.
  146. exec {
  147. // This is the command to exec as a child process. There can be only one
  148. // command per Consul Template process.
  149. command = "/usr/bin/app"
  150.  
  151. // This is a random splay to wait before killing the command. The default
  152. // value is 0 (no wait), but large clusters should consider setting a splay
  153. // value to prevent all child processes from reloading at the same time when
  154. // data changes occur. When this value is set to non-zero, Consul Template
  155. // will wait a random period of time up to the splay value before reloading
  156. // or killing the child process. This can be used to prevent the thundering
  157. // herd problem on applications that do not gracefully reload.
  158. splay = "5s"
  159.  
  160. // This defines the signal that will be sent to the child process when a
  161. // change occurs in a watched template. The signal will only be sent after
  162. // the process is started, and the process will only be started after all
  163. // dependent templates have been rendered at least once. The default value
  164. // is "" (empty or nil), which tells Consul Template to restart the child
  165. // process instead of sending it a signal. This is useful for legacy
  166. // applications or applications that cannot properly reload their
  167. // configuration without a full reload.
  168. reload_signal = "SIGUSR1"
  169.  
  170. // This defines the signal sent to the child process when Consul Template is
  171. // gracefully shutting down. The application should begin a graceful cleanup.
  172. // If the application does not terminate before the `kill_timeout`, it will
  173. // be terminated (effectively "kill -9"). The default value is "SIGTERM".
  174. kill_signal = "SIGINT"
  175.  
  176. // This defines the amount of time to wait for the child process to gracefully
  177. // terminate when Consul Template exits. After this specified time, the child
  178. // process will be force-killed (effectively "kill -9"). The default value is
  179. // "30s".
  180. kill_timeout = "2s"
  181. }
  182.  
  183. // 這部分定義了對模板的配置,和其他配置塊不同.這部分可以針對不同模板配置多次.也可以在CLI命令
  184. // 直接進行配置
  185. template {
  186. // 這是輸入模板的配置文件路徑,必選項
  187. source = "/path/on/disk/to/template.ctmpl"
  188.  
  189. // 這是源模板渲染之後存放的路徑,如果父目錄不存在Consul Template會嘗試進行創建
  190. destination = "/path/on/disk/where/template/will/render.txt"
  191.  
  192. // This is the optional command to run when the template is rendered. The
  193. // command will only run if the resulting template changes. The command must
  194. // return within 30s (configurable), and it must have a successful exit code.
  195. // Consul Template is not a replacement for a process monitor or init system.
  196. // 這是當模板渲染完成後可選的要執行的命令.這個命令只會在模板發生改變後纔會運行.這個命令必須要在30秒
  197. // 內進行返回(可配置),必須返回一個成功的退出碼.Consul Template不能替代進程監視或者init 系統
  198. // 的功能
  199. command = "restart service foo"
  200.  
  201. // 這是最大的等待命令返回的時間,默認是30秒
  202. command_timeout = "60s"
  203.  
  204. // 這是渲染後的文件的權限,如果不設置,Consul Template將去匹配之前已經存在的文件的權限.
  205. // 如果文件不存在,權限會被設置爲 0644
  206. perms = 0600
  207.  
  208. // 這個選項對渲染之前的文件進行備份.他保持一個備份.
  209. // 這個選項在發生意外更高時,有一個回滾策略.
  210. backup = true
  211.  
  212. // 模板的分隔符,默認是 "{{"和"}}".但是對於一些模板用其他的分隔符可能更好
  213. // 可以避免與本身的衝突
  214. left_delimiter = "{{"
  215. right_delimiter = "}}"
  216.  
  217. // 這是最小和最大等待渲染一個新模板和執行命令的時間.使用 分號 個號.如果忽略最大值,最大
  218. // 值會被設置爲最小值的4倍.這個選項沒有默認值.這個值相對全局所以的等待時間有最高優先級
  219. wait = "2s:6s"
  220. }

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

爲了更加安全,token也可以從環境變量裏讀取,使用 CONSUL_TOKEN 和 VAULT_TOKEN.強烈建議你不要把token放到未加密的文本配置文件中.

模版語法

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

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

API 函數

datacenters

查詢目錄中的所有數據中心.使用以下語法:


 
  1. {{datacenters}}
  2.  

file

讀取並輸出磁盤上的本地文件,如果無法讀取產生一個錯誤.使用如下語法


 
  1. {{file "/path/to/local/file"}}
  2.  

這個例子將輸出 /path/to/local/file 文件內容到模板. 注意:這不會在嵌套模板中被處理

key

查詢Consul指定key的值,如果key的值不能轉換爲字符串,將產生錯誤.使用如下語法:


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

上面的例子查詢了在east-aws數據中心的 service/redis/maxconns的值.如果忽略數據中心參數,將會查詢本地數據中心的值:


 
  1. {{key "service/redis/maxconns"}}
  2.  

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

key_or_default

查詢Consul中指定的key的值,如果key不存在,則返回默認值.使用方式如下


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

注意Consul Template使用了多個階段的運算.在第一階段的運算如果Consul沒有返回值,則會一直使用默認值.後續模板解析中如果值存在了則會讀取真實的值.這很重要,運維Consul Templae不會因爲key_or_default沒找到key而阻塞模板的的渲染.即使key存在如果Consul沒有按時返回這個數據,也會使用默認值來進行替代.

ls

查看Consul的所有以指定前綴開頭的key-value對.如果有值無法轉換成字符串則會產生一個錯誤:


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

如果Consul實例在east-aws數據中心存在這個結構service/redis,渲染後的模板應該類似這樣:


 
  1. minconns 2
  2. maxconns 12
  3.  

如果你忽略數據中心屬性,則會返回本地數據中心的查詢結果.

node

查詢目錄中的一個節點信息


 
  1. {{node "node1"}}
  2.  

如果未指定任何參數,則當前agent所在節點將會被返回:


 
  1. {{node}}
  2.  

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


 
  1. {{node "node1" "@east-aws"}}
  2.  

如果指定的節點沒有找到則會返回nil.如果節點存在就會列出節點的信息和節點提供的服務.


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

nodes

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


 
  1. {{nodes}}
  2.  

這個例子會查詢Consul的默認數據中心.你可以使用可選參數指定一個可選參數來指定數據中心:


 
  1. {{nodes "@east-aws"}}
  2.  

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

secret

查詢Vault中指定路徑的密匙.如果指定的路徑不存在或者Vault的Token沒有足夠權限去讀取指定的路徑,將會產生一個錯誤.如果路徑存在但是key不存在則返回.


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

可以使用如下字段:


 
  1. LeaseID - the unique lease identifier
  2. LeaseDuration - the number of seconds the lease is valid
  3. Renewable - if the secret is renewable
  4. Data - the raw data - this is a map[string]interface{}, so it can be queried using Go's templating "dot notation"
  5. If the map key has dots "." in it, you need to access the value using the index function:
  6.  
  7. {{index .Data "my.key.with.dots"}}
  8. 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.
  9.  
  10. {{ with secret "pki/issue/my-domain-dot-com" "common_name=foo.example.com" }}
  11. {{ .Data.certificate }}
  12. {{ end }}
  13. The parameters must be key=value pairs, and each pair must be its own argument to the function:
  14.  
  15. {{ secret "path/" "a=b" "c=d" "e=f" }}
  16. 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.
  17.  

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.


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

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:


 
  1. {{range secrets "secret/"}}
  2. {{with secret (printf "secret/%s" .)}}
  3. {{range $k, $v := .Data}}
  4. {{$k}}: {{$v}}
  5. {{end}}
  6. {{end}}
  7. {{end}}
  8.  

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中匹配表達式的服務.語法如下:


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

上面的例子查詢Consul中,在east-aws數據中心存在的健康的 web服務.tag和數據中心參數是可選的.從當前數據中心查詢所有節點的web服務而不管tag,查詢語法如下:


 
  1. {{service "web"}}
  2.  

這個函數返回[]*HealthService結構.可按照如下方式應用到模板:


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

產生如下輸出:


 
  1. server nyc_web_01 123.456.789.10:8080
  2. server nyc_web_02 456.789.101.213:8080
  3.  

默認值會返回健康的服務,如果你想獲取所有服務,可以增加any選項,如下:


 
  1. {{service "web" "any"}}
  2.  

這樣就會返回註冊過的所有服務,而不論他的狀態如何.

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


 
  1. {{service "web" "passing, warning"}}
  2.  

這樣將會返回被他們的節點和服務級別的檢查定義標記爲 “passing” 或者 “warning”的服務. 請注意逗號是 OR而不是AND的意思.

指定了超過一個狀態過濾,幷包含any將會返回一個錯誤.因爲any是比所有狀態更高級的過濾.

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


 
  1. {{service "web"}}
  2. {{service "web" "passing"}}
  3.  

前者會返回Consul認爲healthypassing的所有服務.後者將返回所有已經在Consul註冊的服務.然後會執行一個客戶端的過濾.通常如果你想獲取健康的服務,你應該不要使用passing參數,直接忽略第三個參數即可.然而第三個參數在你想查詢 passing或者warning的服務會比較有用,如下:


 
  1. {{service "web" "passing, warning"}}
  2.  

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


 
  1. {{range service "web" "any"}}
  2. {{if eq .Status "critical"}}
  3. // Critical state!{{end}}
  4. {{if eq .Status "passing"}}
  5. // Ok{{end}}
  6.  

執行命令時,在Consul將服務設置爲維護模式,只需要在你的命令上包上Consul的 maint 調用:


 
  1. #!/bin/sh
  2. set -e
  3. consul maint -enable -service web -reason "Consul Template updated"
  4. service nginx reload
  5. consul maint -disable -service web
  6.  

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


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

services

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


 
  1. {{services}}
  2.  

這個例子將查詢Consul的默認數據中心,你可以指定一個可選參數來指定數據中心:


 
  1. {{services "@east-aws"}}
  2.  

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


 
  1. {{range services}}
  2. {{.Name}}
  3. {{range .Tags}}
  4. {{.}}{{end}}
  5. {{end}}
  6.  

tree

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


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

如果Consul實例在east-aws數據中心有一個service/redis結構,模板的渲染結果類似下面:


 
  1. minconns 2
  2. maxconns 12
  3. nested/config/value "value"
  4.  

ls不同,tree返回前綴下的所有key.和Unix的tree命令比較像.如果忽略數據中心參數,則會使用本地數據中心

查看更多

項目Github地址

Haproxy 實例

根據haproxy服務的配置文件創建一個consul-template模版渲染文件:haproxy.ctmpl


 
  1. # Consul Haproxy configured
  2.  
  3. global
  4. maxconn 20480
  5. ulimit-n 65535
  6. log 127.0.0.1 local5
  7. uid 200
  8. gid 200
  9. chroot /usr/local/haproxy
  10. nbproc 1
  11. daemon
  12. pidfile /usr/local/haproxy/logs/haproxy.pid
  13.  
  14. defaults
  15. log global
  16. mode http
  17. option httplog
  18. option dontlognull
  19. option forwardfor
  20. option abortonclose
  21. retries 3
  22. maxconn 3000
  23. stats enable
  24. stats hide-version
  25. stats uri /admin
  26. stats auth admin:admin
  27. stats refresh 10s
  28. balance roundrobin
  29. timeout connect 5000ms
  30. timeout client 50000ms
  31. timeout server 50000ms
  32. timeout check 2000ms
  33.  
  34. listen web_haproxy
  35. bind 0.0.0.0:8080
  36. mode http
  37. log 127.0.0.1 local5 err
  38. stats refresh 5s
  39. stats uri /admin
  40. stats realm liang lian
  41. stats auth admin:admin
  42. stats hide-version
  43. stats admin if TRUE
  44.  
  45. frontend consul
  46. bind 0.0.0.0:8500
  47. mode http
  48. log global
  49. default_backend consul-cluster
  50.  
  51. backend consul-cluster
  52. mode http
  53. {{range service "Faceid"}}
  54. server {{.ID}} {{.Address}}:{{.Port}} check inter 5000 fall 1 rise 2 weight 2{{end}}

運行consul-template作爲一個服務,通過上面的渲染模版渲染一個haproxy.cfg的配置文件,然後重啓haproxy服務


 
  1. 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


 
  1. # Consul Haproxy configured
  2.  
  3. global
  4. maxconn 20480
  5. ulimit-n 65535
  6. log 127.0.0.1 local5
  7. uid 200
  8. gid 200
  9. chroot /usr/local/haproxy
  10. nbproc 1
  11. daemon
  12. pidfile /usr/local/haproxy/logs/haproxy.pid
  13.  
  14. defaults
  15. log global
  16. mode http
  17. option httplog
  18. option dontlognull
  19. option forwardfor
  20. option abortonclose
  21. retries 3
  22. maxconn 3000
  23. stats enable
  24. stats hide-version
  25. stats uri /admin
  26. stats auth admin:admin
  27. stats refresh 10s
  28. balance roundrobin
  29. timeout connect 5000ms
  30. timeout client 50000ms
  31. timeout server 50000ms
  32. timeout check 2000ms
  33.  
  34. listen web_haproxy
  35. bind 0.0.0.0:8080
  36. mode http
  37. log 127.0.0.1 local5 err
  38. stats refresh 5s
  39. stats uri /admin
  40. stats realm liang lian
  41. stats auth admin:admin
  42. stats hide-version
  43. stats admin if TRUE
  44.  
  45. frontend consul
  46. bind 0.0.0.0:8500
  47. mode http
  48. log global
  49. default_backend consul-cluster
  50.  
  51. backend consul-cluster
  52. mode http
  53.  
  54. server Faceid 10.201.102.198:9000 check inter 5000 fall 1 rise 2 weight 2
  55. server Faceid 10.201.102.199:9000 check inter 5000 fall 1 rise 2 weight 2
  56. 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

Service RPM Download

Consul 0.7.5

下載

點擊下載PDF文件

本文標題:Consul 使用手冊

文章作者:樑先森

發佈時間:2017-04-06, 19:25:40

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

原始鏈接:http://www.liangxiansen.cn/2017/04/06/consul/ 

許可協議: "署名-非商用-相同方式共享 4.0" 轉載請保留原文鏈接及作者。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章