/
generic_hardware.go
580 lines (499 loc) · 16 KB
/
generic_hardware.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
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
// MIT License
//
// (C) Copyright [2019, 2021-2022] Hewlett Packard Enterprise Development LP
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
package database
import (
"database/sql"
"encoding/json"
"fmt"
"time"
sls_common "github.com/Cray-HPE/hms-sls/pkg/sls-common"
"github.com/lib/pq"
"github.com/pkg/errors"
)
func InsertGenericHardware(hardware sls_common.GenericHardware) (err error) {
q := "INSERT INTO \n" +
" components (xname, \n" +
" parent, \n" +
" comp_type, \n" +
" comp_class, \n" +
" extra_properties, \n" +
" last_updated_version) \n" +
"VALUES \n" +
"($1, \n" +
" $2, \n" +
" $3, \n" +
" $4, \n" +
" $5, \n" +
" $6) "
jsonBytes, jsonErr := json.Marshal(hardware.ExtraPropertiesRaw)
if jsonErr != nil {
err = errors.Errorf("unable to marshal ExtendedProperties: %s", jsonErr)
return err
}
trans, beginErr := DB.Begin()
if beginErr != nil {
err = errors.Errorf("unable to begin transaction: %s", beginErr)
return err
}
version, err := IncrementVersion(trans, hardware.Xname)
if err != nil {
err = errors.Errorf("insert to version_history failed: %s", err)
_ = trans.Rollback()
return err
}
result, transErr := trans.Exec(q, hardware.Xname, hardware.Parent, hardware.Type, hardware.Class, string(jsonBytes), version)
if transErr != nil {
switch transErr.(type) {
case *pq.Error:
if transErr.(*pq.Error).Code.Name() == "unique_violation" {
err = AlreadySuch
_ = trans.Rollback()
return
}
}
// I bet we're getting back the wrong (or no) ID
println(transErr)
err = errors.Errorf("unable to exec transaction: %s", transErr)
_ = trans.Rollback()
return
}
var counter int64
counter, rowsErr := result.RowsAffected()
if rowsErr != nil {
err = errors.Errorf("insert generic component failed: %s", rowsErr)
_ = trans.Rollback()
return
}
if counter < 1 {
err = NoSuch
_ = trans.Rollback()
return
}
commitErr := trans.Commit()
if commitErr != nil {
err = errors.Errorf("unable to commit transaction: %s", commitErr)
return
}
return
}
func DeleteGenericHardware(hardware sls_common.GenericHardware) (err error) {
q := "DELETE \n" +
"FROM \n" +
" components \n" +
"WHERE \n" +
" xname = $1 "
trans, beginErr := DB.Begin()
if beginErr != nil {
err = errors.Errorf("unable to begin transaction: %s", beginErr)
return
}
_, err = IncrementVersion(trans, hardware.Xname)
if err != nil {
err = errors.Errorf("insert to version_history failed: %s", err)
_ = trans.Rollback()
return err
}
result, transErr := trans.Exec(q, hardware.Xname)
if transErr != nil {
err = errors.Errorf("unable to exec transaction: %s", transErr)
_ = trans.Rollback()
return
}
var counter int64
counter, rowsErr := result.RowsAffected()
if rowsErr != nil {
err = errors.Errorf("delete generic component failed: %s", rowsErr)
_ = trans.Rollback()
return
}
if counter < 1 {
err = NoSuch
_ = trans.Rollback()
return
}
commitErr := trans.Commit()
if commitErr != nil {
err = errors.Errorf("unable to commit transaction: %s", commitErr)
return
}
return
}
func DeleteAllGenericHardware() (err error) {
q := "TRUNCATE " +
" components "
trans, beginErr := DB.Begin()
if beginErr != nil {
err = errors.Errorf("unable to begin transaction: %s", beginErr)
return
}
_, err = IncrementVersion(trans, "delete all hardware")
if err != nil {
err = errors.Errorf("insert to version_history failed: %s", err)
_ = trans.Rollback()
return err
}
_, transErr := trans.Exec(q)
if transErr != nil {
err = errors.Errorf("unable to exec transaction: %s", transErr)
return
}
commitErr := trans.Commit()
if commitErr != nil {
err = errors.Errorf("unable to commit transaction: %s", commitErr)
return
}
return
}
func UpdateGenericHardware(hardware sls_common.GenericHardware) (err error) {
q := "UPDATE components \n" +
"SET \n" +
" parent = $2, \n" +
" comp_type = $3, \n" +
" comp_class = $4, \n" +
" extra_properties = $5, \n" +
" last_updated_version = $6 \n" +
"WHERE \n" +
" xname = $1 "
jsonBytes, jsonErr := json.Marshal(hardware.ExtraPropertiesRaw)
if jsonErr != nil {
err = errors.Errorf("unable to marshal ExtendedProperties: %s", jsonErr)
return
}
trans, beginErr := DB.Begin()
if beginErr != nil {
err = errors.Errorf("unable to begin transaction: %s", beginErr)
return
}
version, err := IncrementVersion(trans, hardware.Xname)
if err != nil {
err = errors.Errorf("insert to version_history failed: %s", err)
_ = trans.Rollback()
return err
}
result, transErr := trans.Exec(q, hardware.Xname, hardware.Parent, hardware.Type, hardware.Class, string(jsonBytes), version)
if transErr != nil {
err = errors.Errorf("unable to exec transaction: %s", transErr)
_ = trans.Rollback()
return
}
var counter int64
counter, rowsErr := result.RowsAffected()
if rowsErr != nil {
err = errors.Errorf("update generic component failed: %s", rowsErr)
_ = trans.Rollback()
return
}
if counter < 1 {
err = NoSuch
_ = trans.Rollback()
return
}
commitErr := trans.Commit()
if commitErr != nil {
err = errors.Errorf("unable to commit transaction: %s", commitErr)
return
}
return
}
func getChildrenForXname(xname string) (children []string, err error) {
// Now we find all the children for this object and add them to the base object.
parentQ := "SELECT \n" +
" xname \n" +
"FROM \n" +
" components \n" +
"WHERE \n" +
" parent = $1 "
childrenRows, parentErr := DB.Query(parentQ, xname)
if parentErr != nil {
err = errors.Errorf("unable to query children: %s", parentErr)
return
}
for childrenRows.Next() {
var thisChildXname string
childErr := childrenRows.Scan(&thisChildXname)
if childErr != nil {
err = errors.Errorf("unable to scan child row: %s", childErr)
return
}
children = append(children, thisChildXname)
}
return
}
func GetAllGenericHardware() (hardware []sls_common.GenericHardware, err error) {
// First, get the base object and all its associated data
baseQ := "SELECT \n" +
" c1.xname, \n" +
" c1.parent, \n" +
" c1.comp_type, \n" +
" c1.comp_class, \n" +
" version_history.timestamp, \n" +
" c1.extra_properties, \n" +
" ARRAY_REMOVE(ARRAY_AGG(distinct c2.xname), NULL) as children \n" +
"FROM \n" +
" components c1 \n" +
"INNER JOIN version_history \n" +
" ON c1.last_updated_version = version_history.version \n" +
"LEFT JOIN components c2 \n" +
" ON c1.xname = c2.parent \n" +
" GROUP BY c1.xname, c1.parent, c1.comp_type, c1.comp_class, version_history.timestamp, c1.extra_properties"
baseRows, baseErr := DB.Query(baseQ)
if baseErr != nil {
err = errors.Errorf("unable to query generic hardware: %s", baseErr)
return
}
for baseRows.Next() {
var thisGenericHardware sls_common.GenericHardware
var lastUpdated time.Time
var extraPropertiesBytes []byte
baseErr := baseRows.Scan(&thisGenericHardware.Xname,
&thisGenericHardware.Parent,
&thisGenericHardware.Type,
&thisGenericHardware.Class,
&lastUpdated,
&extraPropertiesBytes,
pq.Array(&thisGenericHardware.Children))
if baseErr != nil {
err = errors.Errorf("unable to scan base row: %s", baseErr)
return
}
thisGenericHardware.LastUpdated = lastUpdated.Unix()
thisGenericHardware.LastUpdatedTime = lastUpdated.String()
thisGenericHardware.TypeString = sls_common.HMSStringTypeToHMSType(thisGenericHardware.Type)
unmarshalErr := json.Unmarshal(extraPropertiesBytes, &thisGenericHardware.ExtraPropertiesRaw)
if unmarshalErr != nil {
err = errors.Errorf("unable to unmarshal extended properties: %s", unmarshalErr)
return
}
hardware = append(hardware, thisGenericHardware)
}
return
}
func GetGenericHardwareFromXname(xname string) (hardware sls_common.GenericHardware, err error) {
// First, get the base object and all its associated data
baseQ := "SELECT \n" +
" c1.xname, \n" +
" c1.parent, \n" +
" c1.comp_type, \n" +
" c1.comp_class, \n" +
" version_history.timestamp, \n" +
" c1.extra_properties, \n" +
" ARRAY_REMOVE(ARRAY_AGG(distinct c2.xname), NULL) as children \n" +
"FROM \n" +
" components c1 \n" +
"INNER JOIN version_history \n" +
" ON c1.last_updated_version = version_history.version \n" +
"LEFT JOIN components c2 \n" +
" ON c1.xname = c2.parent \n" +
"WHERE \n" +
" c1.xname = $1 \n" +
"GROUP BY c1.xname, c1.parent, c1.comp_type, c1.comp_class, version_history.timestamp, c1.extra_properties"
baseRow := DB.QueryRow(baseQ, xname)
var extraPropertiesBytes []byte
var lastUpdated time.Time
baseErr := baseRow.Scan(&hardware.Xname,
&hardware.Parent,
&hardware.Type,
&hardware.Class,
&lastUpdated,
&extraPropertiesBytes,
pq.Array(&hardware.Children))
if baseErr == sql.ErrNoRows {
err = NoSuch
return
} else if baseErr != nil {
err = errors.Errorf("unable to scan generic hardware row: %s", baseErr)
return
}
hardware.TypeString = sls_common.HMSStringTypeToHMSType(hardware.Type)
hardware.LastUpdated = lastUpdated.Unix()
hardware.LastUpdatedTime = lastUpdated.String()
unmarshalErr := json.Unmarshal(extraPropertiesBytes, &hardware.ExtraPropertiesRaw)
if unmarshalErr != nil {
err = errors.Errorf("unable to unmarshal extended properties: %s", unmarshalErr)
return
}
return
}
func GetGenericHardwareForExtraProperties(properties map[string]interface{}) (hardware []sls_common.GenericHardware,
err error) {
return SearchGenericHardware(nil, properties)
}
func SearchGenericHardware(conditions map[string]string, properties map[string]interface{}) (
hardware []sls_common.GenericHardware, err error) {
if len(conditions) == 0 && len(properties) == 0 {
err = errors.Errorf("no conditions/properties with which to search")
return
}
q := "SELECT \n" +
" xname, \n" +
" parent, \n" +
" comp_type, \n" +
" comp_class, \n" +
" timestamp, \n" +
" extra_properties \n" +
"FROM \n" +
" components \n" +
"INNER JOIN \n" +
" version_history \n" +
"ON components.last_updated_version = version_history.version \n" +
"WHERE \n "
// Build the conditions for the regular columns.
index := 1
parameters := make([]interface{}, 0)
for key, value := range conditions {
if index != 1 {
q = q + " AND"
}
q = q + fmt.Sprintf(" %s = $%d \n", key, index)
parameters = append(parameters, value)
index++
}
// Build the conditions for the extra properties JSON column.
for key, value := range properties {
if index != 1 {
q = q + " AND"
}
// Some day I want to come back around and make this work with infinite levels of depth, but for now just
// investigate the type of the value interface. If it's a string then use one syntax, if it's an array use
// another. The rational being that nested types need different syntax to query.
//
// postgres operators: https://www.postgresql.org/docs/current/functions-json.html
// jsonb -> text returns jsonb - finds the given json field and returns the value as json
// jsonb ->> text returns text - finds the given json field and returns the value as text
// jsonb ?| text[] returns boolean - returns true if any of the strings in text[] exist as top level keys or array elements
valueString, ok := value.(string)
if ok {
q = q + fmt.Sprintf(" extra_properties ->> $%d = $%d \n", index, index+1)
parameters = append(parameters, key, valueString)
index += 2
} else if valueArray, ok := value.([]string); ok {
keyIndex := index
index++
var paramArray string
var values []interface{}
index, values, paramArray = ToParameterArray(index, valueArray)
q = q + fmt.Sprintf(" extra_properties -> $%d ?| array[%s] \n", keyIndex, paramArray)
parameters = append(parameters, key)
parameters = append(parameters, values...)
}
}
rows, queryErr := DB.Query(q, parameters...)
if queryErr != nil {
err = errors.Errorf("unable to query extra properties: %s", queryErr)
return
}
for rows.Next() {
newGenericHardware := sls_common.GenericHardware{}
var extraPropertiesBytes []byte
var lastUpdated time.Time
scanErr := rows.Scan(&newGenericHardware.Xname,
&newGenericHardware.Parent,
&newGenericHardware.Type,
&newGenericHardware.Class,
&lastUpdated,
&extraPropertiesBytes)
if scanErr != nil {
err = errors.Errorf("unable to scan row: %s", scanErr)
return
}
newGenericHardware.TypeString = sls_common.HMSStringTypeToHMSType(newGenericHardware.Type)
newGenericHardware.LastUpdated = lastUpdated.Unix()
newGenericHardware.LastUpdatedTime = lastUpdated.String()
unmarshalErr := json.Unmarshal(extraPropertiesBytes, &newGenericHardware.ExtraPropertiesRaw)
if unmarshalErr != nil {
err = errors.Errorf("unable to unmarshal extended properties: %s", unmarshalErr)
return
}
var children []string
children, err = getChildrenForXname(newGenericHardware.Xname)
if err != nil {
return
}
newGenericHardware.Children = children
hardware = append(hardware, newGenericHardware)
}
return
}
func ReplaceAllGenericHardware(hardware []sls_common.GenericHardware) (err error) {
trans, beginErr := DB.Begin()
if beginErr != nil {
err = errors.Errorf("unable to begin transaction: %s", beginErr)
return
}
version, err := IncrementVersion(trans, "replaced all components")
if err != nil {
err = errors.Errorf("insert to version_history failed: %s", err)
_ = trans.Rollback()
return err
}
// Start by deleting all the components currently there.
q := "TRUNCATE " +
" components "
_, transErr := trans.Exec(q)
if transErr != nil {
err = errors.Errorf("unable to exec transaction: %s", transErr)
_ = trans.Rollback()
return
}
// Now bulk load the passed in hardware into the database using a prepared statement.
statement, prepareErr := trans.Prepare(pq.CopyIn("components",
"xname", "parent", "comp_type", "comp_class", "last_updated_version", "extra_properties"))
if prepareErr != nil {
err = errors.Errorf("unable to prepare statement: %s", prepareErr)
_ = trans.Rollback()
return
}
for _, component := range hardware {
jsonBytes, jsonErr := json.Marshal(component.ExtraPropertiesRaw)
if jsonErr != nil {
err = errors.Errorf("unable to marshal ExtendedProperties: %s", jsonErr)
_ = trans.Rollback()
return
}
_, execErr := statement.Exec(component.Xname, component.Parent, component.Type, component.Class,
version, string(jsonBytes))
if execErr != nil {
err = errors.Errorf("unable to exec statement: %s", execErr)
_ = trans.Rollback()
return
}
}
_, statementErr := statement.Exec()
if statementErr != nil {
err = errors.Errorf("unable to exec statement: %s", statementErr)
_ = trans.Rollback()
return
}
statementErr = statement.Close()
if statementErr != nil {
err = errors.Errorf("unable to close statement: %s", statementErr)
_ = trans.Rollback()
return
}
// Now finally we can commit the entire transaction. Assuming this works, we're done here.
commitErr := trans.Commit()
if commitErr != nil {
err = errors.Errorf("unable to commit transaction: %s", commitErr)
return
}
return
}