first comm

This commit is contained in:
2024-10-02 08:29:09 +08:00
parent d8b0c2f766
commit 2e57b24335
10 changed files with 295 additions and 66 deletions

80
dao/mem_store.go Normal file
View File

@ -0,0 +1,80 @@
package dao
import (
"encoding/gob"
"github.com/LiteyukiStudio/go-logger/log"
"os"
"time"
)
var memStore = make(map[string]interface{})
func Save(key string, value interface{}) {
memStore[key] = value
}
func Delete(key string) error {
if _, ok := memStore[key]; ok {
delete(memStore, key)
return nil
} else {
return os.ErrNotExist
}
}
func Get(key string) interface{} {
if v, ok := memStore[key]; ok {
return v
}
return nil
}
func GetAll() map[string]interface{} {
return memStore
}
// init 初始化,从磁盘加载数据到内存
func init() {
gob.Register(Report{})
file, err := os.Open("data.gob")
if err != nil {
log.Error("Open file error: ", err)
}
log.Info("Open file success")
defer file.Close()
decoder := gob.NewDecoder(file)
err = decoder.Decode(&memStore)
if err != nil {
log.Error("Decode error: ", err)
}
// 启动定期持久化goroutine
go func() {
for {
err := persist()
if err != nil {
log.Error("Persist error: ", err)
}
log.Info("Persist success")
time.Sleep(30 * time.Second)
}
}()
}
// persist 持久化,定期将内存中的数据持久化到磁盘
func persist() error {
file, err := os.OpenFile("data.gob", os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Error("Open file error: ", err)
return err
}
defer file.Close()
encoder := gob.NewEncoder(file)
err = encoder.Encode(memStore)
if err != nil {
log.Error("Encode error: ", err)
return err
}
return nil
}

View File

@ -2,20 +2,20 @@ package dao
type Report struct {
// 鉴权字段
Auth struct {
Token string `json:"token"` // 令牌,用于鉴权,防止恶意请求
} `json:"auth"`
Meta struct {
ID string `json:"id"` // 服务器ID用于标识服务器
Name string `json:"name"`
OS struct {
Name string `json:"name"`
Version string `json:"version"`
}
Labels []string `json:"labels"` // 服务器标签
Location string `json:"location"` // Chongqing, China
Duration int64 `json:"duration"` // uptime in seconds
}
Labels []string `json:"labels"` // 服务器标签
Location string `json:"location"` // Chongqing, China
UpTime int64 `json:"uptime"` // uptime in seconds
Link string `json:"link"` // 链接或是nil
ObservedAt int64 `json:"observed_at"` // unix timestamp
} `json:"meta"`
Hardware struct {
Mem struct {
@ -27,14 +27,12 @@ type Report struct {
Used int64 `json:"used"`
} `json:"swap"`
Cpu struct {
Cores int `json:"cores"`
Logics int `json:"logics"`
Cores int `json:"cores"`
Logics int `json:"logics"`
Percent float32 `json:"percent"` // 0-100
} `json:"cpu"`
Disks []struct {
Name string `json:"name"`
Total int64 `json:"total"`
} `json:"disks"`
Net []struct {
Disks map[string]map[string]int64 `json:"disks"`
Net struct {
Up int64 `json:"up"`
Down int64 `json:"down"`
Type string `json:"type"` // IPv4 or IPv6 or IPv4/6