-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathetcd.go
More file actions
93 lines (85 loc) · 2.47 KB
/
etcd.go
File metadata and controls
93 lines (85 loc) · 2.47 KB
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
package main
import (
"errors"
"io/ioutil"
"os"
"strings"
"time"
"golang.org/x/net/context"
etcd "github.com/coreos/etcd/client"
"github.com/spf13/viper"
)
func etcdConnect() error {
hosts := []string{}
if viper.IsSet("etcd.host") {
hosts = []string{viper.GetString("etcd.host")}
} else {
hosts = viper.GetStringSlice("etcd.hosts")
}
cfg := etcd.Config{
Endpoints: hosts,
Transport: etcd.DefaultTransport,
HeaderTimeoutPerRequest: time.Second,
}
cli, err := etcd.New(cfg)
if err != nil {
return err
}
etcdClient = etcd.NewKeysAPI(cli)
_, err = etcdClient.Get(context.Background(), "/foo", nil)
if err != nil && err.Error() == etcd.ErrClusterUnavailable.Error() {
return err
}
return nil
}
func etcdCreate(file string) error {
fd, err := os.Open(viper.GetString("repo.path") + _sep + file)
if err != nil {
return errors.New("Couldn't open file " + file + " : " + err.Error())
}
val, err := ioutil.ReadAll(fd)
if err != nil {
return errors.New("Couldn't read file " + file + " : " + err.Error())
}
// TrimSpace is used mostly to remove trailing newlines from Git files
_, err = etcdClient.Create(context.Background(), file, strings.TrimSpace(string(val)))
if err != nil {
return errors.New("Couldn't create file " + file + " : " + err.Error())
}
return nil
}
func etcdSet(file string) error {
fd, err := os.Open(viper.GetString("repo.path") + _sep + file)
if err != nil {
return errors.New("Couldn't open file " + file + " : " + err.Error())
}
val, err := ioutil.ReadAll(fd)
if err != nil {
return errors.New("Couldn't read file " + file + " : " + err.Error())
}
// TrimSpace is used mostly to remove trailing newlines from Git files
_, err = etcdClient.Set(context.Background(), file, strings.TrimSpace(string(val)), nil)
if err != nil {
return errors.New("Couldn't set file " + file + " : " + err.Error())
}
return nil
}
func etcdDelete(file string) error {
_, err := os.Stat(viper.GetString("repo.path") + _sep + file)
if err != nil && os.IsNotExist(err) {
_, err = etcdClient.Delete(context.Background(), file, nil)
if err != nil {
return errors.New("Couldn't set file " + file + " : " + err.Error())
}
} else {
return errors.New("File still exsits, not deleting " + file + " : " + err.Error())
}
return nil
}
func etcdExists(file string) bool {
_, err := etcdClient.Get(context.Background(), file, nil)
if err != nil && strings.Contains(err.Error(), "Key not found") {
return false
}
return true
}