当前位置:网站首页>API health status self inspection
API health status self inspection
2022-07-25 14:56:00 【Laughter addiction】
One 、 What are the health indicators of the server
1、 disk space
2、 CPU state
3、 MEM state
4、 Service status, etc
Two 、 Define routing packets for server health checks
1、 Later, we will implement many processing functions corresponding to routes , If the quantity is large ,router The files will become very large , therefore , We can also put the processing function into handler Directory
2、”apiserver/handler/sd“ This directory will be used to save the server check related processing functions
3、 Script the routing function apiserver/router/router.go
// Load module - Processing function modularization
"apiserver/handler/sd"
// stay Load Function to add
// -modify here- Add health check handler
svcd := g.Group("/sd")
{
svcd.GET("/health", sd.HealthCheck)
svcd.GET("/disk", sd.DiskCheck)
svcd.GET("/cpu", sd.CPUCheck)
svcd.GET("/ram", sd.RAMCheck)
}
4、 Analyze the above function script
1、 This code block defines a code called sd Routing packets , Registered under this group `/health`、`/disk`、`/cpu`、`/ram` HTTP route , Route to `sd.HealthCheck`、`sd.DiskCheck`、`sd.CPUCheck`、`sd.RAMCheck` function .
2、sd Grouping is mainly used to check API Server The state of : health 、 Server hard disk 、CPU And memory usage .
3、`main()` Function by calling `router.Load` Function to load routes , Routes are mapped to specific processing functions
3、 ... and 、 Server health check implementation
1、 Write check script functions apiserver/handler/sd/check.go
package sd
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/disk"
"github.com/shirou/gopsutil/load"
"github.com/shirou/gopsutil/mem"
)
// Define constants
const (
B = 1
KB = 1024 * B
MB = 1024 * KB
GB = 1024 * MB
)
// HealthCheck shows `OK` as the ping-pong result.
func HealthCheck(c *gin.Context) {
message := "OK"
// http.StatusOK => all HTTP The status code corresponds to a name ( Source code )
c.String(http.StatusOK, "\n"+message)
}
// DiskCheck checks the disk usage.
func DiskCheck(c *gin.Context) {
// You can see disk.Usage Source code , Here are 2 Return values ,*UsageStat, erro
u, _ := disk.Usage("/")
usedMB := int(u.Used) / MB
usedGB := int(u.Used) / GB
totalMB := int(u.Total) / MB
totalGB := int(u.Total) / GB
usedPercent := int(u.UsedPercent)
status := http.StatusOK
text := "OK"
if usedPercent >= 95 {
status = http.StatusInternalServerError
text = "CRITICAL"
} else if usedPercent >= 90 {
status = http.StatusTooManyRequests
text = "WARNING"
}
message := fmt.Sprintf("%s - Free space: %dMB (%dGB) / %dMB (%dGB) | Used: %d%%", text, usedMB, usedGB, totalMB, totalGB, usedPercent)
c.String(status, "\n"+message)
}
// CPUCheck checks the cpu usage.
func CPUCheck(c *gin.Context) {
cores, _ := cpu.Counts(false)
a, _ := load.Avg()
l1 := a.Load1
l5 := a.Load5
l15 := a.Load15
status := http.StatusOK
text := "OK"
if l5 >= float64(cores-1) {
status = http.StatusInternalServerError
text = "CRITICAL"
} else if l5 >= float64(cores-2) {
status = http.StatusTooManyRequests
text = "WARNING"
}
message := fmt.Sprintf("%s - Load average: %.2f, %.2f, %.2f | Cores: %d", text, l1, l5, l15, cores)
c.String(status, "\n"+message)
}
// RAMCheck checks the disk usage.
func RAMCheck(c *gin.Context) {
u, _ := mem.VirtualMemory()
usedMB := int(u.Used) / MB
usedGB := int(u.Used) / GB
totalMB := int(u.Total) / MB
totalGB := int(u.Total) / GB
usedPercent := int(u.UsedPercent)
status := http.StatusOK
text := "OK"
if usedPercent >= 95 {
status = http.StatusInternalServerError
text = "CRITICAL"
} else if usedPercent >= 90 {
status = http.StatusTooManyRequests
text = "WARNING"
}
message := fmt.Sprintf("%s - Free space: %dMB (%dGB) / %dMB (%dGB) | Used: %d%%", text, usedMB, usedGB, totalMB, totalGB, usedPercent)
c.String(status, "\n"+message)
}
Four 、 Resolve dependencies and test
go mod tidy
go get github.com/shirou/gopsutil/cpu
go get github.com/shirou/gopsutil/disk
go get github.com/shirou/gopsutil/load
go get github.com/shirou/gopsutil/mem
5、 ... and 、 test

