Compare commits
5
Commits
331415bbab
...
c0c7152b47
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0c7152b47 | ||
|
|
262413e2e3 | ||
|
|
f5219f3c68 | ||
|
|
bceee08ce4 | ||
|
|
2aa0c3be86 |
@@ -0,0 +1,14 @@
|
||||
FROM golang:1.22-alpine AS builder
|
||||
WORKDIR /app
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o nanometrics-server .
|
||||
|
||||
FROM alpine:3.19
|
||||
RUN apk add --no-cache ca-certificates
|
||||
WORKDIR /app
|
||||
COPY --from=builder /app/nanometrics-server .
|
||||
VOLUME /data
|
||||
EXPOSE 8080 9999/udp
|
||||
CMD ["./nanometrics-server"]
|
||||
@@ -0,0 +1,38 @@
|
||||
package config
|
||||
|
||||
import "os"
|
||||
|
||||
type Config struct {
|
||||
UDPAddr string
|
||||
DBPath string
|
||||
HTTPAddr string
|
||||
MQTTBroker string
|
||||
MQTTTopicBase string
|
||||
}
|
||||
|
||||
func Load() Config {
|
||||
return Config{
|
||||
UDPAddr: getEnv("UDP_ADDR", "0.0.0.0:9999"),
|
||||
DBPath: getEnv("DB_PATH", "/data/nanometrics.db"),
|
||||
HTTPAddr: getEnv("HTTP_ADDR", "0.0.0.0:8080"),
|
||||
MQTTBroker: getEnv("MQTT_BROKER", "tcp://10.0.0.3:1883"),
|
||||
MQTTTopicBase: getEnv("MQTT_TOPIC_BASE", "nanometrics/agents"),
|
||||
}
|
||||
}
|
||||
|
||||
func getEnv(key, fallback string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func Default() Config {
|
||||
return Config{
|
||||
UDPAddr: "127.0.0.1:19999",
|
||||
DBPath: ":memory:",
|
||||
HTTPAddr: "127.0.0.1:18080",
|
||||
MQTTBroker: "tcp://127.0.0.1:11883",
|
||||
MQTTTopicBase: "test/nanometrics",
|
||||
}
|
||||
}
|
||||
+240
@@ -0,0 +1,240 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
|
||||
"github.com/user/nanometrics/server/models"
|
||||
)
|
||||
|
||||
type DB struct {
|
||||
conn *sql.DB
|
||||
}
|
||||
|
||||
const schema = `
|
||||
CREATE TABLE IF NOT EXISTS agents (
|
||||
id TEXT PRIMARY KEY, hostname TEXT NOT NULL,
|
||||
ip TEXT NOT NULL DEFAULT '', status TEXT NOT NULL DEFAULT 'offline',
|
||||
last_seen INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS metrics (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, agent_id TEXT NOT NULL, ts INTEGER NOT NULL,
|
||||
cpu_percent REAL, memory_used INTEGER, memory_free INTEGER, memory_total INTEGER,
|
||||
hdd_used INTEGER, hdd_free INTEGER, hdd_total INTEGER,
|
||||
uptime INTEGER, network_rx INTEGER, network_tx INTEGER, temperature REAL,
|
||||
smart_passed INTEGER, smart_temp INTEGER, smart_realloc INTEGER,
|
||||
smart_hours INTEGER, smart_wear INTEGER,
|
||||
FOREIGN KEY (agent_id) REFERENCES agents(id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_metrics_agent_ts ON metrics(agent_id, ts);
|
||||
CREATE TABLE IF NOT EXISTS agent_configs (
|
||||
agent_id TEXT PRIMARY KEY, config_json TEXT NOT NULL DEFAULT '{}',
|
||||
FOREIGN KEY (agent_id) REFERENCES agents(id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS agent_icons (
|
||||
agent_id TEXT PRIMARY KEY, data BLOB NOT NULL, mime_type TEXT NOT NULL DEFAULT 'image/png',
|
||||
FOREIGN KEY (agent_id) REFERENCES agents(id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS server_config (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
||||
`
|
||||
|
||||
func Open(path string) (*DB, error) {
|
||||
conn, err := sql.Open("sqlite", path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open sqlite: %w", err)
|
||||
}
|
||||
conn.SetMaxOpenConns(1)
|
||||
d := &DB{conn: conn}
|
||||
if err := d.migrate(); err != nil {
|
||||
return nil, fmt.Errorf("migrate: %w", err)
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func (d *DB) migrate() error {
|
||||
_, err := d.conn.Exec(schema)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *DB) Close() { _ = d.conn.Close() }
|
||||
|
||||
func (d *DB) UpsertAgent(m *models.AgentMetrics) error {
|
||||
ts := time.Now().Unix()
|
||||
_, err := d.conn.Exec(`
|
||||
INSERT INTO agents (id, hostname, ip, status, last_seen)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
ip=excluded.ip, status=excluded.status, last_seen=excluded.last_seen`,
|
||||
m.Hostname, m.Hostname, m.IP, m.Status, ts)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *DB) InsertMetrics(m *models.AgentMetrics) error {
|
||||
ts := time.Now().Unix()
|
||||
var smartPassed, smartTemp, smartRealloc, smartHours, smartWear interface{}
|
||||
if m.Smart != nil {
|
||||
b := 0
|
||||
if m.Smart.Passed {
|
||||
b = 1
|
||||
}
|
||||
smartPassed = b
|
||||
smartTemp = m.Smart.Temperature
|
||||
smartRealloc = m.Smart.ReallocatedSectors
|
||||
smartHours = m.Smart.PowerOnHours
|
||||
smartWear = m.Smart.WearLevel
|
||||
}
|
||||
_, err := d.conn.Exec(`
|
||||
INSERT INTO metrics (agent_id, ts,
|
||||
cpu_percent, memory_used, memory_free, memory_total,
|
||||
hdd_used, hdd_free, hdd_total,
|
||||
uptime, network_rx, network_tx, temperature,
|
||||
smart_passed, smart_temp, smart_realloc, smart_hours, smart_wear)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
m.Hostname, ts,
|
||||
m.CPUPercent, m.MemoryUsed, m.MemoryFree, m.MemoryTotal,
|
||||
m.HDDUsed, m.HDDFree, m.HDDTotal,
|
||||
m.Uptime, m.NetworkRX, m.NetworkTX, m.Temperature,
|
||||
smartPassed, smartTemp, smartRealloc, smartHours, smartWear)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *DB) GetAgents() ([]models.Agent, error) {
|
||||
rows, err := d.conn.Query(`SELECT id, hostname, ip, status, last_seen FROM agents`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var agents []models.Agent
|
||||
for rows.Next() {
|
||||
var a models.Agent
|
||||
if err := rows.Scan(&a.ID, &a.Hostname, &a.IP, &a.Status, &a.LastSeen); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
agents = append(agents, a)
|
||||
}
|
||||
return agents, nil
|
||||
}
|
||||
|
||||
func (d *DB) GetMetricsHistory(agentID string, from, to int64) ([]map[string]interface{}, error) {
|
||||
rows, err := d.conn.Query(`
|
||||
SELECT ts, cpu_percent, memory_used, memory_total, hdd_used, hdd_total
|
||||
FROM metrics
|
||||
WHERE agent_id = ? AND ts >= ? AND ts <= ?
|
||||
ORDER BY ts ASC`, agentID, from, to)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var result []map[string]interface{}
|
||||
for rows.Next() {
|
||||
var ts int64
|
||||
var cpu, memUsed, memTotal, hddUsed, hddTotal interface{}
|
||||
if err := rows.Scan(&ts, &cpu, &memUsed, &memTotal, &hddUsed, &hddTotal); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, map[string]interface{}{
|
||||
"ts": ts, "cpu_percent": cpu,
|
||||
"memory_used": memUsed, "memory_total": memTotal,
|
||||
"hdd_used": hddUsed, "hdd_total": hddTotal,
|
||||
})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (d *DB) GetAgentConfig(agentID string) (*models.AgentConfig, error) {
|
||||
var raw string
|
||||
err := d.conn.QueryRow(
|
||||
`SELECT config_json FROM agent_configs WHERE agent_id = ?`, agentID,
|
||||
).Scan(&raw)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var cfg models.AgentConfig
|
||||
if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
func (d *DB) UpsertAgentConfig(agentID string, cfg *models.AgentConfig) error {
|
||||
raw, err := json.Marshal(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.conn.Exec(`INSERT OR IGNORE INTO agents (id, hostname, ip, status, last_seen) VALUES (?,?,?,?,?)`,
|
||||
agentID, agentID, "", "offline", 0)
|
||||
_, err = d.conn.Exec(`
|
||||
INSERT INTO agent_configs (agent_id, config_json)
|
||||
VALUES (?, ?)
|
||||
ON CONFLICT(agent_id) DO UPDATE SET config_json=excluded.config_json`,
|
||||
agentID, string(raw))
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *DB) GetServerConfig() (models.ServerConfig, error) {
|
||||
cfg := models.DefaultServerConfig()
|
||||
var raw string
|
||||
if err := d.conn.QueryRow(`SELECT value FROM server_config WHERE key='ui'`).Scan(&raw); err == nil {
|
||||
_ = json.Unmarshal([]byte(raw), &cfg)
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (d *DB) SetServerConfig(cfg models.ServerConfig) error {
|
||||
raw, err := json.Marshal(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = d.conn.Exec(`
|
||||
INSERT INTO server_config (key, value) VALUES ('ui', ?)
|
||||
ON CONFLICT(key) DO UPDATE SET value=excluded.value`, string(raw))
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *DB) SaveIcon(agentID string, data []byte, mimeType string) error {
|
||||
d.conn.Exec(`INSERT OR IGNORE INTO agents (id, hostname, ip, status, last_seen) VALUES (?,?,?,?,?)`,
|
||||
agentID, agentID, "", "offline", 0)
|
||||
_, err := d.conn.Exec(`
|
||||
INSERT INTO agent_icons (agent_id, data, mime_type) VALUES (?,?,?)
|
||||
ON CONFLICT(agent_id) DO UPDATE SET data=excluded.data, mime_type=excluded.mime_type`,
|
||||
agentID, data, mimeType)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *DB) GetIcon(agentID string) ([]byte, string, error) {
|
||||
var data []byte
|
||||
var mime string
|
||||
err := d.conn.QueryRow(
|
||||
`SELECT data, mime_type FROM agent_icons WHERE agent_id=?`, agentID,
|
||||
).Scan(&data, &mime)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return data, mime, nil
|
||||
}
|
||||
|
||||
func (d *DB) PruneOldMetrics(retentionDays int) error {
|
||||
cutoff := time.Now().Unix() - int64(retentionDays)*86400
|
||||
_, err := d.conn.Exec(`DELETE FROM metrics WHERE ts < ?`, cutoff)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *DB) MarkOffline(timeoutSec int64) error {
|
||||
cutoff := time.Now().Unix() - timeoutSec
|
||||
_, err := d.conn.Exec(
|
||||
`UPDATE agents SET status='offline' WHERE last_seen < ? AND status != 'offline'`,
|
||||
cutoff)
|
||||
return err
|
||||
}
|
||||
|
||||
func init() {
|
||||
log.SetFlags(log.LstdFlags | log.Lshortfile)
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package db_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/user/nanometrics/server/db"
|
||||
"github.com/user/nanometrics/server/models"
|
||||
)
|
||||
|
||||
func newTestDB(t *testing.T) *db.DB {
|
||||
t.Helper()
|
||||
d, err := db.Open(":memory:")
|
||||
if err != nil {
|
||||
t.Fatalf("open db: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { d.Close() })
|
||||
return d
|
||||
}
|
||||
|
||||
func TestUpsertAndGetAgents(t *testing.T) {
|
||||
d := newTestDB(t)
|
||||
m := &models.AgentMetrics{Hostname: "srv-01", IP: "10.0.0.1", Status: "online"}
|
||||
if err := d.UpsertAgent(m); err != nil {
|
||||
t.Fatalf("upsert: %v", err)
|
||||
}
|
||||
agents, err := d.GetAgents()
|
||||
if err != nil {
|
||||
t.Fatalf("get agents: %v", err)
|
||||
}
|
||||
if len(agents) != 1 {
|
||||
t.Fatalf("attendu 1 agent, eu %d", len(agents))
|
||||
}
|
||||
if agents[0].Hostname != "srv-01" {
|
||||
t.Errorf("hostname: attendu srv-01, eu %s", agents[0].Hostname)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInsertMetrics(t *testing.T) {
|
||||
d := newTestDB(t)
|
||||
cpu := 42.5
|
||||
m := &models.AgentMetrics{Hostname: "srv-01", IP: "10.0.0.1", Status: "online", CPUPercent: &cpu}
|
||||
_ = d.UpsertAgent(m)
|
||||
if err := d.InsertMetrics(m); err != nil {
|
||||
t.Fatalf("insert metrics: %v", err)
|
||||
}
|
||||
history, err := d.GetMetricsHistory("srv-01", 0, 9999999999)
|
||||
if err != nil {
|
||||
t.Fatalf("history: %v", err)
|
||||
}
|
||||
if len(history) != 1 {
|
||||
t.Fatalf("attendu 1 entrée, eu %d", len(history))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentConfig(t *testing.T) {
|
||||
d := newTestDB(t)
|
||||
cfg := &models.AgentConfig{
|
||||
Metrics: models.MetricsConfig{
|
||||
CPU: models.MetricProto{UDP: true, MQTT: false},
|
||||
},
|
||||
}
|
||||
if err := d.UpsertAgentConfig("srv-01", cfg); err != nil {
|
||||
t.Fatalf("upsert config: %v", err)
|
||||
}
|
||||
got, err := d.GetAgentConfig("srv-01")
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("get config: %v", err)
|
||||
}
|
||||
if !got.Metrics.CPU.UDP {
|
||||
t.Error("CPU.UDP devrait être true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerConfig(t *testing.T) {
|
||||
d := newTestDB(t)
|
||||
cfg := models.DefaultServerConfig()
|
||||
cfg.TileMinWidth = 300
|
||||
if err := d.SetServerConfig(cfg); err != nil {
|
||||
t.Fatalf("set config: %v", err)
|
||||
}
|
||||
got, err := d.GetServerConfig()
|
||||
if err != nil {
|
||||
t.Fatalf("get config: %v", err)
|
||||
}
|
||||
if got.TileMinWidth != 300 {
|
||||
t.Errorf("tile_min_width: attendu 300, eu %d", got.TileMinWidth)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
version: '3.8'
|
||||
services:
|
||||
server:
|
||||
build: .
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
UDP_ADDR: "0.0.0.0:9999"
|
||||
DB_PATH: "/data/nanometrics.db"
|
||||
HTTP_ADDR: "0.0.0.0:8080"
|
||||
MQTT_BROKER: "tcp://10.0.0.3:1883"
|
||||
MQTT_TOPIC_BASE: "nanometrics/agents"
|
||||
volumes:
|
||||
- nanometrics_data:/data
|
||||
ports:
|
||||
- "9999:9999/udp"
|
||||
|
||||
dashboard:
|
||||
image: nginx:alpine
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro
|
||||
- ../dashboard:/usr/share/nginx/html:ro
|
||||
ports:
|
||||
- "80:80"
|
||||
depends_on:
|
||||
- server
|
||||
|
||||
volumes:
|
||||
nanometrics_data:
|
||||
@@ -0,0 +1,31 @@
|
||||
module github.com/user/nanometrics/server
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/disintegration/imaging v1.6.2 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||
github.com/prometheus/client_golang v1.23.2 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/prometheus/common v0.66.1 // indirect
|
||||
github.com/prometheus/procfs v0.16.1 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.2 // indirect
|
||||
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8 // indirect
|
||||
golang.org/x/net v0.44.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/sys v0.42.0 // indirect
|
||||
google.golang.org/protobuf v1.36.8 // indirect
|
||||
modernc.org/libc v1.72.3 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
modernc.org/sqlite v1.50.1 // indirect
|
||||
)
|
||||
@@ -0,0 +1,53 @@
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
|
||||
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1 h1:/VSOv3oDLlpqR2Epjn1Q7b2bSTplJIeV2ISgCl2W7nE=
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1/go.mod h1:1/yJCneuyOoCOzKSsOTUc0AJfpsItBGWvYpBLimhArU=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
|
||||
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
|
||||
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
|
||||
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
||||
github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs=
|
||||
github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=
|
||||
github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg=
|
||||
github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
|
||||
go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
|
||||
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8 h1:hVwzHzIUGRjiF7EcUjqNxk3NCfkPxbDKRdnNE1Rpg0U=
|
||||
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||
golang.org/x/net v0.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I=
|
||||
golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc=
|
||||
google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
modernc.org/libc v1.72.3 h1:ZnDF4tXn4NBXFutMMQC4vtbTFSXhhKzR73fv0beZEAU=
|
||||
modernc.org/libc v1.72.3/go.mod h1:dn0dZNnnn1clLyvRxLxYExxiKRZIRENOfqQ8XEeg4Qs=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/sqlite v1.50.1 h1:l+cQvn0sd0zJJtfygGHuQJ5AjlrwXmWPw4KP3ZMwr9w=
|
||||
modernc.org/sqlite v1.50.1/go.mod h1:tcNzv5p84E0skkmJn038y+hWJbLQXQqEnQfeh5r2JLM=
|
||||
@@ -0,0 +1,20 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/user/nanometrics/server/db"
|
||||
)
|
||||
|
||||
func AgentsHandler(database *db.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
agents, err := database.GetAgents()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(agents)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/user/nanometrics/server/db"
|
||||
"github.com/user/nanometrics/server/models"
|
||||
)
|
||||
|
||||
func AgentConfigHandler(database *db.DB, pushConfig func(agentID string, cfg *models.AgentConfig)) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
|
||||
if len(parts) < 4 {
|
||||
http.Error(w, "invalid path", 400)
|
||||
return
|
||||
}
|
||||
agentID := parts[2]
|
||||
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
cfg, err := database.GetAgentConfig(agentID)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
if cfg == nil {
|
||||
cfg = &models.AgentConfig{}
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(cfg)
|
||||
|
||||
case http.MethodPut:
|
||||
var cfg models.AgentConfig
|
||||
if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
|
||||
http.Error(w, err.Error(), 400)
|
||||
return
|
||||
}
|
||||
if err := database.UpsertAgentConfig(agentID, &cfg); err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
if pushConfig != nil {
|
||||
go pushConfig(agentID, &cfg)
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
|
||||
default:
|
||||
http.Error(w, "method not allowed", 405)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func ServerConfigHandler(database *db.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
cfg, err := database.GetServerConfig()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(cfg)
|
||||
|
||||
case http.MethodPut:
|
||||
var cfg models.ServerConfig
|
||||
if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
|
||||
http.Error(w, err.Error(), 400)
|
||||
return
|
||||
}
|
||||
if err := database.SetServerConfig(cfg); err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
|
||||
default:
|
||||
http.Error(w, "method not allowed", 405)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package handlers_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/user/nanometrics/server/db"
|
||||
"github.com/user/nanometrics/server/handlers"
|
||||
"github.com/user/nanometrics/server/models"
|
||||
)
|
||||
|
||||
func testDB(t *testing.T) *db.DB {
|
||||
d, _ := db.Open(":memory:")
|
||||
t.Cleanup(func() { d.Close() })
|
||||
return d
|
||||
}
|
||||
|
||||
func TestServerConfigGetPut(t *testing.T) {
|
||||
d := testDB(t)
|
||||
h := handlers.ServerConfigHandler(d)
|
||||
|
||||
r := httptest.NewRequest(http.MethodGet, "/api/config", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h(w, r)
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("GET status: %d", w.Code)
|
||||
}
|
||||
var got models.ServerConfig
|
||||
json.NewDecoder(w.Body).Decode(&got)
|
||||
if got.TileMinWidth != 220 {
|
||||
t.Errorf("tile_min_width défaut: %d", got.TileMinWidth)
|
||||
}
|
||||
|
||||
cfg := models.DefaultServerConfig()
|
||||
cfg.TileMinWidth = 300
|
||||
body, _ := json.Marshal(cfg)
|
||||
r2 := httptest.NewRequest(http.MethodPut, "/api/config", bytes.NewReader(body))
|
||||
w2 := httptest.NewRecorder()
|
||||
h(w2, r2)
|
||||
if w2.Code != 204 {
|
||||
t.Fatalf("PUT status: %d", w2.Code)
|
||||
}
|
||||
|
||||
r3 := httptest.NewRequest(http.MethodGet, "/api/config", nil)
|
||||
w3 := httptest.NewRecorder()
|
||||
h(w3, r3)
|
||||
var got2 models.ServerConfig
|
||||
json.NewDecoder(w3.Body).Decode(&got2)
|
||||
if got2.TileMinWidth != 300 {
|
||||
t.Errorf("tile_min_width après PUT: %d", got2.TileMinWidth)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentsHandler(t *testing.T) {
|
||||
d := testDB(t)
|
||||
h := handlers.AgentsHandler(d)
|
||||
|
||||
r := httptest.NewRequest(http.MethodGet, "/api/agents", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h(w, r)
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("status: %d", w.Code)
|
||||
}
|
||||
var agents []models.Agent
|
||||
json.NewDecoder(w.Body).Decode(&agents)
|
||||
if agents == nil {
|
||||
// tableau vide attendu, pas d'erreur
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
"image/png"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/disintegration/imaging"
|
||||
"github.com/user/nanometrics/server/db"
|
||||
)
|
||||
|
||||
const maxIconSize = 128
|
||||
|
||||
func IconUploadHandler(database *db.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
|
||||
if len(parts) < 4 {
|
||||
http.Error(w, "invalid path", 400)
|
||||
return
|
||||
}
|
||||
agentID := parts[2]
|
||||
|
||||
r.ParseMultipartForm(2 << 20)
|
||||
file, header, err := r.FormFile("icon")
|
||||
if err != nil {
|
||||
http.Error(w, "fichier manquant", 400)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
mime := header.Header.Get("Content-Type")
|
||||
if mime == "" {
|
||||
mime = "image/png"
|
||||
}
|
||||
|
||||
if strings.Contains(mime, "svg") {
|
||||
var buf bytes.Buffer
|
||||
buf.ReadFrom(file)
|
||||
if err := database.SaveIcon(agentID, buf.Bytes(), "image/svg+xml"); err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
|
||||
img, _, err := image.Decode(file)
|
||||
if err != nil {
|
||||
http.Error(w, "image invalide", 400)
|
||||
return
|
||||
}
|
||||
resized := imaging.Fit(img, maxIconSize, maxIconSize, imaging.Lanczos)
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, resized); err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
if err := database.SaveIcon(agentID, buf.Bytes(), "image/png"); err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func IconGetHandler(database *db.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
|
||||
if len(parts) < 4 {
|
||||
http.Error(w, "invalid path", 400)
|
||||
return
|
||||
}
|
||||
agentID := parts[2]
|
||||
data, mime, err := database.GetIcon(agentID)
|
||||
if err != nil {
|
||||
http.Error(w, "not found", 404)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", mime)
|
||||
w.Write(data)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/user/nanometrics/server/db"
|
||||
)
|
||||
|
||||
func MetricsHistoryHandler(database *db.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
|
||||
if len(parts) < 4 {
|
||||
http.Error(w, "invalid path", 400)
|
||||
return
|
||||
}
|
||||
agentID := parts[2]
|
||||
|
||||
now := time.Now().Unix()
|
||||
from := now - 3600
|
||||
to := now
|
||||
|
||||
if v := r.URL.Query().Get("from"); v != "" {
|
||||
if n, err := strconv.ParseInt(v, 10, 64); err == nil {
|
||||
from = n
|
||||
}
|
||||
}
|
||||
if v := r.URL.Query().Get("to"); v != "" {
|
||||
if n, err := strconv.ParseInt(v, 10, 64); err == nil {
|
||||
to = n
|
||||
}
|
||||
}
|
||||
|
||||
history, err := database.GetMetricsHistory(agentID, from, to)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(history)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
"github.com/user/nanometrics/server/config"
|
||||
"github.com/user/nanometrics/server/db"
|
||||
"github.com/user/nanometrics/server/handlers"
|
||||
"github.com/user/nanometrics/server/models"
|
||||
prom "github.com/user/nanometrics/server/prometheus"
|
||||
"github.com/user/nanometrics/server/transport"
|
||||
ws "github.com/user/nanometrics/server/websocket"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg := config.Load()
|
||||
|
||||
database, err := db.Open(cfg.DBPath)
|
||||
if err != nil {
|
||||
log.Fatalf("DB: %v", err)
|
||||
}
|
||||
|
||||
hub := ws.NewHub()
|
||||
|
||||
onMetrics := func(m *models.AgentMetrics) {
|
||||
if err := database.UpsertAgent(m); err != nil {
|
||||
log.Printf("[ingest] upsert agent: %v", err)
|
||||
}
|
||||
if err := database.InsertMetrics(m); err != nil {
|
||||
log.Printf("[ingest] insert metrics: %v", err)
|
||||
}
|
||||
prom.Update(m)
|
||||
hub.Broadcast(models.WSMessage{
|
||||
Type: "metrics_update",
|
||||
AgentID: m.Hostname,
|
||||
Data: m,
|
||||
})
|
||||
}
|
||||
|
||||
if err := transport.StartUDP(cfg.UDPAddr, onMetrics); err != nil {
|
||||
log.Fatalf("UDP: %v", err)
|
||||
}
|
||||
|
||||
var mqttClient *transport.MQTTClient
|
||||
if mc, err := transport.StartMQTT(cfg.MQTTBroker, cfg.MQTTTopicBase, onMetrics); err != nil {
|
||||
log.Printf("[mqtt] non disponible: %v", err)
|
||||
} else {
|
||||
mqttClient = mc
|
||||
}
|
||||
|
||||
pushConfig := func(agentID string, agentCfg *models.AgentConfig) {
|
||||
if mqttClient != nil {
|
||||
if err := mqttClient.PushConfig(agentID, agentCfg); err != nil {
|
||||
log.Printf("[mqtt] push config to %s: %v", agentID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
go func() {
|
||||
for range time.Tick(time.Minute) {
|
||||
srvCfg, _ := database.GetServerConfig()
|
||||
_ = database.PruneOldMetrics(srvCfg.RetentionDays)
|
||||
_ = database.MarkOffline(30)
|
||||
}
|
||||
}()
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("/metrics", promhttp.Handler())
|
||||
mux.Handle("/ws", ws.Handler(hub))
|
||||
mux.HandleFunc("/api/agents", handlers.AgentsHandler(database))
|
||||
mux.HandleFunc("/api/agents/", func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case endsWith(r.URL.Path, "/history"):
|
||||
handlers.MetricsHistoryHandler(database)(w, r)
|
||||
case endsWith(r.URL.Path, "/config"):
|
||||
handlers.AgentConfigHandler(database, pushConfig)(w, r)
|
||||
case endsWith(r.URL.Path, "/icon") && r.Method == http.MethodPost:
|
||||
handlers.IconUploadHandler(database)(w, r)
|
||||
case endsWith(r.URL.Path, "/icon") && r.Method == http.MethodGet:
|
||||
handlers.IconGetHandler(database)(w, r)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
})
|
||||
mux.HandleFunc("/api/config", handlers.ServerConfigHandler(database))
|
||||
|
||||
log.Printf("[http] écoute sur %s", cfg.HTTPAddr)
|
||||
log.Fatal(http.ListenAndServe(cfg.HTTPAddr, mux))
|
||||
}
|
||||
|
||||
func endsWith(path, suffix string) bool {
|
||||
return len(path) >= len(suffix) && path[len(path)-len(suffix):] == suffix
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package models
|
||||
|
||||
type AgentMetrics struct {
|
||||
Hostname string `json:"hostname"`
|
||||
IP string `json:"ip"`
|
||||
Status string `json:"status"`
|
||||
CPUPercent *float64 `json:"cpu_percent"`
|
||||
MemoryUsed *int64 `json:"memory_used"`
|
||||
MemoryFree *int64 `json:"memory_free"`
|
||||
MemoryTotal *int64 `json:"memory_total"`
|
||||
HDDUsed *int64 `json:"hdd_used"`
|
||||
HDDFree *int64 `json:"hdd_free"`
|
||||
HDDTotal *int64 `json:"hdd_total"`
|
||||
Uptime *int64 `json:"uptime"`
|
||||
NetworkRX *int64 `json:"network_rx"`
|
||||
NetworkTX *int64 `json:"network_tx"`
|
||||
Temperature *float64 `json:"temperature"`
|
||||
Smart *SmartMetrics `json:"smart"`
|
||||
}
|
||||
|
||||
type SmartMetrics struct {
|
||||
Passed bool `json:"passed"`
|
||||
Temperature *int64 `json:"temperature"`
|
||||
ReallocatedSectors *int64 `json:"reallocated_sectors"`
|
||||
PowerOnHours *int64 `json:"power_on_hours"`
|
||||
WearLevel *int64 `json:"wear_level"`
|
||||
}
|
||||
|
||||
type Agent struct {
|
||||
ID string `json:"id"`
|
||||
Hostname string `json:"hostname"`
|
||||
IP string `json:"ip"`
|
||||
Status string `json:"status"`
|
||||
LastSeen int64 `json:"last_seen"`
|
||||
LastMetrics *AgentMetrics `json:"last_metrics,omitempty"`
|
||||
}
|
||||
|
||||
type AgentConfig struct {
|
||||
Metrics MetricsConfig `json:"metrics"`
|
||||
Protocols ProtocolsConfig `json:"protocols"`
|
||||
}
|
||||
|
||||
type ProtocolsConfig struct {
|
||||
UDP UDPConfig `json:"udp"`
|
||||
MQTT MQTTConfig `json:"mqtt"`
|
||||
}
|
||||
|
||||
type UDPConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
type MQTTConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
TopicBase string `json:"topic_base"`
|
||||
AutoDiscovery bool `json:"auto_discovery"`
|
||||
BirthMessage bool `json:"birth_message"`
|
||||
LastWill bool `json:"last_will"`
|
||||
}
|
||||
|
||||
type MetricsConfig struct {
|
||||
CPU MetricProto `json:"cpu"`
|
||||
Memory MetricProto `json:"memory"`
|
||||
Disk MetricProto `json:"disk"`
|
||||
Network MetricProto `json:"network"`
|
||||
Uptime MetricProto `json:"uptime"`
|
||||
Temperature MetricProto `json:"temperature"`
|
||||
Smart MetricProto `json:"smart"`
|
||||
}
|
||||
|
||||
type MetricProto struct {
|
||||
UDP bool `json:"udp"`
|
||||
MQTT bool `json:"mqtt"`
|
||||
}
|
||||
|
||||
type ServerConfig struct {
|
||||
TileMinWidth int `json:"tile_min_width"`
|
||||
FontSize int `json:"font_size"`
|
||||
WarnCPU int `json:"warn_cpu"`
|
||||
ErrCPU int `json:"err_cpu"`
|
||||
WarnDisk int `json:"warn_disk"`
|
||||
RetentionDays int `json:"retention_days"`
|
||||
ChartDurationMin int `json:"chart_duration_min"`
|
||||
HideOffline bool `json:"hide_offline"`
|
||||
Notifications bool `json:"notifications"`
|
||||
PopupDetailW int `json:"popup_detail_w"`
|
||||
PopupDetailH int `json:"popup_detail_h"`
|
||||
}
|
||||
|
||||
func DefaultServerConfig() ServerConfig {
|
||||
return ServerConfig{
|
||||
TileMinWidth: 220, FontSize: 13,
|
||||
WarnCPU: 70, ErrCPU: 85, WarnDisk: 75,
|
||||
RetentionDays: 30, ChartDurationMin: 30,
|
||||
HideOffline: false, Notifications: true,
|
||||
PopupDetailW: 560, PopupDetailH: 600,
|
||||
}
|
||||
}
|
||||
|
||||
type WSMessage struct {
|
||||
Type string `json:"type"`
|
||||
AgentID string `json:"agent_id"`
|
||||
Data interface{} `json:"data"`
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
server {
|
||||
listen 80;
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://server:8080;
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
location /ws {
|
||||
proxy_pass http://server:8080/ws;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
}
|
||||
location /metrics {
|
||||
proxy_pass http://server:8080/metrics;
|
||||
}
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package prometheus
|
||||
|
||||
import (
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promauto"
|
||||
"github.com/user/nanometrics/server/models"
|
||||
)
|
||||
|
||||
var (
|
||||
agentCPU = promauto.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Name: "nanometrics_cpu_percent",
|
||||
Help: "Pourcentage CPU de l'agent",
|
||||
}, []string{"agent"})
|
||||
|
||||
agentMemUsed = promauto.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Name: "nanometrics_memory_used_bytes",
|
||||
Help: "RAM utilisée en octets",
|
||||
}, []string{"agent"})
|
||||
|
||||
agentMemTotal = promauto.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Name: "nanometrics_memory_total_bytes",
|
||||
Help: "RAM totale en octets",
|
||||
}, []string{"agent"})
|
||||
|
||||
agentDiskUsed = promauto.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Name: "nanometrics_disk_used_bytes",
|
||||
Help: "Disque utilisé en octets",
|
||||
}, []string{"agent"})
|
||||
|
||||
agentDiskTotal = promauto.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Name: "nanometrics_disk_total_bytes",
|
||||
Help: "Disque total en octets",
|
||||
}, []string{"agent"})
|
||||
|
||||
agentUptime = promauto.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Name: "nanometrics_uptime_seconds",
|
||||
Help: "Uptime de l'agent en secondes",
|
||||
}, []string{"agent"})
|
||||
|
||||
agentStatus = promauto.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Name: "nanometrics_agent_online",
|
||||
Help: "1 si l'agent est en ligne, 0 sinon",
|
||||
}, []string{"agent"})
|
||||
)
|
||||
|
||||
func Update(m *models.AgentMetrics) {
|
||||
l := prometheus.Labels{"agent": m.Hostname}
|
||||
if m.CPUPercent != nil {
|
||||
agentCPU.With(l).Set(*m.CPUPercent)
|
||||
}
|
||||
if m.MemoryUsed != nil {
|
||||
agentMemUsed.With(l).Set(float64(*m.MemoryUsed))
|
||||
}
|
||||
if m.MemoryTotal != nil {
|
||||
agentMemTotal.With(l).Set(float64(*m.MemoryTotal))
|
||||
}
|
||||
if m.HDDUsed != nil {
|
||||
agentDiskUsed.With(l).Set(float64(*m.HDDUsed))
|
||||
}
|
||||
if m.HDDTotal != nil {
|
||||
agentDiskTotal.With(l).Set(float64(*m.HDDTotal))
|
||||
}
|
||||
if m.Uptime != nil {
|
||||
agentUptime.With(l).Set(float64(*m.Uptime))
|
||||
}
|
||||
online := 0.0
|
||||
if m.Status == "online" {
|
||||
online = 1.0
|
||||
}
|
||||
agentStatus.With(l).Set(online)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
mqtt "github.com/eclipse/paho.mqtt.golang"
|
||||
"github.com/user/nanometrics/server/models"
|
||||
)
|
||||
|
||||
type MQTTClient struct {
|
||||
client mqtt.Client
|
||||
topicBase string
|
||||
}
|
||||
|
||||
func StartMQTT(broker, topicBase string, handler func(*models.AgentMetrics)) (*MQTTClient, error) {
|
||||
mc := &MQTTClient{topicBase: topicBase}
|
||||
|
||||
opts := mqtt.NewClientOptions().
|
||||
AddBroker(broker).
|
||||
SetClientID("nanometrics-server").
|
||||
SetAutoReconnect(true).
|
||||
SetOnConnectHandler(func(c mqtt.Client) {
|
||||
log.Printf("[mqtt] connecté à %s", broker)
|
||||
topic := fmt.Sprintf("%s/+/metrics", topicBase)
|
||||
if tok := c.Subscribe(topic, 0, nil); tok.Wait() && tok.Error() != nil {
|
||||
log.Printf("[mqtt] subscribe error: %v", tok.Error())
|
||||
}
|
||||
}).
|
||||
SetConnectionLostHandler(func(c mqtt.Client, err error) {
|
||||
log.Printf("[mqtt] connexion perdue: %v", err)
|
||||
}).
|
||||
SetDefaultPublishHandler(func(_ mqtt.Client, msg mqtt.Message) {
|
||||
var m models.AgentMetrics
|
||||
if err := json.Unmarshal(msg.Payload(), &m); err != nil {
|
||||
log.Printf("[mqtt] JSON invalide sur %s: %v", msg.Topic(), err)
|
||||
return
|
||||
}
|
||||
if m.Hostname != "" {
|
||||
handler(&m)
|
||||
}
|
||||
})
|
||||
|
||||
mc.client = mqtt.NewClient(opts)
|
||||
if tok := mc.client.Connect(); tok.Wait() && tok.Error() != nil {
|
||||
return nil, fmt.Errorf("mqtt connect: %w", tok.Error())
|
||||
}
|
||||
return mc, nil
|
||||
}
|
||||
|
||||
func (mc *MQTTClient) PushConfig(hostname string, cfg *models.AgentConfig) error {
|
||||
topic := fmt.Sprintf("%s/%s/config", mc.topicBase, hostname)
|
||||
data, err := json.Marshal(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tok := mc.client.Publish(topic, 1, false, data)
|
||||
tok.Wait()
|
||||
return tok.Error()
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net"
|
||||
|
||||
"github.com/user/nanometrics/server/models"
|
||||
)
|
||||
|
||||
func StartUDP(addr string, handler func(*models.AgentMetrics)) error {
|
||||
conn, err := net.ListenPacket("udp", addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Printf("[udp] écoute sur %s", addr)
|
||||
go func() {
|
||||
buf := make([]byte, 65535)
|
||||
for {
|
||||
n, _, err := conn.ReadFrom(buf)
|
||||
if err != nil {
|
||||
log.Printf("[udp] erreur lecture: %v", err)
|
||||
continue
|
||||
}
|
||||
data := make([]byte, n)
|
||||
copy(data, buf[:n])
|
||||
go processUDP(data, handler)
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
func processUDP(data []byte, handler func(*models.AgentMetrics)) {
|
||||
var m models.AgentMetrics
|
||||
if err := json.Unmarshal(data, &m); err != nil {
|
||||
log.Printf("[udp] JSON invalide: %v", err)
|
||||
return
|
||||
}
|
||||
if m.Hostname == "" {
|
||||
return
|
||||
}
|
||||
handler(&m)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package transport_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/user/nanometrics/server/models"
|
||||
"github.com/user/nanometrics/server/transport"
|
||||
)
|
||||
|
||||
func TestUDPReceive(t *testing.T) {
|
||||
received := make(chan *models.AgentMetrics, 1)
|
||||
err := transport.StartUDP("127.0.0.1:29999", func(m *models.AgentMetrics) {
|
||||
received <- m
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("start UDP: %v", err)
|
||||
}
|
||||
|
||||
conn, err := net.Dial("udp", "127.0.0.1:29999")
|
||||
if err != nil {
|
||||
t.Fatalf("dial: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
cpu := 55.0
|
||||
m := models.AgentMetrics{Hostname: "test-01", IP: "127.0.0.1", Status: "online", CPUPercent: &cpu}
|
||||
data, _ := json.Marshal(m)
|
||||
conn.Write(data)
|
||||
|
||||
select {
|
||||
case got := <-received:
|
||||
if got.Hostname != "test-01" {
|
||||
t.Errorf("hostname: attendu test-01, eu %s", got.Hostname)
|
||||
}
|
||||
if got.CPUPercent == nil || *got.CPUPercent != 55.0 {
|
||||
t.Error("cpu_percent incorrect")
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Error("timeout: aucune métrique reçue")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package websocket
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 4096,
|
||||
CheckOrigin: func(r *http.Request) bool { return true },
|
||||
}
|
||||
|
||||
func Handler(hub *Hub) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
log.Printf("[ws] upgrade: %v", err)
|
||||
return
|
||||
}
|
||||
hub.Register(conn)
|
||||
defer func() {
|
||||
hub.Unregister(conn)
|
||||
conn.Close()
|
||||
}()
|
||||
for {
|
||||
if _, _, err := conn.ReadMessage(); err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package websocket
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"sync"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
type Hub struct {
|
||||
mu sync.RWMutex
|
||||
clients map[*websocket.Conn]struct{}
|
||||
}
|
||||
|
||||
func NewHub() *Hub {
|
||||
return &Hub{clients: make(map[*websocket.Conn]struct{})}
|
||||
}
|
||||
|
||||
func (h *Hub) Register(conn *websocket.Conn) {
|
||||
h.mu.Lock()
|
||||
h.clients[conn] = struct{}{}
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
func (h *Hub) Unregister(conn *websocket.Conn) {
|
||||
h.mu.Lock()
|
||||
delete(h.clients, conn)
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
func (h *Hub) Broadcast(msg interface{}) {
|
||||
data, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
log.Printf("[ws] marshal: %v", err)
|
||||
return
|
||||
}
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
for conn := range h.clients {
|
||||
if err := conn.WriteMessage(websocket.TextMessage, data); err != nil {
|
||||
log.Printf("[ws] write: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hub) Count() int {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
return len(h.clients)
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package websocket_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
wslib "github.com/gorilla/websocket"
|
||||
"github.com/user/nanometrics/server/websocket"
|
||||
)
|
||||
|
||||
func TestHubBroadcast(t *testing.T) {
|
||||
hub := websocket.NewHub()
|
||||
srv := httptest.NewServer(websocket.Handler(hub))
|
||||
defer srv.Close()
|
||||
|
||||
url := "ws" + strings.TrimPrefix(srv.URL, "http") + "/ws"
|
||||
conn, _, err := wslib.DefaultDialer.Dial(url, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("dial: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
hub.Broadcast(map[string]string{"type": "test", "msg": "hello"})
|
||||
|
||||
conn.SetReadDeadline(time.Now().Add(time.Second))
|
||||
_, data, err := conn.ReadMessage()
|
||||
if err != nil {
|
||||
t.Fatalf("read: %v", err)
|
||||
}
|
||||
var got map[string]string
|
||||
json.Unmarshal(data, &got)
|
||||
if got["msg"] != "hello" {
|
||||
t.Errorf("attendu hello, eu %s", got["msg"])
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user