当前位置:网站首页>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

边栏推荐
- Syntax summary of easygui
- 国联证券买股票开户安全吗?
- Gson and fastjson
- Writing standard of physical quantities and unit symbols
- I2C device driver hierarchy
- GameFramework制作游戏(二)制作UI界面
- 关于RDBMS和非RDBMS【数据库系统】
- MySQL的登陆【数据库系统】
- "Ask every day" how locksupport realizes thread waiting and wakeup
- 44 Sina navigation, Xiaomi sidebar exercise
猜你喜欢

Raft of distributed consistency protocol

I2C设备驱动程序的层次结构

37 element mode (inline element, block element, inline block element)

41 图片背景综合-五彩导航图

Development of uni app offline ID card identification plug-in based on paddleocr

English语法_不定代词 - other / another

阿里云技术专家邓青琳:云上跨可用区容灾和异地多活最佳实践

Go language founder leaves Google

微信公众号正式环境上线部署,第三方公众平台接入

27 选择器的分类
随机推荐
Gameframework making games (I)
The solution to the problem that the progress bar of ros2 installation connext RMW is stuck at 13%
45padding won't open the box
String type time comparison method with error string.compareto
51 single chip microcomputer learning notes (2)
27 选择器的分类
[Nuxt 3] (十一) 传送 & 模块
[C题目]力扣876. 链表的中间结点
Kibana operation es
"Ask every day" what is volatile
变分(Calculus of variations)的概念及运算规则
云安全技术发展综述
快速搭建Dobbo小Demo
39 simple version of millet sidebar exercise
Spark 参数配置的几种方法
MySQL的登陆【数据库系统】
awk从入门到入土(20)awk解析命令行参数
EDA chip design solution based on AMD epyc server
35 快速格式化代码
Content type corresponding to office file