-
Notifications
You must be signed in to change notification settings - Fork 339
/
db_helpers.go
2375 lines (2187 loc) · 82 KB
/
db_helpers.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
package dbhelpers
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import (
"database/sql"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/apache/trafficcontrol/v8/lib/go-log"
"github.com/apache/trafficcontrol/v8/lib/go-tc"
"github.com/apache/trafficcontrol/v8/traffic_ops/traffic_ops_golang/topology/topology_validation"
"github.com/jmoiron/sqlx"
"github.com/lib/pq"
)
type WhereColumnInfo struct {
Column string
Checker func(string) error
}
const BaseWhere = "\nWHERE"
const BaseOrderBy = "\nORDER BY"
const BaseLimit = "\nLIMIT"
const BaseOffset = "\nOFFSET"
const getDSTenantIDFromXMLIDQuery = `
SELECT deliveryservice.tenant_id
FROM deliveryservice
WHERE deliveryservice.xml_id = $1
`
const getFederationIDForUserIDByXMLIDQuery = `
SELECT federation_deliveryservice.federation
FROM federation_deliveryservice
WHERE federation_deliveryservice.deliveryservice IN (
SELECT deliveryservice.id
FROM deliveryservice
WHERE deliveryservice.xml_id = $1
) AND federation_deliveryservice.federation IN (
SELECT federation_tmuser.federation
FROM federation_tmuser
WHERE federation_tmuser.tm_user = $2
)
`
const getUserBaseQuery = `
SELECT tm_user.address_line1,
tm_user.address_line2,
tm_user.city,
tm_user.company,
tm_user.country,
tm_user.email,
tm_user.full_name,
tm_user.gid,
tm_user.id,
tm_user.last_updated,
tm_user.new_user,
tm_user.phone_number,
tm_user.postal_code,
tm_user.public_ssh_key,
tm_user.registration_sent,
tm_user.role,
role.name AS role_name,
tm_user.state_or_province,
tenant.name AS tenant,
tm_user.tenant_id,
tm_user.token,
tm_user.uid,
tm_user.username
FROM tm_user
LEFT OUTER JOIN role ON role.id = tm_user.role
LEFT OUTER JOIN tenant ON tenant.id = tm_user.tenant_id
`
const getUserByIDQuery = getUserBaseQuery + `
WHERE tm_user.id = $1
`
const getUserByEmailQuery = getUserBaseQuery + `
WHERE tm_user.email = $1
`
// CheckIfCurrentUserHasCdnLock checks if the current user has the lock on the cdn that the requested operation is to be performed on.
// This will succeed if the either there is no lock by any user on the CDN, or if the current user has the lock on the CDN.
func CheckIfCurrentUserHasCdnLock(tx *sql.Tx, cdn, user string) (error, error, int) {
query := `
SELECT c.username, ARRAY_REMOVE(ARRAY_AGG(u.username), NULL) AS shared_usernames
FROM cdn_lock c
LEFT JOIN cdn_lock_user u ON c.username = u.owner AND c.cdn = u.cdn
WHERE c.cdn=$1
GROUP BY c.username`
var userName string
var sharedUserNames []string
rows, err := tx.Query(query, cdn)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, nil, http.StatusOK
}
return nil, errors.New("querying cdn_lock for user " + user + " and cdn " + cdn + ": " + err.Error()), http.StatusInternalServerError
}
defer rows.Close()
for rows.Next() {
err = rows.Scan(&userName, pq.Array(&sharedUserNames))
if err != nil {
return nil, errors.New("scanning cdn_lock for user " + user + " and cdn " + cdn + ": " + err.Error()), http.StatusInternalServerError
}
}
if userName != "" && user != userName {
for _, u := range sharedUserNames {
if u == user {
return nil, nil, http.StatusOK
}
}
return errors.New("user " + user + " currently does not have the lock on cdn " + cdn), nil, http.StatusForbidden
}
return nil, nil, http.StatusOK
}
func BuildWhereAndOrderByAndPagination(parameters map[string]string, queryParamsToSQLCols map[string]WhereColumnInfo) (string, string, string, map[string]interface{}, []error) {
whereClause := BaseWhere
orderBy := BaseOrderBy
paginationClause := BaseLimit
var criteria string
var queryValues map[string]interface{}
var errs []error
criteria, queryValues, errs = parseCriteriaAndQueryValues(queryParamsToSQLCols, parameters)
if len(queryValues) > 0 {
whereClause += " " + criteria
}
if len(errs) > 0 {
return "", "", "", queryValues, errs
}
if orderby, ok := parameters["orderby"]; ok {
log.Debugln("orderby: ", orderby)
if colInfo, ok := queryParamsToSQLCols[orderby]; ok {
log.Debugln("orderby column ", colInfo)
orderBy += " " + colInfo.Column
// if orderby is specified and valid, also check for sortOrder
if sortOrder, exists := parameters["sortOrder"]; exists {
log.Debugln("sortOrder: ", sortOrder)
if sortOrder == "desc" {
orderBy += " DESC"
} else if sortOrder != "asc" {
log.Debugln("sortOrder value must be desc or asc. Invalid value provided: ", sortOrder)
}
}
} else {
log.Debugln("This column is not configured to support orderby: ", orderby)
}
}
if limit, exists := parameters["limit"]; exists {
// try to convert to int, if it fails the limit parameter is invalid, so return an error
limitInt, err := strconv.Atoi(limit)
if err != nil || limitInt < -1 {
errs = append(errs, errors.New("limit parameter must be bigger than -1"))
return "", "", "", queryValues, errs
}
log.Debugln("limit: ", limit)
if limitInt == -1 {
paginationClause = ""
} else {
paginationClause += " " + limit
}
if offset, exists := parameters["offset"]; exists {
// check that offset is valid
offsetInt, err := strconv.Atoi(offset)
if err != nil || offsetInt < 1 {
errs = append(errs, errors.New("offset parameter must be a positive integer"))
return "", "", "", queryValues, errs
}
paginationClause += BaseOffset + " " + offset
} else if page, exists := parameters["page"]; exists {
// check that offset is valid
page, err := strconv.Atoi(page)
if err != nil || page < 1 {
errs = append(errs, errors.New("page parameter must be a positive integer"))
return "", "", "", queryValues, errs
}
paginationClause += BaseOffset + " " + strconv.Itoa((page-1)*limitInt)
}
}
if whereClause == BaseWhere {
whereClause = ""
}
if orderBy == BaseOrderBy {
orderBy = ""
}
if paginationClause == BaseLimit {
paginationClause = ""
}
log.Debugf("\n--\n Where: %s \n Order By: %s \n Limit+Offset: %s", whereClause, orderBy, paginationClause)
return whereClause, orderBy, paginationClause, queryValues, errs
}
// CheckIfCurrentUserCanModifyCDNs checks if the current user has the lock on the list of cdns that the requested operation is to be performed on.
// This will succeed if the either there is no lock by any user on any of the CDNs, or if the current user has the lock on any of the CDNs.
func CheckIfCurrentUserCanModifyCDNs(tx *sql.Tx, cdns []string, user string) (error, error, int) {
query := `SELECT c.username, c.soft, c.cdn, ARRAY_REMOVE(ARRAY_AGG(u.username), NULL) AS shared_usernames FROM cdn_lock c LEFT JOIN cdn_lock_user u ON c.username = u.owner AND c.cdn = u.cdn WHERE c.cdn=ANY($1) GROUP BY c.username, c.soft, c.cdn`
var userName, cdn string
var soft bool
var sharedUserNames []string
rows, err := tx.Query(query, pq.Array(cdns))
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, nil, http.StatusOK
}
return nil, errors.New("querying cdn_lock for user " + user + " and cdn " + cdn + ": " + err.Error()), http.StatusInternalServerError
}
defer rows.Close()
for rows.Next() {
err = rows.Scan(&userName, &soft, &cdn, pq.Array(&sharedUserNames))
if err != nil {
return nil, errors.New("scanning cdn_lock for user " + user + " and cdn " + cdn + ": " + err.Error()), http.StatusInternalServerError
}
if userName != "" && user != userName && !soft {
for _, u := range sharedUserNames {
if u == user {
return nil, nil, http.StatusOK
}
}
return errors.New("user " + userName + " currently has a hard lock on cdn " + cdn), nil, http.StatusForbidden
}
}
return nil, nil, http.StatusOK
}
// CheckIfCurrentUserCanModifyCDNs checks if the current user has the lock on the list of cdns(identified by ID) that the requested operation is to be performed on.
// This will succeed if the either there is no lock by any user on any of the CDNs, or if the current user has the lock on any of the CDNs.
func CheckIfCurrentUserCanModifyCDNsByID(tx *sql.Tx, cdns []int, user string) (error, error, int) {
query := `SELECT name FROM cdn WHERE id=ANY($1)`
var name string
var cdnNames []string
rows, err := tx.Query(query, pq.Array(cdns))
if err != nil {
return nil, errors.New("no cdn names found for the given IDs: " + err.Error()), http.StatusInternalServerError
}
defer rows.Close()
for rows.Next() {
err = rows.Scan(&name)
if err != nil {
return nil, errors.New("scanning cdn name: " + err.Error()), http.StatusInternalServerError
}
cdnNames = append(cdnNames, name)
}
return CheckIfCurrentUserCanModifyCDNs(tx, cdnNames, user)
}
// CheckIfCurrentUserCanModifyCDN checks if the current user has the lock on the cdn that the requested operation is to be performed on.
// This will succeed if the either there is no lock by any user on the CDN, or if the current user has the lock on the CDN.
func CheckIfCurrentUserCanModifyCDN(tx *sql.Tx, cdn, user string) (error, error, int) {
query := `SELECT c.username, c.soft, ARRAY_REMOVE(ARRAY_AGG(u.username), NULL) AS shared_usernames FROM cdn_lock c LEFT JOIN cdn_lock_user u ON c.username = u.owner AND c.cdn = u.cdn WHERE c.cdn=$1 GROUP BY c.username, c.soft`
var userName string
var soft bool
var sharedUserNames []string
rows, err := tx.Query(query, cdn)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, nil, http.StatusOK
}
return nil, errors.New("querying cdn_lock for user " + user + " and cdn " + cdn + ": " + err.Error()), http.StatusInternalServerError
}
defer rows.Close()
for rows.Next() {
err = rows.Scan(&userName, &soft, pq.Array(&sharedUserNames))
if err != nil {
return nil, errors.New("scanning cdn_lock for user " + user + " and cdn " + cdn + ": " + err.Error()), http.StatusInternalServerError
}
if userName != "" && user != userName && !soft {
for _, u := range sharedUserNames {
if u == user {
return nil, nil, http.StatusOK
}
}
return errors.New("user " + userName + " currently has a hard lock on cdn " + cdn), nil, http.StatusForbidden
}
}
return nil, nil, http.StatusOK
}
// CheckIfCurrentUserCanModifyCDNWithID checks if the current user has the lock on the cdn (identified by ID) that the requested operation is to be performed on.
// This will succeed if the either there is no lock by any user on the CDN, or if the current user has the lock on the CDN.
func CheckIfCurrentUserCanModifyCDNWithID(tx *sql.Tx, cdnID int64, user string) (error, error, int) {
cdnName, ok, err := GetCDNNameFromID(tx, cdnID)
if err != nil {
return nil, err, http.StatusInternalServerError
} else if !ok {
return errors.New("CDN not found"), nil, http.StatusNotFound
}
return CheckIfCurrentUserCanModifyCDN(tx, string(cdnName), user)
}
// CheckIfCurrentUserCanModifyCachegroup checks if the current user has the lock on the cdns that are associated with the provided cachegroup ID.
// This will succeed if no other user has a hard lock on any of the CDNs that relate to the cachegroup in question.
func CheckIfCurrentUserCanModifyCachegroup(tx *sql.Tx, cachegroupID int, user string) (error, error, int) {
query := `
SELECT c.username, c.cdn, c.soft, ARRAY_REMOVE(ARRAY_AGG(u.username), NULL) AS shared_usernames
FROM cdn_lock c LEFT JOIN cdn_lock_user u
ON c.username = u.owner
AND c.cdn = u.cdn
WHERE c.cdn IN (
SELECT name FROM cdn
WHERE id IN (
SELECT cdn_id FROM server
WHERE cachegroup = ($1)))
GROUP BY c.username, c.cdn, c.soft`
var userName string
var cdn string
var soft bool
var sharedUserNames []string
rows, err := tx.Query(query, cachegroupID)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, nil, http.StatusOK
}
return nil, errors.New("querying cdn_lock for user " + user + " and cachegroup ID " + strconv.Itoa(cachegroupID) + ": " + err.Error()), http.StatusInternalServerError
}
defer rows.Close()
for rows.Next() {
err = rows.Scan(&userName, &cdn, &soft, pq.Array(&sharedUserNames))
if err != nil {
return nil, errors.New("scanning cdn_lock for user " + user + " and cachegroup ID " + strconv.Itoa(cachegroupID) + ": " + err.Error()), http.StatusInternalServerError
}
if userName != "" && user != userName && !soft {
for _, u := range sharedUserNames {
if u == user {
return nil, nil, http.StatusOK
}
}
return errors.New("user " + userName + " currently has a hard lock on cdn " + cdn), nil, http.StatusForbidden
}
}
return nil, nil, http.StatusOK
}
// CheckIfCurrentUserCanModifyCachegroups checks if the current user has the lock on the cdns that are associated with the provided cachegroup IDs.
// This will succeed if no other user has a hard lock on any of the CDNs that relate to the cachegroups in question.
func CheckIfCurrentUserCanModifyCachegroups(tx *sql.Tx, cachegroupIDs []int, user string) (error, error, int) {
query := `SELECT c.username, c.cdn, c.soft, ARRAY_REMOVE(ARRAY_AGG(u.username), NULL) AS shared_usernames FROM cdn_lock c
LEFT JOIN cdn_lock_user u
ON c.username = u.owner
AND c.cdn = u.cdn
WHERE c.cdn IN (
SELECT name FROM cdn
WHERE id IN (
SELECT cdn_id FROM server
WHERE cachegroup = ANY($1)))
GROUP BY c.username, c.cdn, c.soft`
var userName string
var cdn string
var soft bool
var sharedUserNames []string
rows, err := tx.Query(query, pq.Array(cachegroupIDs))
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, nil, http.StatusOK
}
return nil, errors.New("querying cachegroups cdn_lock for user " + user + ": " + err.Error()), http.StatusInternalServerError
}
defer rows.Close()
for rows.Next() {
err = rows.Scan(&userName, &cdn, &soft, pq.Array(&sharedUserNames))
if err != nil {
return nil, errors.New("scanning cachegroups cdn_lock for user " + user + ": " + err.Error()), http.StatusInternalServerError
}
if userName != "" && user != userName && !soft {
for _, u := range sharedUserNames {
if u == user {
return nil, nil, http.StatusOK
}
}
return errors.New("user " + userName + " currently has a hard lock on cdn " + cdn), nil, http.StatusForbidden
}
}
return nil, nil, http.StatusOK
}
func parseCriteriaAndQueryValues(queryParamsToSQLCols map[string]WhereColumnInfo, parameters map[string]string) (string, map[string]interface{}, []error) {
var criteria string
var criteriaArgs []string
errs := []error{}
queryValues := make(map[string]interface{})
for key, colInfo := range queryParamsToSQLCols {
if urlValue, ok := parameters[key]; ok {
var err error
if colInfo.Checker != nil {
err = colInfo.Checker(urlValue)
}
if err != nil {
errs = append(errs, fmt.Errorf("%s %w", key, err))
} else {
criteria = colInfo.Column + "=:" + key
criteriaArgs = append(criteriaArgs, criteria)
queryValues[key] = urlValue
}
}
}
criteria = strings.Join(criteriaArgs, " AND ")
return criteria, queryValues, errs
}
// AddTenancyCheck takes a WHERE clause (can be ""), the associated queryValues (can be empty),
// a tenantColumnName that should provide a bigint corresponding to the tenantID of the object being checked (this may require a CAST),
// and an array of the tenantIDs the user has access to; it returns a where clause and associated queryValues including filtering based on tenancy.
func AddTenancyCheck(where string, queryValues map[string]interface{}, tenantColumnName string, tenantIDs []int) (string, map[string]interface{}) {
if where == "" {
where = BaseWhere + " " + tenantColumnName + " = ANY(CAST(:accessibleTenants AS bigint[]))"
} else {
where += " AND " + tenantColumnName + " = ANY(CAST(:accessibleTenants AS bigint[]))"
}
queryValues["accessibleTenants"] = pq.Array(tenantIDs)
return where, queryValues
}
// CommitIf commits if doCommit is true at the time of execution.
// This is designed as a defer helper.
//
// Example:
//
// tx, err := db.Begin()
// txCommit := false
// defer dbhelpers.CommitIf(tx, &txCommit)
// if err := tx.Exec("select ..."); err != nil {
// return errors.New("executing: " + err.Error())
// }
// txCommit = true
// return nil
func CommitIf(tx *sql.Tx, doCommit *bool) {
if *doCommit {
tx.Commit()
} else {
tx.Rollback()
}
}
// GetPrivLevelFromRoleID returns the priv_level associated with a role, whether it exists, and any error.
// This method exists on a temporary basis. After priv_level is fully deprecated and capabilities take over,
// this method will not only no longer be needed, but the corresponding new privilege check should be done
// via the primary database query for the users endpoint. The users json response will contain a list of
// capabilities in the future, whereas now the users json response currently does not contain privLevel.
// See the wiki page on the roles/capabilities as a system:
// https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=68715910
func GetPrivLevelFromRoleID(tx *sql.Tx, id int) (int, bool, error) {
var privLevel int
err := tx.QueryRow(`SELECT priv_level FROM role WHERE role.id = $1`, id).Scan(&privLevel)
if errors.Is(err, sql.ErrNoRows) {
return 0, false, nil
}
if err != nil {
return 0, false, fmt.Errorf("getting priv_level from role ID: %w", err)
}
return privLevel, true, nil
}
// GetPrivLevelFromRole returns the priv_level associated with a role, whether it exists, and any error.
// This method exists on a temporary basis. After priv_level is fully deprecated and capabilities take over,
// this method will not only no longer be needed, but the corresponding new privilege check should be done
// via the primary database query for the users endpoint. The users json response will contain a list of
// capabilities in the future, whereas now the users json response currently does not contain privLevel.
// See the wiki page on the roles/capabilities as a system:
// https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=68715910
func GetPrivLevelFromRole(tx *sql.Tx, role string) (int, bool, error) {
var privLevel int
err := tx.QueryRow(`SELECT priv_level FROM role WHERE role.name = $1`, role).Scan(&privLevel)
if errors.Is(err, sql.ErrNoRows) {
return 0, false, nil
}
if err != nil {
return 0, false, fmt.Errorf("getting priv_level from role: %w", err)
}
return privLevel, true, nil
}
// GetCapabilitiesFromRoleID returns the capabilities for the supplied role ID.
func GetCapabilitiesFromRoleID(tx *sql.Tx, roleID int) ([]string, error) {
var caps []string
var cap string
rows, err := tx.Query(`SELECT cap_name FROM role_capability WHERE role_id = $1`, roleID)
if err != nil {
return caps, fmt.Errorf("getting capabilities from role ID: %w", err)
}
defer rows.Close()
for rows.Next() {
err = rows.Scan(&cap)
if err != nil {
return caps, fmt.Errorf("scanning capabilities: %w", err)
}
caps = append(caps, cap)
}
return caps, nil
}
// GetCapabilitiesFromRoleName returns the capabilities for the supplied role name.
func GetCapabilitiesFromRoleName(tx *sql.Tx, role string) ([]string, error) {
var caps []string
var cap string
rows, err := tx.Query(`SELECT cap_name FROM role_capability rc JOIN role r ON r.id = rc.role_id WHERE r.name = $1`, role)
if err != nil {
return caps, fmt.Errorf("getting capabilities from role name: %w", err)
}
defer rows.Close()
for rows.Next() {
err = rows.Scan(&cap)
if err != nil {
return caps, fmt.Errorf("scanning capabilities: %w", err)
}
caps = append(caps, cap)
}
return caps, nil
}
// RoleExists returns whether or not the role with the given roleName exists, and any error that occurred.
func RoleExists(tx *sql.Tx, roleID int) (bool, error) {
exists := false
err := tx.QueryRow(`SELECT EXISTS(SELECT * FROM role WHERE role.id = $1)`, roleID).Scan(&exists)
return exists, err
}
// GetDSNameFromID loads the DeliveryService's xml_id from the database, from the ID. Returns whether the delivery service was found, and any error.
func GetDSNameFromID(tx *sql.Tx, id int) (tc.DeliveryServiceName, bool, error) {
name := tc.DeliveryServiceName("")
if err := tx.QueryRow(`SELECT xml_id FROM deliveryservice WHERE id = $1`, id).Scan(&name); err != nil {
if err == sql.ErrNoRows {
return tc.DeliveryServiceName(""), false, nil
}
return tc.DeliveryServiceName(""), false, fmt.Errorf("querying xml_id for delivery service ID '%v': %v", id, err)
}
return name, true, nil
}
// GetDSNameFromID loads the DeliveryService's xml_id from the database, from the ID. Returns whether the delivery service was found, and any error.
func GetDSIDFromXMLID(tx *sql.Tx, xmlID string) (int, bool, error) {
var id int
if err := tx.QueryRow(`SELECT id FROM deliveryservice WHERE xml_id = $1`, xmlID).Scan(&id); err != nil {
if err == sql.ErrNoRows {
return id, false, nil
}
return id, false, fmt.Errorf("querying ID for delivery service XMLID '%v': %v", xmlID, err)
}
return id, true, nil
}
// GetDSCDNIdFromID loads the DeliveryService's cdn ID from the database, from the delivery service ID. Returns whether the delivery service was found, and any error.
func GetDSCDNIdFromID(tx *sql.Tx, dsID int) (int, bool, error) {
var cdnID int
if err := tx.QueryRow(`SELECT cdn_id FROM deliveryservice WHERE id = $1`, dsID).Scan(&cdnID); err != nil {
if err == sql.ErrNoRows {
return 0, false, nil
}
return 0, false, fmt.Errorf("querying cdn_id for delivery service ID '%v': %v", dsID, err)
}
return cdnID, true, nil
}
// GetDSTenantIDFromXMLID fetches the ID of the Tenant to whom the Delivery Service identified by the
// the provided XMLID belongs. It returns, in order, the requested ID (if one could be found), a
// boolean indicating whether or not a Delivery Service with the provided xmlid could be found, and
// an error for logging in case something unexpected goes wrong.
func GetDSTenantIDFromXMLID(tx *sql.Tx, xmlid string) (int, bool, error) {
var id int
if err := tx.QueryRow(getDSTenantIDFromXMLIDQuery, xmlid).Scan(&id); err != nil {
if err == sql.ErrNoRows {
return -1, false, nil
}
return -1, false, fmt.Errorf("Fetching Tenant ID for DS %s: %v", xmlid, err)
}
return id, true, nil
}
// GetServerDSNamesByCDN returns a map of ONLINE/REPORTED/ADMIN_DOWN cache names to slice of
// strings which are the XML IDs of the active, non-ANYMAP delivery services to which the cache
// is assigned in the given CDN.
func GetServerDSNamesByCDN(tx *sql.Tx, cdn string) (map[tc.CacheName][]string, error) {
q := `
SELECT s.host_name, ds.xml_id
FROM deliveryservice_server AS dss
INNER JOIN server AS s ON dss.server = s.id
INNER JOIN deliveryservice AS ds ON ds.id = dss.deliveryservice
INNER JOIN type AS dt ON dt.id = ds.type
INNER JOIN profile AS p ON p.id = s.profile
INNER JOIN status AS st ON st.id = s.status
WHERE ds.cdn_id = (SELECT id FROM cdn WHERE name = $1)
AND ds.active = $2
AND dt.name != $3
AND p.routing_disabled = false
AND (
st.name = $4
OR st.name = $5
OR st.name = $6
)
`
rows, err := tx.Query(q, cdn, tc.DSActiveStateActive, tc.DSTypeAnyMap, tc.CacheStatusOnline, tc.CacheStatusReported, tc.CacheStatusAdminDown)
if err != nil {
return nil, errors.New("querying server deliveryservice names by CDN: " + err.Error())
}
defer log.Close(rows, "closing rows after querying server deliveryservice names by CDN")
serverDSes := map[tc.CacheName][]string{}
for rows.Next() {
ds := ""
server := ""
if err := rows.Scan(&server, &ds); err != nil {
return nil, errors.New("scanning server deliveryservice names: " + err.Error())
}
serverDSes[tc.CacheName(server)] = append(serverDSes[tc.CacheName(server)], ds)
}
return serverDSes, nil
}
// returns returns the delivery service name and cdn, whether it existed, and any error.
func GetDSNameAndCDNFromID(tx *sql.Tx, id int) (tc.DeliveryServiceName, tc.CDNName, bool, error) {
name := tc.DeliveryServiceName("")
cdn := tc.CDNName("")
if err := tx.QueryRow(`
SELECT ds.xml_id, cdn.name
FROM deliveryservice as ds
JOIN cdn on cdn.id = ds.cdn_id
WHERE ds.id = $1
`, id).Scan(&name, &cdn); err != nil {
if err == sql.ErrNoRows {
return tc.DeliveryServiceName(""), tc.CDNName(""), false, nil
}
return tc.DeliveryServiceName(""), tc.CDNName(""), false, errors.New("querying delivery service name and CDN name: " + err.Error())
}
return name, cdn, true, nil
}
// GetDSIDAndCDNFromName returns the delivery service ID and cdn name given from the delivery service name, whether a result existed, and any error.
func GetDSIDAndCDNFromName(tx *sql.Tx, xmlID string) (int, tc.CDNName, bool, error) {
dsId := 0
cdn := tc.CDNName("")
if err := tx.QueryRow(`
SELECT ds.id, cdn.name
FROM deliveryservice as ds
JOIN cdn on cdn.id = ds.cdn_id
WHERE ds.xml_id = $1
`, xmlID).Scan(&dsId, &cdn); err != nil {
if err == sql.ErrNoRows {
return dsId, tc.CDNName(""), false, nil
}
return dsId, tc.CDNName(""), false, errors.New("querying delivery service ID and CDN name: " + err.Error())
}
return dsId, cdn, true, nil
}
// GetFederationResolversByFederationID fetches all of the federation resolvers currently assigned to a federation.
// In the event of an error, it will return an empty slice and the error.
func GetFederationResolversByFederationID(tx *sql.Tx, fedID int) ([]tc.FederationResolver, error) {
qry := `
SELECT
fr.ip_address,
frt.name as resolver_type,
ffr.federation_resolver
FROM
federation_federation_resolver ffr
JOIN federation_resolver fr ON ffr.federation_resolver = fr.id
JOIN type frt on fr.type = frt.id
WHERE
ffr.federation = $1
ORDER BY fr.ip_address
`
rows, err := tx.Query(qry, fedID)
if err != nil {
return nil, fmt.Errorf(
"error querying federation_resolvers by federation ID [%d]: %s", fedID, err.Error(),
)
}
defer rows.Close()
resolvers := []tc.FederationResolver{}
for rows.Next() {
fr := tc.FederationResolver{}
err := rows.Scan(
&fr.IPAddress,
&fr.Type,
&fr.ID,
)
if err != nil {
return resolvers, fmt.Errorf(
"error scanning federation_resolvers rows for federation ID [%d]: %s", fedID, err.Error(),
)
}
resolvers = append(resolvers, fr)
}
return resolvers, nil
}
// GetFederationNameFromID returns the federation's name, whether a federation with ID exists, or any error.
func GetFederationNameFromID(id int, tx *sql.Tx) (string, bool, error) {
var name string
if err := tx.QueryRow(`SELECT cname from federation where id = $1`, id).Scan(&name); err != nil {
if err == sql.ErrNoRows {
return "", false, nil
}
return name, false, fmt.Errorf(
"error querying federation name from id [%d]: %s", id, err.Error(),
)
}
return name, true, nil
}
// GetCDNIDFromFedID returns the ID of the CDN for the current federation.
func GetCDNIDFromFedID(id int, tx *sql.Tx) (int, bool, error) {
var cdnID int
if err := tx.QueryRow(`SELECT cdn_id FROM deliveryservice WHERE id = (SELECT deliveryservice FROM federation_deliveryservice WHERE federation = $1)`, id).Scan(&cdnID); err != nil {
if err == sql.ErrNoRows {
return cdnID, false, nil
}
return cdnID, false, err
}
return cdnID, true, nil
}
// GetCDNIDFromFedResolverID returns the IDs of the CDNs that the fed resolver is associated with.
func GetCDNIDsFromFedResolverID(id int, tx *sql.Tx) ([]int, bool, error) {
var cdnIDs []int
var cdnID int
rows, err := tx.Query(`SELECT cdn_id FROM deliveryservice WHERE id = ANY(SELECT deliveryservice FROM federation_deliveryservice fds JOIN federation_federation_resolver ffr ON ffr.federation = fds.federation WHERE ffr.federation_resolver = $1)`, id)
if err != nil {
if err == sql.ErrNoRows {
return cdnIDs, false, nil
}
return cdnIDs, false, err
}
defer rows.Close()
for rows.Next() {
if err := rows.Scan(&cdnID); err != nil {
return cdnIDs, false, errors.New("scanning cdn IDs: " + err.Error())
}
cdnIDs = append(cdnIDs, cdnID)
}
return cdnIDs, true, nil
}
// GetProfileNameFromID returns the profile's name, whether a profile with ID exists, or any error.
func GetProfileNameFromID(id int, tx *sql.Tx) (string, bool, error) {
name := ""
if err := tx.QueryRow(`SELECT name from profile where id = $1`, id).Scan(&name); err != nil {
if err == sql.ErrNoRows {
return "", false, nil
}
return "", false, errors.New("querying profile name from id: " + err.Error())
}
return name, true, nil
}
// GetProfileIDFromName returns the profile's ID, whether a profile with name exists, or any error.
func GetProfileIDFromName(name string, tx *sql.Tx) (int, bool, error) {
id := 0
if err := tx.QueryRow(`SELECT id from profile where name = $1`, name).Scan(&id); err != nil {
if err == sql.ErrNoRows {
return 0, false, nil
}
return 0, false, errors.New("querying profile id from name: " + err.Error())
}
return id, true, nil
}
// GetServerCapabilitiesFromName returns the server's capabilities.
func GetServerCapabilitiesFromName(name string, tx *sql.Tx) ([]string, error) {
var caps []string
q := `SELECT ARRAY(SELECT ssc.server_capability FROM server s JOIN server_server_capability ssc ON s.id = ssc.server WHERE s.host_name = $1 ORDER BY ssc.server_capability);`
rows, err := tx.Query(q, name)
if err != nil {
return nil, errors.New("querying server capabilities from name: " + err.Error())
}
defer rows.Close()
for rows.Next() {
if err := rows.Scan(pq.Array(&caps)); err != nil {
return nil, errors.New("scanning capability: " + err.Error())
}
}
return caps, nil
}
// GetServerCapabilitiesOfServers gets all of the server capabilities of the given server hostnames.
func GetServerCapabilitiesOfServers(names []string, tx *sql.Tx) (map[string][]string, error) {
serverCaps := make(map[string][]string, len(names))
q := `
SELECT
s.host_name,
ARRAY_REMOVE(ARRAY_AGG(ssc.server_capability ORDER BY ssc.server_capability), NULL) AS capabilities
FROM server s
LEFT JOIN server_server_capability ssc ON s.id = ssc.server
WHERE
s.host_name = ANY($1)
GROUP BY s.host_name
`
rows, err := tx.Query(q, pq.Array(&names))
if err != nil {
return nil, errors.New("querying server capabilities by host names: " + err.Error())
}
defer log.Close(rows, "closing rows in GetServerCapabilitiesOfServers")
for rows.Next() {
hostname := ""
caps := []string{}
if err := rows.Scan(&hostname, pq.Array(&caps)); err != nil {
return nil, errors.New("scanning server capabilities: " + err.Error())
}
serverCaps[hostname] = caps
}
return serverCaps, nil
}
// GetRequiredCapabilitiesOfDeliveryServices gets all of the required capabilities of the given delivery service IDs.
func GetRequiredCapabilitiesOfDeliveryServices(ids []int, tx *sql.Tx) (map[int][]string, error) {
queryIDs := make([]int64, 0, len(ids))
for _, id := range ids {
queryIDs = append(queryIDs, int64(id))
}
dsCaps := make(map[int][]string, len(ids))
q := `
SELECT
ds.id,
ARRAY_REMOVE((ds.required_capabilities), NULL) AS required_capabilities
FROM deliveryservice ds
WHERE ds.id = ANY($1)
GROUP BY ds.id, ds.required_capabilities
`
rows, err := tx.Query(q, pq.Array(&queryIDs))
if err != nil {
return nil, errors.New("querying delivery service required capabilities by IDs: " + err.Error())
}
defer log.Close(rows, "closing rows in GetRequiredCapabilitiesOfDeliveryServices")
for rows.Next() {
id := 0
caps := []string{}
if err := rows.Scan(&id, pq.Array(&caps)); err != nil {
return nil, errors.New("scanning required capabilities: " + err.Error())
}
dsCaps[id] = caps
}
return dsCaps, nil
}
const dsrExistsQuery = `
SELECT EXISTS(
SELECT id
FROM deliveryservice_request
WHERE status <> 'complete' AND
status <> 'rejected' AND
deliveryservice ->> 'xmlId' = $1
)
`
// DSRExistsWithXMLID returns whether or not an **open** Delivery Service
// Request with the given xmlid exists, and any error that occurred.
func DSRExistsWithXMLID(xmlid string, tx *sql.Tx) (bool, error) {
if tx == nil {
return false, errors.New("checking for DSR with nil transaction")
}
var exists bool
err := tx.QueryRow(dsrExistsQuery, xmlid).Scan(&exists)
return exists, err
}
// ScanCachegroupsServerCapabilities, given rows of (server ID, CDN ID, cachegroup name, server capabilities),
// returns a map of cachegroup names to server IDs, a map of server IDs to a map of their capabilities,
// a map of server IDs to CDN IDs, and an error (if one occurs).
func ScanCachegroupsServerCapabilities(rows *sql.Rows) (map[string][]int, map[int]map[string]struct{}, map[int]int, error) {
defer log.Close(rows, "closing rows in ScanCachegroupsServerCapabilities")
cachegroupServers := make(map[string][]int)
serverCapabilities := make(map[int]map[string]struct{})
serverCDNs := make(map[int]int)
for rows.Next() {
serverID := 0
cdnID := 0
cachegroup := ""
serverCap := []string{}
if err := rows.Scan(&serverID, &cdnID, &cachegroup, pq.Array(&serverCap)); err != nil {
return nil, nil, nil, fmt.Errorf("scanning rows in ScanCachegroupsServerCapabilities: %v", err)
}
cachegroupServers[cachegroup] = append(cachegroupServers[cachegroup], serverID)
serverCapabilities[serverID] = make(map[string]struct{}, len(serverCap))
serverCDNs[serverID] = cdnID
for _, sc := range serverCap {
serverCapabilities[serverID][sc] = struct{}{}
}
}
return cachegroupServers, serverCapabilities, serverCDNs, nil
}
// GetDSRequiredCapabilitiesFromID returns the server's capabilities.
func GetDSRequiredCapabilitiesFromID(id int, tx *sql.Tx) ([]string, error) {
q := `
SELECT required_capabilities
FROM deliveryservice
WHERE id = $1
ORDER BY required_capabilities`
caps := []string{}
if err := tx.QueryRow(q, id).Scan(pq.Array(&caps)); err != nil {
return nil, errors.New("getting/ scanning capability: " + err.Error())
}
return caps, nil
}
// Returns true if the cdn exists
func CDNExists(cdnName string, tx *sql.Tx) (bool, error) {
var id int
if err := tx.QueryRow(`SELECT id FROM cdn WHERE name = $1`, cdnName).Scan(&id); err != nil {
if err == sql.ErrNoRows {
return false, nil
}
return false, errors.New("Error querying CDN name: " + err.Error())
}
return true, nil
}
// GetCDNNameFromID gets the CDN name from the given CDN ID.
func GetCDNNameFromID(tx *sql.Tx, id int64) (tc.CDNName, bool, error) {
name := ""
if err := tx.QueryRow(`SELECT name FROM cdn WHERE id = $1`, id).Scan(&name); err != nil {
if err == sql.ErrNoRows {
return "", false, nil
}
return "", false, errors.New("querying CDN name from ID: " + err.Error())
}
return tc.CDNName(name), true, nil
}
// GetCDNNameFromServerID gets the CDN name for the server with the given ID.
func GetCDNNameFromServerID(tx *sql.Tx, serverId int64) (tc.CDNName, error) {
name := ""
if err := tx.QueryRow(`SELECT name FROM cdn WHERE id = (SELECT cdn_id FROM server WHERE id=$1)`, serverId).Scan(&name); err != nil {
return "", fmt.Errorf("querying CDN name from server ID: %w", err)
}
return tc.CDNName(name), nil
}
// GetCDNIDFromName returns the ID of the CDN if a CDN with the name exists
func GetCDNIDFromName(tx *sql.Tx, name tc.CDNName) (int, bool, error) {
id := 0
if err := tx.QueryRow(`SELECT id FROM cdn WHERE name = $1`, name).Scan(&id); err != nil {
if err == sql.ErrNoRows {
return id, false, nil
}
return id, false, errors.New("querying CDN ID from name: " + err.Error())
}
return id, true, nil
}
// GetCDNDomainFromName returns the domain, whether the cdn exists, and any error.
func GetCDNDomainFromName(tx *sql.Tx, cdnName tc.CDNName) (string, bool, error) {
domain := ""
if err := tx.QueryRow(`SELECT domain_name FROM cdn WHERE name = $1`, cdnName).Scan(&domain); err != nil {
if err == sql.ErrNoRows {
return "", false, nil
}
return "", false, errors.New("Error querying CDN name: " + err.Error())
}
return domain, true, nil
}
// GetServerInterfaces, given the IDs of one or more servers, returns all of their network
// interfaces mapped by their ids, or an error if one occurs during retrieval.
func GetServersInterfaces(ids []int, tx *sql.Tx) (map[int]map[string]tc.ServerInterfaceInfoV40, error) {
q := `