martes, 7 de febrero de 2023

Hacer un endpoit para saber el estado del host con echo en Golang parte 2


Todo muy lindo en el post anterior peeeeroo nos falto saber el estado del server, para ello vamos a utilizar la librería : "github.com/shirou/gopsutil". La idea es saber si tiene memoria libre, si el micro esta a full, etc. (estado de los recursos) 

Vamos a necesitar una estructura que contenga toda la información a mostrar : 


type StatusInfo struct {

RuntimeOS            string `json:"runtimeOS"`

TotalMemory          string `json:"total_memory"`

FreeMemory           string `json:"free_memory"`

PercentageUsedMemory string `json:"percentage_used_memory"`


TotalDiskSpace           string `json:"total_disk_space"`

UsedDiskSpace            string `json:"used_disk_space"`

FreeDiskSpace            string `json:"free_disk_space"`

PercentageDiskSpaceUsage string `json:"percentage_disk_space_usage"`


CpuIndexNumber string `json:"cpu_index_number"`

VendorId       string `json:"vendorId"`

Family         string `json:"family"`

NumberOfCores  string `json:"number_of_cores"`

ModelName      string `json:"model_name"`

Speed          string `json:"speed"`


Hostname                 string `json:"hostname"`

Uptime                   string `json:"uptime"`

NumberOfProcessesRunning string `json:"number_of_processes_running"`


Os       string `json:"os"`

Platform string `json:"platform"`


HostId string `json:"host_id"`

}

Y con la librería gopsutil podemos llenar el struct: 


func status(c echo.Context) error {

runtimeOS := runtime.GOOS

// memory

vmStat, err := mem.VirtualMemory()

dealwithErr(err)


diskStat, err := disk.Usage("/")

dealwithErr(err)


// cpu - get CPU number of cores and speed

cpuStat, err := cpu.Info()

dealwithErr(err)


// host or machine kernel, uptime, platform Info

hostStat, err := host.Info()

dealwithErr(err)


var sInfo StatusInfo


sInfo.RuntimeOS = runtimeOS

sInfo.TotalMemory = strconv.FormatUint(vmStat.Total, 10) + " bytes "

sInfo.FreeMemory = strconv.FormatUint(vmStat.Free, 10) + " bytes"

sInfo.PercentageUsedMemory = strconv.FormatFloat(vmStat.UsedPercent, 'f', 2, 64) + "%"


sInfo.TotalDiskSpace = strconv.FormatInt(int64(diskStat.Total), 10) + " bytes "

sInfo.UsedDiskSpace = strconv.FormatInt(int64(diskStat.Used), 10) + " bytes"

sInfo.FreeDiskSpace = strconv.FormatInt(int64(diskStat.Free), 10) + " bytes"

sInfo.PercentageDiskSpaceUsage = strconv.FormatFloat(diskStat.UsedPercent, 'f', 2, 64) + "%"


sInfo.CpuIndexNumber = strconv.FormatInt(int64(cpuStat[0].CPU), 10)

sInfo.VendorId = cpuStat[0].VendorID

sInfo.Family = cpuStat[0].Family

sInfo.NumberOfCores = strconv.FormatInt(int64(cpuStat[0].Cores), 10)

sInfo.ModelName = cpuStat[0].ModelName

sInfo.Speed = strconv.FormatFloat(cpuStat[0].Mhz, 'f', 2, 64)


sInfo.Hostname = hostStat.Hostname

sInfo.Uptime = strconv.FormatUint(hostStat.Uptime, 10)

sInfo.NumberOfProcessesRunning = strconv.FormatUint(hostStat.Procs, 10)


sInfo.Os = hostStat.OS

sInfo.Platform = hostStat.Platform


sInfo.HostId = hostStat.HostID


return c.JSON(http.StatusOK, sInfo)

}


Uso una función para mostrar el error : 


func dealwithErr(err error) {

if err != nil {

fmt.Println(err)

}

}



Y por último agregamos un endpoint en nuestro main: 


func main() {

e := echo.New()

        ....

e.GET("/status", func(c echo.Context) error {

return status(c)

})

e.Logger.Fatal(e.Start(":1323"))

}

Si vamos a localhost:1323/status podemos obtenere una salida como esta : 

{"runtimeOS":"linux","total_memory":"20769558528 bytes ","free_memory":"2220945408 bytes","percentage_used_memory":"75.97%","total_disk_space":"745407905792 bytes ","used_disk_space":"7737049088 bytes","free_disk_space":"737670856704 bytes","percentage_disk_space_usage":"1.04%","cpu_index_number":"0","vendorId":"GenuineIntel","family":"6","number_of_cores":"1","model_name":"11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz","speed":"4700.00","hostname":"crespo","uptime":"262837","number_of_processes_running":"462","os":"linux","platform":"ubuntu","host_id":"c47f72aa-2ce5-414b-97ad-d51759c9a406"}



No hay comentarios.:

Publicar un comentario