blob: c327fc3a27daaf6ba6dd30e7c04798da88e3d58c [file] [log] [blame]
Stephane Barbarie4a2564d2018-07-26 11:02:58 -04001package model
2
3import (
4 "errors"
5 "fmt"
6 "github.com/opencord/voltha-go/db/kvstore"
7 "strconv"
8)
9
10//TODO: missing cache stuff
11//TODO: missing retry stuff
12//TODO: missing proper logging
13
14type Backend struct {
15 Client kvstore.Client
16 StoreType string
17 Host string
18 Port int
19 Timeout int
20 PathPrefix string
21}
22
23func NewBackend(storeType string, host string, port int, timeout int, pathPrefix string) *Backend {
24 var err error
25
26 b := &Backend{
27 StoreType: storeType,
28 Host: host,
29 Port: port,
30 Timeout: timeout,
31 PathPrefix: pathPrefix,
32 }
33
34 address := host + ":" + strconv.Itoa(port)
35 if b.Client, err = b.newClient(address, timeout); err != nil {
36 fmt.Errorf("failed to create a new kv Client - %s", err.Error())
37 }
38
39 return b
40}
41
42func (b *Backend) newClient(address string, timeout int) (kvstore.Client, error) {
43 switch b.StoreType {
44 case "consul":
45 return kvstore.NewConsulClient(address, timeout)
46 case "etcd":
47 return kvstore.NewEtcdClient(address, timeout)
48 }
49 return nil, errors.New("Unsupported KV store")
50}
51
52func (b *Backend) makePath(key string) string {
53 return fmt.Sprintf("%s/%s", b.PathPrefix, key)
54}
55func (b *Backend) Get(key string) (*kvstore.KVPair, error) {
56 return b.Client.Get(b.makePath(key), b.Timeout)
57}
58func (b *Backend) Put(key string, value interface{}) error {
59 return b.Client.Put(b.makePath(key), value, b.Timeout)
60}
61func (b *Backend) Delete(key string) error {
62 return b.Client.Delete(b.makePath(key), b.Timeout)
63}