Merge "Add suport for query api on root level"
[multicloud/k8s.git] / src / k8splugin / internal / utils / utils.go
1 /*
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.
12 */
13
14 package utils
15
16 import (
17         "io/ioutil"
18         "log"
19         "os"
20         "path"
21         "path/filepath"
22         "plugin"
23         "strings"
24
25         "github.com/onap/multicloud-k8s/src/k8splugin/internal/config"
26         "github.com/onap/multicloud-k8s/src/k8splugin/internal/db"
27
28         pkgerrors "github.com/pkg/errors"
29         "k8s.io/apimachinery/pkg/runtime"
30         "k8s.io/client-go/kubernetes/scheme"
31 )
32
33 // LoadedPlugins stores references to the stored plugins
34 var LoadedPlugins = map[string]*plugin.Plugin{}
35
36 const ResourcesListLimit = 10
37
38 // ResourceData stores all supported Kubernetes plugin types
39 type ResourceData struct {
40         YamlFilePath string
41         Namespace    string
42         VnfId        string
43 }
44
45 // DecodeYAML reads a YAMl file to extract the Kubernetes object definition
46 func DecodeYAML(path string, into runtime.Object) (runtime.Object, error) {
47         if _, err := os.Stat(path); err != nil {
48                 if os.IsNotExist(err) {
49                         return nil, pkgerrors.New("File " + path + " not found")
50                 } else {
51                         return nil, pkgerrors.Wrap(err, "Stat file error")
52                 }
53         }
54
55         rawBytes, err := ioutil.ReadFile(path)
56         if err != nil {
57                 return nil, pkgerrors.Wrap(err, "Read YAML file error")
58         }
59
60         decode := scheme.Codecs.UniversalDeserializer().Decode
61         obj, _, err := decode(rawBytes, nil, into)
62         if err != nil {
63                 return nil, pkgerrors.Wrap(err, "Deserialize YAML error")
64         }
65
66         return obj, nil
67 }
68
69 // CheckDatabaseConnection checks if the database is up and running and
70 // plugin can talk to it
71 func CheckDatabaseConnection() error {
72         err := db.CreateDBClient(config.GetConfiguration().DatabaseType)
73         if err != nil {
74                 return pkgerrors.Cause(err)
75         }
76
77         err = db.DBconn.HealthCheck()
78         if err != nil {
79                 return pkgerrors.Cause(err)
80         }
81         // TODO Convert these to configuration files instead of environment variables.
82         c := db.EtcdConfig{
83                 Endpoint: config.GetConfiguration().EtcdIP,
84                 CertFile: config.GetConfiguration().EtcdCert,
85                 KeyFile:  config.GetConfiguration().EtcdKey,
86                 CAFile:   config.GetConfiguration().EtcdCAFile,
87         }
88         err = db.NewEtcdClient(nil, c)
89         if err != nil {
90                 log.Printf("Etcd Client Initialization failed with error: %s", err.Error())
91         }
92         return nil
93 }
94
95 // LoadPlugins loads all the compiled .so plugins
96 func LoadPlugins() error {
97         pluginsDir := config.GetConfiguration().PluginDir
98         err := filepath.Walk(pluginsDir,
99                 func(path string, info os.FileInfo, err error) error {
100                         if strings.Contains(path, ".so") {
101                                 p, err := plugin.Open(path)
102                                 if err != nil {
103                                         return pkgerrors.Cause(err)
104                                 }
105                                 LoadedPlugins[info.Name()[:len(info.Name())-3]] = p
106                         }
107                         return err
108                 })
109         if err != nil {
110                 return err
111         }
112
113         return nil
114 }
115
116 // CheckInitialSettings is used to check initial settings required to start api
117 func CheckInitialSettings() error {
118         err := CheckDatabaseConnection()
119         if err != nil {
120                 return pkgerrors.Cause(err)
121         }
122
123         err = LoadPlugins()
124         if err != nil {
125                 return pkgerrors.Cause(err)
126         }
127
128         return nil
129 }
130
131 //EnsureDirectory makes sure that the directories specified in the path exist
132 //If not, it will create them, if possible.
133 func EnsureDirectory(f string) error {
134         base := path.Dir(f)
135         _, err := os.Stat(base)
136         if err != nil && !os.IsNotExist(err) {
137                 return err
138         }
139         return os.MkdirAll(base, 0755)
140 }