blob: 396e233e07f412f3779e85749c7f4c6c509bc8b4 [file] [log] [blame]
khenaidoobf6e7bb2018-08-14 22:27:29 -04001/*
2 * Copyright 2018-present Open Networking Foundation
3
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7
8 * http://www.apache.org/licenses/LICENSE-2.0
9
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Stephane Barbarie4a2564d2018-07-26 11:02:58 -040016package model
17
18import (
19 "errors"
20 "fmt"
21 "github.com/opencord/voltha-go/db/kvstore"
22 "strconv"
23)
24
25//TODO: missing cache stuff
26//TODO: missing retry stuff
27//TODO: missing proper logging
28
29type Backend struct {
30 Client kvstore.Client
31 StoreType string
32 Host string
33 Port int
34 Timeout int
35 PathPrefix string
36}
37
38func NewBackend(storeType string, host string, port int, timeout int, pathPrefix string) *Backend {
39 var err error
40
41 b := &Backend{
42 StoreType: storeType,
43 Host: host,
44 Port: port,
45 Timeout: timeout,
46 PathPrefix: pathPrefix,
47 }
48
49 address := host + ":" + strconv.Itoa(port)
50 if b.Client, err = b.newClient(address, timeout); err != nil {
51 fmt.Errorf("failed to create a new kv Client - %s", err.Error())
52 }
53
54 return b
55}
56
57func (b *Backend) newClient(address string, timeout int) (kvstore.Client, error) {
58 switch b.StoreType {
59 case "consul":
60 return kvstore.NewConsulClient(address, timeout)
61 case "etcd":
62 return kvstore.NewEtcdClient(address, timeout)
63 }
64 return nil, errors.New("Unsupported KV store")
65}
66
67func (b *Backend) makePath(key string) string {
68 return fmt.Sprintf("%s/%s", b.PathPrefix, key)
69}
70func (b *Backend) Get(key string) (*kvstore.KVPair, error) {
71 return b.Client.Get(b.makePath(key), b.Timeout)
72}
73func (b *Backend) Put(key string, value interface{}) error {
74 return b.Client.Put(b.makePath(key), value, b.Timeout)
75}
76func (b *Backend) Delete(key string) error {
77 return b.Client.Delete(b.makePath(key), b.Timeout)
78}