-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
95 lines (71 loc) · 1.76 KB
/
database.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"context"
"encoding/json"
"log"
"github.com/hetznercloud/hcloud-go/hcloud"
)
type Database struct {
Store map[string]string
Name string
Client *hcloud.Client
Context context.Context
Self *hcloud.SSHKey
NoInfo bool
}
func (d *Database) Init() {
keyPlaceholder := "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAUqWKFtn3P3p0tOWXMgkfc7aTc5Z17+LSlf50X/ep/Z"
database, response, err := d.Client.SSHKey.Create(d.Context, hcloud.SSHKeyCreateOpts{Name: d.Name, PublicKey: keyPlaceholder})
if err != nil && response.StatusCode == 409 {
log.Fatalf("database %s already exists", d.Name)
} else if err != nil {
log.Fatalf("unhandled error: %s\n", err)
}
d.Store = database.Labels
}
func (d *Database) Fetch() *hcloud.SSHKey {
db, _, err := d.Client.SSHKey.Get(d.Context, d.Name)
d.Self = db
if err != nil {
log.Fatalf("error retrieving database: %s\n", err)
}
if d.Self != nil {
d.Store = d.Self.Labels
} else {
log.Fatalf("database %s not found", d.Name)
}
checkSize(d)
return d.Self
}
func (d *Database) Set(key, value string) bool {
d.Fetch()
d.Store[key] = value
database, _, err := d.Client.SSHKey.Update(d.Context, d.Self, hcloud.SSHKeyUpdateOpts{Labels: d.Store})
if err != nil {
log.Fatalf("error updating db: %s\n", err)
}
d.Store = database.Labels
log.Println("OK")
checkSize(d)
return true
}
func (d *Database) Get(key string) string {
d.Fetch()
return d.Store[key]
}
func (d *Database) List() []string {
d.Fetch()
keys := make([]string, len(d.Store))
i := 0
for k := range d.Store {
keys[i] = k
i++
}
return keys
}
func checkSize(db *Database) {
if !db.NoInfo {
jsonStr, _ := json.Marshal(db.Store)
log.Printf("[Info] Database usage: %.2f%%", float64(len(jsonStr))/float64(maxDBBytes)*100)
}
}