blob: 0a0c62d25b6f5acc17f7a5ffc0a828a9fc4860cf [file] [log] [blame]
David K. Bainbridge546cdc32016-06-29 15:30:22 -07001package main
2
3import (
4 "encoding/json"
5 consul "github.com/hashicorp/consul/api"
David K. Bainbridge546cdc32016-06-29 15:30:22 -07006 "net/url"
7)
8
9const (
10 PREFIX = "cord/provisioner/"
11)
12
13type ConsulStorage struct {
14 client *consul.Client
15 kv *consul.KV
16}
17
18func NewConsulStorage(spec string) (*ConsulStorage, error) {
19 conn, err := url.Parse(spec)
20 if err != nil {
21 return nil, err
22 }
23
24 cfg := consul.Config{
25 Address: conn.Host,
26 Scheme: "http",
27 }
28
David K. Bainbridgea9c2e0a2016-07-01 18:33:50 -070029 log.Debugf("Consul config = %+v", cfg)
David K. Bainbridge546cdc32016-06-29 15:30:22 -070030
31 client, err := consul.NewClient(&cfg)
32 if err != nil {
33 return nil, err
34 }
35 return &ConsulStorage{
36 client: client,
37 kv: client.KV(),
38 }, nil
39}
40
41func (s *ConsulStorage) Put(id string, update StatusMsg) error {
42 data, err := json.Marshal(update)
43 if err != nil {
44 return err
45 }
46 _, err = s.kv.Put(&consul.KVPair{
47 Key: PREFIX + id,
48 Value: data,
49 }, nil)
50 return err
51}
52
David K. Bainbridge068e87d2016-06-30 13:53:19 -070053func (s *ConsulStorage) Delete(id string) error {
54 _, err := s.kv.Delete(PREFIX+id, nil)
55 return err
56}
57
David K. Bainbridge546cdc32016-06-29 15:30:22 -070058func (s *ConsulStorage) Get(id string) (*StatusMsg, error) {
59 pair, _, err := s.kv.Get(PREFIX+id, nil)
60 if err != nil {
61 return nil, err
62 }
63
64 if pair == nil {
65 return nil, nil
66 }
67
68 var record StatusMsg
69 err = json.Unmarshal([]byte(pair.Value), &record)
70 if err != nil {
71 return nil, err
72 }
73 return &record, nil
74}
75
76func (s *ConsulStorage) List() ([]StatusMsg, error) {
77 pairs, _, err := s.kv.List(PREFIX, nil)
78 if err != nil {
79 return nil, err
80 }
81 result := make([]StatusMsg, len(pairs))
82 i := 0
83 for _, pair := range pairs {
84 err = json.Unmarshal([]byte(pair.Value), &(result[i]))
85 if err != nil {
86 return nil, err
87 }
88 i += 1
89 }
90 return result, nil
91}