2 Copyright 2018 Intel Corporation.
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 http://www.apache.org/licenses/LICENSE-2.0
7 Unless required by applicable law or agreed to in writing, software
8 distributed under the License is distributed on an "AS IS" BASIS,
9 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 See the License for the specific language governing permissions and
11 limitations under the License.
20 pkgerrors "github.com/pkg/errors"
23 // DBconn interface used to talk a concrete Database connection
26 // Store is an interface for accessing a database
27 type Store interface {
28 // Returns nil if db health is good
31 // Unmarshal implements any unmarshaling needed for the database
32 Unmarshal(inp []byte, out interface{}) error
34 // Creates a new master table with key and links data with tag and
35 // creates a pointer to the newly added data in the master table
36 Create(table, key, tag string, data interface{}) error
38 // Reads data for a particular key with specific tag.
39 Read(table, key, tag string) ([]byte, error)
41 //TODO: Update(context.Context, string, interface{}) error
43 // Deletes a specific tag data for key.
44 // TODO: If tag is empty, it will delete all tags under key.
45 Delete(table, key, tag string) error
47 // Reads all master tables and data from the specified tag in table
48 ReadAll(table, tag string) (map[string][]byte, error)
51 // CreateDBClient creates the DB client
52 func CreateDBClient(dbType string) error {
56 // create a mongodb database with k8splugin as the name
57 DBconn, err = NewMongoStore("k8splugin", nil)
59 // create a consul kv store
60 DBconn, err = NewConsulStore(nil)
62 return pkgerrors.New(dbType + "DB not supported")
67 // Serialize converts given data into a JSON string
68 func Serialize(v interface{}) (string, error) {
69 out, err := json.Marshal(v)
71 return "", pkgerrors.Wrap(err, "Error serializing "+reflect.TypeOf(v).String())
73 return string(out), nil
76 // DeSerialize converts string to a json object specified by type
77 func DeSerialize(str string, v interface{}) error {
78 err := json.Unmarshal([]byte(str), &v)
80 return pkgerrors.Wrap(err, "Error deSerializing "+str)