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

边栏推荐
- Development of uni app offline ID card identification plug-in based on paddleocr
- Gson and fastjson
- How to realize a correct double check locking
- 35 快速格式化代码
- awk从入门到入土(21)awk脚本调试
- IP地址分类,判断一个网段是子网超网
- 直播课堂系统05-后台管理系统
- 35 quick format code
- Educational Codeforces Round 132 (Rated for Div. 2) C,D+AC自动机
- The concept and operation rules of calculus of variations
猜你喜欢
![[MySQL series] - how much do you know about the index](/img/d7/5045a846580be106e2bf16d7b30581.png)
[MySQL series] - how much do you know about the index

Share a department design method that avoids recursion
![[Nacos] what does nacosclient do during service registration](/img/76/3c2e8f9ba19e36d9581f34fda65923.png)
[Nacos] what does nacosclient do during service registration

06、类神经网络

Go language founder leaves Google

51 single chip microcomputer learning notes (2)

GameFramework制作游戏(一)

51 single chip microcomputer learning notes (1)

51单片机学习笔记(2)

The solution to the problem that the progress bar of ros2 installation connext RMW is stuck at 13%
随机推荐
变分(Calculus of variations)的概念及运算规则
L1和L2正则化
"How to use" observer mode
Ssh server rejected password
云安全技术发展综述
[C题目]力扣876. 链表的中间结点
Gson and fastjson
37 元素模式(行内元素,块元素,行内块元素)
Melody + realsense d435i configuration and error resolution
Overview of cloud security technology development
LeetCode_ String_ Medium_ 151. Reverse the words in the string
45padding不会撑开盒子的情况
Niuke multi school E G J L
[eloquence] negotiation persuasion skills and Strategies
[MySQL series] - how much do you know about the index
kibana操作es
直播课堂系统05-后台管理系统
物理量与单位符号的书写标准
awk从入门到入土(24)提取指令网卡的ip
06、类神经网络