-
Notifications
You must be signed in to change notification settings - Fork 5
/
hmsds-tx-postgres.go
5757 lines (5323 loc) · 167 KB
/
hmsds-tx-postgres.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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// MIT License
//
// (C) Copyright [2018-2023] 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 hmsds
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"log"
"strconv"
"strings"
"time"
base "github.com/Cray-HPE/hms-base/v2"
"github.com/Cray-HPE/hms-xname/xnametypes"
"github.com/Cray-HPE/hms-smd/v2/pkg/sm"
sq "github.com/Masterminds/squirrel"
"github.com/google/uuid"
"github.com/lib/pq"
)
//
// hmsdbPgTx struct - This is a private implementation of the HMSDBTx
// interface. HMSDBTx represents an abstracted notion of a database
// transaction. This is used when the package user needs to combine
// multiple operations in an atomic fashion.
//
type hmsdbPgTx struct {
hdb *hmsdbPg
tx *sql.Tx
ctx context.Context
stmt *sql.Stmt
sc *sq.StmtCache
query string
}
// This should only be called by hdb.Begin()
func newHMSDBPgTx(hdb *hmsdbPg) (HMSDBTx, error) {
var err error
t := new(hmsdbPgTx)
t.hdb = hdb
// Note this is just a placeholder so we don't have a null pointer
// Later we will do more useful things, so we are just using the context
// aware versions of the sql functions so they are plumbed.
t.ctx = context.TODO()
// Create a new transaction from from using the exiting DB connection pool
t.tx, err = t.hdb.db.BeginTx(t.ctx, nil)
if err != nil {
return nil, err
}
t.sc = sq.NewStmtCache(t.tx)
return t, nil
}
////////////////////////////////////////////////////////////////////////////
//
// Helper functions
//
////////////////////////////////////////////////////////////////////////////
// Prepare the given query string and return a pointer to the statement
// handle. If the same query is being done (i.e. in a transaction), return
// a cached pointer so it does not need to be reprepared multiple times.
// If another query is being done, close the cached stmt handle and prepare
// the new one, caching it in the hmsdbTx. Ditto the latter when the
// cached statment will be the first for the transaction.
func (t *hmsdbPgTx) conditionalPrepare(qname, query string) (*sql.Stmt, error) {
var err error
if query == "" {
t.LogAlways("Error: %s(): query was empty.", qname)
return nil, ErrHMSDSArgNil
}
if !t.IsConnected() {
return nil, ErrHMSDSPtrClosed
}
// Replace ? placeholders for prepared query args with postgres type.
// These have to be numbered ($1, $2,...), but since the number of args
// matches the number of placeholders, this is no problem, though we
// don't take advantage of not needing to reuse things that appear
// more than once. NOTE THAT THIS DOES NOT IGNORE QUOTED ?
// VALUES. So don't build queries like that (the arguments
// themselves can have whatever).
origQuery := query
query = ToPGQueryArgs(origQuery)
if t.query == "" {
t.stmt, err = t.tx.PrepareContext(t.ctx, query)
if err != nil {
t.LogAlways("Error: Prepare(%s) Failed: %s", qname, err)
return nil, err
}
t.query = query
} else if t.query != query {
if t.stmt != nil {
if err := t.stmt.Close(); err != nil {
t.LogAlways("Warning: %s: Failed to close old stmt: %s",
qname, err)
}
}
t.query = ""
t.stmt, err = t.tx.PrepareContext(t.ctx, query)
if err != nil {
t.LogAlways("Error: Re-prepare(%s) Failed: %s", qname, err)
return nil, err
}
t.query = query
}
return t.stmt, nil
}
// Helper function. Prepares, and issues query with the provided arguments.
// Close *Rows when operation is complete.
func (t *hmsdbPgTx) getRowsForQuery(qname, query string, args ...interface{}) (*sql.Rows, error) {
t.Log(LOG_DEBUG, "%s(%v) starting....", qname, args)
stmt, err := t.conditionalPrepare(qname, query)
if err != nil {
return nil, err
}
rows, err := stmt.QueryContext(t.ctx, args...)
return rows, err
}
//
// Logging
//
// Produces an object implementing a log interface.
func (t *hmsdbPgTx) GetLog() *log.Logger {
return t.hdb.lg
}
// Abstraction layer to logging infrastructure. Works like log.Printf.
func (t *hmsdbPgTx) LogAlways(format string, a ...interface{}) {
// Call depth of 2 - report caller's line number.
t.hdb.lg.Output(2, fmt.Sprintf(format, a...))
}
// Works like log.Printf, but registers error for function calling the
// function that is printing the error. e.g. instead of always saying
// an error occurred in begin(), we show where begin() was called, so
// we don't have to guess, and the message can make clear what in begin()
// failed.
func (t *hmsdbPgTx) LogAlwaysParentFunc(format string, a ...interface{}) {
// Call depth of 3 - report caller's caller's line number.
t.hdb.lg.Output(3, fmt.Sprintf(format, a...))
}
// Conditional logging based on current log level
func (t *hmsdbPgTx) Log(l LogLevel, format string, a ...interface{}) {
if int(l) <= int(t.hdb.lgLvl) {
// Call depth of 2 - report caller's line number.
t.hdb.lg.Output(2, fmt.Sprintf(format, a...))
}
}
// Checks log level of parent connection pool vs arg
func (t *hmsdbPgTx) IsLogLevel(lvl LogLevel) bool {
if int(t.hdb.lgLvl) <= int(lvl) {
return true
} else {
return false
}
}
/////////////////////////////////////////////////////////////////////////////
//
// HMSDBTx Interface Implementation
//
/////////////////////////////////////////////////////////////////////////////
// Terminates transaction, reversing all changes made prior to Begin()
func (t *hmsdbPgTx) Rollback() error {
if t.stmt != nil {
if err := t.stmt.Close(); err != nil {
t.LogAlways("Warning: Rollback(): Failed to close old stmt: %s", err)
}
}
return t.tx.Rollback()
}
// Terminates transaction successfully, committing all operations
// performed against it in an atomic fashion. Closes any non-nil
// statement handles that may still be open.
func (t *hmsdbPgTx) Commit() error {
if t.stmt != nil {
t.stmt.Close()
if err := t.stmt.Close(); err != nil {
t.LogAlways("Warning: Commit(): Failed to close old stmt: %s", err)
}
}
return t.tx.Commit()
}
// Checks to see if parent connection pool is still healthy.
func (t *hmsdbPgTx) IsConnected() bool {
return t.hdb.connected
}
/////////////////////////////////////////////////////////////////////////////
//
// HMSDBTx Interface - Generic value queries
//
/////////////////////////////////////////////////////////////////////////////
// For queries that obtain a single string value such as an ID/xname. The
// entry type does not matter as long as the query returns one string per row.
func (t *hmsdbPgTx) querySingleStringValue(qname, query string, args ...interface{}) ([]string, error) {
vals := make([]string, 0, 1)
rows, err := t.getRowsForQuery(qname, query, args...)
if err != nil {
return vals, err
}
defer rows.Close()
i := 0
for rows.Next() {
val, err := t.hdb.scanSingleStringValue(rows)
if err != nil {
t.LogAlways("Error: %s(%v): Scan failed: %s", qname, args, err)
return vals, err
}
t.Log(LOG_DEBUG, "Debug: %s() scanned[%d]: %v", qname, i, val)
if val != nil {
vals = append(vals, *val)
}
i += 1
}
err = rows.Err()
t.Log(LOG_INFO, "Info: %s(%v) returned %d values.", qname, args, len(vals))
return vals, err
}
// Get the id values for either all labels in the given table, or a
// filtered set based on filter f (*ComponentFilter, *RedfishEPFilter,
// *CompEPFilter)
// Use one of the *Table values in hmsds-api for 'table' arg,
// e.g. ComponentsTable, RedfishEndpointsTable, etc.
func (t *hmsdbPgTx) GetIDListTx(tbl string, f interface{}) ([]string, error) {
query := ""
var args []interface{}
// Name of function to use in errors, if not given by filter.label
label := "GetIDListTx"
var err error = nil
switch tbl {
case ComponentsTable:
queryBase := getCompIDPrefix
if filter, ok := f.(*ComponentFilter); ok {
query, args, err = buildComponentQuery(queryBase, filter)
if filter.label != "" {
label = filter.label
}
} else {
query = queryBase + ";"
}
case RedfishEndpointsTable:
queryBase := getRFEndpointIDPrefix
if filter, ok := f.(*RedfishEPFilter); ok {
query, args, err = buildRedfishEPQuery(queryBase, filter)
if filter.label != "" {
label = filter.label
}
} else {
query = queryBase + ";"
}
case ComponentEndpointsTable:
queryBase := getCompEndpointIDPrefix
if filter, ok := f.(*CompEPFilter); ok {
query, args, err = buildCompEPQuery(queryBase, filter)
if filter.label != "" {
label = filter.label
}
} else {
query = queryBase + ";"
}
case NodeMapTable:
query = getNodeMapIDPrefix + ";"
case HWInvByLocTable:
query = getHWInvByLocIDPrefix + ";"
case HWInvByFRUTable:
query = getHWInvByFRUIDPrefix + ";"
case DiscoveryStatusTable:
query = getDiscoveryStatusIDPrefix + ";"
default:
t.LogAlways("Error: %s(): Bad input: %s", label, err)
return []string{}, ErrHMSDSArgMissing
}
// Check for error building query
if err != nil {
t.LogAlways("Error: %s(): Got error '%s' building query: %s",
label, err, query)
return []string{}, err
}
// Call DB and get IDs per table contents and optional filter.
return t.querySingleStringValue(label, query, args...)
}
// Build filter query for Component IDs using filter functions and
// then return the list of matching xname IDs as a string array, write locking
// the rows if requested. The IDs will be normalized.
func (t *hmsdbPgTx) GetComponentIDsTx(f_opts ...CompFiltFunc) ([]string, error) {
f := new(ComponentFilter)
for _, opts := range f_opts {
opts(f)
}
affectedIDs, err := t.GetIDListTx(ComponentsTable, f)
if err != nil {
return []string{}, err
}
return affectedIDs, nil
}
// Build filter query for ComponentEndpoints IDs using filter functions and
// then return the list of matching xname IDs as a string array, write locking
// the rows if requested.
func (t *hmsdbPgTx) GetCompEndpointIDsTx(
f_opts ...CompEPFiltFunc,
) ([]string, error) {
f := new(CompEPFilter)
for _, opts := range f_opts {
opts(f)
}
affectedIDs, err := t.GetIDListTx(ComponentEndpointsTable, f)
if err != nil {
return []string{}, err
}
return affectedIDs, nil
}
// Build filter query for RedfishEndpoints IDs using filter functions and
// then return the list of matching xname IDs as a string array, write locking
// the rows if requested.
func (t *hmsdbPgTx) GetRFEndpointIDsTx(
f_opts ...RedfishEPFiltFunc,
) ([]string, error) {
f := new(RedfishEPFilter)
for _, opts := range f_opts {
opts(f)
}
affectedIDs, err := t.GetIDListTx(RedfishEndpointsTable, f)
if err != nil {
return []string{}, err
}
return affectedIDs, nil
}
/////////////////////////////////////////////////////////////////////////////
//
// HMSDBTx Interface - Component queries
//
/////////////////////////////////////////////////////////////////////////////
// Back end for all queries that produce one or more HMS Component rows in
// the result.
func (t *hmsdbPgTx) queryComponent(qname string, fltr FieldFilter, query string, args ...interface{}) ([]*base.Component, error) {
// Add a row filter to only get the rows that we want
switch fltr {
case FLTR_DEFAULT:
case FLTR_STATEONLY:
query = strings.TrimSuffix(query, ";")
query = getCompStatePrefix + query + suffixCompFilter
case FLTR_FLAGONLY:
query = strings.TrimSuffix(query, ";")
query = getCompFlagPrefix + query + suffixCompFilter
case FLTR_ROLEONLY:
query = strings.TrimSuffix(query, ";")
query = getCompRolePrefix + query + suffixCompFilter
case FLTR_NIDONLY:
query = strings.TrimSuffix(query, ";")
query = getCompNIDPrefix + query + suffixCompFilter
default:
// Default to using the default filter
fltr = FLTR_DEFAULT
}
t.Log(LOG_DEBUG, "Debug: %s(%v) starting query '%s'",
qname, args, strings.Replace(query, "\n", " ", -1))
stmt, err := t.conditionalPrepare(qname, query)
if err != nil {
return nil, err
}
rows, err := stmt.QueryContext(t.ctx, args...)
if err != nil {
return nil, err
}
defer rows.Close()
comps := make([]*base.Component, 0, 1)
i := 0
for rows.Next() {
comp, err := t.hdb.scanComponent(rows, fltr)
if err != nil {
t.LogAlways("Error: %s(%v): Scan failed: %s", qname, args, err)
return comps, err
}
t.Log(LOG_DEBUG, "Debug: %s() scanned[%d]: %v", qname, i, comp)
comps = append(comps, comp)
i += 1
}
err = rows.Err()
t.Log(LOG_INFO, "Info: %s(%v) returned %d comps.", qname, args, len(comps))
return comps, err
}
// Back end for all queries that produce one or more HMS Component rows in
// the result.
func (t *hmsdbPgTx) sqQueryComponent(q sq.SelectBuilder,
qname string, fltr FieldFilter) ([]*base.Component, error) {
queryString, args, _ := q.ToSql()
t.Log(LOG_DEBUG, "%s(): Submitting '%s' with '%v'",
qname, queryString, args)
// Run provided query to get rows to scan.
q = q.PlaceholderFormat(sq.Dollar)
rows, err := q.RunWith(t.sc).QueryContext(t.ctx)
if err != nil {
t.LogAlways("Error: %s(): query failed: %s", qname, err)
return nil, err
}
defer rows.Close()
comps := make([]*base.Component, 0, 1)
i := 0
for rows.Next() {
comp, err := t.hdb.scanComponent(rows, fltr)
if err != nil {
t.LogAlways("Error: %s(%v): Scan failed: %s", qname, args, err)
return comps, err
}
t.Log(LOG_DEBUG, "Debug: %s() scanned[%d]: %v", qname, i, comp)
comps = append(comps, comp)
i += 1
}
err = rows.Err()
t.Log(LOG_INFO, "Info: %s(%v) returned %d comps.", qname, args, len(comps))
return comps, err
}
// Build filter query for State/Components using filter functions and
// then return the set of matching components as an array, write locking
// the rows if requested.
//
// NOTE: Most args allow negated arguments, i.e. "!x0c0s0b0", so be careful about
// passing in user data if the query should only return a single result. ID()
// does not and takes a single arg.
func (t *hmsdbPgTx) GetComponentsTx(f_opts ...CompFiltFunc) ([]*base.Component, error) {
f := new(ComponentFilter)
for _, opts := range f_opts {
opts(f)
}
return t.GetComponentsFilterTx(f, FLTR_DEFAULT)
}
// Same as above, but allows only certain fields to be returned
// via FieldFilter
func (t *hmsdbPgTx) GetComponentsFieldFilterTx(
fieldFltr FieldFilter,
f_opts ...CompFiltFunc,
) ([]*base.Component, error) {
f := new(ComponentFilter)
for _, opts := range f_opts {
opts(f)
}
return t.GetComponentsFilterTx(f, fieldFltr)
}
// Look up a single HMS Component by id, i.e. xname (in transaction).
func (t *hmsdbPgTx) GetComponentByIDTx(id string) (*base.Component, error) {
return t.getComponentByIDRawTx(id, false)
}
// Look up a single HMS Component by id, i.e. xname (in transaction).
// THIS WILL CREATE A WRITE LOCK ON THE ENTRY, so the transaction should
// not be kept open longer than needed.
func (t *hmsdbPgTx) GetComponentByIDForUpdateTx(id string) (*base.Component, error) {
return t.getComponentByIDRawTx(id, true)
}
// Helper... get comp by ID, with or without SELECT ... FOR UPDATE
func (t *hmsdbPgTx) getComponentByIDRawTx(id string, for_update bool) (*base.Component, error) {
fname := "GetComponentByIDTx"
query := getComponentByIDQuery
if for_update == true {
fname = "GetComponentByIDForUpdateTx"
query = getComponentByIDForUpdQuery
}
if id == "" {
t.LogAlways("Error: %s(): xname was empty", fname)
return nil, ErrHMSDSArgMissing
}
// Perform corresponding query on DB
comps, err := t.queryComponent(fname, FLTR_DEFAULT, query,
xnametypes.NormalizeHMSCompID(id))
if err != nil {
return nil, err
}
// Query succeeded. There should be at most 1 row returned...
if len(comps) == 0 {
t.Log(LOG_INFO, "Info: %s(%s) matched no comps.",
fname, xnametypes.NormalizeHMSCompID(id))
return nil, nil
} else if len(comps) > 1 {
t.LogAlways("WARNING: %s(%s): multiple comps!.",
fname, xnametypes.NormalizeHMSCompID(id))
}
return comps[0], nil
}
// Get all HMS Components in system (in transaction).
func (t *hmsdbPgTx) GetComponentsAllTx() ([]*base.Component, error) {
return t.GetComponentsTx(From("GetComponentsAllTx"))
}
// Get some or all HMS Components in system (in transaction), with
// filtering options to possibly narrow the returned values.
// If no filter provided, just get everything. Otherwise use it
// to create a custom WHERE... string that filters out entries that
// do not match ALL of the non-empty strings in the filter struct
func (t *hmsdbPgTx) GetComponentsFilterTx(f *ComponentFilter, fieldFltr FieldFilter) ([]*base.Component, error) {
var comps []*base.Component
var err error
label := "GetComponentsFilterTx"
query, err := selectComponents(f, fieldFltr)
if err != nil {
t.LogAlways("Error: %s(): makeComponentQuery failed: %s", label, err)
return comps, err
}
// Perform corresponding query on DB
comps, err = t.sqQueryComponent(query, label, fieldFltr)
if err != nil {
return comps, err
}
// Query succeeded.
if len(comps) == 0 {
t.Log(LOG_INFO, "Info: %s(): no matches", label)
return comps, nil
}
return comps, nil
}
// Get some or all HMS Components in system (in transaction) under
// a set of parent components, with filtering options to possibly
// narrow the returned values. If no filter provided, just get
// the parent components. Otherwise use it to create a custom
// WHERE... string that filters out entries that do not match ALL
// of the non-empty strings in the filter struct.
func (t *hmsdbPgTx) GetComponentsQueryTx(f *ComponentFilter, fieldFltr FieldFilter, ids []string) ([]*base.Component, error) {
var comps []*base.Component
var err error
label := "GetComponentsQueryTx"
for i := 0; i < len(ids); i++ {
if ids[i] == "s0" || ids[i] == "all" {
// Reseting the length of our xname slice to 0
// will cause the query to not be filtered by xname.
ids = ids[:0]
break
}
}
if f == nil {
f = new(ComponentFilter)
}
// Get query string
query, err := selectComponentsHierarchy(f, fieldFltr, ids)
if err != nil {
return nil, err
}
// Perform corresponding query on DB
comps, err = t.sqQueryComponent(query, label, fieldFltr)
if err != nil {
return nil, err
}
// Query succeeded.
if len(comps) == 0 {
t.Log(LOG_INFO, "Info: %s(): no matches: %v", label, ids)
return comps, nil
}
return comps, nil
}
// Get a single HMS Component by its NID, if the NID exists (in transaction)
func (t *hmsdbPgTx) GetComponentByNIDTx(nid string) (*base.Component, error) {
if nid == "" {
t.LogAlways("Error: GetComponentByNID(): NID was empty.")
return nil, ErrHMSDSArgMissing
}
// Verify nid string is an int and is positive.
if i, err := strconv.Atoi(nid); err != nil {
return nil, ErrHMSDSArgNotAnInt
} else if i < 0 {
return nil, ErrHMSDSArgBadRange
}
// Perform corresponding query on DB
comps, err := t.queryComponent("GetComponentByNID", FLTR_DEFAULT,
getComponentByNIDQuery, nid)
if err != nil {
return nil, err
}
// Query succeeded. There should be at most 1 row returned...
if len(comps) == 0 {
t.Log(LOG_INFO, "Info: GetComponentByNID(%s) matched no comps.", nid)
return nil, nil
} else if len(comps) > 1 {
t.LogAlways("WARNING: GetComponentByNID(%s): multiple comps!.", nid)
}
return comps[0], nil
}
// Insert HMS Component into database, updating it if it exists.
// Returns the number of affected rows. < 0 means RowsAffected() is not supported.
func (t *hmsdbPgTx) InsertComponentTx(c *base.Component) (int64, error) {
var enabledFlg bool
if c == nil {
t.LogAlways("Error: InsertComponentTx(): Component was nil.")
return 0, ErrHMSDSArgNil
}
if !t.IsConnected() {
return 0, ErrHMSDSPtrClosed
}
// If NID is not a valid number (e.g. empty string), set to -1.
//
var rawNID int64
if num, err := c.NID.Int64(); err != nil {
rawNID = -1
} else {
rawNID = num
}
// Prepare query
stmt, err := t.conditionalPrepare("InsertComponentTx", insertPgCompQuery)
if err != nil {
return 0, err
}
// Default to enabled.
if c.Enabled == nil {
enabledFlg = true
} else {
enabledFlg = *c.Enabled
}
// Normalize key
normID := xnametypes.NormalizeHMSCompID(c.ID)
// Perform insert
result, err := stmt.ExecContext(t.ctx,
&normID,
&c.Type,
&c.State,
&c.Flag,
&enabledFlg,
&c.SwStatus,
&c.Role,
&c.SubRole,
&rawNID,
&c.Subtype,
&c.NetType,
&c.Arch,
&c.Class,
&c.ReservationDisabled,
&c.Locked)
if err != nil {
t.LogAlways("Error: InsertComponentTx(): stmt.Exec: %s", err)
return 0, err
}
t.Log(LOG_DEBUG, "Debug: InsertComponentTx() - %v", c)
rowsAffected, err := result.RowsAffected()
if err != nil {
// This likely means that RowsAffected() is unsupported.
// Default to reporting that an update happened by returning non-zero.
return -1, nil
}
return rowsAffected, nil
}
// Insert HMS Components into the database, updating it if it exists.
// Returns the IDs of the affected components.
//
// Example Query:
// INSERT INTO components (
// id,
// type,
// state,
// flag,
// enabled,
// admin,
// role,
// subrole,
// nid,
// subtype,
// nettype,
// arch,
// class,
// reservation_disabled,
// locked)
// VALUES
// ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15),
// ...
// ($#, $#, $#, $#, $#, $#, $#, $#, $#, $#, $#, $#, $#, $#, $#)
// ON CONFLICT(id) DO UPDATE SET
// state = EXCLUDED.state,
// flag = EXCLUDED.flag,
// subtype = EXCLUDED.subtype,
// nettype = EXCLUDED.nettype,
// arch = EXCLUDED.arch,
// class = EXCLUDED.class
// RETURNING *;
func (t *hmsdbPgTx) InsertComponentsTx(comps []*base.Component) ([]string, error) {
results := []string{}
if len(comps) == 0 {
return []string{}, nil
}
if !t.IsConnected() {
return []string{}, ErrHMSDSPtrClosed
}
valueMap := make(map[string]bool)
// Generate query
query := sq.Insert(compTable).
Columns(compColsDefault...)
for _, c := range comps {
// Normalize key
normID := xnametypes.NormalizeHMSCompID(c.ID)
// Take out duplicates so that we don't get errors for modifying a row multiple times.
if _, ok := valueMap[normID]; ok {
continue
} else {
valueMap[normID] = true
}
// If NID is not a valid number (e.g. empty string), set to -1.
var rawNID int64
if num, err := c.NID.Int64(); err != nil {
rawNID = -1
} else {
rawNID = num
}
// Default to enabled.
var enabledFlg bool
if c.Enabled == nil {
enabledFlg = true
} else {
enabledFlg = *c.Enabled
}
// Set fields for the INSERT
query = query.Values(
normID,
c.Type,
c.State,
c.Flag,
enabledFlg,
c.SwStatus,
c.Role,
c.SubRole,
rawNID,
c.Subtype,
c.NetType,
c.Arch,
c.Class,
c.ReservationDisabled,
c.Locked)
}
query = query.Suffix("ON CONFLICT(" + compIdCol + ") DO UPDATE SET " +
compStateCol + " = EXCLUDED." + compStateCol + ", " +
compFlagCol + " = EXCLUDED." + compFlagCol + ", " +
compSubTypeCol + " = EXCLUDED." + compSubTypeCol + ", " +
compNetTypeCol + " = EXCLUDED." + compNetTypeCol + ", " +
compArchCol + " = EXCLUDED." + compArchCol + ", " +
compClassCol + " = EXCLUDED." + compClassCol +
" RETURNING " + compIdCol)
query = query.PlaceholderFormat(sq.Dollar)
qStr, qArgs, _ := query.ToSql()
t.Log(LOG_DEBUG, "Debug: InsertComponentsTx(): Query: %s - With args: %v", qStr, qArgs)
rows, err := query.RunWith(t.sc).QueryContext(t.ctx)
if err != nil {
t.LogAlways("Error: InsertComponentsTx(): QueryContext: %s", err)
return []string{}, err
}
defer rows.Close()
for rows.Next() {
var id string
err := rows.Scan(&id)
if err != nil {
return []string{}, err
}
results = append(results, id)
}
return results, nil
}
// Update state and flag fields only in DB for xname IDs 'ids'
// If force = true ignores any starting state restrictions and will always
// set ids to state, unless it is already set.
//
// If noVerify = true, don't add extra where clauses to ensure only the
// rows that should change do. If true, either we already verified that
// the ids list will be changed, and have locked the rows, or else we don't
// care to know the exact ids that actually changed.
//
// Returns the number of affected rows. < 0 means RowsAffected() is not
// supported.
// Note: If flag is not set, it will be set to OK (i.e. no flag)
func (t *hmsdbPgTx) UpdateCompStatesTx(
ids []string,
state, flag string,
force, noVerify bool,
pi *PartInfo,
) (int64, error) {
var filterQuery string
var args []interface{}
var fname string = "UpdateCompStatesTx"
var startStates []string
var err error
if ids == nil || len(ids) == 0 {
t.LogAlways("Error: %s(): ID list was nil.", fname)
return 0, ErrHMSDSArgNil
}
if !t.IsConnected() {
return 0, ErrHMSDSPtrClosed
}
// If flag is not provided, default is to unset flag, i.e. set to OK.
nflag := base.VerifyNormalizeFlagOK(flag)
nstate := base.VerifyNormalizeState(state)
if nstate == "" {
return 0, ErrHMSDSArgBadState
}
// The {State:"Ready", Flag:"Warning"} case needs to only affect components in
// the "Ready" state. This prevents HBTD from accidentally turning nodes back
// to Ready if the node state changed before HBTD noticed that the heartbeat
// was late.
if nstate == base.StateReady.String() && nflag == base.FlagWarning.String() {
startStates = []string{base.StateReady.String()}
} else {
// Get list of required starting states, if any, given the requested
// start state and the status of the force flag.
startStates, err = base.GetValidStartStateWForce(state, force)
if err != nil {
return 0, err
}
}
// Start an State and Flag update for c.ID. Note: this normalizes all
// of the fields and verifies them.
q, err := startCompUpdate(ids, true, State(state), Flag(nflag), FlagCondNoChange(base.FlagLocked.String()))
if err != nil {
return 0, err
}
// Construct rest of WHERE clause, if needed.
if noVerify == true {
// We don't care if the state actually changes, either because we
// already locked the rows, or we don't need detailed info on
// who updated what.
filterQuery, args, err = finishCompUpdate(q, From(fname))
} else {
// Finish the where clause so we only change states if value
// will actually be updated.
filterQuery, args, err = finishCompUpdate(
q,
NotStateOrFlag(state, nflag),
States(startStates),
From(fname))
}
if err != nil {
return 0, err
}
// Prepare statement if this query is not already prepared
stmt, err := t.conditionalPrepare(fname, filterQuery)
if err != nil {
return 0, err
}
// Update entry
result, err := stmt.ExecContext(t.ctx, args...)
if err != nil {
t.LogAlways("Error: %s(): stmt.Exec: %s", fname, err)
return 0, err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
// This likely means that RowsAffected() is unsupported.
// Default to reporting that an update happened by returning non-zero.
return -1, nil
}
return rowsAffected, nil
}
// Update Flag field in DB from c's Flag field.
// Returns the number of affected rows. < 0 means RowsAffected() is not supported.
// Note: Flag cannot be blank/invalid.
func (t *hmsdbPgTx) UpdateCompFlagOnlyTx(id string, flag string) (int64, error) {
if len(id) == 0 {
t.LogAlways("Error: UpdateCompFlagOnlyTx(): ID was empty.")
return 0, ErrHMSDSArgNil
}
if !t.IsConnected() {
return 0, ErrHMSDSPtrClosed
}
// Flag is mandatory
if len(flag) == 0 {
return 0, ErrHMSDSArgMissing
} else {
// Verify input flag and normalize any capitalization differences.
flag = base.VerifyNormalizeFlag(flag)
if flag == "" {
return 0, ErrHMSDSArgNoMatch
}
}
// Prepare statement
stmt, err := t.conditionalPrepare("UpdateCompFlagOnlyTx",
updateCompFlagOnlyByIDQuery)
if err != nil {
return 0, err
}
// Normalize key
normID := xnametypes.NormalizeHMSCompID(id)
// Make update in database.
result, err := stmt.ExecContext(t.ctx,
&flag,
&normID)
if err != nil {
t.LogAlways("Error: UpdateCompFlagOnlyTx(): stmt.Exec: %s", err)
return 0, err
}
t.Log(LOG_DEBUG, "Debug: UpdateCompFlagOnlyTx() - %v", normID)
rowsAffected, err := result.RowsAffected()
if err != nil {
// This likely means that RowsAffected() is unsupported.
// Default to reporting that an update happened by returning non-zero.
return -1, nil
}
return rowsAffected, nil
}
// Update flag field in DB for a list of components.
// Returns the number of affected rows. < 0 means RowsAffected() is not supported.
// Note: Flag cannot be empty/invalid.
func (t *hmsdbPgTx) BulkUpdateCompFlagOnlyTx(ids []string, flag string) (int64, error) {
var filterQuery string
var err error
args := make([]interface{}, 0, 1)
newArgs := make([]interface{}, 0, 1)
if ids == nil || len(ids) == 0 {
t.LogAlways("Error: BulkUpdateCompFlagOnlyTx(): ID list was nil.")
return 0, ErrHMSDSArgNil
}
if !t.IsConnected() {
return 0, ErrHMSDSPtrClosed
}
// Verify input flag and normalize any capitalization differences.
flag = base.VerifyNormalizeFlag(flag)
if flag == "" {
return 0, ErrHMSDSArgNoMatch
}
args = append(args, flag)
filterQuery, newArgs, err = buildBulkCompUpdateQuery(updateCompFlagOnlyPrefix, ids)
if err != nil {
return 0, err
}
args = append(args, newArgs...)
// Prepare statement if this query is not already prepared
stmt, err := t.conditionalPrepare("BulkUpdateCompFlagOnlyTx", filterQuery)
if err != nil {
return 0, err