95 lines
2.4 KiB
Go
95 lines
2.4 KiB
Go
// Package activity stores local preferences and optional execution metadata.
|
|
// No command arguments, environment variables, tokens or command output are logged.
|
|
package activity
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"sort"
|
|
"time"
|
|
|
|
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
|
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/storage"
|
|
"golang.org/x/sys/unix"
|
|
)
|
|
|
|
type Record struct {
|
|
Time time.Time `json:"time"`
|
|
Host string `json:"host"`
|
|
Command string `json:"command"`
|
|
Code int `json:"exit_code"`
|
|
Duration time.Duration `json:"duration_ns"`
|
|
}
|
|
type State struct {
|
|
Favorites map[string]bool `json:"favorites,omitempty"`
|
|
Pinned map[string]bool `json:"pinned,omitempty"`
|
|
Records []Record `json:"records,omitempty"`
|
|
}
|
|
|
|
func Path() string { return filepath.Join(filepath.Dir(config.Path()), "netssh", "activity.json") }
|
|
func Read() (State, error) {
|
|
var s State
|
|
data, err := os.ReadFile(Path())
|
|
if os.IsNotExist(err) {
|
|
err = nil
|
|
} else if err == nil {
|
|
err = json.Unmarshal(data, &s)
|
|
}
|
|
if s.Favorites == nil {
|
|
s.Favorites = map[string]bool{}
|
|
}
|
|
if s.Pinned == nil {
|
|
s.Pinned = map[string]bool{}
|
|
}
|
|
return s, err
|
|
}
|
|
func Update(change func(*State)) error {
|
|
p := Path()
|
|
if err := os.MkdirAll(filepath.Dir(p), 0700); err != nil {
|
|
return err
|
|
}
|
|
f, err := os.OpenFile(p+".lock", os.O_CREATE|os.O_RDWR, 0600)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer f.Close()
|
|
if err = unix.Flock(int(f.Fd()), unix.LOCK_EX); err != nil {
|
|
return err
|
|
}
|
|
defer unix.Flock(int(f.Fd()), unix.LOCK_UN)
|
|
s, err := Read()
|
|
if err != nil {
|
|
return fmt.Errorf("local state: %w", err)
|
|
}
|
|
change(&s)
|
|
data, err := json.MarshalIndent(s, "", " ")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return storage.WriteFile(p, data, 0600)
|
|
}
|
|
func Prune(s *State, c config.ActivityConfig) {
|
|
if c.RetentionDays > 0 {
|
|
cutoff := time.Now().Add(-time.Duration(c.RetentionDays) * 24 * time.Hour)
|
|
keep := s.Records[:0]
|
|
for _, r := range s.Records {
|
|
if !r.Time.Before(cutoff) {
|
|
keep = append(keep, r)
|
|
}
|
|
}
|
|
s.Records = keep
|
|
}
|
|
sort.SliceStable(s.Records, func(i, j int) bool { return s.Records[i].Time.Before(s.Records[j].Time) })
|
|
if c.MaxEntries > 0 && len(s.Records) > c.MaxEntries {
|
|
s.Records = s.Records[len(s.Records)-c.MaxEntries:]
|
|
}
|
|
}
|
|
func Append(c config.ActivityConfig, r Record) error {
|
|
if !c.Enabled {
|
|
return nil
|
|
}
|
|
return Update(func(s *State) { s.Records = append(s.Records, r); Prune(s, c) })
|
|
}
|