|
|
package database |
|
|
|
|
|
import ( |
|
|
"time" |
|
|
|
|
|
"gorm.io/datatypes" |
|
|
"gorm.io/gorm" |
|
|
) |
|
|
|
|
|
|
|
|
type Agent struct { |
|
|
ID string `gorm:"primaryKey;column:id" json:"agent_id"` |
|
|
Hostname string `gorm:"column:hostname;not null" json:"hostname"` |
|
|
IP string `gorm:"column:ip;not null" json:"ip"` |
|
|
Version string `gorm:"column:version" json:"version"` |
|
|
Capabilities datatypes.JSON `gorm:"column:capabilities" json:"capabilities"` |
|
|
Meta string `gorm:"column:meta;not null" json:"meta"` |
|
|
LastSeen int64 `gorm:"column:last_seen;not null" json:"last_seen"` |
|
|
CreatedAt int64 `gorm:"column:created_at;not null" json:"created_at"` |
|
|
UpdatedAt int64 `gorm:"column:updated_at;not null" json:"updated_at"` |
|
|
Online bool `gorm:"column:online;not null;default:false" json:"online"` |
|
|
} |
|
|
|
|
|
type AgentStore struct { |
|
|
db *gorm.DB |
|
|
} |
|
|
|
|
|
|
|
|
func NewAgentStore(db *gorm.DB) *AgentStore { |
|
|
return &AgentStore{db: db} |
|
|
} |
|
|
|
|
|
|
|
|
func (s *AgentStore) Init() error { |
|
|
return s.db.AutoMigrate(&Agent{}) |
|
|
} |
|
|
|
|
|
|
|
|
func (s *AgentStore) Register(agent *Agent) error { |
|
|
now := time.Now().UnixMilli() |
|
|
agent.LastSeen = now |
|
|
if agent.CreatedAt == 0 { |
|
|
agent.CreatedAt = now |
|
|
} |
|
|
agent.UpdatedAt = now |
|
|
return s.db.Save(agent).Error |
|
|
} |
|
|
|
|
|
|
|
|
func (s *AgentStore) GetAgent(id string) (*Agent, error) { |
|
|
var agent Agent |
|
|
err := s.db.First(&agent, "id = ?", id).Error |
|
|
if err != nil { |
|
|
return nil, err |
|
|
} |
|
|
return &agent, nil |
|
|
} |
|
|
|
|
|
|
|
|
func (s *AgentStore) ListAgents() ([]*Agent, error) { |
|
|
var agents []*Agent |
|
|
err := s.db.Find(&agents).Error |
|
|
if err != nil { |
|
|
return nil, err |
|
|
} |
|
|
return agents, nil |
|
|
} |
|
|
|
|
|
|
|
|
func (s *AgentStore) UpdateLastSeen(id string) error { |
|
|
now := time.Now().UnixMilli() |
|
|
return s.db.Model(&Agent{}).Where("id = ?", id).Updates(map[string]interface{}{ |
|
|
"last_seen": now, |
|
|
"updated_at": now, |
|
|
}).Error |
|
|
} |
|
|
|
|
|
|
|
|
func (s *AgentStore) DeleteAgent(id string) error { |
|
|
return s.db.Delete(&Agent{}, "id = ?", id).Error |
|
|
} |
|
|
|
|
|
func (s *AgentStore) UpdateOnlineStatus(id string, online bool) error { |
|
|
return s.db.Model(&Agent{}).Where("id = ?", id).Update("online", online).Error |
|
|
} |
|
|
|