-
Notifications
You must be signed in to change notification settings - Fork 5
/
hmsds-postgres.go
4982 lines (4669 loc) · 133 KB
/
hmsds-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"
"errors"
"fmt"
"log"
"os"
"strconv"
"strings"
"time"
base "github.com/Cray-HPE/hms-base/v2"
"github.com/Cray-HPE/hms-xname/xnametypes"
rf "github.com/Cray-HPE/hms-smd/v2/pkg/redfish"
"github.com/Cray-HPE/hms-smd/v2/pkg/sm"
sq "github.com/Masterminds/squirrel"
"github.com/lib/pq"
)
// MUST be kept in sync with schema installed via smd-init job
const HMSDS_PG_SCHEMA = 20
const HMSDS_PG_SYSTEM_ID = 0
type hmsdbPg struct {
dsn string // dataSourceName
connected bool // Has db.Open been called?
db *sql.DB
ctx context.Context
sc *sq.StmtCache
lg *log.Logger
lgLvl LogLevel
}
// Gen DSN for MySQL/MariaDB
func GenDsnHMSDB_PB(name, user, pass, host, opts string, port int) string {
dsn := ""
sep := ""
if name != "" {
dsn = fmt.Sprintf("dbname=%s", name)
sep = " "
}
if user != "" {
dsn = fmt.Sprintf("%s%suser=%s", dsn, sep, user)
sep = " "
}
if pass != "" {
dsn = fmt.Sprintf("%s%spassword=%s", dsn, sep, pass)
sep = " "
}
if host != "" {
dsn = fmt.Sprintf("%s%shost=%s", dsn, sep, host)
sep = " "
}
if port != 0 {
dsn = fmt.Sprintf("%s%sport=%d", dsn, sep, port)
sep = " "
}
if opts != "" {
dsn = fmt.Sprintf("%s%s%s", dsn, sep, opts)
sep = " "
}
return dsn
}
// Variant for Postgres databases.
func NewHMSDB_PG(dsn string, l *log.Logger) HMSDB {
d := new(hmsdbPg)
d.dsn = dsn
d.db = nil
d.connected = false
d.lgLvl = LOG_DEFAULT
d.ctx = context.TODO()
if l == nil {
d.lg = log.New(os.Stdout, "", log.Lshortfile|log.LstdFlags|log.Lmicroseconds)
} else {
d.lg = l
}
return d
}
// Conditional logging function (based on current log level set for conn)
func (d *hmsdbPg) Log(l LogLevel, format string, a ...interface{}) {
if int(l) <= int(d.lgLvl) {
// depth=2, get line num of caller, not us
d.lg.Output(2, fmt.Sprintf(format, a...))
}
}
// Log to logging infrastructure regardless of current log level.
func (d *hmsdbPg) LogAlways(format string, a ...interface{}) {
// Use caller's line number (depth=2)
d.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 (d *hmsdbPg) LogAlwaysParentFunc(format string, a ...interface{}) {
// Use caller's caller's line number (depth=3)
d.lg.Output(3, fmt.Sprintf(format, a...))
}
func (d *hmsdbPg) ImplementationName() string {
return "Postgres"
}
func (d *hmsdbPg) SetLogLevel(lvl LogLevel) error {
if lvl >= LOG_DEFAULT && lvl < LOG_LVL_MAX {
d.lgLvl = lvl
return nil
} else {
return errors.New("Warning: verbose level unchanged")
}
}
// Is error from postgres?
func IsDBErrorPg(err error) bool {
_, ok := err.(*pq.Error)
if !ok {
return false
} else {
return true
}
}
// Is error from postgres and indicating a duplicate key error?
func IsPgDuplicateKeyErr(err error) bool {
if pgError, ok := err.(*pq.Error); ok {
if pgError.Code == "23505" {
// Key already exists, user error.
return true
}
}
return false
}
// Is error from postgres and indicating a foreign key error?
func IsPgForeignKeyErr(err error) bool {
if pgError, ok := err.(*pq.Error); ok {
if pgError.Code == "23503" {
// Key already exists, user error.
return true
}
}
return false
}
// Takes an error from the database driver, and if it matches certain
// expected scenarios, we will return an HMSError that gives the user-
// friendly message suitable for returning to the client.
// If not, we will return the original error (which should fail
// base.IsHMSError, and so can be treated as a potentially sensitive
// internal error where we just log it an send something generic to the
// client.
func ParsePgDBError(err error) error {
if IsPgDuplicateKeyErr(err) {
if pgErr, ok := err.(*pq.Error); ok {
// Look at which key - component_id and group_namespace or group_id
if strings.Contains(pgErr.Detail, compGroupMembersNsCol) {
if strings.Contains(pgErr.Detail, partGroupNamespace) {
return ErrHMSDSExclusivePartition
} else {
return ErrHMSDSExclusiveGroup
}
}
}
return ErrHMSDSDuplicateKey
}
if IsPgForeignKeyErr(err) {
return ErrHMSDSNoComponent
}
return err
}
////////////////////////////////////////////////////////////////////////////
//
// DB operations - Open, Close, Start Transaction
//
////////////////////////////////////////////////////////////////////////////
func (d *hmsdbPg) Open() error {
var err error
if d.connected == true {
d.LogAlways("Warning: Open(): Already called, but no Close()")
return nil
}
// Create long-lived database handle. This handle can manage many
// concurrent DB connections up to the configured limit and is
// safe for use by multiple Go routes.
d.db, err = sql.Open("postgres", d.dsn)
if err != nil {
d.LogAlways("Error: Open(): sql.Open failed: %s", err)
return err
}
// Ping the new DB handle. sql.Open does not actually connect to the DB;
// this is done as-needed, so make sure we can actually do so.
err = d.db.Ping()
if err != nil {
d.LogAlways("Error: Open(): Failed to ping DB: %s", err)
d.db.Close()
return err
}
// If we can read the DB, we should be able to get the schema version.
// Make sure the expected version is installed and it's not still updating.
err = d.checkPgSchemaVersion(HMSDS_PG_SYSTEM_ID, HMSDS_PG_SCHEMA)
if err != nil {
d.LogAlways("Error: Open(): Schema check failed: %s", err)
d.db.Close()
return err
}
//
// Configure connection here
//
// This needs to be less than MariaDB's current global max_connections
// via a cnf file or the default of 151. The sql package default is
// unlimited and this causes the server-side limit to get overwhelmed.
// This should be kept in sync with the configured value in the
// mariadb docker container, which presently has it set to 100 (likely
// way too low). Note that it is a global value, however, and we should
// leave a little slack in any case (setting it to 100 exacly causes
// an occasional failure, even with no other processes connecting).
d.db.SetMaxOpenConns(70)
// Workaround for HMS-1080, one of these, so long as a minute is less
// than wait_timeout.
//d.db.SetMaxIdleConns(0)
//d.db.SetConnMaxLifetime(time.Minute)
// Mark handle as connected, as we've successfully contacted the DB
// and are ready to perform queries.
d.connected = true
// Create statement cache now that we're open.
d.sc = sq.NewStmtCache(d.db)
d.LogAlways("Open() completed successfully.")
return nil
}
// Check the systemId (should only be 0 currently) schema_version and
// if it does not match, return ErrHMSDSBadSchema. If no other
// error, will return nil if schema is obtained and matches expected
// version.
func (d *hmsdbPg) checkPgSchemaVersion(sysId, expectedVersion int) error {
var schemaVersion int
query := selectSystemSchemaVersion(sysId)
query = query.PlaceholderFormat(sq.Dollar)
err := query.RunWith(d.db).QueryRow().Scan(&schemaVersion)
if err != nil {
d.LogAlways("Error: System table query failed: %s", err)
return err
}
// New schema are backwards compatible
if schemaVersion < expectedVersion {
d.LogAlways("Got schema version %d, expected %d+, for id=%d",
schemaVersion, expectedVersion, sysId)
return ErrHMSDSBadSchema
}
d.LogAlways("Running schema version %d.", expectedVersion)
return nil
}
// Closes the database connection. This is a global operation that
// affects all go routines using a hmsdb handle. It is only used when
// we are done with the DB entirely. Individual connections are pooled
// and managed transparently by the sql API, so fine-grained management
// is not needed for individual DB calls.
func (d *hmsdbPg) Close() error {
if d.connected != true {
d.LogAlways("Warning: Close(): Not open.")
return nil
}
d.connected = false
err := d.db.Close()
return err
}
// Starts a new transaction, returning a HMSDBTx handle which allows
// transaction-friendly operations to be invoked in sequence. You
// MUST close the HMSDBTx handle with one of Commit or Rollback when
// done or the operations will eventually time out and rollback anyways,
// but in such a way that they may block operations on the same DB
// resources until then.
func (d *hmsdbPg) Begin() (HMSDBTx, error) {
if d.connected == false {
return nil, ErrHMSDSPtrClosed
}
// We back off and retry if we can't create a new transaction.
// We should keep things tuned so we never run out of connections,
// but we don't want things just randomly failing unless things are
// really bad on the server side,
var err error = nil
var tx HMSDBTx = nil
for i := 0; i < 8; i++ {
tx, err = newHMSDBPgTx(d)
if err == nil {
return tx, err
}
if i == 0 {
d.Log(LOG_INFO, "BeginTx failed: DBStats: %+v", d.db.Stats())
}
time.Sleep(time.Millisecond * time.Duration(10+(50*i)))
}
// Should always have an error here.
if err == nil {
err = ErrHMSDSTxFailed
}
d.LogAlwaysParentFunc("BeginTx failed even after retries: %s", err)
return nil, err
}
// Test the database connection to make sure that it is healthy
func (d *hmsdbPg) TestConnection() error {
if !d.connected {
d.LogAlways("Warning: TestConnection(): Not open")
return ErrHMSDSPtrClosed
}
// Ping the DB handle. This is done as-needed, so make sure we can
// actually do so.
err := d.db.Ping()
if err != nil {
d.LogAlways("Error: TestConnection(): Failed to ping DB: %s", err)
return err
}
return nil
}
////////////////////////////////////////////////////////////////////////////
//
// HMSDB Interface - Generic ID queries
//
// Return IDs of given type based on Arguments
//
////////////////////////////////////////////////////////////////////////////
// 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.
func (d *hmsdbPg) GetComponentIDs(f_opts ...CompFiltFunc) ([]string, error) {
t, err := d.Begin()
if err != nil {
return nil, err
}
ids, err := t.GetComponentIDsTx(f_opts...)
if err != nil {
t.Rollback()
return ids, err
}
err = t.Commit()
return ids, err
}
// 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 (d *hmsdbPg) GetCompEndpointIDs(f_opts ...CompEPFiltFunc) ([]string, error) {
t, err := d.Begin()
if err != nil {
return nil, err
}
ids, err := t.GetCompEndpointIDsTx(f_opts...)
if err != nil {
t.Rollback()
return ids, err
}
err = t.Commit()
return ids, err
}
// 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 (d *hmsdbPg) GetRFEndpointIDs(f_opts ...RedfishEPFiltFunc) ([]string, error) {
t, err := d.Begin()
if err != nil {
return nil, err
}
ids, err := t.GetRFEndpointIDsTx(f_opts...)
if err != nil {
t.Rollback()
return ids, err
}
err = t.Commit()
return ids, err
}
////////////////////////////////////////////////////////////////////////////
//
// HMS Components - Managed plane info: State, NID, Role
//
////////////////////////////////////////////////////////////////////////////
// Get a single component entry by its ID/xname
func (d *hmsdbPg) GetComponentByID(id string) (*base.Component, error) {
t, err := d.Begin()
if err != nil {
return nil, err
}
comp, err := t.GetComponentByIDTx(id)
if err != nil {
t.Rollback()
return comp, err
}
err = t.Commit()
return comp, err
}
// Get all HMS Components in system.
func (d *hmsdbPg) GetComponentsAll() ([]*base.Component, error) {
t, err := d.Begin()
if err != nil {
return nil, err
}
comps, err := t.GetComponentsAllTx()
if err != nil {
t.Rollback()
return comps, err
}
err = t.Commit()
return comps, err
}
// Get some or all HMS Components in system, 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 (d *hmsdbPg) GetComponentsFilter(f *ComponentFilter, fieldFltr FieldFilter) ([]*base.Component, error) {
t, err := d.Begin()
if err != nil {
return nil, err
}
comps, err := t.GetComponentsFilterTx(f, fieldFltr)
if err != nil {
t.Rollback()
return comps, err
}
err = t.Commit()
return comps, err
}
// Get some or all HMS Components in system 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 (d *hmsdbPg) GetComponentsQuery(f *ComponentFilter, fieldFltr FieldFilter, ids []string) ([]*base.Component, error) {
t, err := d.Begin()
if err != nil {
return nil, err
}
comps, err := t.GetComponentsQueryTx(f, fieldFltr, ids)
if err != nil {
t.Rollback()
return comps, err
}
err = t.Commit()
return comps, err
}
// Get a single component by its NID, if one exists.
func (d *hmsdbPg) GetComponentByNID(nid string) (*base.Component, error) {
t, err := d.Begin()
if err != nil {
return nil, err
}
comp, err := t.GetComponentByNIDTx(nid)
if err != nil {
t.Rollback()
return comp, err
}
t.Commit()
return comp, err
}
// Insert HMS Component into database, updating it if it exists.
// Returns the number of affected rows. < 0 means RowsAffected() is not supported.
func (d *hmsdbPg) InsertComponent(c *base.Component) (int64, error) {
t, err := d.Begin()
if err != nil {
return 0, err
}
rowsAffected, err := t.InsertComponentTx(c)
if err != nil {
t.Rollback()
return 0, err
}
if err = t.Commit(); err != nil {
return 0, err
}
return rowsAffected, nil
}
// Inserts or updates ComponentArray entries in database within a
// single all-or-none transaction.
func (d *hmsdbPg) InsertComponents(comps *base.ComponentArray) ([]string, error) {
if comps == nil {
d.LogAlways("Error: InsertComponents(): Component array was nil.")
return []string{}, ErrHMSDSArgNil
}
t, err := d.Begin()
if err != nil {
return []string{}, err
}
affectedIDs, err := t.InsertComponentsTx(comps.Components)
if err != nil {
t.Rollback()
return []string{}, err
}
if err := t.Commit(); err != nil {
return []string{}, err
}
return affectedIDs, nil
}
// Inserts or updates ComponentArray entries in database within a single
// all-or-none transaction. If force=true, only the state, flag, subtype,
// nettype, and arch will be overwritten for existing components. Otherwise,
// this won't overwrite existing components.
func (d *hmsdbPg) UpsertComponents(comps []*base.Component, force bool) (map[string]map[string]bool, error) {
affectedRowMap := make(map[string]map[string]bool, 0)
cmap := make(map[string]*base.Component, 0)
compList := make([]*base.Component, 0, 1)
t, err := d.Begin()
if err != nil {
return nil, err
}
ids := make([]string, len(comps))
for i, comp := range comps {
ids[i] = comp.ID
}
// Lock components for update
affectedComps, err := t.GetComponentsTx(IDs(ids), From("UpsertComponents"))
if err != nil {
t.Rollback()
return nil, err
}
for _, comp := range affectedComps {
cmap[comp.ID] = comp
}
for _, comp := range comps {
changeMap := make(map[string]bool, 0)
aComp, ok := cmap[comp.ID]
if ok {
if !force {
// Don't affect existing components
continue
} else {
otherChange := false
// Replace everything
if comp.State != aComp.State {
changeMap["state"] = true
}
if comp.Flag != aComp.Flag {
changeMap["flag"] = true
}
if len(comp.Subtype) != 0 && comp.Subtype != aComp.Subtype {
otherChange = true
}
if len(comp.NetType) != 0 && comp.NetType != aComp.NetType {
otherChange = true
}
if len(comp.Arch) != 0 && comp.Arch != aComp.Arch {
otherChange = true
}
if len(comp.Class) != 0 && comp.Class != aComp.Class {
otherChange = true
}
// Move on if there are no changes
if len(changeMap) == 0 && !otherChange {
continue
}
}
} else {
// We are creating a component here
changeMap["state"] = true
changeMap["flag"] = true
changeMap["enabled"] = true
if len(comp.SwStatus) != 0 {
changeMap["swStatus"] = true
}
changeMap["role"] = true
changeMap["subRole"] = true
changeMap["nid"] = true
}
compList = append(compList, comp)
affectedRowMap[comp.ID] = changeMap
}
compsAffected, err := t.InsertComponentsTx(compList)
if err != nil {
t.Rollback()
return nil, err
}
if err := t.Commit(); err != nil {
return nil, err
}
// Remove changes that didn't happen
if len(compsAffected) != len(compList) {
compsAffectedMap := make(map[string]string)
for _, comp := range compsAffected {
compsAffectedMap[comp] = comp
}
for _, comp := range compList {
if id, ok := compsAffectedMap[comp.ID]; !ok {
delete(affectedRowMap, id)
}
}
}
return affectedRowMap, nil
}
// Update state and flag fields only in DB for a list of components
// Note: If flag is not set, it will be set to OK (i.e. no flag)
func (d *hmsdbPg) BulkUpdateCompState(ids []string, state string, flag string) ([]string, error) {
return d.UpdateCompStates(ids, state, flag, false, new(PartInfo))
}
// Update state and flag fields only in DB for the given IDs. If
// len(ids) is > 1 a locking read will be done to ensure the list o
// components that was actually modified is always returned.
//
// If force = true ignores any starting state restrictions and will
// always set ids to 'state', unless it is already set.
// Note: If flag is not set, it will be set to OK (i.e. no flag)
func (d *hmsdbPg) UpdateCompStates(
ids []string,
state string,
flag string,
force bool,
pi *PartInfo,
) ([]string, error) {
// Verify input
numIds := len(ids)
fname := "UpdateCompStates"
if numIds < 1 {
d.LogAlways("Error: %s(): id list is empty", fname)
return []string{}, ErrHMSDSArgMissing
}
nflag := base.VerifyNormalizeFlagOK(flag)
// Start transaction
t, err := d.Begin()
if err != nil {
return []string{}, err
}
// We need to figure out the modified components. If there are more
// than one, we need to do a locking read with those that can be
// updated given their current state and the allowed starting state
// for the new state requested.
// If there is just one, we don't need to worry about this because
// there is no ambiguity as far as what components got updated and
// which didn't.
affectedIDs := []string{}
if numIds == 1 {
// Normalize the input as it comes from the user.
idArray := []string{xnametypes.NormalizeHMSCompID(ids[0])}
// Let the Update itself verify the starting states.
cnt, err := t.UpdateCompStatesTx(idArray, state, nflag, force, false, pi)
if err != nil {
t.Rollback()
return []string{}, err
}
if cnt > 0 {
affectedIDs = idArray
if cnt != 1 {
d.LogAlways("ERROR: %s: cnt(%d) is not one!", fname, cnt)
}
}
} else {
var startStates []string
nstate := base.VerifyNormalizeState(state)
if nstate == "" {
return []string{}, 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.
// We only have to do this once when getting the affectedIDs.
startStates, err = base.GetValidStartStateWForce(state, force)
if err != nil {
return []string{}, err
}
}
// Lock components for update and select components we need to change.
// This should produce normalized affectedIDs.
affectedIDs, err = t.GetComponentIDsTx(IDs(ids),
NotStateOrFlag(state, nflag), States(startStates),
From(fname))
if err != nil {
t.Rollback()
return []string{}, err
}
if affectedIDs != nil && len(affectedIDs) != 0 {
// We already tested the list, so we don't need to do the
// starting state filtering again, so this always works like force.
_, err = t.UpdateCompStatesTx(affectedIDs, state, nflag,
true, true, pi)
if err != nil {
t.Rollback()
return []string{}, err
}
}
}
if err := t.Commit(); err != nil {
return []string{}, err
}
return affectedIDs, nil
}
// Update state and flag fields only in DB from those in c
// 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 (d *hmsdbPg) UpdateCompState(c *base.Component) (int64, error) {
ids, err := d.UpdateCompStates([]string{c.ID}, c.State, c.Flag,
false, new(PartInfo))
return int64(len(ids)), err
}
// Update flag field in DB for a list of components
// Note: Flag cannot be empty/invalid.
func (d *hmsdbPg) BulkUpdateCompFlagOnly(ids []string, flag string) ([]string, error) {
// Verify input
if len(ids) < 1 {
d.LogAlways("Error: BulkUpdateCompFlagOnly(): id list is empty")
return nil, ErrHMSDSArgMissing
}
flag = base.VerifyNormalizeFlag(flag)
if flag == "" {
return []string{}, ErrHMSDSArgNoMatch
}
// Start transaction
t, err := d.Begin()
if err != nil {
return []string{}, err
}
// Lock components for update and get components that don't already have
// flag
// Lock components for update and select components we need to change.
affectedIDs, err := t.GetComponentIDsTx(IDs(ids), Flag("!"+flag),
From("BulkUpdateCompFlagOnly"))
if err != nil {
t.Rollback()
return []string{}, err
}
if len(affectedIDs) != 0 {
if _, err := t.BulkUpdateCompFlagOnlyTx(affectedIDs, flag); err != nil {
t.Rollback()
return []string{}, err
}
}
if err := t.Commit(); err != nil {
return []string{}, err
}
return affectedIDs, 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 (d *hmsdbPg) UpdateCompFlagOnly(id string, flag string) (int64, error) {
t, err := d.Begin()
if err != nil {
return 0, err
}
rowsAffected, err := t.UpdateCompFlagOnlyTx(id, flag)
if err != nil {
t.Rollback()
return 0, err
}
if err := t.Commit(); err != nil {
return 0, err
}
return rowsAffected, nil
}
// Update enabled field in DB from c's Enabled field.
// Returns the number of affected rows. < 0 means RowsAffected() is not supported.
// Note: c.Enabled cannot be nil.
func (d *hmsdbPg) UpdateCompEnabled(id string, enabled bool) (int64, error) {
t, err := d.Begin()
if err != nil {
return 0, err
}
rowsAffected, err := t.UpdateCompEnabledTx(id, enabled)
if err != nil {
t.Rollback()
return 0, err
}
if err := t.Commit(); err != nil {
return 0, err
}
return rowsAffected, nil
}
// Update Enabled field only in DB for a list of components
func (d *hmsdbPg) BulkUpdateCompEnabled(ids []string, enabled bool) ([]string, error) {
// Verify input
if len(ids) < 1 {
d.LogAlways("Error: BulkUpdateCompEnabled(): id list is empty")
return nil, ErrHMSDSArgMissing
}
// Start transaction
t, err := d.Begin()
if err != nil {
return []string{}, err
}
// Lock components for update and select those that still need updates.
affectedIDs, err := t.GetComponentIDsTx(IDs(ids),
Enabled("!"+strconv.FormatBool(enabled)),
From("BulkUpdateCompEnabled"))
if err != nil {
t.Rollback()
return []string{}, err
}
if len(affectedIDs) != 0 {
if _, err := t.BulkUpdateCompEnabledTx(affectedIDs, enabled); err != nil {
t.Rollback()
return []string{}, err
}
}
if err := t.Commit(); err != nil {
return []string{}, err
}
return affectedIDs, nil
}
// Update SwStatus field in DB from c's SwStatus field.
// Returns the number of affected rows. < 0 means RowsAffected() is not supported.
func (d *hmsdbPg) UpdateCompSwStatus(id string, swStatus string) (int64, error) {
t, err := d.Begin()
if err != nil {
return 0, err
}
rowsAffected, err := t.UpdateCompSwStatusTx(id, swStatus)
if err != nil {
t.Rollback()
return 0, err
}
if err := t.Commit(); err != nil {
return 0, err
}
return rowsAffected, nil
}
// Update SwStatus field only in DB for a list of components
func (d *hmsdbPg) BulkUpdateCompSwStatus(ids []string, swstatus string) ([]string, error) {
// Verify input
if len(ids) < 1 {
d.LogAlways("Error: BulkUpdateCompSwStatus(): id list is empty")
return nil, ErrHMSDSArgMissing
}
// Start transaction
t, err := d.Begin()
if err != nil {
return []string{}, err
}
// Lock components for update
affectedIDs, err := t.GetComponentIDsTx(IDs(ids), SwStatus("!"+swstatus),
From("BulkUpdateCompSwStatus"))
if err != nil {
t.Rollback()
return []string{}, err
}
if len(affectedIDs) != 0 {
if _, err := t.BulkUpdateCompSwStatusTx(affectedIDs, swstatus); err != nil {
t.Rollback()
return []string{}, err
}
}
if err := t.Commit(); err != nil {
return []string{}, err
}
return affectedIDs, nil
}
// Update Role/SubRole field in DB for a list of components
// Note: Role cannot be empty/invalid.
func (d *hmsdbPg) BulkUpdateCompRole(ids []string, role, subRole string) ([]string, error) {
var affectedIDs []string
// Verify input
if len(ids) < 1 {
d.LogAlways("Error: BulkUpdateCompRole(): id list is empty")
return nil, ErrHMSDSArgMissing
}
role = base.VerifyNormalizeRole(role)
if role == "" {
return []string{}, ErrHMSDSArgNoMatch
}
// Allow SubRole to be empty
if subRole != "" {
subRole = base.VerifyNormalizeRole(subRole)
if subRole == "" {
return []string{}, ErrHMSDSArgNoMatch
}
}
// Start transaction
t, err := d.Begin()
if err != nil {
return []string{}, err
}
// Lock components for update that still need changes (i.e. !role)
if subRole == "" {
affectedIDs, err = t.GetComponentIDsTx(IDs(ids), Role("!"+role),
From("BulkUpdateCompRole"))
} else {
affectedIDs, err = t.GetComponentIDsTx(IDs(ids), Role("!"+role),
SubRole("!"+subRole), From("BulkUpdateCompRole"))
}
if err != nil {
t.Rollback()
return []string{}, err
}
if len(affectedIDs) != 0 {
if _, err := t.BulkUpdateCompRoleTx(affectedIDs, role, subRole); err != nil {
t.Rollback()
return []string{}, err
}
}
if err := t.Commit(); err != nil {
return []string{}, err
}
return affectedIDs, nil
}
// Update Role/SubRole field in DB from c's Role/SubRole field.
// Returns the number of affected rows. < 0 means RowsAffected() is not supported.
// Note: Role cannot be blank/invalid.
func (d *hmsdbPg) UpdateCompRole(id string, role, subRole string) (int64, error) {
t, err := d.Begin()
if err != nil {
return 0, err
}
rowsAffected, err := t.UpdateCompRoleTx(id, role, subRole)
if err != nil {
t.Rollback()
return 0, err
}
if err := t.Commit(); err != nil {
return 0, err
}
return rowsAffected, nil
}
// Update Class field only in DB for a list of components
func (d *hmsdbPg) BulkUpdateCompClass(ids []string, class string) ([]string, error) {
// Verify input
if len(ids) < 1 {
d.LogAlways("Error: BulkUpdateCompClass(): id list is empty")
return nil, ErrHMSDSArgMissing
}
// Start transaction
t, err := d.Begin()
if err != nil {