David K. Bainbridge | 546cdc3 | 2016-06-29 15:30:22 -0700 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | consul "github.com/hashicorp/consul/api" |
David K. Bainbridge | 546cdc3 | 2016-06-29 15:30:22 -0700 | [diff] [blame] | 6 | "net/url" |
| 7 | ) |
| 8 | |
| 9 | const ( |
| 10 | PREFIX = "cord/provisioner/" |
| 11 | ) |
| 12 | |
| 13 | type ConsulStorage struct { |
| 14 | client *consul.Client |
| 15 | kv *consul.KV |
| 16 | } |
| 17 | |
| 18 | func 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. Bainbridge | a9c2e0a | 2016-07-01 18:33:50 -0700 | [diff] [blame] | 29 | log.Debugf("Consul config = %+v", cfg) |
David K. Bainbridge | 546cdc3 | 2016-06-29 15:30:22 -0700 | [diff] [blame] | 30 | |
| 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 | |
| 41 | func (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. Bainbridge | 068e87d | 2016-06-30 13:53:19 -0700 | [diff] [blame] | 53 | func (s *ConsulStorage) Delete(id string) error { |
| 54 | _, err := s.kv.Delete(PREFIX+id, nil) |
| 55 | return err |
| 56 | } |
| 57 | |
David K. Bainbridge | 546cdc3 | 2016-06-29 15:30:22 -0700 | [diff] [blame] | 58 | func (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 | |
| 76 | func (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 | } |