-
Notifications
You must be signed in to change notification settings - Fork 147
Expand file tree
/
Copy pathexample_test.go
More file actions
560 lines (494 loc) · 13.6 KB
/
Copy pathexample_test.go
File metadata and controls
560 lines (494 loc) · 13.6 KB
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//
// SPDX-License-Identifier: BSD-3-Clause
//
package gofish_test
import (
"errors"
"fmt"
"log"
"time"
"github.com/stmcginnis/gofish"
"github.com/stmcginnis/gofish/schemas"
)
// ExampleConnect demonstrates the basic pattern for connecting to a Redfish
// service and ensuring the session is cleaned up on exit.
func ExampleConnect() {
c, err := gofish.Connect(gofish.ClientConfig{
Endpoint: "https://bmc-ip",
Username: "my-username",
Password: "my-password",
Insecure: true,
})
if err != nil {
log.Fatal(err)
}
defer c.Logout()
fmt.Println(c.Service.RedfishVersion)
}
// ExampleConnect_basicAuth shows how to use HTTP Basic Auth instead of
// session-based authentication. Basic Auth avoids creating a server-side
// session but sends credentials with every request.
func ExampleConnect_basicAuth() {
c, err := gofish.Connect(gofish.ClientConfig{
Endpoint: "https://bmc-ip",
Username: "my-username",
Password: "my-password",
Insecure: true,
BasicAuth: true,
})
if err != nil {
log.Fatal(err)
}
defer c.Logout()
fmt.Println(c.Service.RedfishVersion)
}
// ExampleConnect_reuseSession shows how to save a session token from one
// connection and reuse it in a later connection, avoiding the overhead of
// creating a new session each time.
func ExampleConnect_reuseSession() {
// Initial connection that creates a session.
c, err := gofish.Connect(gofish.ClientConfig{
Endpoint: "https://bmc-ip",
Username: "my-username",
Password: "my-password",
Insecure: true,
})
if err != nil {
log.Fatal(err)
}
// Save the session token for later reuse.
session, err := c.GetSession()
if err != nil {
log.Fatal(err)
}
// ... save session.ID and session.Token to persistent storage ...
// Reconnect later using the saved session instead of credentials.
c2, err := gofish.Connect(gofish.ClientConfig{
Endpoint: "https://bmc-ip",
Insecure: true,
Session: &gofish.Session{
ID: session.ID,
Token: session.Token,
},
})
if err != nil {
log.Fatal(err)
}
defer c2.Logout()
fmt.Println(c2.Service.RedfishVersion)
}
// Example_querySystemInventory demonstrates how to retrieve processor and
// memory information from all systems registered with the service.
func Example_querySystemInventory() {
c, err := gofish.Connect(gofish.ClientConfig{
Endpoint: "https://bmc-ip",
Username: "my-username",
Password: "my-password",
Insecure: true,
})
if err != nil {
log.Fatal(err)
}
defer c.Logout()
systems, err := c.Service.Systems()
if err != nil {
log.Print(err)
return
}
for _, system := range systems {
fmt.Printf("System: %s\n", system.Name)
processors, err := system.Processors()
if err != nil {
log.Printf("error getting processors: %v", err)
}
for _, p := range processors {
fmt.Printf(" CPU: %s %s\n", p.Manufacturer, p.Model)
fmt.Printf(" Cores: %d Threads: %d\n",
gofish.Deref(p.TotalCores), gofish.Deref(p.TotalThreads))
fmt.Printf(" Max speed: %d MHz\n", gofish.Deref(p.MaxSpeedMHz))
}
memory, err := system.Memory()
if err != nil {
log.Printf("error getting memory: %v", err)
}
for _, dimm := range memory {
fmt.Printf(" DIMM: %s %d MiB %d MHz\n",
dimm.Name,
gofish.Deref(dimm.CapacityMiB),
gofish.Deref(dimm.OperatingSpeedMhz))
}
}
}
// Example_queryThermal shows how to read temperature sensor and fan speed
// readings from all chassis managed by the service.
func Example_queryThermal() {
c, err := gofish.Connect(gofish.ClientConfig{
Endpoint: "https://bmc-ip",
Username: "my-username",
Password: "my-password",
Insecure: true,
})
if err != nil {
log.Fatal(err)
}
defer c.Logout()
chassis, err := c.Service.Chassis()
if err != nil {
log.Print(err)
return
}
for _, ch := range chassis {
thermal, err := ch.Thermal()
if err != nil {
log.Printf("error getting thermal for chassis %s: %v", ch.Name, err)
continue
}
fmt.Printf("Chassis: %s\n", ch.Name)
for i := range thermal.Temperatures {
temp := &thermal.Temperatures[i]
if temp.ReadingCelsius == nil {
continue
}
fmt.Printf(" Temp: %-30s %.1f °C\n", temp.Name, *temp.ReadingCelsius)
}
for i := range thermal.Fans {
fan := &thermal.Fans[i]
if fan.Reading == nil {
continue
}
fmt.Printf(" Fan: %-30s %d %s\n", fan.Name, *fan.Reading, fan.ReadingUnits)
}
}
}
// Example_pollThermalConditionally shows how to poll a resource efficiently with
// a conditional GET. schemas.Refresh re-fetches the object using its own ETag as
// If-None-Match; when the service reports no change it returns
// schemas.ErrNotModified and the existing object stays valid, avoiding the JSON
// parse and most of the bytes on the wire. This is the intended pattern for
// polling fleets of BMCs for resources that change infrequently.
func Example_pollThermalConditionally() {
c, err := gofish.Connect(gofish.ClientConfig{
Endpoint: "https://bmc-ip",
Username: "my-username",
Password: "my-password",
Insecure: true,
})
if err != nil {
log.Fatal(err)
}
defer c.Logout()
chassis, err := c.Service.Chassis()
if err != nil || len(chassis) == 0 {
log.Print(err)
return
}
// Initial fetch captures the resource and its ETag.
thermal, err := chassis[0].Thermal()
if err != nil {
log.Print(err)
return
}
// Poll on an interval; only re-parse when the BMC reports a change.
for range time.Tick(30 * time.Second) {
refreshed, err := schemas.Refresh(thermal)
switch {
case errors.Is(err, schemas.ErrNotModified):
continue // unchanged since last poll; keep using the cached object
case err != nil:
log.Printf("error refreshing thermal: %v", err)
continue
}
thermal = refreshed
for i := range thermal.Temperatures {
if temp := &thermal.Temperatures[i]; temp.ReadingCelsius != nil {
fmt.Printf("%s: %.1f °C\n", temp.Name, *temp.ReadingCelsius)
}
}
}
}
// Example_conditionalReload shows schemas.Reload, the general form of a
// conditional GET where the caller supplies the request headers directly. Use it
// when you cache ETags outside the object, or when a vendor requires an unquoted
// ETag in If-None-Match. schemas.Refresh is the convenience wrapper over this.
func Example_conditionalReload() {
c, err := gofish.Connect(gofish.ClientConfig{
Endpoint: "https://bmc-ip",
Username: "my-username",
Password: "my-password",
Insecure: true,
})
if err != nil {
log.Fatal(err)
}
defer c.Logout()
chassis, err := c.Service.Chassis()
if err != nil || len(chassis) == 0 {
log.Print(err)
return
}
power, err := chassis[0].Power()
if err != nil {
log.Print(err)
return
}
power, err = schemas.Reload(power, map[string]string{"If-None-Match": power.GetETag()})
if errors.Is(err, schemas.ErrNotModified) {
fmt.Println("power metrics unchanged")
return
}
if err != nil {
log.Print(err)
return
}
fmt.Printf("refreshed power resource: %s\n", power.Name)
}
// Example_queryManagers shows how to list BMC/management controller details,
// such as firmware version and network protocol configuration.
func Example_queryManagers() {
c, err := gofish.Connect(gofish.ClientConfig{
Endpoint: "https://bmc-ip",
Username: "my-username",
Password: "my-password",
Insecure: true,
})
if err != nil {
log.Fatal(err)
}
defer c.Logout()
managers, err := c.Service.Managers()
if err != nil {
log.Print(err)
return
}
for _, mgr := range managers {
fmt.Printf("Manager: %s type=%s firmware=%s\n",
mgr.Name, mgr.ManagerType, mgr.FirmwareVersion)
netProto, err := mgr.NetworkProtocol()
if err != nil {
continue
}
fmt.Printf(" Hostname: %s\n", netProto.HostName)
}
}
// Example_firmwareInventory shows how to list all firmware components
// reported by the UpdateService, which is useful for auditing installed
// firmware versions across the managed system.
func Example_firmwareInventory() {
c, err := gofish.Connect(gofish.ClientConfig{
Endpoint: "https://bmc-ip",
Username: "my-username",
Password: "my-password",
Insecure: true,
})
if err != nil {
log.Fatal(err)
}
defer c.Logout()
updateService, err := c.Service.UpdateService()
if err != nil {
log.Print(err)
return
}
inventory, err := updateService.FirmwareInventory()
if err != nil {
log.Print(err)
return
}
for _, item := range inventory {
fmt.Printf("%-40s version=%-20s updateable=%v\n",
item.Name, item.Version, item.Updateable)
}
}
// Example_firmwareUpdate demonstrates a simple firmware update using an
// image URI. The update is submitted to the service and a task monitor is
// returned for polling completion status.
func Example_firmwareUpdate() {
c, err := gofish.Connect(gofish.ClientConfig{
Endpoint: "https://bmc-ip",
Username: "my-username",
Password: "my-password",
Insecure: true,
})
if err != nil {
log.Fatal(err)
}
defer c.Logout()
updateService, err := c.Service.UpdateService()
if err != nil {
log.Print(err)
return
}
taskInfo, err := updateService.SimpleUpdate(&schemas.UpdateServiceSimpleUpdateParameters{
ImageURI: "https://firmware-server/bmc-firmware-2.0.bin",
TransferProtocol: schemas.HTTPSTransferProtocolType,
})
if err != nil {
log.Print(err)
return
}
if taskInfo != nil {
fmt.Printf("Update task submitted: %s\n", taskInfo.TaskMonitor)
}
}
// Example_readEventLog shows how to read entries from the system event log
// via the Manager's LogService. This is useful for diagnostics and auditing.
func Example_readEventLog() {
c, err := gofish.Connect(gofish.ClientConfig{
Endpoint: "https://bmc-ip",
Username: "my-username",
Password: "my-password",
Insecure: true,
})
if err != nil {
log.Fatal(err)
}
defer c.Logout()
managers, err := c.Service.Managers()
if err != nil {
log.Print(err)
return
}
for _, mgr := range managers {
logServices, err := mgr.LogServices()
if err != nil {
continue
}
for _, ls := range logServices {
entries, err := ls.Entries()
if err != nil {
continue
}
fmt.Printf("Log: %s\n", ls.Name)
for _, entry := range entries {
fmt.Printf(" [%s] %s: %s\n",
entry.Severity, entry.Created, entry.Message)
}
}
}
}
// Example_subscribeEvents shows how to register a webhook endpoint to
// receive Redfish event notifications. The returned subscription URI can
// be used later to modify or delete the subscription.
func Example_subscribeEvents() {
c, err := gofish.Connect(gofish.ClientConfig{
Endpoint: "https://bmc-ip",
Username: "my-username",
Password: "my-password",
Insecure: true,
})
if err != nil {
log.Fatal(err)
}
defer c.Logout()
eventService, err := c.Service.EventService()
if err != nil {
log.Print(err)
return
}
// Subscribe using registry prefixes (Redfish v1.5+).
subscriptionURI, err := eventService.CreateEventSubscriptionInstance(
"https://my-event-receiver/redfish/events", // destination
[]string{"Alert", "ResourceEvent"}, // registry prefixes
[]string{}, // all resource types
nil, // no custom HTTP headers
schemas.RedfishEventDestinationProtocol,
"my-monitoring-service", // client-supplied context string
schemas.RetryForeverDeliveryRetryPolicy,
nil, // no OEM data
)
if err != nil {
log.Print(err)
return
}
fmt.Printf("Subscription created: %s\n", subscriptionURI)
// Delete the subscription when no longer needed.
if err := eventService.DeleteEventSubscription(subscriptionURI); err != nil {
log.Print(err)
}
}
// Example_updateBiosAttributes shows how to read and modify BIOS settings.
// Changes are applied at the next reboot unless an immediate apply time
// is specified.
func Example_updateBiosAttributes() {
c, err := gofish.Connect(gofish.ClientConfig{
Endpoint: "https://bmc-ip",
Username: "my-username",
Password: "my-password",
Insecure: true,
})
if err != nil {
log.Fatal(err)
}
defer c.Logout()
systems, err := c.Service.Systems()
if err != nil {
log.Print(err)
return
}
for _, system := range systems {
bios, err := system.Bios()
if err != nil {
log.Printf("error getting BIOS for %s: %v", system.Name, err)
continue
}
// Print current attribute values.
for name, value := range bios.Attributes {
fmt.Printf(" %s = %v\n", name, value)
}
// Update an attribute to take effect on next reboot.
if err := bios.UpdateBiosAttributesApplyAt(
schemas.SettingsAttributes{"NumaGroupSizeOpt": "Flat"},
schemas.OnResetSettingsApplyTime,
); err != nil {
log.Printf("error updating BIOS: %v", err)
}
}
}
// Example_mountVirtualMedia demonstrates how to mount a remote ISO image as
// virtual media on a manager, enabling virtual CD/DVD boot without physical
// media.
func Example_mountVirtualMedia() {
c, err := gofish.Connect(gofish.ClientConfig{
Endpoint: "https://bmc-ip",
Username: "my-username",
Password: "my-password",
Insecure: true,
})
if err != nil {
log.Fatal(err)
}
defer c.Logout()
managers, err := c.Service.Managers()
if err != nil {
log.Print(err)
return
}
for _, mgr := range managers {
virtualMedia, err := mgr.VirtualMedia()
if err != nil {
continue
}
for _, vm := range virtualMedia {
// Find the CD/DVD slot.
if vm.MediaTypes == nil {
continue
}
for _, mt := range vm.MediaTypes {
if mt != schemas.CDVirtualMediaType && mt != schemas.DVDVirtualMediaType {
continue
}
_, err := vm.InsertMedia(&schemas.VirtualMediaInsertMediaParameters{
Image: "https://file-server/os-installer.iso",
TransferProtocolType: gofish.ToRef(schemas.HTTPSTransferProtocolType),
Inserted: gofish.ToRef(true),
WriteProtected: gofish.ToRef(true),
})
if err != nil {
log.Printf("error inserting media: %v", err)
continue
}
fmt.Printf("Mounted ISO on %s\n", vm.Name)
}
}
}
}