Prometheus 的優雅關閉姿勢

最近在看 Prometheus 的源代碼,發現它自帶了優雅的關閉方式,這和我以前博文講到的熱更新十分相似。

如何優雅關閉

  • 使用 kill 命令

因爲 Prometheus 是一個 Unix 二進制程序,我們可以向 Prometheus 進程發送 SIGTERM關閉信號。

  1. 使用 pgrep-f prometheus 找到運行的 Prometheus 進程號

  2. 使用 kill-TERM1234 來關閉

PS: 這裏 1234 指進程號。

  • 使用 HTTP 接口

Prometheus 提供了 HTTP 關閉接口,但在使用之前,需要通過 --web.enable-lifecycle 參數開啓 lifecycle 功能,然後你就可以使用 HTTP 請求來關閉程序了,例如:

curl -X POST http://localhost:9090/-/quit

此時 HTTP 接口會返回:

Requesting termination... Goodbye!

優雅關閉做了什麼

當我們使用以上兩種方法來關閉 Prometheus 的時候,在它的 log 中可以看到如下信息:

level=warn ts=2018-06-26T03:37:35.209100753Z caller=main.go:381 msg="Received termination request via web service, exiting gracefully..."

level=info ts=2018-06-26T03:37:35.212894277Z caller=main.go:402 msg="Stopping scrape discovery manager..."

level=info ts=2018-06-26T03:37:35.212937719Z caller=main.go:416 msg="Stopping notify discovery manager..."

level=info ts=2018-06-26T03:37:35.212963663Z caller=main.go:438 msg="Stopping scrape manager..."

level=info ts=2018-06-26T03:37:35.212975269Z caller=main.go:398 msg="Scrape discovery manager stopped"

level=info ts=2018-06-26T03:37:35.213029699Z caller=main.go:412 msg="Notify discovery manager stopped"

level=info ts=2018-06-26T03:37:35.21332349Z caller=main.go:432 msg="Scrape manager stopped"

level=info ts=2018-06-26T03:37:35.237387659Z caller=manager.go:464 component="rule manager" msg="Stopping rule manager..."

level=info ts=2018-06-26T03:37:35.238240277Z caller=manager.go:470 component="rule manager" msg="Rule manager stopped"

level=info ts=2018-06-26T03:37:35.238625599Z caller=notifier.go:512 component=notifier msg="Stopping notification manager..."

level=info ts=2018-06-26T03:37:35.238693489Z caller=main.go:588 msg="Notifier manager stopped"

level=info ts=2018-06-26T03:37:35.238723167Z caller=main.go:599 msg="See you next time!"

可以發現在程序終止之前它依次關閉瞭如下服務:

  • scrape discovery manager

  • notify discovery manager

  • scrape manager

  • rule manager

  • notification manager

  • fanoutStorage

優雅關閉的好處

雖然優雅關閉 Prometheus 耗時較長,但這個等待是值得的。

因爲它在關閉的同時做了很多依賴服務的清理工作,其中最主要的就是 fanoutStorage,如果它沒有正常關閉,很有可能破壞 TSDB 正在落盤的數據,從而導致一些莫名的 bug,以至於再也無法啓動 Prometheus 了。

突然想到一點,通常我們會使用 supervisord 來管理 Prometheus,那 supervisord 默認的 stop 命令發送的是什麼進程關閉信號呢?

查看了文檔,確認 supervisord 的 stopsignal 默認配置爲 TERM,恰好滿足 Prometheus 的優雅關閉方式,從而避免了對其進行額外的配置操作。

感謝作者:宋佳洋
閱讀原文

51Reboot golang課程 6.15開班

有想要諮詢的WeChat:17812796384

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