blob: 7f8f8d0ee3d8655a35be249d88821f40593d8b46 [file] [log] [blame]
David K. Bainbridgedf9df632016-07-07 18:47:46 -07001// Copyright 2016 Open Networking Laboratory
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
David K. Bainbridge546cdc32016-06-29 15:30:22 -070014package main
15
16import (
17 "encoding/json"
18 consul "github.com/hashicorp/consul/api"
David K. Bainbridge546cdc32016-06-29 15:30:22 -070019 "net/url"
20)
21
22const (
23 PREFIX = "cord/provisioner/"
24)
25
26type ConsulStorage struct {
27 client *consul.Client
28 kv *consul.KV
29}
30
31func NewConsulStorage(spec string) (*ConsulStorage, error) {
32 conn, err := url.Parse(spec)
33 if err != nil {
34 return nil, err
35 }
36
37 cfg := consul.Config{
38 Address: conn.Host,
39 Scheme: "http",
40 }
41
David K. Bainbridgea9c2e0a2016-07-01 18:33:50 -070042 log.Debugf("Consul config = %+v", cfg)
David K. Bainbridge546cdc32016-06-29 15:30:22 -070043
44 client, err := consul.NewClient(&cfg)
45 if err != nil {
46 return nil, err
47 }
48 return &ConsulStorage{
49 client: client,
50 kv: client.KV(),
51 }, nil
52}
53
54func (s *ConsulStorage) Put(id string, update StatusMsg) error {
55 data, err := json.Marshal(update)
56 if err != nil {
57 return err
58 }
59 _, err = s.kv.Put(&consul.KVPair{
60 Key: PREFIX + id,
61 Value: data,
62 }, nil)
63 return err
64}
65
David K. Bainbridge068e87d2016-06-30 13:53:19 -070066func (s *ConsulStorage) Delete(id string) error {
67 _, err := s.kv.Delete(PREFIX+id, nil)
68 return err
69}
70
David K. Bainbridge546cdc32016-06-29 15:30:22 -070071func (s *ConsulStorage) Get(id string) (*StatusMsg, error) {
72 pair, _, err := s.kv.Get(PREFIX+id, nil)
73 if err != nil {
74 return nil, err
75 }
76
77 if pair == nil {
78 return nil, nil
79 }
80
81 var record StatusMsg
82 err = json.Unmarshal([]byte(pair.Value), &record)
83 if err != nil {
84 return nil, err
85 }
86 return &record, nil
87}
88
89func (s *ConsulStorage) List() ([]StatusMsg, error) {
90 pairs, _, err := s.kv.List(PREFIX, nil)
91 if err != nil {
92 return nil, err
93 }
94 result := make([]StatusMsg, len(pairs))
95 i := 0
96 for _, pair := range pairs {
97 err = json.Unmarshal([]byte(pair.Value), &(result[i]))
98 if err != nil {
99 return nil, err
100 }
101 i += 1
102 }
103 return result, nil
104}