BlueGit

timfa bluegit

Files

bluegit / internal / backupserver / config / fields.go

fields.go

fields.go 6.1 KiB Download Raw
1package config
2
3import (
4 "errors"
5 "fmt"
6 "net"
7 "os"
8 "path/filepath"
9 "sort"
10 "strconv"
11 "strings"
12 "time"
13
14 "gopkg.in/yaml.v3"
15)
16
17// Field beschrijft één instelling die de webinterface, de API en BlueGit
18// kunnen lezen en wijzigen. Alles wat in Fields staat, is overal hetzelfde
19// instelbaar.
20type Field struct {
21 Key string `json:"key"`
22 Label string `json:"label"`
23 Help string `json:"help"`
24 // Kind is duration, int of text.
25 Kind string `json:"kind"`
26 // Restart: pas na een herstart van kracht.
27 Restart bool `json:"restart,omitempty"`
28}
29
30// Fields zijn de instelbare velden, in de volgorde van de webinterface.
31var Fields = []Field{
32 {Key: "public_url", Label: "Publiek adres", Help: "Waar BlueGit deze server bereikt, bijvoorbeeld http://backup.lan:8080.", Kind: "text"},
33 {Key: "archive_interval", Label: "Archiefinterval", Help: "Zo vaak wordt de hele kopie gecomprimeerd opgeslagen (bijvoorbeeld 24h, 12h, 7d).", Kind: "duration"},
34 {Key: "retention_days", Label: "Bewaartermijn (dagen)", Help: "Archieven ouder dan dit gaan weg. 0 = nooit op leeftijd. Het nieuwste blijft altijd staan.", Kind: "int"},
35 {Key: "min_free_mb", Label: "Minimaal vrij (MB)", Help: "Minder vrije schijfruimte dan dit: het oudste archief gaat weg.", Kind: "int"},
36 {Key: "rate_limit_kib", Label: "Downloadsnelheid (KiB/s)", Help: "Zo snel wordt BlueGit hoogstens gelezen. 0 = onbeperkt.", Kind: "int"},
37 {Key: "full_sync_interval", Label: "Volledige controle", Help: "Ook zonder melding zo vaak alles nalopen.", Kind: "duration"},
38 {Key: "min_sync_interval", Label: "Minimale tijd tussen syncs", Help: "Na een melding wacht de server minstens zo lang sinds de vorige sync.", Kind: "duration"},
39 {Key: "listen", Label: "Luisteradres", Help: "Adres en poort van de webinterface en API. Geldt na een herstart.", Kind: "text", Restart: true},
40}
41
42// FieldByKey zoekt een veld.
43func FieldByKey(key string) (Field, bool) {
44 for _, f := range Fields {
45 if f.Key == key {
46 return f, true
47 }
48 }
49 return Field{}, false
50}
51
52// Get geeft de waarde van key als tekst.
53func (c Config) Get(key string) string {
54 switch key {
55 case "listen":
56 return c.Listen
57 case "public_url":
58 return c.PublicURL
59 case "data_dir":
60 return c.DataDir
61 case "archive_interval":
62 return FormatDuration(c.ArchiveInterval.Duration)
63 case "retention_days":
64 return strconv.Itoa(c.RetentionDays)
65 case "min_free_mb":
66 return strconv.FormatInt(c.MinFreeMB, 10)
67 case "rate_limit_kib":
68 return strconv.FormatInt(c.RateLimitKiB, 10)
69 case "full_sync_interval":
70 return FormatDuration(c.FullSyncInterval.Duration)
71 case "min_sync_interval":
72 return FormatDuration(c.MinSyncInterval.Duration)
73 }
74 return ""
75}
76
77// FormatDuration schrijft 24h als "24h" en 30m als "30m".
78func FormatDuration(d time.Duration) string {
79 if d%(24*time.Hour) == 0 && d >= 48*time.Hour {
80 return fmt.Sprintf("%dd", d/(24*time.Hour))
81 }
82 switch {
83 case d == 0:
84 return "0s"
85 case d%time.Hour == 0:
86 return fmt.Sprintf("%dh", d/time.Hour)
87 case d%time.Minute == 0:
88 return fmt.Sprintf("%dm", d/time.Minute)
89 case d%time.Second == 0:
90 return fmt.Sprintf("%ds", d/time.Second)
91 }
92 return d.String()
93}
94
95// ParseDuration leest een Go-duur of een aantal dagen ("7d").
96func ParseDuration(s string) (time.Duration, error) {
97 s = strings.TrimSpace(s)
98 if strings.HasSuffix(s, "d") {
99 n, err := strconv.Atoi(strings.TrimSuffix(s, "d"))
100 if err == nil && n >= 0 {
101 return time.Duration(n) * 24 * time.Hour, nil
102 }
103 }
104 d, err := time.ParseDuration(s)
105 if err != nil {
106 return 0, fmt.Errorf("ongeldige duur %q", s)
107 }
108 return d, nil
109}
110
111// Set zet key op val. Alleen velden uit Fields.
112func (c *Config) Set(key, val string) error {
113 f, ok := FieldByKey(key)
114 if !ok {
115 return fmt.Errorf("onbekende instelling %q", key)
116 }
117 val = strings.TrimSpace(val)
118 switch f.Kind {
119 case "duration":
120 d, err := ParseDuration(val)
121 if err != nil {
122 return fmt.Errorf("%s: %w", key, err)
123 }
124 switch key {
125 case "archive_interval":
126 c.ArchiveInterval.Duration = d
127 case "full_sync_interval":
128 c.FullSyncInterval.Duration = d
129 case "min_sync_interval":
130 c.MinSyncInterval.Duration = d
131 }
132 case "int":
133 n, err := strconv.ParseInt(val, 10, 64)
134 if err != nil || n < 0 {
135 return fmt.Errorf("%s: geef een geheel getal van 0 of meer", key)
136 }
137 switch key {
138 case "retention_days":
139 c.RetentionDays = int(n)
140 case "min_free_mb":
141 c.MinFreeMB = n
142 case "rate_limit_kib":
143 c.RateLimitKiB = n
144 }
145 default:
146 switch key {
147 case "public_url":
148 c.PublicURL = strings.TrimRight(val, "/")
149 case "listen":
150 if _, _, err := net.SplitHostPort(val); err != nil {
151 return fmt.Errorf("listen: verwacht host:poort, bijvoorbeeld 0.0.0.0:8080")
152 }
153 c.Listen = val
154 }
155 }
156 return nil
157}
158
159// Apply zet een reeks instellingen in één keer. Bij een fout verandert er niets.
160func (c *Config) Apply(set map[string]string) error {
161 next := *c
162 keys := make([]string, 0, len(set))
163 for k := range set {
164 keys = append(keys, k)
165 }
166 sort.Strings(keys)
167 for _, k := range keys {
168 if err := next.Set(k, set[k]); err != nil {
169 return err
170 }
171 }
172 if err := next.Validate(); err != nil {
173 return err
174 }
175 *c = next
176 return nil
177}
178
179// SettingsFile bewaart wat via de webinterface, API of BlueGit is ingesteld.
180// Het gaat boven config.yml, zodat config.yml van root mag blijven.
181const SettingsFile = "settings.yml"
182
183// LoadSettings leest data_dir/settings.yml (ontbreekt: leeg).
184func LoadSettings(dataDir string) (map[string]string, error) {
185 out := map[string]string{}
186 b, err := os.ReadFile(filepath.Join(dataDir, SettingsFile))
187 if errors.Is(err, os.ErrNotExist) {
188 return out, nil
189 }
190 if err != nil {
191 return nil, err
192 }
193 if err := yaml.Unmarshal(b, &out); err != nil {
194 return nil, fmt.Errorf("%s: %w", SettingsFile, err)
195 }
196 return out, nil
197}
198
199// SaveSettings schrijft data_dir/settings.yml.
200func SaveSettings(dataDir string, set map[string]string) error {
201 b, err := yaml.Marshal(set)
202 if err != nil {
203 return err
204 }
205 b = append([]byte("# Door de webinterface, API of BlueGit ingesteld. Gaat boven config.yml.\n"), b...)
206 tmp := filepath.Join(dataDir, SettingsFile+".tmp")
207 if err := os.WriteFile(tmp, b, 0o600); err != nil {
208 return err
209 }
210 return os.Rename(tmp, filepath.Join(dataDir, SettingsFile))
211}