3-Consul 使用手冊-推薦

原文:http://www.liangxiansen.cn/2017/04/06/consul/html

 

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

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

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

consul-cluster

基礎架構

Consul是一個分佈式高可用的系統. 這節將包含一些基礎,咱們忽略掉一些細節這樣你能夠快速瞭解Consul是如何工做的.若是要了解更多細節,請參考深刻的架構描述.mysql

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

Agent與一個和多個Consul Server 進行交互.Consul Server 用於存放和複製數據.server自行選舉一個領袖.雖然Consul能夠運行在一臺server , 可是建議使用3到5臺來避免失敗狀況下數據的丟失.每一個數據中心建議配置一個server集羣.nginx

你基礎設施中須要發現其餘服務的組件能夠查詢任何一個Consul 的server或者 agent.Agent會自動轉發請求到server .git

每一個數據中運行了一個Consul server集羣.當一個跨數據中心的服務發現和配置請求建立時.本地Consul Server轉發請求到遠程的數據中心並返回結果.github

更多介紹查看官網點擊前往web

安裝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. Available commands are:
  4. agent Runs a Consul agent
  5. configtest Validate config file
  6. event Fire a new event
  7. exec Executes a command on Consul nodes
  8. force-leave Forces a member of the cluster to enter the "left" state
  9. info Provides debugging information for operators
  10. join Tell Consul agent to join cluster
  11. keygen Generates a new encryption key
  12. keyring Manages gossip layer encryption keys
  13. kv Interact with the key-value store
  14. leave Gracefully leaves the Consul cluster and shuts down
  15. lock Execute a command holding a lock
  16. maint Controls node or service maintenance mode
  17. members Lists the members of a Consul cluster
  18. monitor Stream logs from a Consul agent
  19. operator Provides cluster-level tools for Consul operators
  20. reload Triggers the agent to reload configuration files
  21. rtt Estimates network round trip time between nodes
  22. snapshot Saves, restores and inspects snapshots of Consul server state
  23. version Prints the Consul version
  24. 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. ==> Log data will now stream in as it occurs:
  16. 2017/03/17 18:03:08 [INFO] raft: Restored from snapshot 139-352267-1489707086023
  17. 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}]
  18. 2017/03/17 18:03:08 [INFO] raft: Node at 10.201.102.198:8300 [Follower] entering Follower state (Leader: "")
  19. 2017/03/17 18:03:08 [INFO] serf: EventMemberJoin: s1 10.201.102.198
  20. 2017/03/17 18:03:08 [INFO] serf: Attempting re-join to previously known node: s2: 10.201.102.199:8301
  21. 2017/03/17 18:03:08 [INFO] consul: Adding LAN server s1 (Addr: tcp/10.201.102.198:8300) (DC: dc1)
  22. 2017/03/17 18:03:08 [INFO] consul: Raft data found, disabling bootstrap mode
  23. 2017/03/17 18:03:08 [INFO] serf: EventMemberJoin: s2 10.201.102.199
  24. 2017/03/17 18:03:08 [INFO] serf: EventMemberJoin: s3 10.201.102.200
  25. 2017/03/17 18:03:08 [INFO] serf: Re-joined to previously known node: s2: 10.201.102.199:8301
  26. 2017/03/17 18:03:08 [INFO] consul: Adding LAN server s2 (Addr: tcp/10.201.102.199:8300) (DC: dc1)
  27. 2017/03/17 18:03:08 [INFO] consul: Adding LAN server s3 (Addr: tcp/10.201.102.200:8300) (DC: dc1)
  28. 2017/03/17 18:03:08 [INFO] serf: EventMemberJoin: s1.dc1 10.201.102.198
  29. 2017/03/17 18:03:08 [INFO] consul: Adding WAN server s1.dc1 (Addr: tcp/10.201.102.198:8300) (DC: dc1)
  30. 2017/03/17 18:03:08 [WARN] serf: Failed to re-join any previously known node
  31. 2017/03/17 18:03:14 [INFO] agent: Synced service 'consul'
  32. 2017/03/17 18:03:14 [INFO] agent: Deregistered service 'consul01'
  33. 2017/03/17 18:03:14 [INFO] agent: Deregistered service 'consul02'
  34. 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. ==> Log data will now stream in as it occurs:
  17. 2017/03/17 15:35:16 [INFO] serf: EventMemberJoin: c1 10.201.102.248
  18. 2017/03/17 15:35:16 [INFO] agent: (LAN) joining: [10.201.102.198]
  19. 2017/03/17 15:35:16 [INFO] serf: EventMemberJoin: s2 10.201.102.199
  20. 2017/03/17 15:35:16 [INFO] serf: EventMemberJoin: s3 10.201.102.200
  21. 2017/03/17 15:35:16 [INFO] serf: EventMemberJoin: s1 10.201.102.198
  22. 2017/03/17 15:35:16 [INFO] agent: (LAN) joined: 1 Err: <nil>
  23. 2017/03/17 15:35:16 [INFO] consul: adding server s2 (Addr: tcp/10.201.102.199:8300) (DC: dc1)
  24. 2017/03/17 15:35:16 [INFO] consul: adding server s3 (Addr: tcp/10.201.102.200:8300) (DC: dc1)
  25. 2017/03/17 15:35:16 [INFO] consul: adding server s1 (Addr: tcp/10.201.102.198:8300) (DC: dc1)
  26. 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. [INFO] agent: Synced service 'web'
  4. ...
  • -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. ; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6 <<>> @127.0.0.1 -p 8600 web.service.consul
  3. ; (1 server found)
  4. ;; global options: +cmd
  5. ;; Got answer:
  6. ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 39468
  7. ;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
  8. ;; WARNING: recursion requested but not available
  9. ;; QUESTION SECTION:
  10. ;web.service.consul. IN A
  11. ;; ANSWER SECTION:
  12. web.service.consul. 0 IN A 10.201.102.198
  13. ;; Query time: 0 msec
  14. ;; SERVER: 127.0.0.1#8600(127.0.0.1)
  15. ;; WHEN: Tue Mar 28 16:10:24 2017
  16. ;; MSG SIZE rcvd: 52
  17. [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. ; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6 <<>> @127.0.0.1 -p 8600 web.service.consul SRV
  3. ; (1 server found)
  4. ;; global options: +cmd
  5. ;; Got answer:
  6. ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 13331
  7. ;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
  8. ;; WARNING: recursion requested but not available
  9. ;; QUESTION SECTION:
  10. ;web.service.consul. IN SRV
  11. ;; ANSWER SECTION:
  12. web.service.consul. 0 IN SRV 1 1 80 s1.node.dc1.consul.
  13. ;; ADDITIONAL SECTION:
  14. s1.node.dc1.consul. 0 IN A 10.201.102.198
  15. ;; Query time: 0 msec
  16. ;; SERVER: 127.0.0.1#8600(127.0.0.1)
  17. ;; WHEN: Tue Mar 28 16:10:56 2017
  18. ;; MSG SIZE rcvd: 84
  19. [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. ; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6 <<>> @127.0.0.1 -p 8600 rails.web.service.consul SRV
  3. ; (1 server found)
  4. ;; global options: +cmd
  5. ;; Got answer:
  6. ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 37307
  7. ;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
  8. ;; WARNING: recursion requested but not available
  9. ;; QUESTION SECTION:
  10. ;rails.web.service.consul. IN SRV
  11. ;; ANSWER SECTION:
  12. rails.web.service.consul. 0 IN SRV 1 1 80 s1.node.dc1.consul.
  13. ;; ADDITIONAL SECTION:
  14. s1.node.dc1.consul. 0 IN A 10.201.102.198
  15. ;; Query time: 0 msec
  16. ;; SERVER: 127.0.0.1#8600(127.0.0.1)
  17. ;; WHEN: Tue Mar 28 16:11:45 2017
  18. ;; MSG SIZE rcvd: 90
  19. [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. ; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6 <<>> @127.0.0.1 -p 8600 Faceid.service.consul SRV
  3. ; (1 server found)
  4. ;; global options: +cmd
  5. ;; Got answer:
  6. ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 40884
  7. ;; flags: qr aa rd; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 3
  8. ;; WARNING: recursion requested but not available
  9. ;; QUESTION SECTION:
  10. ;Faceid.service.consul. IN SRV
  11. ;; ANSWER SECTION:
  12. Faceid.service.consul. 0 IN SRV 1 1 9000 s3.node.dc1.consul.
  13. Faceid.service.consul. 0 IN SRV 1 1 9000 s1.node.dc1.consul.
  14. Faceid.service.consul. 0 IN SRV 1 1 9000 s2.node.dc1.consul.
  15. ;; ADDITIONAL SECTION:
  16. s3.node.dc1.consul. 0 IN A 10.201.102.200
  17. s1.node.dc1.consul. 0 IN A 10.201.102.198
  18. s2.node.dc1.consul. 0 IN A 10.201.102.199
  19. ;; Query time: 0 msec
  20. ;; SERVER: 127.0.0.1#8600(127.0.0.1)
  21. ;; WHEN: Tue Mar 28 18:20:15 2017
  22. ;; 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. Available commands are:
  4. agent Runs a Consul agent 運行一個consul agent
  5. configtest Validate config file
  6. event Fire a new event
  7. exec Executes a command on Consul nodes consul節點上執行一個命令
  8. force-leave Forces a member of the cluster to enter the "left" state 強制節點成員在集羣中的狀態轉換到left狀態
  9. info Provides debugging information for operators 提供操做的debug級別的信息
  10. join Tell Consul agent to join cluster 加入consul節點到集羣中
  11. keygen Generates a new encryption key 生成一個新的加密key
  12. keyring Manages gossip layer encryption keys
  13. kv Interact with the key-value store
  14. leave Gracefully leaves the Consul cluster and shuts down
  15. lock Execute a command holding a lock
  16. maint Controls node or service maintenance mode
  17. members Lists the members of a Consul cluster 列出集羣中成員
  18. monitor Stream logs from a Consul agent 打印consul節點的日誌信息
  19. operator Provides cluster-level tools for Consul operators
  20. reload Triggers the agent to reload configuration files 觸發節點從新加載配置文件
  21. rtt Estimates network round trip time between nodes
  22. snapshot Saves, restores and inspects snapshots of Consul server state
  23. version Prints the Consul version 打印consul的版本信息
  24. watch Watch for changes in Consul 監控consul的改變

更詳細見官網

Agent

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

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

event

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

  1. -http-addrhttp服務的地址,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-addrhttp服務的地址,agent能夠連接上來發送命令,若是沒有設置,則默認是127.0.0.1:8500
  2. -datacenter:數據中心。
  3. -prefixkeyKV系統中的前綴,用來存儲請求數據,默認是_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. -wanagent運行在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. -wanxxxxxx

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-addrhttp服務的地址,agent能夠連接上來發送命令,若是沒有設置,則默認是127.0.0.1:8500
  2. -datacenter:數據中心查詢。
  3. -tokenACL 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:監控類型,通常有keykeyprefixservicenodeschecksevent

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. -clientconsul綁定在哪一個client地址上,這個地址提供HTTPDNSRPC等服務,默認是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:加入一個已經啓動的agentip地址,能夠屢次指定多個agent的地址。若是consul不能加入任何指定的地址中,則agent會啓動失敗,默認agent啓動時不會加入任何節點。
  12. -retry-join:和join相似,可是容許你在第一次失敗後進行嘗試。
  13. -retry-interval:兩次join之間的時間間隔,默認是30s
  14. -retry-max:嘗試重複join的次數,默認是0,也就是無限次嘗試
  15. -log-levelconsul agent啓動後顯示的日誌信息級別。默認是info,可選:tracedebuginfowarnerr
  16. -node:節點在集羣中的名稱,在一個集羣中必須是惟一的,默認是該節點的主機名
  17. -protocolconsul使用的協議版本
  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信息,全部的serversdatacenter必須贊成ACL datacenter
  2. acl_default_policy:默認是allow
  3. acl_down_policy
  4. acl_master_token
  5. acl_tokenagent會使用這個tokenconsul server進行請求
  6. acl_ttl:控制TTLcache,默認是30s
  7. addresses:一個嵌套對象,能夠設置如下keydnshttprpc
  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:禁止支持遠程執行,設置爲trueagent會忽視全部進入的遠程執行請求
  20. disable_update_check:禁止自動檢查安全公告和新版本信息
  21. dns_config:是一個嵌套對象,能夠設置如下參數:allow_stalemax_stalenode_ttl service_ttlenable_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:這是一個嵌套對象,能夠設置如下keydns(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 CAnode_name,能夠用來確認CA namehostname相匹配
  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 serverclient都須要使用,由於二者都有出去的連接
  46. watcheswatch一個詳細名單

HTTP API

consul的主要接口是RESTful HTTP API,該API能夠用來增刪查改nodes、services、checks、configguration。全部的endpoints主要分爲如下類別:

  1. kv - Key/Value存儲
  2. agent - Agent控制
  3. catalog - 管理nodesservices
  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中給定nodeservice
  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中的服務目錄、keykey-values等。這種強大的抽象功能和查詢語言模板可使consul template特別適合動態的建立配置文件。例如:建立apache/nginx proxy balancershaproxy backendsvarnish serversapplication configurations

consul template的特性:

  1. quiescenceconsul 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 APItoken
  11. -syslog 把標準輸出和標準錯誤重定向到syslogsyslog的默認級別是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

命令行

一、查詢本地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

二、運行consul-temple做爲一個服務

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

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

  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"

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

注意: 不是全部的選項都是必選的.例如: 若是你沒有使用Vault你不用設置這一塊. 相似的你沒有使用syslog系統你也不須要指定syslog配置.

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

模版語法

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

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

API 函數

datacenters

查詢目錄中的全部數據中心.使用如下語法:

  1. {{datacenters}}
file

讀取並輸出磁盤上的本地文件,若是沒法讀取產生一個錯誤.使用以下語法

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

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

key

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

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

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

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

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

key_or_default

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

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

注意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}}

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

  1. minconns 2
  2. maxconns 12

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

node

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

  1. {{node "node1"}}

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

  1. {{node}}

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

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

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

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

查詢目錄中的所有節點,使用以下語法

  1. {{nodes}}

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

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

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

secret

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

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

可使用以下字段:

  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. {{index .Data "my.key.with.dots"}}
  7. 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.
  8. {{ with secret "pki/issue/my-domain-dot-com" "common_name=foo.example.com" }}
  9. {{ .Data.certificate }}
  10. {{ end }}
  11. The parameters must be key=value pairs, and each pair must be its own argument to the function:
  12. {{ secret "path/" "a=b" "c=d" "e=f" }}
  13. 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.

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

  1. {{range secrets "secret/"}}
  2. {{with secret (printf "secret/%s" .)}}
  3. {{range $k, $v := .Data}}
  4. {{$k}}: {{$v}}
  5. {{end}}
  6. {{end}}
  7. {{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中匹配表達式的服務.語法以下:

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

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

  1. {{service "web"}}

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

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

產生以下輸出:

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

默認值會返回健康的服務,若是你想獲取全部服務,能夠增長any選項,以下:

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

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

若是你想過濾指定的一個或者多個健康狀態,你能夠經過逗號隔開多個健康狀態:

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

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

指定了超過一個狀態過濾,幷包含any將會返回一個錯誤.由於any是比全部狀態更高級的過濾.

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

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

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

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

服務的狀態也是可見的,若是你想本身作一些額外的過濾,語法以下:

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

執行命令時,在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

另外若是你沒有安裝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"
services

查詢Consul目錄中的全部服務,使用以下語法:

  1. {{services}}

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

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

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

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

查詢全部指定前綴的key-value值對,若是其中的值有沒法轉換爲字符串的則引起錯誤:

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

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

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

ls不一樣,tree返回前綴下的全部key.和Unix的tree命令比較像.若是忽略數據中心參數,則會使用本地數據中心

查看更多

項目Github地址

Haproxy 實例

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

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

相關文章
相關標籤/搜索