-
Notifications
You must be signed in to change notification settings - Fork 59
/
common.go
291 lines (273 loc) · 10.4 KB
/
common.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
//(C) Copyright [2020] Hewlett Packard Enterprise Development LP
//
//Licensed under the Apache License, Version 2.0 (the "License"); you may
//not use this file except in compliance with the License. You may obtain
//a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
//License for the specific language governing permissions and limitations
// under the License.
// Package tcommon ...
package tcommon
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"reflect"
"strconv"
"strings"
"sync"
dmtf "github.com/ODIM-Project/ODIM/lib-dmtf/model"
"github.com/ODIM-Project/ODIM/lib-utilities/common"
"github.com/ODIM-Project/ODIM/lib-utilities/config"
"github.com/ODIM-Project/ODIM/lib-utilities/errors"
l "github.com/ODIM-Project/ODIM/lib-utilities/logs"
"github.com/ODIM-Project/ODIM/svc-telemetry/tmodel"
)
// PluginContactRequest hold the request of contact plugin
type PluginContactRequest struct {
Token string
OID string
DeviceInfo interface{}
BasicAuth map[string]string
ContactClient func(context.Context, string, string, string, string, interface{}, map[string]string) (*http.Response, error)
GetPluginStatus func(context.Context, tmodel.Plugin) bool
Plugin tmodel.Plugin
HTTPMethodType string
}
// ResponseStatus holds the response of Contact Plugin
type ResponseStatus struct {
StatusCode int32
StatusMessage string
}
// ResourceInfoRequest hold the request of getting Resource
type ResourceInfoRequest struct {
URL string
ContactClient func(context.Context, string, string, string, string, interface{}, map[string]string) (*http.Response, error)
DevicePassword func([]byte) ([]byte, error)
GetPluginStatus func(context.Context, tmodel.Plugin) bool
ResourceName string
GetAllKeysFromTable func(context.Context, string, common.DbType) ([]string, error)
GetPluginData func(string) (tmodel.Plugin, *errors.Error)
GetResource func(context.Context, string, string, common.DbType) (string, *errors.Error)
GenericSave func(context.Context, []byte, string, string) error
}
var (
// ConfigFilePath holds the value of odim config file path
ConfigFilePath string
)
// GetResourceInfoFromDevice will contact to the southbound client and gets the Particular resource info from device
func GetResourceInfoFromDevice(ctx context.Context, req ResourceInfoRequest) ([]byte, error) {
var metricReportData dmtf.MetricReports
plugins, err := req.GetAllKeysFromTable(ctx, "Plugin", common.OnDisk)
if err != nil {
return []byte{}, err
}
var wg sync.WaitGroup
var lock sync.Mutex
var threadID int = 1
for _, value := range plugins {
wg.Add(1)
ctxt := context.WithValue(ctx, common.ThreadName, common.GetTelemetryResource)
ctxt = context.WithValue(ctxt, common.ThreadID, strconv.Itoa(threadID))
go getResourceInfo(ctxt, value, &metricReportData, req, &lock, &wg)
threadID++
}
wg.Wait()
if reflect.DeepEqual(metricReportData, dmtf.MetricReports{}) {
removeNonExistingID(ctx, req)
return []byte{}, fmt.Errorf("metric report not found")
}
data, err := json.Marshal(metricReportData)
if err != nil {
return []byte{}, err
}
l.LogWithFields(ctx).Debugf("resource info from device: %s", string(data))
return data, nil
}
func getResourceInfo(ctx context.Context, pluginID string, metricReportData *dmtf.MetricReports, req ResourceInfoRequest, lock *sync.Mutex, wg *sync.WaitGroup) {
defer wg.Done()
// Get the Plugin info
plugin, gerr := req.GetPluginData(pluginID)
if gerr != nil || plugin.PluginType != "Compute" {
return
}
var contactRequest PluginContactRequest
contactRequest.ContactClient = req.ContactClient
contactRequest.Plugin = plugin
contactRequest.GetPluginStatus = req.GetPluginStatus
if strings.EqualFold(plugin.PreferredAuthType, "XAuthToken") {
var err error
contactRequest.HTTPMethodType = http.MethodPost
contactRequest.DeviceInfo = map[string]interface{}{
"Username": plugin.Username,
"Password": string(plugin.Password),
}
contactRequest.OID = "/ODIM/v1/Sessions"
_, token, _, err := ContactPlugin(ctx, contactRequest, "error while getting the details "+contactRequest.OID+": ")
if err != nil {
return
}
contactRequest.Token = token
} else {
contactRequest.BasicAuth = map[string]string{
"UserName": plugin.Username,
"Password": string(plugin.Password),
}
}
contactRequest.OID = req.URL
contactRequest.HTTPMethodType = http.MethodGet
body, _, _, err := ContactPlugin(ctx, contactRequest, "error while getting the details "+contactRequest.OID+": ")
if err != nil {
return
}
lock.Lock()
defer lock.Unlock()
var metricsData dmtf.MetricReports
if err := json.Unmarshal(body, &metricsData); err != nil {
return
}
metricReportData.ODataID = metricsData.ODataID
metricReportData.ODataType = metricsData.ODataType
metricReportData.ODataContext = metricsData.ODataContext
metricReportData.ID = metricsData.ID
metricReportData.Name = metricsData.Name
metricReportData.Description = metricsData.Description
metricReportData.MetricReportDefinition = metricsData.MetricReportDefinition
metricReportData.Context = metricsData.Context
metricReportData.MetricValues = append(metricReportData.MetricValues, metricsData.MetricValues...)
}
// ContactPlugin is commons which handles the request and response of Contact Plugin usage
func ContactPlugin(ctx context.Context, req PluginContactRequest, errorMessage string) ([]byte, string, ResponseStatus, error) {
var resp ResponseStatus
var response *http.Response
var err error
response, err = callPlugin(req)
if err != nil {
if req.GetPluginStatus(ctx, req.Plugin) {
response, err = callPlugin(req)
}
if err != nil {
errorMessage = errorMessage + err.Error()
resp.StatusCode = http.StatusInternalServerError
resp.StatusMessage = errors.InternalError
l.LogWithFields(ctx).Error(errorMessage)
return nil, "", resp, fmt.Errorf(errorMessage)
}
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
errorMessage := "error while trying to read response body: " + err.Error()
resp.StatusCode = http.StatusInternalServerError
resp.StatusMessage = errors.InternalError
l.LogWithFields(ctx).Error(errorMessage)
return nil, "", resp, fmt.Errorf(errorMessage)
}
l.LogWithFields(ctx).Info("Response StatusCode: " + strconv.Itoa(int(response.StatusCode)))
if response.StatusCode != http.StatusCreated && response.StatusCode != http.StatusOK {
resp.StatusCode = int32(response.StatusCode)
l.LogWithFields(ctx).Println(errorMessage)
return body, "", resp, fmt.Errorf(errorMessage)
}
data := string(body)
//replacing the response with north bound translation URL
for key, value := range config.Data.URLTranslation.NorthBoundURL {
data = strings.Replace(data, key, value, -1)
}
l.LogWithFields(ctx).Debugf("response from contact plugin : %s", data)
return []byte(data), response.Header.Get("X-Auth-Token"), resp, nil
}
// GetPluginStatus checks the status of given plugin in configured interval
func GetPluginStatus(ctx context.Context, plugin tmodel.Plugin) bool {
var pluginStatus = common.PluginStatus{
Method: http.MethodGet,
RequestBody: common.StatusRequest{
Comment: "",
},
ResponseWaitTime: config.Data.PluginStatusPolling.ResponseTimeoutInSecs,
Count: config.Data.PluginStatusPolling.MaxRetryAttempt,
RetryInterval: config.Data.PluginStatusPolling.RetryIntervalInMins,
PluginIP: plugin.IP,
PluginPort: plugin.Port,
PluginUsername: plugin.Username,
PluginUserPassword: string(plugin.Password),
PluginPreferredAuthType: plugin.PreferredAuthType,
CACertificate: &config.Data.KeyCertConf.RootCACertificate,
}
status, _, _, err := pluginStatus.CheckStatus()
if err != nil && !status {
l.LogWithFields(ctx).Error("Error While getting the status for plugin " + plugin.ID + ": " + err.Error())
return status
}
l.LogWithFields(ctx).Info("Status of plugin" + plugin.ID + strconv.FormatBool(status))
return status
}
func callPlugin(req PluginContactRequest) (*http.Response, error) {
var oid string
for key, value := range config.Data.URLTranslation.SouthBoundURL {
oid = strings.Replace(req.OID, key, value, -1)
}
var reqURL = "https://" + req.Plugin.IP + ":" + req.Plugin.Port + oid
if strings.EqualFold(req.Plugin.PreferredAuthType, "BasicAuth") {
return req.ContactClient(context.TODO(), reqURL, req.HTTPMethodType, "", oid, req.DeviceInfo, req.BasicAuth)
}
return req.ContactClient(context.TODO(), reqURL, req.HTTPMethodType, req.Token, oid, req.DeviceInfo, nil)
}
func removeNonExistingID(ctx context.Context, req ResourceInfoRequest) {
collectionURL := "/redfish/v1/TelemetryService/MetricReports"
data, err := req.GetResource(ctx, "MetricReportsCollection", collectionURL, common.InMemory)
if err != nil {
return
}
var resource map[string]interface{}
json.Unmarshal([]byte(data), &resource)
var result []*dmtf.Link
if resource["Members"] != nil {
members := resource["Members"].([]interface{})
for _, v := range members {
oid := v.(map[string]interface{})
if oid["@odata.id"].(string) != req.URL {
result = append(result, &dmtf.Link{Oid: oid["@odata.id"].(string)})
}
}
}
if len(result) > 0 {
resource["Members"] = result
resource["Members@odata.count"] = len(result)
reportCollection, jerr := json.Marshal(resource)
if jerr != nil {
return
}
req.GenericSave(ctx, reportCollection, "MetricReportsCollection", collectionURL)
}
}
// TrackConfigFileChanges monitors the host file using fsnotfiy
func TrackConfigFileChanges(errChan chan error) {
eventChan := make(chan interface{})
format := config.Data.LogFormat
go common.TrackConfigFileChanges(ConfigFilePath, eventChan, errChan)
for {
select {
case info := <-eventChan:
l.Log.Info(info) // new data arrives through eventChan channel
if l.Log.Level != config.Data.LogLevel {
l.Log.Info("Log level is updated, new log level is ", config.Data.LogLevel)
l.Log.Logger.SetLevel(config.Data.LogLevel)
}
if format != config.Data.LogFormat {
l.SetFormatter(config.Data.LogFormat)
format = config.Data.LogFormat
l.Log.Info("Log format is updated, new log format is ", config.Data.LogFormat)
}
case err := <-errChan:
l.Log.Error(err)
}
}
}