6、 ... and 、 start-up apiserver Time self check
1、 Timing task / The monitoring system : Write monitoring scripts , Remind me when there is a problem ( mail / SMS / Telephone / WeChat / nailing …)
2、 When starting the service : Take the initiative to check , Stop the service directly if there is a problem , Remind the Administrator
3、 stay apiserver/main.go The final definition of the document pingServer() Used for inspection /sd/health Normal access
// pingServer pings the http server to make sure the router is working.
func pingServer() error {
for i := 0; i < 10; i++ {
// request /sd/health => Get There are two return values
resp, err := http.Get("http://127.0.0.1:8000" + "/sd/health")
log.Print("Waiting for the router, retry in 1 second.")
// If you return 200, Indicates that the system has been started successfully , Go straight back to nil
if err == nil && resp.StatusCode == 200 {
return nil
}
// otherwise 1 Try again in seconds
log.Print("Waiting for the router, retry in 1 second.")
time.Sleep(time.Second)
}
// Try 10 Time , If both fail, an error is returned
return errors.New("Cannot connect to the router.")
}
# Function analysis
# stay `pingServer()` Function ,`http.Get` towards `http://0.0.0.0:8000/sd/health` send out HTTP GET request
# If the function executes correctly and returns HTTP StatusCode by 200, shows API Server available .
# If more than a specified number of times , The service is still inaccessible ,`pingServer` Meeting return errors, Express API Server not available .
4. stay apiserver/main.go The main function of the file main It calls pingServer() Function to check whether the service is normal
func main() {
...
// Call the coroutine function , Check service health
go func() {
if err := pingServer(); err != nil {
log.Fatal("The router has no response, or it might took too long to start up.", err)
}
log.Print("The router has been deployed successfully.")
}()
// Let the application run on the local server , The default listening port is 8080
g.Run("0.0.0.0:8000") // listen and serve on 0.0.0.0:8000
}
# Code parsing
# Start up HTTP Port front go One `pingServer` coroutines ( A task executed in parallel in the background )
# start-up HTTP After the port , The process continues ping `/sd/health` route
# If it works , Then the prompt of successful deployment will be output
# If the number of failures exceeds a certain number , Then terminate HTTP Server process
7、 ... and 、 test

边栏推荐
- Realsense ROS installation configuration introduction and problem solving
- 转载----如何阅读代码?
- Idea error failed to determine a suitable driver class
- SSH服务器拒绝了密码
- Several methods of spark parameter configuration
- Awk from entry to earth (24) extract the IP of the instruction network card
- [C题目]牛客 链表中倒数第k个结点
- Raft of distributed consistency protocol
- MySQL sort
- gson与fastjson
猜你喜欢

牛客多校 E G J L

冈萨雷斯 数字图像处理 第一章绪论

As methods for viewing and excluding dependencies

直播课堂系统05-后台管理系统

"Ask every day" how locksupport realizes thread waiting and wakeup

河源市区推出消防安全主题奶茶 助推夏季火灾防控

D2. picking carrots (hard version) (one question per day)

Leetcode-198- house raiding

Raft of distributed consistency protocol

Ssh server rejected password
随机推荐
Awk from getting started to digging in (23) awk built-in variables argc, argc -- command line parameter transfer
物理量与单位符号的书写标准
How to use the random number function of JMeter
06. Neural network like
Gameframework making games (II) making UI interface
Jmeter的随机数函数怎么用
"How to use" decorator mode
EDA chip design solution based on AMD epyc server
Several methods of spark parameter configuration
Melody + realsense d435i configuration and error resolution
Go语言创始人从Google离职
没错,请求DNS服务器还可以使用UDP协议
C language and SQL Server database technology
39 简洁版小米侧边栏练习
006操作符简介
Dpkg package download addresses of various platforms (including arm64)
软件测试 -- 1 软件测试知识大纲梳理
Thymeleaf controls whether display is displayed through style
"Ask every day" briefly talk about JMM / talk about your understanding of JMM
各种平台dpkg包下载地址(包括arm64)