-
Notifications
You must be signed in to change notification settings - Fork 37
/
client.go
338 lines (295 loc) · 12.8 KB
/
client.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
// Package bmclib client.go is intended to be the main public API.
// Its purpose is to make interacting with bmclib as friendly as possible.
package bmclib
import (
"context"
"crypto/x509"
"io"
"net/http"
"sync"
"time"
"github.com/bmc-toolbox/bmclib/v2/bmc"
"github.com/bmc-toolbox/bmclib/v2/internal/httpclient"
"github.com/bmc-toolbox/bmclib/v2/internal/redfishwrapper"
"github.com/bmc-toolbox/bmclib/v2/providers/asrockrack"
"github.com/bmc-toolbox/bmclib/v2/providers/intelamt"
"github.com/bmc-toolbox/bmclib/v2/providers/ipmitool"
"github.com/bmc-toolbox/bmclib/v2/providers/redfish"
"github.com/bmc-toolbox/common"
"github.com/go-logr/logr"
"github.com/jacobweinstock/registrar"
)
// Client for BMC interactions
type Client struct {
Auth Auth
Logger logr.Logger
Registry *registrar.Registry
httpClient *http.Client
httpClientSetupFuncs []func(*http.Client)
mdLock *sync.Mutex
metadata *bmc.Metadata
perProviderTimeout func(context.Context) time.Duration
redfishVersionsNotCompatible []string
}
const (
// default connection timeout
defaultConnectTimeout = 30 * time.Second
)
// Auth details for connecting to a BMC
type Auth struct {
Host string
Port string
User string
Pass string
}
// Option for setting optional Client values
type Option func(*Client)
// WithLogger sets the logger
func WithLogger(logger logr.Logger) Option {
return func(args *Client) { args.Logger = logger }
}
// WithRegistry sets the Registry
func WithRegistry(registry *registrar.Registry) Option {
return func(args *Client) { args.Registry = registry }
}
// WithSecureTLS enforces trusted TLS connections, with an optional CA certificate pool.
// Using this option with an nil pool uses the system CAs.
func WithSecureTLS(rootCAs *x509.CertPool) Option {
return func(args *Client) {
args.httpClientSetupFuncs = append(args.httpClientSetupFuncs, httpclient.SecureTLSOption(rootCAs))
}
}
// WithHTTPClient sets an http client
func WithHTTPClient(c *http.Client) Option {
return func(args *Client) {
args.httpClient = c
}
}
// WithPerProviderTimeout sets the timeout when interacting with a BMC.
// This timeout value is applied per provider.
// When not defined and a context with a timeout is passed to a method, the default timeout
// will be the context timeout duration divided by the number of providers in the registry,
// meaning, the len(Client.Registry.Drivers).
// If this per provider timeout is not defined and no context timeout is defined,
// the defaultConnectTimeout is used.
func WithPerProviderTimeout(timeout time.Duration) Option {
return func(args *Client) {
args.perProviderTimeout = func(context.Context) time.Duration { return timeout }
}
}
// WithRedfishVersionsNotCompatible sets the list of incompatible redfish versions.
//
// With this option set, The bmclib.Registry.FilterForCompatible(ctx) method will not proceed on
// devices with the given redfish version(s).
func WithRedfishVersionsNotCompatible(versions []string) Option {
return func(args *Client) {
args.redfishVersionsNotCompatible = append(args.redfishVersionsNotCompatible, versions...)
}
}
// NewClient returns a new Client struct
func NewClient(host, port, user, pass string, opts ...Option) *Client {
var defaultClient = &Client{
Logger: logr.Discard(),
Registry: registrar.NewRegistry(),
redfishVersionsNotCompatible: []string{},
}
for _, opt := range opts {
opt(defaultClient)
}
if defaultClient.httpClient == nil {
defaultClient.httpClient, _ = httpclient.Build(defaultClient.httpClientSetupFuncs...)
} else {
for _, setupFunc := range defaultClient.httpClientSetupFuncs {
setupFunc(defaultClient.httpClient)
}
}
defaultClient.Registry.Logger = defaultClient.Logger
defaultClient.Auth.Host = host
defaultClient.Auth.Port = port
defaultClient.Auth.User = user
defaultClient.Auth.Pass = pass
// len of 0 means that no Registry, with any registered providers was passed in.
if len(defaultClient.Registry.Drivers) == 0 {
defaultClient.registerProviders()
}
defaultClient.mdLock = &sync.Mutex{}
if defaultClient.perProviderTimeout == nil {
defaultClient.perProviderTimeout = defaultClient.defaultTimeout
}
return defaultClient
}
func (c *Client) defaultTimeout(ctx context.Context) time.Duration {
deadline, ok := ctx.Deadline()
if !ok {
return defaultConnectTimeout
}
l := len(c.Registry.Drivers)
if l == 0 {
return time.Until(deadline)
}
return time.Until(deadline) / time.Duration(l)
}
func (c *Client) registerProviders() {
// register ipmitool provider
driverIpmitool := &ipmitool.Conn{Host: c.Auth.Host, Port: c.Auth.Port, User: c.Auth.User, Pass: c.Auth.Pass, Log: c.Logger}
c.Registry.Register(ipmitool.ProviderName, ipmitool.ProviderProtocol, ipmitool.Features, nil, driverIpmitool)
// register ASRR vendorapi provider
driverAsrockrack, _ := asrockrack.NewWithOptions(c.Auth.Host, c.Auth.User, c.Auth.Pass, c.Logger, asrockrack.WithHTTPClient(c.httpClient))
c.Registry.Register(asrockrack.ProviderName, asrockrack.ProviderProtocol, asrockrack.Features, nil, driverAsrockrack)
// register gofish provider
driverGoFish := redfish.New(c.Auth.Host, c.Auth.Port, c.Auth.User, c.Auth.Pass, c.Logger, redfishwrapper.WithHTTPClient(c.httpClient), redfishwrapper.WithVersionsNotCompatible(c.redfishVersionsNotCompatible))
c.Registry.Register(redfish.ProviderName, redfish.ProviderProtocol, redfish.Features, nil, driverGoFish)
// register AMT provider
driverAMT := intelamt.New(c.Logger, c.Auth.Host, c.Auth.Port, c.Auth.User, c.Auth.Pass)
c.Registry.Register(intelamt.ProviderName, intelamt.ProviderProtocol, intelamt.Features, nil, driverAMT)
}
// GetMetadata returns the metadata that is populated after each BMC function/method call
func (c *Client) GetMetadata() bmc.Metadata {
if c.metadata != nil {
return *c.metadata
}
return bmc.Metadata{}
}
// setMetadata wraps setting metadata with a mutex for cases where users are
// making calls to multiple *Client.X functions/methods across goroutines
func (c *Client) setMetadata(metadata bmc.Metadata) {
// a mutex is created with the NewClient func, in the case
// where a user doesn't call NewClient we handle by checking if
// the mutex is nil
if c.mdLock != nil {
c.mdLock.Lock()
defer c.mdLock.Unlock()
}
c.metadata = &metadata
}
// Open calls the OpenConnectionFromInterfaces library function
// Any providers/drivers that do not successfully connect are removed
// from the client.Registry.Drivers. If client.Registry.Drivers ends up
// being empty then we error.
func (c *Client) Open(ctx context.Context) error {
ifs, metadata, err := bmc.OpenConnectionFromInterfaces(ctx, c.perProviderTimeout(ctx), c.Registry.GetDriverInterfaces())
if err != nil {
return err
}
var reg registrar.Drivers
for _, elem := range c.Registry.Drivers {
for _, em := range ifs {
if em == elem.DriverInterface {
elem.DriverInterface = em
reg = append(reg, elem)
}
}
}
c.Registry.Drivers = reg
c.setMetadata(metadata)
return nil
}
// Close pass through to library function
func (c *Client) Close(ctx context.Context) (err error) {
// Generally, we always want the close function to run.
// We don't want a context timeout or cancellation to prevent this.
// But because the current model is to pass just a single context to all
// functions, we need to create a new context here allowing closing connections.
// This is a short term solution, and we should consider a better/more holistic model.
if err := ctx.Err(); err != nil {
var done context.CancelFunc
ctx, done = context.WithTimeout(context.Background(), defaultConnectTimeout)
defer done()
}
metadata, err := bmc.CloseConnectionFromInterfaces(ctx, c.Registry.GetDriverInterfaces())
c.setMetadata(metadata)
return err
}
// FilterForCompatible removes any drivers/providers that are not compatible. It wraps the
// Client.Registry.FilterForCompatible func in order to provide a per provider timeout.
func (c *Client) FilterForCompatible(ctx context.Context) {
perProviderTimeout, cancel := context.WithTimeout(ctx, c.perProviderTimeout(ctx))
defer cancel()
c.Registry.Drivers = c.Registry.FilterForCompatible(perProviderTimeout)
}
// GetPowerState pass through to library function
func (c *Client) GetPowerState(ctx context.Context) (state string, err error) {
state, metadata, err := bmc.GetPowerStateFromInterfaces(ctx, c.perProviderTimeout(ctx), c.Registry.GetDriverInterfaces())
c.setMetadata(metadata)
return state, err
}
// SetPowerState pass through to library function
func (c *Client) SetPowerState(ctx context.Context, state string) (ok bool, err error) {
ok, metadata, err := bmc.SetPowerStateFromInterfaces(ctx, c.perProviderTimeout(ctx), state, c.Registry.GetDriverInterfaces())
c.setMetadata(metadata)
return ok, err
}
// CreateUser pass through to library function
func (c *Client) CreateUser(ctx context.Context, user, pass, role string) (ok bool, err error) {
ok, metadata, err := bmc.CreateUserFromInterfaces(ctx, c.perProviderTimeout(ctx), user, pass, role, c.Registry.GetDriverInterfaces())
c.setMetadata(metadata)
return ok, err
}
// UpdateUser pass through to library function
func (c *Client) UpdateUser(ctx context.Context, user, pass, role string) (ok bool, err error) {
ok, metadata, err := bmc.UpdateUserFromInterfaces(ctx, c.perProviderTimeout(ctx), user, pass, role, c.Registry.GetDriverInterfaces())
c.setMetadata(metadata)
return ok, err
}
// DeleteUser pass through to library function
func (c *Client) DeleteUser(ctx context.Context, user string) (ok bool, err error) {
ok, metadata, err := bmc.DeleteUserFromInterfaces(ctx, c.perProviderTimeout(ctx), user, c.Registry.GetDriverInterfaces())
c.setMetadata(metadata)
return ok, err
}
// ReadUsers pass through to library function
func (c *Client) ReadUsers(ctx context.Context) (users []map[string]string, err error) {
users, metadata, err := bmc.ReadUsersFromInterfaces(ctx, c.perProviderTimeout(ctx), c.Registry.GetDriverInterfaces())
c.setMetadata(metadata)
return users, err
}
// SetBootDevice pass through to library function
func (c *Client) SetBootDevice(ctx context.Context, bootDevice string, setPersistent, efiBoot bool) (ok bool, err error) {
ok, metadata, err := bmc.SetBootDeviceFromInterfaces(ctx, c.perProviderTimeout(ctx), bootDevice, setPersistent, efiBoot, c.Registry.GetDriverInterfaces())
c.setMetadata(metadata)
return ok, err
}
// SetVirtualMedia controls the virtual media simulated by the BMC as being connected to the
// server. Specifically, the method ejects any currently attached virtual media, and then if
// mediaURL isn't empty, attaches a virtual media device of type kind whose contents are
// streamed from the indicated URL.
func (c *Client) SetVirtualMedia(ctx context.Context, kind string, mediaURL string) (ok bool, err error) {
ok, metadata, err := bmc.SetVirtualMediaFromInterfaces(ctx, kind, mediaURL, c.Registry.GetDriverInterfaces())
c.setMetadata(metadata)
return ok, err
}
// ResetBMC pass through to library function
func (c *Client) ResetBMC(ctx context.Context, resetType string) (ok bool, err error) {
ok, metadata, err := bmc.ResetBMCFromInterfaces(ctx, c.perProviderTimeout(ctx), resetType, c.Registry.GetDriverInterfaces())
c.setMetadata(metadata)
return ok, err
}
// Inventory pass through library function to collect hardware and firmware inventory
func (c *Client) Inventory(ctx context.Context) (device *common.Device, err error) {
device, metadata, err := bmc.GetInventoryFromInterfaces(ctx, c.Registry.GetDriverInterfaces())
c.setMetadata(metadata)
return device, err
}
func (c *Client) GetBiosConfiguration(ctx context.Context) (biosConfig map[string]string, err error) {
biosConfig, metadata, err := bmc.GetBiosConfigurationInterfaces(ctx, c.Registry.GetDriverInterfaces())
c.setMetadata(metadata)
return biosConfig, err
}
// FirmwareInstall pass through library function to upload firmware and install firmware
func (c *Client) FirmwareInstall(ctx context.Context, component, applyAt string, forceInstall bool, reader io.Reader) (taskID string, err error) {
taskID, metadata, err := bmc.FirmwareInstallFromInterfaces(ctx, component, applyAt, forceInstall, reader, c.Registry.GetDriverInterfaces())
c.setMetadata(metadata)
return taskID, err
}
// FirmwareInstallStatus pass through library function to check firmware install status
func (c *Client) FirmwareInstallStatus(ctx context.Context, installVersion, component, taskID string) (status string, err error) {
status, metadata, err := bmc.FirmwareInstallStatusFromInterfaces(ctx, installVersion, component, taskID, c.Registry.GetDriverInterfaces())
c.setMetadata(metadata)
return status, err
}
// PostCodeGetter pass through library function to return the BIOS/UEFI POST code
func (c *Client) PostCode(ctx context.Context) (status string, code int, err error) {
status, code, metadata, err := bmc.GetPostCodeInterfaces(ctx, c.Registry.GetDriverInterfaces())
c.setMetadata(metadata)
return status, code, err
}