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

边栏推荐
- Go language founder leaves Google
- (原创)自定义一个滚屏的RecyclerView
- Several methods of spark parameter configuration
- Reprint ---- how to read the code?
- "Ask every day" what is volatile
- I2C device driver hierarchy
- Spark 参数配置的几种方法
- awk从入门到入土(23)awk内置变量ARGC、ARGC--命令行参数传递
- 06、类神经网络
- How to realize a correct double check locking
猜你喜欢

Live classroom system 05 background management system

The concept and operation rules of calculus of variations

【MySQL系列】-索引知多少

"How to use" agent mode

Unable to start web server when Nacos starts
![优质数对的数目[位运算特点+抽象能力考察+分组快速统计]](/img/c9/8f8f0934111f7ae8f8abd656d92f12.png)
优质数对的数目[位运算特点+抽象能力考察+分组快速统计]

51单片机学习笔记(2)

Heyuan City launched fire safety themed milk tea to boost fire prevention and control in summer

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

39 simple version of millet sidebar exercise
随机推荐
IP address classification, which determines whether a network segment is a subnet supernetwork
spark参数调整调优
45padding不会撑开盒子的情况
[thread knowledge points] - spin lock
32 chrome调试工具的使用
C language and SQL Server database technology
[C topic] the penultimate node in the Niuke linked list
Add the jar package under lib directory to the project in idea
Yarn: the file yarn.ps1 cannot be loaded because running scripts is prohibited on this system.
Idea error failed to determine a suitable driver class
As methods for viewing and excluding dependencies
37 元素模式(行内元素,块元素,行内块元素)
QObject source code analysis -d pointer and Q pointer
27 选择器的分类
快速搭建Dobbo小Demo
Spark parameter adjustment and tuning
[C题目]牛客 链表中倒数第k个结点
Yes, UDP protocol can also be used to request DNS server
awk从入门到入土(20)awk解析命令行参数
[Nuxt 3] (十一) 传送 & 模块