-
Notifications
You must be signed in to change notification settings - Fork 0
/
cloud_datastore.go
82 lines (67 loc) · 2 KB
/
cloud_datastore.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
package persist
import (
"context"
"fmt"
"github.com/coffee-dns/coffee-dns/nameserver/record"
"cloud.google.com/go/datastore"
)
// Datastore uses Google Cloud Datastore to persist dns records
type Datastore struct {
// The Google Cloud project hosting the datastore
ProjectID string
// Cloud Datastore entity Kind
Kind string
client *datastore.Client
}
// Init configures the cloud datastore client
func (d *Datastore) Init() error {
if d.ProjectID == "" {
return fmt.Errorf("field must be set: ProjectID")
}
if d.Kind == "" {
return fmt.Errorf("field must be set: Kind")
}
ctx := context.Background()
c, err := datastore.NewClient(ctx, d.ProjectID)
if err != nil {
return fmt.Errorf("failed to configure cloud datastore in project %s: %s", d.ProjectID, err)
}
d.client = c
return nil
}
// Get returns a value from the domain map
func (d *Datastore) Get(key string) (string, error) {
ctx := context.Background()
k := datastore.NameKey(d.Kind, key, nil)
e := record.Record{}
if err := d.client.Get(ctx, k, &e); err != nil {
return "", fmt.Errorf("failed to get key %s from cloud datastore: %s", key, err)
}
return e.Value, nil
}
// Set adds a key value pair to the domain map
func (d *Datastore) Set(r record.Record) error {
ctx := context.Background()
k := datastore.NameKey(d.Kind, r.Hostname, nil)
if _, err := d.client.Put(ctx, k, &r); err != nil {
return fmt.Errorf("failed to create record %s with value %s: %s", r.Hostname, r.Value, err)
}
return nil
}
// Delete deletes a key from the domain map
func (d *Datastore) Delete(key string) error {
ctx := context.Background()
k := datastore.NameKey(d.Kind, key, nil)
if err := d.client.Delete(ctx, k); err != nil {
return fmt.Errorf("failed to delete key %s from cloud datastore: %s", key, err)
}
return nil
}
// Close always returns nil
func (d *Datastore) Close() error {
return d.client.Close()
}
// Dump is not implemented
func (d *Datastore) Dump() ([]byte, error) {
return nil, fmt.Errorf("datastore does not implement Dump()")
}