/
deliveryservices.go
2468 lines (2279 loc) · 82.5 KB
/
deliveryservices.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 deliveryservice
/*
* 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"
"encoding/json"
"errors"
"fmt"
"net/http"
"regexp"
"strconv"
"strings"
"time"
"github.com/apache/trafficcontrol/lib/go-log"
"github.com/apache/trafficcontrol/lib/go-tc"
"github.com/apache/trafficcontrol/lib/go-tc/tovalidate"
"github.com/apache/trafficcontrol/lib/go-util"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/dbhelpers"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/tenant"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/util/ims"
"github.com/asaskevich/govalidator"
validation "github.com/go-ozzo/ozzo-validation"
"github.com/jmoiron/sqlx"
"github.com/lib/pq"
)
type tierType int
const (
midTier tierType = iota
edgeTier
)
//we need a type alias to define functions on
type TODeliveryService struct {
api.APIInfoImpl
tc.DeliveryServiceV4
}
// TODeliveryServiceOldDetails is the struct to store the old details while updating a DS.
type TODeliveryServiceOldDetails struct {
OldOrgServerFqdn *string
OldCdnName string
OldCdnId int
OldRoutingName string
OldSSLKeyVersion *int
}
func (ds TODeliveryService) MarshalJSON() ([]byte, error) {
return json.Marshal(ds.DeliveryServiceV4)
}
func (ds *TODeliveryService) UnmarshalJSON(data []byte) error {
return json.Unmarshal(data, &ds.DeliveryServiceV4)
}
func (ds *TODeliveryService) APIInfo() *api.APIInfo { return ds.ReqInfo }
func (ds *TODeliveryService) SetKeys(keys map[string]interface{}) {
i, _ := keys["id"].(int) //this utilizes the non panicking type assertion, if the thrown away ok variable is false i will be the zero of the type, 0 here.
ds.ID = &i
}
func (ds TODeliveryService) GetKeys() (map[string]interface{}, bool) {
if ds.ID == nil {
return map[string]interface{}{"id": 0}, false
}
return map[string]interface{}{"id": *ds.ID}, true
}
func (ds TODeliveryService) GetKeyFieldsInfo() []api.KeyFieldInfo {
return []api.KeyFieldInfo{{Field: "id", Func: api.GetIntKey}}
}
func (ds *TODeliveryService) GetAuditName() string {
if ds.XMLID != nil {
return *ds.XMLID
}
return ""
}
func (ds *TODeliveryService) GetType() string {
return "ds"
}
// IsTenantAuthorized checks that the user is authorized for both the delivery service's existing tenant, and the new tenant they're changing it to (if different).
func (ds *TODeliveryService) IsTenantAuthorized(user *auth.CurrentUser) (bool, error) {
return isTenantAuthorized(ds.ReqInfo, &ds.DeliveryServiceV4)
}
const baseTLSVersionsQuery = `SELECT ARRAY_AGG(tls_version ORDER BY tls_version) FROM deliveryservice_tls_version`
const getTLSVersionsQuery = baseTLSVersionsQuery + `
WHERE deliveryservice = $1
`
// GetDSTLSVersions retrieves the TLS versions explicitly supported by a
// Delivery Service identified by dsID. This will panic if handed a nil
// transaction.
func GetDSTLSVersions(dsID int, tx *sql.Tx) ([]string, error) {
var vers []string
err := tx.QueryRow(getTLSVersionsQuery, dsID).Scan(pq.Array(&vers))
if err != nil {
err = fmt.Errorf("querying: %w", err)
}
return vers, err
}
func CreateV30(w http.ResponseWriter, r *http.Request) {
inf, userErr, sysErr, errCode := api.NewInfo(r, nil, nil)
if userErr != nil || sysErr != nil {
api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
return
}
defer inf.Close()
ds := tc.DeliveryServiceV30{}
if err := json.NewDecoder(r.Body).Decode(&ds); err != nil {
api.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, errors.New("decoding: "+err.Error()), nil)
return
}
res, status, userErr, sysErr := createV30(w, r, inf, ds)
if userErr != nil || sysErr != nil {
api.HandleErr(w, r, inf.Tx.Tx, status, userErr, sysErr)
return
}
api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Delivery Service creation was successful", []tc.DeliveryServiceV30{*res})
}
func CreateV31(w http.ResponseWriter, r *http.Request) {
inf, userErr, sysErr, errCode := api.NewInfo(r, nil, nil)
if userErr != nil || sysErr != nil {
api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
return
}
defer inf.Close()
ds := tc.DeliveryServiceV31{}
if err := json.NewDecoder(r.Body).Decode(&ds); err != nil {
api.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, errors.New("decoding: "+err.Error()), nil)
return
}
res, status, userErr, sysErr := createV31(w, r, inf, ds)
if userErr != nil || sysErr != nil {
api.HandleErr(w, r, inf.Tx.Tx, status, userErr, sysErr)
return
}
api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Delivery Service creation was successful", []tc.DeliveryServiceV31{*res})
}
func CreateV40(w http.ResponseWriter, r *http.Request) {
inf, userErr, sysErr, errCode := api.NewInfo(r, nil, nil)
if userErr != nil || sysErr != nil {
api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
return
}
defer inf.Close()
ds := tc.DeliveryServiceV40{}
if err := json.NewDecoder(r.Body).Decode(&ds); err != nil {
api.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, errors.New("decoding: "+err.Error()), nil)
return
}
res, status, userErr, sysErr := createV40(w, r, inf, ds, true)
if userErr != nil || sysErr != nil {
api.HandleErr(w, r, inf.Tx.Tx, status, userErr, sysErr)
return
}
alerts := res.TLSVersionsAlerts()
alerts.AddNewAlert(tc.SuccessLevel, "Delivery Service creation was successful")
w.Header().Set("Location", fmt.Sprintf("/api/4.0/deliveryservices?id=%d", *res.ID))
api.WriteAlertsObj(w, r, http.StatusCreated, alerts, []tc.DeliveryServiceV40{*res})
}
func createV30(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV30 tc.DeliveryServiceV30) (*tc.DeliveryServiceV30, int, error, error) {
ds := tc.DeliveryServiceV31{DeliveryServiceV30: dsV30}
res, status, userErr, sysErr := createV31(w, r, inf, ds)
if res != nil {
return &res.DeliveryServiceV30, status, userErr, sysErr
}
return nil, status, userErr, sysErr
}
func createV31(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV31 tc.DeliveryServiceV31) (*tc.DeliveryServiceV31, int, error, error) {
tx := inf.Tx.Tx
dsNullable := tc.DeliveryServiceNullableV30(dsV31)
ds := dsNullable.UpgradeToV4()
res, status, userErr, sysErr := createV40(w, r, inf, tc.DeliveryServiceV40(ds), false)
if res == nil {
return nil, status, userErr, sysErr
}
ds = tc.DeliveryServiceV4(*res)
if dsV31.CacheURL != nil {
_, err := tx.Exec("UPDATE deliveryservice SET cacheurl = $1 WHERE ID = $2",
&dsV31.CacheURL,
&ds.ID)
if err != nil {
usrErr, sysErr, code := api.ParseDBError(err)
return nil, code, usrErr, sysErr
}
}
if err := EnsureCacheURLParams(tx, *ds.ID, *ds.XMLID, dsV31.CacheURL); err != nil {
return nil, http.StatusInternalServerError, nil, err
}
oldRes := tc.DeliveryServiceV31(ds.DowngradeToV31())
return &oldRes, status, userErr, sysErr
}
// 'ON CONFLICT DO NOTHING' should be unnecessary because all data should be
// dumped from the table before re-insertion, but it's also harmless because
// the only conflict that could occur is a fully duplicate row, which is fine
// since we're intending to create that data anyway. Although it is weird.
const insertTLSVersionsQuery = `
INSERT INTO public.deliveryservice_tls_version (deliveryservice, tls_version)
SELECT
$1 AS deliveryservice,
UNNEST($2::text[]) AS tls_version
ON CONFLICT DO NOTHING
`
func recreateTLSVersions(versions []string, dsid int, tx *sql.Tx) error {
_, err := tx.Exec(`DELETE FROM public.deliveryservice_tls_version WHERE deliveryservice = $1`, dsid)
if err != nil {
return fmt.Errorf("cleaning up existing TLS version for DS #%d: %w", dsid, err)
}
if len(versions) < 1 {
return nil
}
_, err = tx.Exec(insertTLSVersionsQuery, dsid, pq.Array(versions))
if err != nil {
return fmt.Errorf("inserting new TLS versions: %w", err)
}
return nil
}
// create creates the given ds in the database, and returns the DS with its id and other fields created on insert set. On error, the HTTP status code, user error, and system error are returned. The status code SHOULD NOT be used, if both errors are nil.
func createV40(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV40 tc.DeliveryServiceV40, omitExtraLongDescFields bool) (*tc.DeliveryServiceV40, int, error, error) {
user := inf.User
tx := inf.Tx.Tx
ds := tc.DeliveryServiceV4(dsV40)
err := Validate(tx, &ds)
var geoLimitCountries string
if err != nil {
return nil, http.StatusBadRequest, errors.New("invalid request: " + err.Error()), nil
}
if authorized, err := isTenantAuthorized(inf, &ds); err != nil {
return nil, http.StatusInternalServerError, nil, errors.New("checking tenant: " + err.Error())
} else if !authorized {
return nil, http.StatusForbidden, errors.New("not authorized on this tenant"), nil
}
// TODO change DeepCachingType to implement sql.Valuer and sql.Scanner, so sqlx struct scan can be used.
deepCachingType := tc.DeepCachingType("").String()
if ds.DeepCachingType != nil {
deepCachingType = ds.DeepCachingType.String() // necessary, because DeepCachingType's default needs to insert the string, not "", and Query doesn't call .String().
}
if errCode, userErr, sysErr := dbhelpers.CheckTopology(inf.Tx, ds); userErr != nil || sysErr != nil {
return nil, errCode, userErr, sysErr
}
userErr, sysErr, errCode := dbhelpers.CheckIfCurrentUserCanModifyCDNWithID(inf.Tx.Tx, int64(*ds.CDNID), inf.User.UserName)
if userErr != nil || sysErr != nil {
return nil, errCode, userErr, sysErr
}
geo := ([]string)(ds.GeoLimitCountries)
geoLimitCountries = strings.Join(geo, ",")
var resultRows *sql.Rows
if omitExtraLongDescFields {
if ds.LongDesc1 != nil || ds.LongDesc2 != nil {
return nil, http.StatusBadRequest, errors.New("the longDesc1 and longDesc2 fields are no longer supported in API 4.0 onwards"), nil
}
resultRows, err = tx.Query(insertQueryWithoutLD1AndLD2(),
&ds.Active,
&ds.AnonymousBlockingEnabled,
&ds.CCRDNSTTL,
&ds.CDNID,
&ds.CheckPath,
&ds.ConsistentHashRegex,
&deepCachingType,
&ds.DisplayName,
&ds.DNSBypassCNAME,
&ds.DNSBypassIP,
&ds.DNSBypassIP6,
&ds.DNSBypassTTL,
&ds.DSCP,
&ds.EdgeHeaderRewrite,
&ds.GeoLimitRedirectURL,
&ds.GeoLimit,
&geoLimitCountries,
&ds.GeoProvider,
&ds.GlobalMaxMBPS,
&ds.GlobalMaxTPS,
&ds.FQPacingRate,
&ds.HTTPBypassFQDN,
&ds.InfoURL,
&ds.InitialDispersion,
&ds.IPV6RoutingEnabled,
&ds.LogsEnabled,
&ds.LongDesc,
&ds.MaxDNSAnswers,
&ds.MaxOriginConnections,
&ds.MidHeaderRewrite,
&ds.MissLat,
&ds.MissLong,
&ds.MultiSiteOrigin,
&ds.OriginShield,
&ds.ProfileID,
&ds.Protocol,
&ds.QStringIgnore,
&ds.RangeRequestHandling,
&ds.RegexRemap,
&ds.RegionalGeoBlocking,
&ds.RemapText,
&ds.RoutingName,
&ds.SigningAlgorithm,
&ds.SSLKeyVersion,
&ds.TenantID,
&ds.Topology,
&ds.TRRequestHeaders,
&ds.TRResponseHeaders,
&ds.TypeID,
&ds.XMLID,
&ds.EcsEnabled,
&ds.RangeSliceBlockSize,
&ds.FirstHeaderRewrite,
&ds.InnerHeaderRewrite,
&ds.LastHeaderRewrite,
&ds.ServiceCategory,
&ds.MaxRequestHeaderBytes,
)
} else {
resultRows, err = tx.Query(insertQuery(),
&ds.Active,
&ds.AnonymousBlockingEnabled,
&ds.CCRDNSTTL,
&ds.CDNID,
&ds.CheckPath,
&ds.ConsistentHashRegex,
&deepCachingType,
&ds.DisplayName,
&ds.DNSBypassCNAME,
&ds.DNSBypassIP,
&ds.DNSBypassIP6,
&ds.DNSBypassTTL,
&ds.DSCP,
&ds.EdgeHeaderRewrite,
&ds.GeoLimitRedirectURL,
&ds.GeoLimit,
&geoLimitCountries,
&ds.GeoProvider,
&ds.GlobalMaxMBPS,
&ds.GlobalMaxTPS,
&ds.FQPacingRate,
&ds.HTTPBypassFQDN,
&ds.InfoURL,
&ds.InitialDispersion,
&ds.IPV6RoutingEnabled,
&ds.LogsEnabled,
&ds.LongDesc,
&ds.LongDesc1,
&ds.LongDesc2,
&ds.MaxDNSAnswers,
&ds.MaxOriginConnections,
&ds.MidHeaderRewrite,
&ds.MissLat,
&ds.MissLong,
&ds.MultiSiteOrigin,
&ds.OriginShield,
&ds.ProfileID,
&ds.Protocol,
&ds.QStringIgnore,
&ds.RangeRequestHandling,
&ds.RegexRemap,
&ds.RegionalGeoBlocking,
&ds.RemapText,
&ds.RoutingName,
&ds.SigningAlgorithm,
&ds.SSLKeyVersion,
&ds.TenantID,
&ds.Topology,
&ds.TRRequestHeaders,
&ds.TRResponseHeaders,
&ds.TypeID,
&ds.XMLID,
&ds.EcsEnabled,
&ds.RangeSliceBlockSize,
&ds.FirstHeaderRewrite,
&ds.InnerHeaderRewrite,
&ds.LastHeaderRewrite,
&ds.ServiceCategory,
&ds.MaxRequestHeaderBytes,
)
}
if err != nil {
usrErr, sysErr, code := api.ParseDBError(err)
return nil, code, usrErr, sysErr
}
defer resultRows.Close()
id := 0
var lastUpdated tc.TimeNoMod
if !resultRows.Next() {
return nil, http.StatusInternalServerError, nil, errors.New("no deliveryservice request inserted, no id was returned")
}
if err := resultRows.Scan(&id, &lastUpdated); err != nil {
return nil, http.StatusInternalServerError, nil, errors.New("could not scan id from insert: " + err.Error())
}
if resultRows.Next() {
return nil, http.StatusInternalServerError, nil, errors.New("too many ids returned from deliveryservice request insert")
}
ds.ID = &id
if ds.ID == nil {
return nil, http.StatusInternalServerError, nil, errors.New("missing id after insert")
}
if ds.XMLID == nil {
return nil, http.StatusInternalServerError, nil, errors.New("missing xml_id after insert")
}
if ds.TypeID == nil {
return nil, http.StatusInternalServerError, nil, errors.New("missing type id after insert")
}
if ds.RoutingName == nil {
return nil, http.StatusInternalServerError, nil, errors.New("missing routing name after insert")
}
dsType, err := getTypeFromID(*ds.TypeID, tx)
if err != nil {
return nil, http.StatusInternalServerError, nil, errors.New("getting delivery service type: " + err.Error())
}
ds.Type = &dsType
if len(ds.TLSVersions) < 1 {
ds.TLSVersions = nil
} else if err = recreateTLSVersions(ds.TLSVersions, *ds.ID, tx); err != nil {
return nil, http.StatusInternalServerError, nil, fmt.Errorf("creating TLS versions for new Delivery Service: %w", err)
}
if err := createDefaultRegex(tx, *ds.ID, *ds.XMLID); err != nil {
return nil, http.StatusInternalServerError, nil, errors.New("creating default regex: " + err.Error())
}
if _, err := createConsistentHashQueryParams(tx, *ds.ID, ds.ConsistentHashQueryParams); err != nil {
usrErr, sysErr, code := api.ParseDBError(err)
return nil, code, usrErr, sysErr
}
matchlists, err := GetDeliveryServicesMatchLists([]string{*ds.XMLID}, tx)
if err != nil {
return nil, http.StatusInternalServerError, nil, errors.New("creating DS: reading matchlists: " + err.Error())
}
if matchlist, ok := matchlists[*ds.XMLID]; !ok {
return nil, http.StatusInternalServerError, nil, errors.New("creating DS: reading matchlists: not found")
} else {
ds.MatchList = &matchlist
}
cdnName, cdnDomain, dnssecEnabled, err := getCDNNameDomainDNSSecEnabled(*ds.ID, tx)
if err != nil {
return nil, http.StatusInternalServerError, nil, errors.New("creating DS: getting CDN info: " + err.Error())
}
ds.ExampleURLs = MakeExampleURLs(ds.Protocol, *ds.Type, *ds.RoutingName, *ds.MatchList, cdnDomain)
if err := EnsureParams(tx, *ds.ID, *ds.XMLID, ds.EdgeHeaderRewrite, ds.MidHeaderRewrite, ds.RegexRemap, ds.SigningAlgorithm, dsType, ds.MaxOriginConnections); err != nil {
return nil, http.StatusInternalServerError, nil, errors.New("ensuring ds parameters:: " + err.Error())
}
if dnssecEnabled && ds.Type.UsesDNSSECKeys() {
if !inf.Config.TrafficVaultEnabled {
return nil, http.StatusInternalServerError, nil, errors.New("cannot create DNSSEC keys for delivery service: Traffic Vault is not configured")
}
if userErr, sysErr, statusCode := PutDNSSecKeys(tx, *ds.XMLID, cdnName, ds.ExampleURLs, inf.Vault, r.Context()); userErr != nil || sysErr != nil {
return nil, statusCode, userErr, sysErr
}
}
if err := createPrimaryOrigin(tx, user, ds); err != nil {
return nil, http.StatusInternalServerError, nil, errors.New("creating delivery service: " + err.Error())
}
ds.LastUpdated = &lastUpdated
if err := api.CreateChangeLogRawErr(api.ApiChange, "DS: "+*ds.XMLID+", ID: "+strconv.Itoa(*ds.ID)+", ACTION: Created delivery service", user, tx); err != nil {
return nil, http.StatusInternalServerError, nil, errors.New("error writing to audit log: " + err.Error())
}
dsV40 = ds
if inf.Config.TrafficVaultEnabled && ds.Protocol != nil && (*ds.Protocol == tc.DSProtocolHTTPS || *ds.Protocol == tc.DSProtocolHTTPAndHTTPS || *ds.Protocol == tc.DSProtocolHTTPToHTTPS) {
err, errCode := GeneratePlaceholderSelfSignedCert(dsV40, inf, r.Context())
if err != nil || errCode != http.StatusOK {
return nil, errCode, nil, fmt.Errorf("creating self signed default cert: %v", err)
}
}
return &dsV40, http.StatusOK, nil, nil
}
func createDefaultRegex(tx *sql.Tx, dsID int, xmlID string) error {
regexStr := `.*\.` + xmlID + `\..*`
regexID := 0
if err := tx.QueryRow(`INSERT INTO regex (type, pattern) VALUES ((select id from type where name = 'HOST_REGEXP'), $1::text) RETURNING id`, regexStr).Scan(®exID); err != nil {
return errors.New("insert regex: " + err.Error())
}
if _, err := tx.Exec(`INSERT INTO deliveryservice_regex (deliveryservice, regex, set_number) VALUES ($1::bigint, $2::bigint, 0)`, dsID, regexID); err != nil {
return errors.New("executing parameter query to insert location: " + err.Error())
}
return nil
}
func createConsistentHashQueryParams(tx *sql.Tx, dsID int, consistentHashQueryParams []string) (int, error) {
if len(consistentHashQueryParams) == 0 {
return 0, nil
}
c := 0
q := `INSERT INTO deliveryservice_consistent_hash_query_param (name, deliveryservice_id) VALUES ($1, $2)`
for _, k := range consistentHashQueryParams {
if _, err := tx.Exec(q, k, dsID); err != nil {
return c, err
}
c++
}
return c, nil
}
func (ds *TODeliveryService) Read(h http.Header, useIMS bool) ([]interface{}, error, error, int, *time.Time) {
version := ds.APIInfo().Version
if version == nil {
return nil, nil, errors.New("TODeliveryService.Read called with nil API version"), http.StatusInternalServerError, nil
}
returnable := []interface{}{}
dses, userErr, sysErr, errCode, maxTime := readGetDeliveryServices(h, ds.APIInfo().Params, ds.APIInfo().Tx, ds.APIInfo().User, useIMS)
if sysErr != nil {
sysErr = errors.New("reading dses: " + sysErr.Error())
errCode = http.StatusInternalServerError
}
if userErr != nil || sysErr != nil {
return nil, userErr, sysErr, errCode, nil
}
for _, ds := range dses {
switch {
// NOTE: it's required to handle minor version cases in a descending >= manner
case version.Major > 3:
returnable = append(returnable, ds.RemoveLD1AndLD2())
case version.Major >= 3 && version.Minor >= 1:
returnable = append(returnable, ds.DowngradeToV31())
case version.Major >= 3:
returnable = append(returnable, ds.DowngradeToV31().DeliveryServiceV30)
default:
return nil, nil, fmt.Errorf("TODeliveryService.Read called with invalid API version: %d.%d", version.Major, version.Minor), http.StatusInternalServerError, nil
}
}
return returnable, nil, nil, errCode, maxTime
}
func UpdateV30(w http.ResponseWriter, r *http.Request) {
inf, userErr, sysErr, errCode := api.NewInfo(r, nil, []string{"id"})
if userErr != nil || sysErr != nil {
api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
return
}
defer inf.Close()
id := inf.IntParams["id"]
ds := tc.DeliveryServiceV30{}
if err := json.NewDecoder(r.Body).Decode(&ds); err != nil {
api.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, errors.New("malformed JSON: "+err.Error()), nil)
return
}
ds.ID = &id
res, status, userErr, sysErr := updateV30(w, r, inf, &ds)
if userErr != nil || sysErr != nil {
api.HandleErr(w, r, inf.Tx.Tx, status, userErr, sysErr)
return
}
api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Delivery Service update was successful", []tc.DeliveryServiceV30{*res})
}
func UpdateV31(w http.ResponseWriter, r *http.Request) {
inf, userErr, sysErr, errCode := api.NewInfo(r, nil, []string{"id"})
if userErr != nil || sysErr != nil {
api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
return
}
defer inf.Close()
id := inf.IntParams["id"]
ds := tc.DeliveryServiceV31{}
if err := json.NewDecoder(r.Body).Decode(&ds); err != nil {
api.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, errors.New("malformed JSON: "+err.Error()), nil)
return
}
ds.ID = &id
res, status, userErr, sysErr := updateV31(w, r, inf, &ds)
if userErr != nil || sysErr != nil {
api.HandleErr(w, r, inf.Tx.Tx, status, userErr, sysErr)
return
}
api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Delivery Service update was successful", []tc.DeliveryServiceV31{*res})
}
func UpdateV40(w http.ResponseWriter, r *http.Request) {
inf, userErr, sysErr, errCode := api.NewInfo(r, nil, []string{"id"})
if userErr != nil || sysErr != nil {
api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
return
}
defer inf.Close()
id := inf.IntParams["id"]
ds := tc.DeliveryServiceV40{}
if err := json.NewDecoder(r.Body).Decode(&ds); err != nil {
api.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, errors.New("malformed JSON: "+err.Error()), nil)
return
}
ds.ID = &id
_, cdn, _, err := dbhelpers.GetDSNameAndCDNFromID(inf.Tx.Tx, id)
if err != nil {
api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New("deliveryservice update: getting CDN from DS ID "+err.Error()))
return
}
userErr, sysErr, statusCode := dbhelpers.CheckIfCurrentUserCanModifyCDN(inf.Tx.Tx, string(cdn), inf.User.UserName)
if userErr != nil || sysErr != nil {
api.HandleErr(w, r, inf.Tx.Tx, statusCode, userErr, sysErr)
return
}
res, status, userErr, sysErr := updateV40(w, r, inf, &ds, true)
if userErr != nil || sysErr != nil {
api.HandleErr(w, r, inf.Tx.Tx, status, userErr, sysErr)
return
}
alerts := res.TLSVersionsAlerts()
alerts.AddNewAlert(tc.SuccessLevel, "Delivery Service update was successful")
api.WriteAlertsObj(w, r, http.StatusOK, alerts, []tc.DeliveryServiceV40{*res})
}
func updateV30(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV30 *tc.DeliveryServiceV30) (*tc.DeliveryServiceV30, int, error, error) {
dsV31 := tc.DeliveryServiceV31{DeliveryServiceV30: *dsV30}
// query the DB for existing 3.1 fields in order to "upgrade" this 3.0 request into a 3.1 request
query := `
SELECT
ds.max_request_header_bytes
FROM
deliveryservice ds
WHERE
ds.id = $1`
if err := inf.Tx.Tx.QueryRow(query, *dsV30.ID).Scan(
&dsV31.MaxRequestHeaderBytes,
); err != nil {
if err == sql.ErrNoRows {
return nil, http.StatusNotFound, fmt.Errorf("delivery service ID %d not found", *dsV31.ID), nil
}
return nil, http.StatusInternalServerError, nil, fmt.Errorf("querying delivery service ID %d: %s", *dsV31.ID, err.Error())
}
res, status, userErr, sysErr := updateV31(w, r, inf, &dsV31)
if res != nil {
return &res.DeliveryServiceV30, status, userErr, sysErr
}
return nil, status, userErr, sysErr
}
func updateV31(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV31 *tc.DeliveryServiceV31) (*tc.DeliveryServiceV31, int, error, error) {
dsNull := tc.DeliveryServiceNullableV30(*dsV31)
ds := dsNull.UpgradeToV4()
dsV40 := ds
if dsV40.ID == nil {
return nil, http.StatusInternalServerError, nil, errors.New("cannot update a Delivery Service with nil ID")
}
tx := inf.Tx.Tx
var sysErr error
if dsV40.TLSVersions, sysErr = GetDSTLSVersions(*dsV40.ID, tx); sysErr != nil {
return nil, http.StatusInternalServerError, nil, fmt.Errorf("getting TLS versions for DS #%d in API version < 4.0: %w", *dsV40.ID, sysErr)
}
res, status, usrErr, sysErr := updateV40(w, r, inf, &dsV40, false)
if res == nil || usrErr != nil || sysErr != nil {
return nil, status, usrErr, sysErr
}
ds = *res
if dsV31.CacheURL != nil {
_, err := tx.Exec("UPDATE deliveryservice SET cacheurl = $1 WHERE ID = $2",
&dsV31.CacheURL,
&ds.ID)
if err != nil {
usrErr, sysErr, code := api.ParseDBError(err)
return nil, code, usrErr, sysErr
}
}
if err := EnsureCacheURLParams(tx, *ds.ID, *ds.XMLID, dsV31.CacheURL); err != nil {
return nil, http.StatusInternalServerError, nil, err
}
oldRes := tc.DeliveryServiceV31(ds.DowngradeToV31())
return &oldRes, http.StatusOK, nil, nil
}
func updateV40(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV40 *tc.DeliveryServiceV40, omitExtraLongDescFields bool) (*tc.DeliveryServiceV40, int, error, error) {
tx := inf.Tx.Tx
user := inf.User
ds := tc.DeliveryServiceV4(*dsV40)
if err := Validate(tx, &ds); err != nil {
return nil, http.StatusBadRequest, errors.New("invalid request: " + err.Error()), nil
}
if authorized, err := isTenantAuthorized(inf, &ds); err != nil {
return nil, http.StatusInternalServerError, nil, errors.New("checking tenant: " + err.Error())
} else if !authorized {
return nil, http.StatusForbidden, errors.New("not authorized on this tenant"), nil
}
if ds.XMLID == nil {
return nil, http.StatusBadRequest, errors.New("missing xml_id"), nil
}
if ds.ID == nil {
return nil, http.StatusBadRequest, errors.New("missing id"), nil
}
dsType, ok, err := getDSType(tx, *ds.XMLID)
if !ok {
return nil, http.StatusNotFound, errors.New("delivery service '" + *ds.XMLID + "' not found"), nil
}
if err != nil {
return nil, http.StatusInternalServerError, nil, errors.New("getting delivery service type during update: " + err.Error())
}
errCode := http.StatusOK
var userErr error
var sysErr error
var oldDetails TODeliveryServiceOldDetails
var sslKeysExist, cdnRoutingDetailDiff bool
if dsType.HasSSLKeys() {
oldDetails, userErr, sysErr, errCode = getOldDetails(*ds.ID, tx)
if userErr != nil || sysErr != nil {
return nil, errCode, userErr, sysErr
}
if sslKeysExist, err = getSSLVersion(*ds.XMLID, tx); err != nil {
return nil, http.StatusInternalServerError, nil, fmt.Errorf("querying delivery service with sslKeyVersion failed: %w", err)
}
if ds.CDNID == nil {
return nil, http.StatusBadRequest, errors.New("invalid request: 'cdnId' cannot be blank"), nil
}
if sslKeysExist {
if oldDetails.OldCdnId != *ds.CDNID {
cdnRoutingDetailDiff = true
}
if ds.CDNName != nil && oldDetails.OldCdnName != *ds.CDNName {
cdnRoutingDetailDiff = true
}
if ds.RoutingName != nil && oldDetails.OldRoutingName != *ds.RoutingName {
cdnRoutingDetailDiff = true
}
if cdnRoutingDetailDiff {
return nil, http.StatusBadRequest, errors.New("delivery service has ssl keys that cannot be automatically changed, therefore CDN and routing name are immutable"), nil
}
ds.SSLKeyVersion = oldDetails.OldSSLKeyVersion
}
}
// TODO change DeepCachingType to implement sql.Valuer and sql.Scanner, so sqlx struct scan can be used.
deepCachingType := tc.DeepCachingType("").String()
if ds.DeepCachingType != nil {
deepCachingType = ds.DeepCachingType.String() // necessary, because DeepCachingType's default needs to insert the string, not "", and Query doesn't call .String().
}
userErr, sysErr, errCode = api.CheckIfUnModified(r.Header, inf.Tx, *ds.ID, "deliveryservice")
if userErr != nil || sysErr != nil {
return nil, errCode, userErr, sysErr
}
if errCode, userErr, sysErr = dbhelpers.CheckTopology(inf.Tx, ds); userErr != nil || sysErr != nil {
return nil, errCode, userErr, sysErr
}
if ds.Topology != nil {
requiredCapabilities, err := dbhelpers.GetDSRequiredCapabilitiesFromID(*ds.ID, tx)
if err != nil {
return nil, http.StatusInternalServerError, nil, errors.New("getting existing DS required capabilities: " + err.Error())
}
if len(requiredCapabilities) > 0 {
if userErr, sysErr, status := EnsureTopologyBasedRequiredCapabilities(tx, *ds.ID, *ds.Topology, requiredCapabilities); userErr != nil || sysErr != nil {
return nil, status, userErr, sysErr
}
}
userErr, sysErr, status := dbhelpers.CheckOriginServerInDSCG(tx, *ds.ID, *ds.Topology)
if userErr != nil || sysErr != nil {
return nil, status, userErr, sysErr
}
}
var geoLimitCountries string
if ds.GeoLimitCountries != nil {
geo := ([]string)(ds.GeoLimitCountries)
geoLimitCountries = strings.Join(geo, ",")
}
var resultRows *sql.Rows
if omitExtraLongDescFields {
if ds.LongDesc1 != nil || ds.LongDesc2 != nil {
return nil, http.StatusBadRequest, errors.New("the longDesc1 and longDesc2 fields are no longer supported in API 4.0 onwards"), nil
}
resultRows, err = tx.Query(updateDSQueryWithoutLD1AndLD2(),
&ds.Active,
&ds.CCRDNSTTL,
&ds.CDNID,
&ds.CheckPath,
&deepCachingType,
&ds.DisplayName,
&ds.DNSBypassCNAME,
&ds.DNSBypassIP,
&ds.DNSBypassIP6,
&ds.DNSBypassTTL,
&ds.DSCP,
&ds.EdgeHeaderRewrite,
&ds.GeoLimitRedirectURL,
&ds.GeoLimit,
&geoLimitCountries,
&ds.GeoProvider,
&ds.GlobalMaxMBPS,
&ds.GlobalMaxTPS,
&ds.FQPacingRate,
&ds.HTTPBypassFQDN,
&ds.InfoURL,
&ds.InitialDispersion,
&ds.IPV6RoutingEnabled,
&ds.LogsEnabled,
&ds.LongDesc,
&ds.MaxDNSAnswers,
&ds.MidHeaderRewrite,
&ds.MissLat,
&ds.MissLong,
&ds.MultiSiteOrigin,
&ds.OriginShield,
&ds.ProfileID,
&ds.Protocol,
&ds.QStringIgnore,
&ds.RangeRequestHandling,
&ds.RegexRemap,
&ds.RegionalGeoBlocking,
&ds.RemapText,
&ds.RoutingName,
&ds.SigningAlgorithm,
&ds.SSLKeyVersion,
&ds.TenantID,
&ds.TRRequestHeaders,
&ds.TRResponseHeaders,
&ds.TypeID,
&ds.XMLID,
&ds.AnonymousBlockingEnabled,
&ds.ConsistentHashRegex,
&ds.MaxOriginConnections,
&ds.EcsEnabled,
&ds.RangeSliceBlockSize,
&ds.Topology,
&ds.FirstHeaderRewrite,
&ds.InnerHeaderRewrite,
&ds.LastHeaderRewrite,
&ds.ServiceCategory,
&ds.MaxRequestHeaderBytes,
&ds.ID)
} else {
resultRows, err = tx.Query(updateDSQuery(),
&ds.Active,
&ds.CCRDNSTTL,
&ds.CDNID,
&ds.CheckPath,
&deepCachingType,
&ds.DisplayName,
&ds.DNSBypassCNAME,
&ds.DNSBypassIP,
&ds.DNSBypassIP6,
&ds.DNSBypassTTL,
&ds.DSCP,
&ds.EdgeHeaderRewrite,
&ds.GeoLimitRedirectURL,
&ds.GeoLimit,
&geoLimitCountries,
&ds.GeoProvider,
&ds.GlobalMaxMBPS,
&ds.GlobalMaxTPS,
&ds.FQPacingRate,
&ds.HTTPBypassFQDN,
&ds.InfoURL,
&ds.InitialDispersion,
&ds.IPV6RoutingEnabled,
&ds.LogsEnabled,
&ds.LongDesc,
&ds.LongDesc1,
&ds.LongDesc2,
&ds.MaxDNSAnswers,
&ds.MidHeaderRewrite,
&ds.MissLat,
&ds.MissLong,
&ds.MultiSiteOrigin,
&ds.OriginShield,
&ds.ProfileID,
&ds.Protocol,
&ds.QStringIgnore,
&ds.RangeRequestHandling,
&ds.RegexRemap,
&ds.RegionalGeoBlocking,
&ds.RemapText,
&ds.RoutingName,
&ds.SigningAlgorithm,
&ds.SSLKeyVersion,
&ds.TenantID,
&ds.TRRequestHeaders,
&ds.TRResponseHeaders,
&ds.TypeID,
&ds.XMLID,
&ds.AnonymousBlockingEnabled,
&ds.ConsistentHashRegex,
&ds.MaxOriginConnections,
&ds.EcsEnabled,
&ds.RangeSliceBlockSize,
&ds.Topology,
&ds.FirstHeaderRewrite,
&ds.InnerHeaderRewrite,
&ds.LastHeaderRewrite,
&ds.ServiceCategory,
&ds.MaxRequestHeaderBytes,
&ds.ID)
}
if err != nil {
usrErr, sysErr, code := api.ParseDBError(err)
return nil, code, usrErr, sysErr
}
defer resultRows.Close()
if !resultRows.Next() {
return nil, http.StatusNotFound, errors.New("no delivery service found with this id"), nil
}
var lastUpdated tc.TimeNoMod
if err := resultRows.Scan(&lastUpdated); err != nil {
return nil, http.StatusInternalServerError, nil, errors.New("scan updating delivery service: " + err.Error())
}
if resultRows.Next() {
xmlID := ""
if ds.XMLID != nil {
xmlID = *ds.XMLID
}
return nil, http.StatusInternalServerError, nil, errors.New("updating delivery service " + xmlID + ": " + "this update affected too many rows: > 1")
}
if ds.ID == nil {
return nil, http.StatusInternalServerError, nil, errors.New("missing id after update")
}
if ds.XMLID == nil {
return nil, http.StatusInternalServerError, nil, errors.New("missing XMLID after update")
}
if ds.TypeID == nil {
return nil, http.StatusInternalServerError, nil, errors.New("missing type id after update")
}
if ds.RoutingName == nil {
return nil, http.StatusInternalServerError, nil, errors.New("missing routing name after update")
}
if len(ds.TLSVersions) < 1 {
ds.TLSVersions = nil
}
err = recreateTLSVersions(ds.TLSVersions, *ds.ID, tx)
if err != nil {
return nil, http.StatusInternalServerError, nil, fmt.Errorf("updating TLS versions for DS #%d: %w", *ds.ID, err)
}
newDSType, err := getTypeFromID(*ds.TypeID, tx)
if err != nil {
return nil, http.StatusInternalServerError, nil, errors.New("getting delivery service type after update: " + err.Error())
}