29e554d15f93eb5e1c0ba3bf28db86ea08d0a2b9
[icn/sdwan.git] /
1 // SPDX-License-Identifier: Apache-2.0
2 // Copyright (c) 2020 Intel Corporation
3
4 package contextdb
5
6 import (
7         "github.com/open-ness/EMCO/src/orchestrator/pkg/infra/config"
8         pkgerrors "github.com/pkg/errors"
9 )
10
11 // Db interface used to talk a concrete Database connection
12 var Db ContextDb
13
14 // ContextDb is an interface for accessing the context database
15 type ContextDb interface {
16         // Returns nil if db health is good
17         HealthCheck() error
18         // Puts Json Struct in db with key
19         Put(key string, value interface{}) error
20         // Delete k,v
21         Delete(key string) error
22         // Delete all keys in heirarchy
23         DeleteAll(key string) error
24         // Gets Json Struct from db
25         Get(key string, value interface{}) error
26         // Returns all keys with a prefix
27         GetAllKeys(path string) ([]string, error)
28 }
29
30 // createContextDBClient creates the DB client
31 func createContextDBClient(dbType string) error {
32         var err error
33         switch dbType {
34         case "etcd":
35                 c := EtcdConfig{
36                         Endpoint: config.GetConfiguration().EtcdIP,
37                         CertFile: config.GetConfiguration().EtcdCert,
38                         KeyFile:  config.GetConfiguration().EtcdKey,
39                         CAFile:   config.GetConfiguration().EtcdCAFile,
40                 }
41                 Db, err = NewEtcdClient(nil, c)
42                 if err != nil {
43                         pkgerrors.Wrap(err, "Etcd Client Initialization failed with error")
44                 }
45         default:
46                 return pkgerrors.New(dbType + "DB not supported")
47         }
48         return err
49 }
50
51 // InitializeContextDatabase sets up the connection to the
52 // configured database to allow the application to talk to it.
53 func InitializeContextDatabase() error {
54         // Only support Etcd for now
55         err := createContextDBClient("etcd")
56         if err != nil {
57                 return pkgerrors.Cause(err)
58         }
59         err = Db.HealthCheck()
60         if err != nil {
61                 return pkgerrors.Cause(err)
62         }
63         return nil
64 }