From 4ca5d511d451a624d2298edb3c7bc46b3dbce615 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Tue, 25 Oct 2022 12:59:37 -0600 Subject: [PATCH 01/48] Fix APIv4.0 returning APIv4.1 DS structures --- .../traffic_ops_golang/deliveryservice/deliveryservices.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go index b918638c7a..b820a0a908 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go @@ -614,7 +614,7 @@ func (ds *TODeliveryService) Read(h http.Header, useIMS bool) ([]interface{}, er for _, ds := range dses { switch { // NOTE: it's required to handle minor version cases in a descending >= manner - case version.Major > 4 || (version.Major == 4 && version.Minor >= 1): + case version.Major >= 4 && version.Minor >= 1: returnable = append(returnable, ds.RemoveLD1AndLD2()) case version.Major >= 4: returnable = append(returnable, ds.DeliveryServiceV40.RemoveLD1AndLD2()) From 3249425ea783172c8ac9eef4cc37c6cef4bc20e1 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Tue, 25 Oct 2022 14:33:19 -0600 Subject: [PATCH 02/48] Fix version matching in read handler --- .../traffic_ops_golang/deliveryservice/deliveryservices.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go index b820a0a908..b918638c7a 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go @@ -614,7 +614,7 @@ func (ds *TODeliveryService) Read(h http.Header, useIMS bool) ([]interface{}, er for _, ds := range dses { switch { // NOTE: it's required to handle minor version cases in a descending >= manner - case version.Major >= 4 && version.Minor >= 1: + case version.Major > 4 || (version.Major == 4 && version.Minor >= 1): returnable = append(returnable, ds.RemoveLD1AndLD2()) case version.Major >= 4: returnable = append(returnable, ds.DeliveryServiceV40.RemoveLD1AndLD2()) From 2b55a7e809181ff0f36df71c5876146b03e2dc88 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Wed, 7 Sep 2022 08:53:21 -0600 Subject: [PATCH 03/48] Add migration to change active from boolean to enum --- .../2022090708494015_ds_active_flag.down.sql | 74 +++++++++++++++++++ .../2022090708494015_ds_active_flag.up.sql | 68 +++++++++++++++++ 2 files changed, 142 insertions(+) create mode 100644 traffic_ops/app/db/migrations/2022090708494015_ds_active_flag.down.sql create mode 100644 traffic_ops/app/db/migrations/2022090708494015_ds_active_flag.up.sql diff --git a/traffic_ops/app/db/migrations/2022090708494015_ds_active_flag.down.sql b/traffic_ops/app/db/migrations/2022090708494015_ds_active_flag.down.sql new file mode 100644 index 0000000000..eb001e9b4c --- /dev/null +++ b/traffic_ops/app/db/migrations/2022090708494015_ds_active_flag.down.sql @@ -0,0 +1,74 @@ +/* + * 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. + */ + +ALTER TABLE public.deliveryservice +ADD COLUMN active_flag boolean DEFAULT FALSE NOT NULL; + +UPDATE public.deliveryservice +SET active_flag = FALSE +WHERE active IS 'PRIMED' OR active IS 'INACTIVE'; + +UPDATE public.deliveryservice +SET active_flag = TRUE +WHERE active IS 'ACTIVE'; + +ALTER TABLE public.deliveryservice DROP COLUMN active; +ALTER TABLE public.deliveryservice RENAME COLUMN active_flag TO active; +DROP TYPE public.ds_active_state; + +UPDATE public.deliveryservice_request +SET + deliveryservice = jsonb_set(deliveryservice, '{active}', 'true') +WHERE + deliveryservice IS NOT NULL + AND + deliveryservice ? 'active' + AND + deliveryservice ->> 'active' = 'ACTIVE'; +UPDATE public.deliveryservice_request +SET + deliveryservice = jsonb_set(deliveryservice, '{active}', 'false') +WHERE + deliveryservice IS NOT NULL + AND + deliveryservice ? 'active' + AND ( + deliveryservice ->> 'active' = 'PRIMED' + OR + deliveryservice ->> 'active' = 'INACTIVE' + ); +UPDATE public.deliveryservice_request +SET + original = jsonb_set(original, '{active}', 'true') +WHERE + original IS NOT NULL + AND + original ? 'active' + AND + original ->> 'active' = 'ACTIVE'; +UPDATE public.deliveryservice_request +SET + original = jsonb_set(original, '{active}', 'false') +WHERE + original IS NOT NULL + AND + original ? 'active' + AND ( + original ->> 'active' = 'PRIMED' + OR + original ->> 'active' = 'INACTIVE' + ); diff --git a/traffic_ops/app/db/migrations/2022090708494015_ds_active_flag.up.sql b/traffic_ops/app/db/migrations/2022090708494015_ds_active_flag.up.sql new file mode 100644 index 0000000000..1074e7cff5 --- /dev/null +++ b/traffic_ops/app/db/migrations/2022090708494015_ds_active_flag.up.sql @@ -0,0 +1,68 @@ +/* + * 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. + */ + +CREATE TYPE public.ds_active_state AS ENUM ( + 'ACTIVE', + 'INACTIVE', + 'PRIMED' +); + +ALTER TABLE public.deliveryservice +ADD COLUMN active_state ds_active_state NOT NULL DEFAULT 'INACTIVE'; + +UPDATE public.deliveryservice SET active_state = 'ACTIVE' WHERE active IS TRUE; +UPDATE public.deliveryservice SET active_state = 'PRIMED' WHERE active IS FALSE; + +ALTER TABLE public.deliveryservice DROP COLUMN active; +ALTER TABLE public.deliveryservice RENAME COLUMN active_state TO active; + +UPDATE public.deliveryservice_request +SET + deliveryservice = jsonb_set(deliveryservice, '{active}', '"ACTIVE"') +WHERE + deliveryservice IS NOT NULL + AND + deliveryservice ? 'active' + AND + (deliveryservice -> 'active')::boolean IS TRUE; +UPDATE public.deliveryservice_request +SET + deliveryservice = jsonb_set(deliveryservice, '{active}', '"PRIMED"') +WHERE + deliveryservice IS NOT NULL + AND + deliveryservice ? 'active' + AND + (deliveryservice -> 'active')::boolean IS FALSE; +UPDATE public.deliveryservice_request +SET + original = jsonb_set(original, '{active}', '"ACTIVE"') +WHERE + original IS NOT NULL + AND + original ? 'active' + AND + (original -> 'active')::boolean IS TRUE; +UPDATE public.deliveryservice_request +SET + original = jsonb_set(original, '{active}', '"PRIMED"') +WHERE + original IS NOT NULL + AND + original ? 'active' + AND + (original -> 'active')::boolean IS FALSE; From 4ef9156ee81c9e913052868347e085dac9039949 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Mon, 19 Sep 2022 12:45:51 -0600 Subject: [PATCH 04/48] Move copy utilities to their own file, add copies for bool and float --- lib/go-tc/copy.go | 64 +++++++++++++++++++++++ lib/go-tc/copy_test.go | 110 ++++++++++++++++++++++++++++++++++++++++ lib/go-tc/users.go | 22 -------- lib/go-tc/users_test.go | 42 --------------- 4 files changed, 174 insertions(+), 64 deletions(-) create mode 100644 lib/go-tc/copy.go create mode 100644 lib/go-tc/copy_test.go diff --git a/lib/go-tc/copy.go b/lib/go-tc/copy.go new file mode 100644 index 0000000000..7570094911 --- /dev/null +++ b/lib/go-tc/copy.go @@ -0,0 +1,64 @@ +package tc + +/* + * 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. + */ + +// copyStringIfNotNil makes a deep copy of s - unless it's nil, in which case it +// just returns nil. +func copyStringIfNotNil(s *string) *string { + if s == nil { + return nil + } + ret := new(string) + *ret = *s + return ret +} + +// copyIntIfNotNil makes a deep copy of i - unless it's nil, in which case it +// just returns nil. +func copyIntIfNotNil(i *int) *int { + if i == nil { + return nil + } + ret := new(int) + *ret = *i + return ret +} + +// copyBoolIfNotNil makes a deep copy of b - unless it's nil, in which case it +// just returns nil. +func copyBoolIfNotNil(b *bool) *bool { + if b == nil { + return nil + } + ret := new(bool) + *ret = *b + return ret +} + +// copyFloatIfNotNil makes a deep copy of f - unless it's nil, in which case it +// just returns nil. +func copyFloatIfNotNil(f *float64) *float64 { + if f == nil { + return nil + } + ret := new(float64) + *ret = *f + return ret +} diff --git a/lib/go-tc/copy_test.go b/lib/go-tc/copy_test.go new file mode 100644 index 0000000000..f7d66e50e1 --- /dev/null +++ b/lib/go-tc/copy_test.go @@ -0,0 +1,110 @@ +package tc + +/* + * 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 "testing" + +func TestCopyIntIfNotNil(t *testing.T) { + var i *int + copiedI := copyIntIfNotNil(i) + if copiedI != nil { + t.Errorf("Copying a nil int should've given nil, got: %d", *copiedI) + } + i = new(int) + *i = 9000 + copiedI = copyIntIfNotNil(i) + if copiedI == nil { + t.Errorf("Copied pointer to %d was nil", *i) + } else { + if *copiedI != *i { + t.Errorf("Incorrectly copied int pointer; expected: %d, got: %d", *i, *copiedI) + } + *i = 9001 + if *copiedI == *i { + t.Error("Expected copy to be 'deep' but modifying the original int changed the copy") + } + } +} + +func TestCopyFloatIfNotNil(t *testing.T) { + var f *float64 + copiedF := copyFloatIfNotNil(f) + if copiedF != nil { + t.Errorf("Copying a nil int should've given nil, got: %f", *copiedF) + } + f = new(float64) + *f = 9000 + copiedF = copyFloatIfNotNil(f) + if copiedF == nil { + t.Errorf("Copied pointer to %f was nil", *f) + } else { + if *copiedF != *f { + t.Errorf("Incorrectly copied float64 pointer; expected: %f, got: %f", *f, *copiedF) + } + *f = 9001 + if *copiedF == *f { + t.Error("Expected copy to be 'deep' but modifying the original float changed the copy") + } + } +} + +func TestCopyBoolIfNotNil(t *testing.T) { + var b *bool + copiedB := copyBoolIfNotNil(b) + if copiedB != nil { + t.Errorf("Copying a nil int should've given nil, got: %t", *copiedB) + } + b = new(bool) + *b = true + copiedB = copyBoolIfNotNil(b) + if copiedB == nil { + t.Errorf("Copied pointer to %t was nil", *b) + } else { + if *copiedB != *b { + t.Errorf("Incorrectly copied bool pointer; expected: %t, got: %t", *b, *copiedB) + } + *b = false + if *copiedB == *b { + t.Error("Expected copy to be 'deep' but modifying the original bool changed the copy") + } + } +} + +func TestCopyStringIfNotNil(t *testing.T) { + var s *string + copiedS := copyStringIfNotNil(s) + if copiedS != nil { + t.Errorf("Copying a nil string should've given nil, got: %s", *copiedS) + } + s = new(string) + *s = "test string" + copiedS = copyStringIfNotNil(s) + if copiedS == nil { + t.Errorf("Copied pointer to '%s' was nil", *s) + } else { + if *copiedS != *s { + t.Errorf("Incorrectly copied string pointer; expected: '%s', got: '%s'", *s, *copiedS) + } + *s = "a different test string" + if *copiedS == *s { + t.Error("Expected copy to be 'deep' but modifying the original string changed the copy") + } + } +} diff --git a/lib/go-tc/users.go b/lib/go-tc/users.go index dd4ff5c4e1..18e997f090 100644 --- a/lib/go-tc/users.go +++ b/lib/go-tc/users.go @@ -33,28 +33,6 @@ import ( "github.com/go-ozzo/ozzo-validation/is" ) -// copyStringIfNotNil makes a deep copy of s - unless it's nil, in which case it -// just returns nil. -func copyStringIfNotNil(s *string) *string { - if s == nil { - return nil - } - ret := new(string) - *ret = *s - return ret -} - -// copyIntIfNotNil makes a deep copy of i - unless it's nil, in which case it -// just returns nil. -func copyIntIfNotNil(i *int) *int { - if i == nil { - return nil - } - ret := new(int) - *ret = *i - return ret -} - // Upgrade converts a User to a UserV4 (as seen in API versions 4.x). func (u User) Upgrade() UserV4 { var ret UserV4 diff --git a/lib/go-tc/users_test.go b/lib/go-tc/users_test.go index 9d6440ad5b..701b8235a8 100644 --- a/lib/go-tc/users_test.go +++ b/lib/go-tc/users_test.go @@ -436,45 +436,3 @@ func TestUserV4_Downgrade(t *testing.T) { t.Errorf("Incorrect Username after downgrade; want: '%s', got: '%s'", username, *downgraded.Username) } } - -func TestCopyUtilities(t *testing.T) { - var s *string - copiedS := copyStringIfNotNil(s) - if copiedS != nil { - t.Errorf("Copying a nil string should've given nil, got: %s", *copiedS) - } - s = new(string) - *s = "test string" - copiedS = copyStringIfNotNil(s) - if copiedS == nil { - t.Errorf("Copied pointer to '%s' was nil", *s) - } else { - if *copiedS != *s { - t.Errorf("Incorrectly copied string pointer; expected: '%s', got: '%s'", *s, *copiedS) - } - *s = "a different test string" - if *copiedS == *s { - t.Error("Expected copy to be 'deep' but modifying the original string changed the copy") - } - } - - var i *int - copiedI := copyIntIfNotNil(i) - if copiedI != nil { - t.Errorf("Copying a nil int should've given nil, got: %d", *copiedI) - } - i = new(int) - *i = 9000 - copiedI = copyIntIfNotNil(i) - if copiedI == nil { - t.Errorf("Copied pointer to %d was nil", *i) - } else { - if *copiedI != *i { - t.Errorf("Incorrectly copied int pointer; expected: %d, got: %d", *i, *copiedI) - } - *i = 9001 - if *copiedI == *i { - t.Error("Expected copy to be 'deep' but modifying the original int changed the copy") - } - } -} From 116d4acb75bc5c10e840a9b4e531d3c076add81e Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Wed, 21 Sep 2022 07:54:28 -0600 Subject: [PATCH 05/48] Add pointer-to-value coalescence helpers --- lib/go-tc/copy.go | 48 +++++++++++++++++++++++++++++++++ lib/go-tc/copy_test.go | 60 ++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 106 insertions(+), 2 deletions(-) diff --git a/lib/go-tc/copy.go b/lib/go-tc/copy.go index 7570094911..57152635d3 100644 --- a/lib/go-tc/copy.go +++ b/lib/go-tc/copy.go @@ -30,6 +30,18 @@ func copyStringIfNotNil(s *string) *string { return ret } +// coalesceString coalesces a possibly nil pointer to a string to a concrete +// string, using the provided default value in case `nil` is encountered. +// +// This can be thought of as roughly the inverse of +// github.com/apache/trafficcontrol/lib/go-util.StrPtr. +func coalesceString(s *string, def string) string { + if s == nil { + return def + } + return *s +} + // copyIntIfNotNil makes a deep copy of i - unless it's nil, in which case it // just returns nil. func copyIntIfNotNil(i *int) *int { @@ -41,6 +53,18 @@ func copyIntIfNotNil(i *int) *int { return ret } +// coalesceInt coalesces a possibly nil pointer to an integer to a concrete +// integer, using the provided default value in case `nil` is encountered. +// +// This can be thought of as roughly the inverse of +// github.com/apache/trafficcontrol/lib/go-util.IntPtr. +func coalesceInt(i *int, def int) int { + if i == nil { + return def + } + return *i +} + // copyBoolIfNotNil makes a deep copy of b - unless it's nil, in which case it // just returns nil. func copyBoolIfNotNil(b *bool) *bool { @@ -52,6 +76,18 @@ func copyBoolIfNotNil(b *bool) *bool { return ret } +// coalesceBool coalesces a possibly nil pointer to a boolean to a concrete +// boolean, using the provided default value in case `nil` is encountered. +// +// This can be thought of as roughly the inverse of +// github.com/apache/trafficcontrol/lib/go-util.BoolPtr. +func coalesceBool(b *bool, def bool) bool { + if b == nil { + return def + } + return *b +} + // copyFloatIfNotNil makes a deep copy of f - unless it's nil, in which case it // just returns nil. func copyFloatIfNotNil(f *float64) *float64 { @@ -62,3 +98,15 @@ func copyFloatIfNotNil(f *float64) *float64 { *ret = *f return ret } + +// coalesceFloat coalesces a possibly nil pointer to a float64 to a concrete +// float64, using the provided default value in case `nil` is encountered. +// +// This can be thought of as roughly the inverse of +// github.com/apache/trafficcontrol/lib/go-util.FloatPtr. +func coalesceFloat(f *float64, def float64) float64 { + if f == nil { + return def + } + return *f +} diff --git a/lib/go-tc/copy_test.go b/lib/go-tc/copy_test.go index f7d66e50e1..b4afb30b57 100644 --- a/lib/go-tc/copy_test.go +++ b/lib/go-tc/copy_test.go @@ -43,11 +43,25 @@ func TestCopyIntIfNotNil(t *testing.T) { } } +func TestCoalesceInt(t *testing.T) { + var i *int + copiedI := coalesceInt(i, 9000) + if copiedI != 9000 { + t.Errorf("Coalescing a nil int should've given the default value, got: %d", copiedI) + } + i = new(int) + *i = 9001 + copiedI = coalesceInt(i, 9000) + if copiedI != 9001 { + t.Errorf("Coalescing a non-nil int should've given %d, got: %d", *i, copiedI) + } +} + func TestCopyFloatIfNotNil(t *testing.T) { var f *float64 copiedF := copyFloatIfNotNil(f) if copiedF != nil { - t.Errorf("Copying a nil int should've given nil, got: %f", *copiedF) + t.Errorf("Copying a nil float should've given nil, got: %f", *copiedF) } f = new(float64) *f = 9000 @@ -65,11 +79,25 @@ func TestCopyFloatIfNotNil(t *testing.T) { } } +func TestCoalesceFloat(t *testing.T) { + var f *float64 + copiedF := coalesceFloat(f, 9000) + if copiedF != 9000 { + t.Errorf("Coalescing a nil float should've given the default value, got: %f", copiedF) + } + f = new(float64) + *f = 9001 + copiedF = coalesceFloat(f, 9000) + if copiedF != 9001 { + t.Errorf("Coalescing a non-nil float should've given %f, got: %f", *f, copiedF) + } +} + func TestCopyBoolIfNotNil(t *testing.T) { var b *bool copiedB := copyBoolIfNotNil(b) if copiedB != nil { - t.Errorf("Copying a nil int should've given nil, got: %t", *copiedB) + t.Errorf("Copying a nil boolean should've given nil, got: %t", *copiedB) } b = new(bool) *b = true @@ -87,6 +115,20 @@ func TestCopyBoolIfNotNil(t *testing.T) { } } +func TestCoalesceBool(t *testing.T) { + var b *bool + copiedB := coalesceBool(b, true) + if copiedB != true { + t.Errorf("Coalescing a nil boolean should've given the default value, got: %t", copiedB) + } + b = new(bool) + *b = false + copiedB = coalesceBool(b, true) + if copiedB != false { + t.Errorf("Coalescing a non-nil bool should've given %t, got: %t", *b, copiedB) + } +} + func TestCopyStringIfNotNil(t *testing.T) { var s *string copiedS := copyStringIfNotNil(s) @@ -108,3 +150,17 @@ func TestCopyStringIfNotNil(t *testing.T) { } } } + +func TestCoalesceString(t *testing.T) { + var s *string + copiedS := coalesceString(s, "test") + if copiedS != "test" { + t.Errorf("Coalescing a nil string should've given the default value, got: %s", copiedS) + } + s = new(string) + *s = "quest" + copiedS = coalesceString(s, "test") + if copiedS != "quest" { + t.Errorf("Coalescing a non-nil string should've given %s, got: %s", *s, copiedS) + } +} From 134274f35a378d12c331e4aefbc351ced5e8fdf3 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Wed, 21 Sep 2022 09:09:42 -0600 Subject: [PATCH 06/48] Force MSO to be true or false, never null It already defaulted to false, but only when explicitly set to its default so I assume that was an oversight. --- .../2022092107561215_ds_explicit_mso.down.sql | 20 ++++++++ .../2022092107561215_ds_explicit_mso.up.sql | 47 +++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 traffic_ops/app/db/migrations/2022092107561215_ds_explicit_mso.down.sql create mode 100644 traffic_ops/app/db/migrations/2022092107561215_ds_explicit_mso.up.sql diff --git a/traffic_ops/app/db/migrations/2022092107561215_ds_explicit_mso.down.sql b/traffic_ops/app/db/migrations/2022092107561215_ds_explicit_mso.down.sql new file mode 100644 index 0000000000..6fe6741b35 --- /dev/null +++ b/traffic_ops/app/db/migrations/2022092107561215_ds_explicit_mso.down.sql @@ -0,0 +1,20 @@ +/* + * 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. + */ + +ALTER TABLE public.deliveryservice +ALTER COLUMN multi_site_origin +DROP NOT NULL; diff --git a/traffic_ops/app/db/migrations/2022092107561215_ds_explicit_mso.up.sql b/traffic_ops/app/db/migrations/2022092107561215_ds_explicit_mso.up.sql new file mode 100644 index 0000000000..9b452d9d12 --- /dev/null +++ b/traffic_ops/app/db/migrations/2022092107561215_ds_explicit_mso.up.sql @@ -0,0 +1,47 @@ +/* + * 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. + */ + +UPDATE public.deliveryservice +SET multi_site_origin = FALSE +WHERE multi_site_origin IS NULL; + +ALTER TABLE public.deliveryservice +ALTER COLUMN multi_site_origin +SET NOT NULL; + +UPDATE public.deliveryservice_request +SET + deliveryservice = jsonb_set(deliveryservice, '{multiSiteOrigin}', 'false') +WHERE + deliveryservice IS NOT NULL + AND + ( + NOT (deliveryservice ? 'multiSiteOrigin') + OR + jsonb_typeof(deliveryservice -> 'multiSiteOrigin') = 'null' + ); +UPDATE public.deliveryservice_request +SET + original = jsonb_set(original, '{multiSiteOrigin}', 'false') +WHERE + original IS NOT NULL + AND + ( + NOT (original ? 'multiSiteOrigin') + OR + jsonb_typeof(original -> 'multiSiteOrigin') = 'null' + ); From cdd4e7dce6bd5f0ef68f486e6915155e3ac94097 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Wed, 21 Sep 2022 08:47:17 -0600 Subject: [PATCH 07/48] Add DSv5 model and tests for upgrade/downgrade to/from it --- lib/go-tc/deliveryservices.go | 584 +++++++++++++++++++++++++++-- lib/go-tc/deliveryservices_test.go | 66 +++- 2 files changed, 627 insertions(+), 23 deletions(-) diff --git a/lib/go-tc/deliveryservices.go b/lib/go-tc/deliveryservices.go index 082501a237..e9a9c6f658 100644 --- a/lib/go-tc/deliveryservices.go +++ b/lib/go-tc/deliveryservices.go @@ -22,6 +22,7 @@ import ( "errors" "fmt" "strings" + "time" "github.com/apache/trafficcontrol/lib/go-util" ) @@ -44,6 +45,24 @@ const MinRangeSliceBlockSize = 262144 // Range Slice Block Size, in bytes. This is 32MiB. const MaxRangeSliceBlockSize = 33554432 +// DeliveryServiceActiveState is an "enumerated" type which encodes the valid +// values of a Delivery Service's 'Active' property (v3.0+). +type DeliveryServiceActiveState string + +// A DeliveryServiceActiveState describes the availability of Delivery Service +// content from the perspective of caching servers and Traffic Routers. +const ( + // Traffic Router routes clients for this Delivery Service and cache + // servers are configured to serve its content. + DSActiveStateActive = DeliveryServiceActiveState("ACTIVE") + // Traffic Router does not route for this Delivery Service and cache + // servers cannot serve its content. + DSActiveStateInactive = DeliveryServiceActiveState("INACTIVE") + // Traffic Router does not route for this Delivery Service, but cache + // servers are configured to serve its content. + DSActiveStatePrimed = DeliveryServiceActiveState("PRIMED") +) + // DeliveryServicesResponseV30 is the type of a response from the // /api/3.0/deliveryservices Traffic Ops endpoint. // @@ -250,10 +269,6 @@ type DeliveryServiceV40 struct { DeliveryServiceFieldsV13 DeliveryServiceNullableFieldsV11 - // Regional indicates whether the Delivery Service's MaxOriginConnections is - // only per Cache Group, rather than divided over all Cache Servers in child - // Cache Groups of the Origin. - Regional bool `json:"regional" db:"regional"` // TLSVersions is the list of explicitly supported TLS versions for cache // servers serving the Delivery Service's content. TLSVersions []string `json:"tlsVersions" db:"tls_versions"` @@ -319,10 +334,10 @@ func newerTLSVersionsDisallowedMessage(old string, newer []string) string { return msg.String() } -func tlsVersionsAlerts(vers []string, protocol int) Alerts { +func tlsVersionsAlerts(versions []string, protocol int) Alerts { messages := []string{} - if len(vers) > 0 { + if len(versions) > 0 { messages = append(messages, "setting TLS Versions that are explicitly supported may break older clients that can't use the specified versions") } else { return Alerts{Alerts: []Alert{}} @@ -335,7 +350,7 @@ func tlsVersionsAlerts(vers []string, protocol int) Alerts { TLSVersion13: false, } - for _, v := range vers { + for _, v := range versions { switch v { case TLSVersion10: found[TLSVersion10] = true @@ -406,13 +421,7 @@ func tlsVersionsAlerts(vers []string, protocol int) Alerts { // to CDN operation, but can, in fact, work. func (ds DeliveryServiceV40) TLSVersionsAlerts() Alerts { vers := ds.TLSVersions - var protocol int - if ds.Protocol != nil { - protocol = *ds.Protocol - } else { - protocol = -1 - } - return tlsVersionsAlerts(vers, protocol) + return tlsVersionsAlerts(vers, coalesceInt(ds.Protocol, 3)) } // TLSVersionsAlerts generates warning-level alerts for the Delivery Service's @@ -949,11 +958,6 @@ func (ds *DeliveryServiceNullableV30) UpgradeToV4() DeliveryServiceV4 { } } -func jsonValue(v interface{}) (driver.Value, error) { - b, err := json.Marshal(v) - return b, err -} - func jsonScan(src interface{}, dest interface{}) error { b, ok := src.([]byte) if !ok { @@ -969,7 +973,7 @@ func jsonScan(src interface{}, dest interface{}) error { // Value implements the database/sql/driver.Valuer interface by marshaling the // struct to JSON to pass back as an encoding/json.RawMessage. func (ds *DeliveryServiceNullable) Value() (driver.Value, error) { - return jsonValue(ds) + return json.Marshal(ds) } // Scan implements the database/sql.Scanner interface. @@ -983,7 +987,7 @@ func (ds *DeliveryServiceNullable) Scan(src interface{}) error { // Value implements the database/sql/driver.Valuer interface by marshaling the // struct to JSON to pass back as an encoding/json.RawMessage. func (ds *DeliveryServiceV4) Value() (driver.Value, error) { - return jsonValue(ds) + return json.Marshal(ds) } // Scan implements the database/sql.Scanner interface. @@ -1201,3 +1205,541 @@ type DeliveryServiceSafeUpdateResponseV40 struct { // This is always a type alias for the structure of a response in the latest // minor APIv4 version. type DeliveryServiceSafeUpdateResponseV4 = DeliveryServiceSafeUpdateResponseV40 + +// DeliveryServiceV50 is a Delivery Service as it appears in version 5.0 of the +// Traffic Ops API. +type DeliveryServiceV50 struct { + // Active dictates whether the Delivery Service is routed by Traffic Router, + // and whether cache servers have its configuration downloaded. + Active DeliveryServiceActiveState `json:"active" db:"active"` + // AnonymousBlockingEnabled sets whether or not anonymized IP addresses + // (e.g. Tor exit nodes) should be restricted from accessing the Delivery + // Service's content. + AnonymousBlockingEnabled bool `json:"anonymousBlockingEnabled" db:"anonymous_blocking_enabled"` + // CCRDNSTTL sets the Time-to-Live - in seconds - for DNS responses for this + // Delivery Service from Traffic Router. + CCRDNSTTL *int `json:"ccrDnsTtl" db:"ccr_dns_ttl"` + // CDNID is the integral, unique identifier for the CDN to which the + // Delivery Service belongs. + CDNID int `json:"cdnId" db:"cdn_id"` + // CDNName is the name of the CDN to which the Delivery Service belongs. + CDNName *string `json:"cdnName"` + // CheckPath is a path which may be requested of the Delivery Service's + // origin to ensure it's working properly. + CheckPath *string `json:"checkPath" db:"check_path"` + // ConsistentHashQueryParams is a list of al of the query string parameters + // which ought to be considered by Traffic Router in client request URIs for + // HTTP-routed Delivery Services in the hashing process. + ConsistentHashQueryParams []string `json:"consistentHashQueryParams"` + // ConsistentHashRegex is used by Traffic Router to extract meaningful parts + // of a client's request URI for HTTP-routed Delivery Services before + // hashing the request to find a cache server to which to direct the client. + ConsistentHashRegex *string `json:"consistentHashRegex"` + // DeepCachingType may only be 'ALWAYS' or 'NEVER', which + // define whether "deep caching" may or may not be used for this Delivery + // Service, respectively. + DeepCachingType DeepCachingType `json:"deepCachingType" db:"deep_caching_type"` + // DisplayName is a human-friendly name that might be used in some UIs + // somewhere. + DisplayName string `json:"displayName" db:"display_name"` + // DNSBypassCNAME is a fully qualified domain name to be used in a CNAME + // record presented to clients in bypass scenarios. + DNSBypassCNAME *string `json:"dnsBypassCname" db:"dns_bypass_cname"` + // DNSBypassIP is an IPv4 address to be used in an A record presented to + // clients in bypass scenarios. + DNSBypassIP *string `json:"dnsBypassIp" db:"dns_bypass_ip"` + // DNSBypassIP6 is an IPv6 address to be used in an AAAA record presented to + // clients in bypass scenarios. + DNSBypassIP6 *string `json:"dnsBypassIp6" db:"dns_bypass_ip6"` + // DNSBypassTTL sets the Time-to-Live - in seconds - of DNS responses from + // the Traffic Router that contain records for bypass destinations. + DNSBypassTTL *int `json:"dnsBypassTtl" db:"dns_bypass_ttl"` + // DSCP sets the Differentiated Services Code Point for IP packets + // transferred between clients, origins, and cache servers when obtaining + // and serving content for this Delivery Service. + // See Also: https://en.wikipedia.org/wiki/Differentiated_services + DSCP int `json:"dscp" db:"dscp"` + // EcsEnabled describes whether or not the Traffic Router's EDNS0 Client + // Subnet extensions should be enabled when serving DNS responses for this + // Delivery Service. Even if this is true, the Traffic Router may still + // have the extensions unilaterally disabled in its own configuration. + EcsEnabled bool `json:"ecsEnabled" db:"ecs_enabled"` + // EdgeHeaderRewrite is a "header rewrite rule" used by ATS at the Edge-tier + // of caching. This has no effect on Delivery Services that don't use a + // Topology. + EdgeHeaderRewrite *string `json:"edgeHeaderRewrite" db:"edge_header_rewrite"` + // ExampleURLs is a list of all of the URLs from which content may be + // requested from the Delivery Service. + ExampleURLs []string `json:"exampleURLs"` + // FirstHeaderRewrite is a "header rewrite rule" used by ATS at the first + // caching layer encountered in the Delivery Service's Topology, or nil if + // there is no such rule. This has no effect on Delivery Services that don't + // employ Topologies. + FirstHeaderRewrite *string `json:"firstHeaderRewrite" db:"first_header_rewrite"` + // FQPacingRate sets the maximum bytes per second a cache server will deliver + // on any single TCP connection for this Delivery Service. This may never + // legally point to a value less than zero. + FQPacingRate *int `json:"fqPacingRate" db:"fq_pacing_rate"` + // GeoLimit defines whether or not access to a Delivery Service's content + // should be limited based on the requesting client's geographic location. + // The only valid values are 0 (which indicates that content should not be + // limited geographically), 1 (which indicates that content should only be + // served to clients whose IP addresses can be found within a Coverage Zone + // File), and 2 (which indicates that content should be served to clients + // whose IP addresses can be found within a Coverage Zone File OR are + // allowed access according to the array in GeoLimitCountries). + GeoLimit int `json:"geoLimit" db:"geo_limit"` + // GeoLimitCountries is an "array" of "country codes" that itemizes the + // countries within which the Delivery Service's content ought to be made + // available. This has no effect if GeoLimit is not a pointer to exactly the + // value 2. + GeoLimitCountries []string `json:"geoLimitCountries"` + // GeoLimitRedirectURL is a URL to which clients will be redirected if their + // access to the Delivery Service's content is blocked by GeoLimit rules. + GeoLimitRedirectURL *string `json:"geoLimitRedirectURL" db:"geolimit_redirect_url"` + // GeoProvider names the type of database to be used for providing IP + // address-to-geographic-location mapping for this Delivery Service. The + // only valid values are 0 (which indicates the use of a MaxMind GeoIP2 + // database) and 1 (which indicates the use of a Neustar GeoPoint IP address + // database). + GeoProvider int `json:"geoProvider" db:"geo_provider"` + // GlobalMaxMBPS defines a maximum number of MegaBytes Per Second which may + // be served for the Delivery Service before redirecting clients to bypass + // locations. + GlobalMaxMBPS *int `json:"globalMaxMbps" db:"global_max_mbps"` + // GlobalMaxTPS defines a maximum number of Transactions Per Second which + // may be served for the Delivery Service before redirecting clients to + // bypass locations. + GlobalMaxTPS *int `json:"globalMaxTps" db:"global_max_tps"` + // HTTPBypassFQDN is a network location to which clients will be redirected + // in bypass scenarios using HTTP "Location" headers and appropriate + // redirection response codes. + HTTPBypassFQDN *string `json:"httpBypassFqdn" db:"http_bypass_fqdn"` + // ID is an integral, unique identifier for the Delivery Service. + ID *int `json:"id" db:"id"` + // InfoURL is a URL to which operators or clients may be directed to obtain + // further information about a Delivery Service. + InfoURL *string `json:"infoUrl" db:"info_url"` + // InitialDispersion sets the number of cache servers within the first + // caching layer ("Edge-tier" in a non-Topology context) across which + // content will be dispersed per Cache Group. + InitialDispersion *int `json:"initialDispersion" db:"initial_dispersion"` + // InnerHeaderRewrite is a "header rewrite rule" used by ATS at all caching + // layers encountered in the Delivery Service's Topology except the first + // and last, or nil if there is no such rule. This has no effect on Delivery + // Services that don't employ Topologies. + InnerHeaderRewrite *string `json:"innerHeaderRewrite" db:"inner_header_rewrite"` + // IPV6RoutingEnabled controls whether or not routing over IPv6 should be + // done for this Delivery Service. + IPV6RoutingEnabled *bool `json:"ipv6RoutingEnabled" db:"ipv6_routing_enabled"` + // LastHeaderRewrite is a "header rewrite rule" used by ATS at the first + // caching layer encountered in the Delivery Service's Topology, or nil if + // there is no such rule. This has no effect on Delivery Services that don't + // employ Topologies. + LastHeaderRewrite *string `json:"lastHeaderRewrite" db:"last_header_rewrite"` + // LastUpdated is the time and date at which the Delivery Service was last + // updated. + LastUpdated time.Time `json:"lastUpdated" db:"last_updated"` + // LogsEnabled controls nothing. It is kept only for legacy compatibility. + LogsEnabled bool `json:"logsEnabled" db:"logs_enabled"` + // LongDesc is a description of the Delivery Service, having arbitrary + // length. + LongDesc string `json:"longDesc" db:"long_desc"` + // MatchList is a list of Regular Expressions used for routing the Delivery + // Service. Order matters, and the array is not allowed to be sparse. + MatchList []DeliveryServiceMatch `json:"matchList"` + // MaxDNSAnswers sets the maximum number of records which should be returned + // by Traffic Router in DNS responses to requests for resolving names for + // this Delivery Service. + MaxDNSAnswers *int `json:"maxDnsAnswers" db:"max_dns_answers"` + // MaxOriginConnections defines the total maximum number of connections + // that the highest caching layer ("Mid-tier" in a non-Topology context) is + // allowed to have concurrently open to the Delivery Service's Origin. This + // may never legally point to a value less than 0. + MaxOriginConnections *int `json:"maxOriginConnections" db:"max_origin_connections"` + // MaxRequestHeaderBytes is the maximum size (in bytes) of the request + // header that is allowed for this Delivery Service. + MaxRequestHeaderBytes *int `json:"maxRequestHeaderBytes" db:"max_request_header_bytes"` + // MidHeaderRewrite is a "header rewrite rule" used by ATS at the Mid-tier + // of caching. This has no effect on Delivery Services that don't use a + // Topology. + MidHeaderRewrite *string `json:"midHeaderRewrite" db:"mid_header_rewrite"` + // MissLat is a latitude to default to for clients of this Delivery Service + // when geolocation attempts fail. + MissLat *float64 `json:"missLat" db:"miss_lat"` + // MissLong is a longitude to default to for clients of this Delivery + // Service when geolocation attempts fail. + MissLong *float64 `json:"missLong" db:"miss_long"` + // MultiSiteOrigin determines whether or not the Delivery Service makes use + // of "Multi-Site Origin". + MultiSiteOrigin bool `json:"multiSiteOrigin" db:"multi_site_origin"` + // OriginShield is a field that does nothing. It is kept only for legacy + // compatibility reasons. + OriginShield *string `json:"originShield" db:"origin_shield"` + // OrgServerFQDN is the URL - NOT Fully Qualified Domain Name - of the + // origin of the Delivery Service's content. + OrgServerFQDN *string `json:"orgServerFqdn" db:"org_server_fqdn"` + // ProfileDesc is the Description of the Profile used by the Delivery + // Service, if any. + ProfileDesc *string `json:"profileDescription"` + // ProfileID is the integral, unique identifier of the Profile used by the + // Delivery Service, if any. + ProfileID *int `json:"profileId" db:"profile"` + // ProfileName is the Name of the Profile used by the Delivery Service, if + // any. + ProfileName *string `json:"profileName"` + // Protocol defines the protocols by which caching servers may communicate + // with clients. The valid values are 0 (which implies that only HTTP may be + // used), 1 (which implies that only HTTPS may be used), 2 (which implies + // that either HTTP or HTTPS may be used), and 3 (which implies that clients + // using HTTP must be redirected to use HTTPS, while communications over + // HTTPS may proceed as normal). + Protocol *int `json:"protocol" db:"protocol"` + // QStringIgnore sets how query strings in HTTP requests to cache servers + // from clients are treated. The only valid values are 0 (which implies that + // all caching layers will pass query strings in upstream requests and use + // them in the cache key), 1 (which implies that all caching layers will + // pass query strings in upstream requests, but not use them in cache keys), + // and 2 (which implies that the first encountered caching layer - + // "Edge-tier" in a non-Topology context - will strip query strings, + // effectively preventing them from being passed in upstream requests, and + // not use them in the cache key). + QStringIgnore *int `json:"qstringIgnore" db:"qstring_ignore"` + // RangeRequestHandling defines how HTTP GET requests with a Range header + // will be handled by cache servers serving the Delivery Service's content. + // The only valid values are 0 (which implies that Range requests will not + // be cached at all), 1 (which implies that the background_fetch plugin will + // be used to service the range request while caching the whole object), 2 + // (which implies that the cache_range_requests plugin will be used to cache + // ranges as unique objects), and 3 (which implies that the slice plugin + // will be used to slice range based requests into deterministic chunks.) + RangeRequestHandling *int `json:"rangeRequestHandling" db:"range_request_handling"` + // RangeSliceBlockSize defines the size of range request blocks - or + // "slices" - used by the "slice" plugin. This has no effect if + // RangeRequestHandling does not point to exactly 3. This may never legally + // point to a value less than zero. + RangeSliceBlockSize *int `json:"rangeSliceBlockSize" db:"range_slice_block_size"` + // Regex Remap is a raw line to be inserted into "regex_remap.config" on the + // cache server. Care is necessitated in its use, because the input is in no + // way restricted, validated, or limited in scope to the Delivery Service. + RegexRemap *string `json:"regexRemap" db:"regex_remap"` + // Regional indicates whether the Delivery Service's MaxOriginConnections is + // only per Cache Group, rather than divided over all Cache Servers in child + // Cache Groups of the Origin. + Regional bool `json:"regional" db:"regional"` + // RegionalGeoBlocking defines whether or not whatever Regional Geo Blocking + // rules are configured on the Traffic Router serving content for this + // Delivery Service will have an effect on the traffic of this Delivery + // Service. + RegionalGeoBlocking bool `json:"regionalGeoBlocking" db:"regional_geo_blocking"` + // RemapText is raw text to insert in "remap.config" on the cache servers + // serving content for this Delivery Service. Care is necessitated in its + // use, because the input is in no way restricted, validated, or limited in + // scope to the Delivery Service. + RemapText *string `json:"remapText" db:"remap_text"` + // RoutingName defines the lowest-level DNS label used by the Delivery + // Service, e.g. if trafficcontrol.apache.org were a Delivery Service, it + // would have a RoutingName of "trafficcontrol". + RoutingName string `json:"routingName" db:"routing_name"` + // ServiceCategory defines a category to which a Delivery Service may + // belong, which will cause HTTP Responses containing content for the + // Delivery Service to have the "X-CDN-SVC" header with a value that is the + // XMLID of the Delivery Service. + ServiceCategory *string `json:"serviceCategory" db:"service_category"` + // Signed is a legacy field. It is allowed to be `true` if and only if + // SigningAlgorithm is not nil. + Signed bool `json:"signed"` + // SigningAlgorithm is the name of the algorithm used to sign CDN URIs for + // this Delivery Service's content, or nil if no URI signing is done for the + // Delivery Service. This may only point to the values "url_sig" or + // "uri_signing" when it is not `nil`. + SigningAlgorithm *string `json:"signingAlgorithm" db:"signing_algorithm"` + // SSLKeyVersion incremented whenever Traffic Portal generates new SSL keys + // for the Delivery Service, effectively making it a "generational" marker. + SSLKeyVersion *int `json:"sslKeyVersion" db:"ssl_key_version"` + // Tenant is the Tenant to which the Delivery Service belongs. + Tenant *string `json:"tenant"` + // TenantID is the integral, unique identifier for the Tenant to which the + // Delivery Service belongs. + TenantID int `json:"tenantId" db:"tenant_id"` + // TLSVersions is the list of explicitly supported TLS versions for cache + // servers serving the Delivery Service's content. + TLSVersions []string `json:"tlsVersions" db:"tls_versions"` + // Topology is the name of the Topology used by the Delivery Service, or nil + // if no Topology is used. + Topology *string `json:"topology" db:"topology"` + // TRResponseHeaders is a set of headers (separated by CRLF pairs as per the + // HTTP spec) and their values (separated by a colon as per the HTTP spec) + // which will be sent by Traffic Router in HTTP responses to client requests + // for this Delivery Service's content. This has no effect on DNS-routed or + // un-routed Delivery Service Types. + TRResponseHeaders *string `json:"trResponseHeaders"` + // TRRequestHeaders is an "array" of HTTP headers which should be logged + // from client HTTP requests for this Delivery Service's content by Traffic + // Router, separated by newlines. This has no effect on DNS-routed or + // un-routed Delivery Service Types. + TRRequestHeaders *string `json:"trRequestHeaders"` + // Type describes how content is routed and cached for this Delivery Service + // as well as what other properties have any meaning. + Type *string `json:"type"` + // TypeID is an integral, unique identifier for the Tenant to which the + // Delivery Service belongs. + TypeID int `json:"typeId" db:"type"` + // XMLID is a unique identifier that is also the second lowest-level DNS + // label used by the Delivery Service. For example, if a Delivery Service's + // content may be requested from video.demo1.mycdn.ciab.test, it may be + // inferred that the Delivery Service's XMLID is demo1. + XMLID string `json:"xmlId" db:"xml_id"` +} + +// DeliveryServiceV5 is the type of a Delivery Service as it appears in the +// latest minor version of Traffic Ops API version 5. +type DeliveryServiceV5 = DeliveryServiceV50 + +// TLSVersionsAlerts generates warning-level alerts for the Delivery Service's +// TLS versions array. It will warn if newer versions are disallowed while +// older, less secure versions are allowed, if there are unrecognized versions +// present, if the Delivery Service's Protocol does not make use of TLS +// Versions, and whenever TLSVersions are explicitly set at all. +// +// This does NOT verify that the Delivery Service's TLS versions are _valid_, +// it ONLY creates warnings based on conditions that are possibly detrimental +// to CDN operation, but can, in fact, work. +func (ds DeliveryServiceV5) TLSVersionsAlerts() Alerts { + return tlsVersionsAlerts(ds.TLSVersions, coalesceInt(ds.Protocol, 3)) +} + +// Value implements the database/sql/driver.Valuer interface by marshaling the +// struct to JSON to pass back as an encoding/json.RawMessage. +func (ds *DeliveryServiceV5) Value() (driver.Value, error) { + return json.Marshal(ds) +} + +// Scan implements the database/sql.Scanner interface. +// +// This expects src to be an encoding/json.RawMessage and unmarshals that into +// the DeliveryServiceV5. +func (ds *DeliveryServiceV5) Scan(src interface{}) error { + return jsonScan(src, ds) +} + +// Downgrade downgrades an APIv5 Delivery Service into an APIv4 Delivery Service +// of the latest minor version. +func (ds DeliveryServiceV5) Downgrade() DeliveryServiceV4 { + downgraded := DeliveryServiceV4{ + DeliveryServiceV40: DeliveryServiceV40{ + DeliveryServiceFieldsV31: DeliveryServiceFieldsV31{ + MaxRequestHeaderBytes: copyIntIfNotNil(ds.MaxRequestHeaderBytes), + }, + DeliveryServiceFieldsV30: DeliveryServiceFieldsV30{ + FirstHeaderRewrite: copyStringIfNotNil(ds.FirstHeaderRewrite), + InnerHeaderRewrite: copyStringIfNotNil(ds.InnerHeaderRewrite), + LastHeaderRewrite: copyStringIfNotNil(ds.LastHeaderRewrite), + ServiceCategory: copyStringIfNotNil(ds.ServiceCategory), + Topology: copyStringIfNotNil(ds.Topology), + }, + DeliveryServiceFieldsV15: DeliveryServiceFieldsV15{ + EcsEnabled: ds.EcsEnabled, + RangeSliceBlockSize: copyIntIfNotNil(ds.RangeSliceBlockSize), + }, + DeliveryServiceFieldsV14: DeliveryServiceFieldsV14{ + ConsistentHashQueryParams: make([]string, len(ds.ConsistentHashQueryParams)), + ConsistentHashRegex: copyStringIfNotNil(ds.ConsistentHashRegex), + MaxOriginConnections: copyIntIfNotNil(ds.MaxOriginConnections), + }, + DeliveryServiceFieldsV13: DeliveryServiceFieldsV13{ + DeepCachingType: new(DeepCachingType), + FQPacingRate: copyIntIfNotNil(ds.FQPacingRate), + SigningAlgorithm: copyStringIfNotNil(ds.SigningAlgorithm), + Tenant: copyStringIfNotNil(ds.Tenant), + TRResponseHeaders: copyStringIfNotNil(ds.TRResponseHeaders), + TRRequestHeaders: copyStringIfNotNil(ds.TRRequestHeaders), + }, + DeliveryServiceNullableFieldsV11: DeliveryServiceNullableFieldsV11{ + Active: new(bool), + AnonymousBlockingEnabled: util.BoolPtr(ds.AnonymousBlockingEnabled), + CCRDNSTTL: copyIntIfNotNil(ds.CCRDNSTTL), + CDNID: util.IntPtr(ds.CDNID), + CDNName: copyStringIfNotNil(ds.CDNName), + CheckPath: copyStringIfNotNil(ds.CheckPath), + DisplayName: util.StrPtr(ds.DisplayName), + DNSBypassCNAME: copyStringIfNotNil(ds.DNSBypassCNAME), + DNSBypassIP: copyStringIfNotNil(ds.DNSBypassIP), + DNSBypassIP6: copyStringIfNotNil(ds.DNSBypassIP6), + DNSBypassTTL: copyIntIfNotNil(ds.DNSBypassTTL), + DSCP: util.IntPtr(ds.DSCP), + EdgeHeaderRewrite: copyStringIfNotNil(ds.EdgeHeaderRewrite), + GeoLimit: util.IntPtr(ds.GeoLimit), + GeoLimitRedirectURL: copyStringIfNotNil(ds.GeoLimitRedirectURL), + GeoProvider: util.IntPtr(ds.GeoProvider), + GlobalMaxMBPS: copyIntIfNotNil(ds.GlobalMaxMBPS), + GlobalMaxTPS: copyIntIfNotNil(ds.GlobalMaxTPS), + HTTPBypassFQDN: copyStringIfNotNil(ds.HTTPBypassFQDN), + ID: copyIntIfNotNil(ds.ID), + InfoURL: copyStringIfNotNil(ds.InfoURL), + InitialDispersion: copyIntIfNotNil(ds.InitialDispersion), + IPV6RoutingEnabled: copyBoolIfNotNil(ds.IPV6RoutingEnabled), + LastUpdated: TimeNoModFromTime(ds.LastUpdated), + LogsEnabled: util.BoolPtr(ds.LogsEnabled), + LongDesc: util.StrPtr(ds.LongDesc), + MaxDNSAnswers: copyIntIfNotNil(ds.MaxDNSAnswers), + MidHeaderRewrite: copyStringIfNotNil(ds.MidHeaderRewrite), + MissLat: copyFloatIfNotNil(ds.MissLat), + MissLong: copyFloatIfNotNil(ds.MissLong), + MultiSiteOrigin: util.BoolPtr(ds.MultiSiteOrigin), + OriginShield: copyStringIfNotNil(ds.OriginShield), + OrgServerFQDN: copyStringIfNotNil(ds.OrgServerFQDN), + ProfileDesc: copyStringIfNotNil(ds.ProfileDesc), + ProfileID: copyIntIfNotNil(ds.ProfileID), + ProfileName: copyStringIfNotNil(ds.ProfileName), + Protocol: copyIntIfNotNil(ds.Protocol), + QStringIgnore: copyIntIfNotNil(ds.QStringIgnore), + RangeRequestHandling: copyIntIfNotNil(ds.RangeRequestHandling), + RegexRemap: copyStringIfNotNil(ds.RegexRemap), + RegionalGeoBlocking: util.BoolPtr(ds.RegionalGeoBlocking), + RemapText: copyStringIfNotNil(ds.RemapText), + RoutingName: util.StrPtr(ds.RoutingName), + Signed: ds.Signed, + SSLKeyVersion: copyIntIfNotNil(ds.SSLKeyVersion), + TenantID: util.IntPtr(ds.TenantID), + Type: (*DSType)(copyStringIfNotNil(ds.Type)), + TypeID: util.IntPtr(ds.TypeID), + XMLID: util.StrPtr(ds.XMLID), + }, + TLSVersions: make([]string, len(ds.TLSVersions)), + }, + Regional: ds.Regional, + } + + *downgraded.Active = ds.Active == DSActiveStateActive + copy(downgraded.ConsistentHashQueryParams, ds.ConsistentHashQueryParams) + if ds.ExampleURLs != nil { + downgraded.ExampleURLs = make([]string, len(ds.ExampleURLs)) + copy(downgraded.ExampleURLs, ds.ExampleURLs) + } + if len(ds.GeoLimitCountries) > 0 { + countries := make([]string, len(ds.GeoLimitCountries)) + copy(countries, ds.GeoLimitCountries) + downgraded.GeoLimitCountries = GeoLimitCountriesType(countries) + } + if ds.MatchList != nil { + downgraded.MatchList = new([]DeliveryServiceMatch) + *downgraded.MatchList = make([]DeliveryServiceMatch, len(ds.MatchList)) + copy(*downgraded.MatchList, ds.MatchList) + } + copy(downgraded.TLSVersions, ds.TLSVersions) + + return downgraded +} + +// Upgrade upgrades an APIv4 Delivery Service into an APIv5 Delivery Service of +// the latest minor version. +func (ds DeliveryServiceV4) Upgrade() DeliveryServiceV5 { + upgraded := DeliveryServiceV5{ + AnonymousBlockingEnabled: coalesceBool(ds.AnonymousBlockingEnabled, false), + CCRDNSTTL: copyIntIfNotNil(ds.CCRDNSTTL), + CDNID: coalesceInt(ds.CDNID, -1), + CDNName: copyStringIfNotNil(ds.CDNName), + CheckPath: copyStringIfNotNil(ds.CheckPath), + ConsistentHashQueryParams: make([]string, len(ds.ConsistentHashQueryParams)), + ConsistentHashRegex: copyStringIfNotNil(ds.ConsistentHashRegex), + DeepCachingType: DeepCachingType(coalesceString((*string)(ds.DeepCachingType), string(DeepCachingTypeInvalid))), + DisplayName: coalesceString(ds.DisplayName, ""), + DNSBypassCNAME: copyStringIfNotNil(ds.DNSBypassCNAME), + DNSBypassIP: copyStringIfNotNil(ds.DNSBypassIP), + DNSBypassIP6: copyStringIfNotNil(ds.DNSBypassIP6), + DNSBypassTTL: copyIntIfNotNil(ds.DNSBypassTTL), + DSCP: coalesceInt(ds.DSCP, -1), + EcsEnabled: ds.EcsEnabled, + EdgeHeaderRewrite: copyStringIfNotNil(ds.EdgeHeaderRewrite), + ExampleURLs: nil, + FirstHeaderRewrite: copyStringIfNotNil(ds.FirstHeaderRewrite), + FQPacingRate: copyIntIfNotNil(ds.FQPacingRate), + GeoLimit: coalesceInt(ds.GeoLimit, -1), + GeoLimitCountries: make([]string, len(ds.GeoLimitCountries)), + GeoLimitRedirectURL: copyStringIfNotNil(ds.GeoLimitRedirectURL), + GeoProvider: coalesceInt(ds.GeoProvider, -1), + GlobalMaxMBPS: copyIntIfNotNil(ds.GlobalMaxMBPS), + GlobalMaxTPS: copyIntIfNotNil(ds.GlobalMaxTPS), + HTTPBypassFQDN: copyStringIfNotNil(ds.HTTPBypassFQDN), + ID: copyIntIfNotNil(ds.ID), + InfoURL: copyStringIfNotNil(ds.InfoURL), + InitialDispersion: copyIntIfNotNil(ds.InitialDispersion), + InnerHeaderRewrite: copyStringIfNotNil(ds.InnerHeaderRewrite), + IPV6RoutingEnabled: copyBoolIfNotNil(ds.IPV6RoutingEnabled), + LastHeaderRewrite: copyStringIfNotNil(ds.LastHeaderRewrite), + LogsEnabled: coalesceBool(ds.LogsEnabled, false), + LongDesc: coalesceString(ds.LongDesc, ""), + MatchList: nil, + MaxDNSAnswers: copyIntIfNotNil(ds.MaxDNSAnswers), + MaxOriginConnections: copyIntIfNotNil(ds.MaxOriginConnections), + MaxRequestHeaderBytes: copyIntIfNotNil(ds.MaxRequestHeaderBytes), + MidHeaderRewrite: copyStringIfNotNil(ds.MidHeaderRewrite), + MissLat: copyFloatIfNotNil(ds.MissLat), + MissLong: copyFloatIfNotNil(ds.MissLong), + MultiSiteOrigin: coalesceBool(ds.MultiSiteOrigin, false), + OriginShield: copyStringIfNotNil(ds.OriginShield), + OrgServerFQDN: copyStringIfNotNil(ds.OrgServerFQDN), + ProfileDesc: copyStringIfNotNil(ds.ProfileDesc), + ProfileID: copyIntIfNotNil(ds.ProfileID), + ProfileName: copyStringIfNotNil(ds.ProfileName), + Protocol: copyIntIfNotNil(ds.Protocol), + QStringIgnore: copyIntIfNotNil(ds.QStringIgnore), + RangeRequestHandling: copyIntIfNotNil(ds.RangeRequestHandling), + RangeSliceBlockSize: copyIntIfNotNil(ds.RangeSliceBlockSize), + RegexRemap: copyStringIfNotNil(ds.RegexRemap), + Regional: ds.Regional, + RegionalGeoBlocking: coalesceBool(ds.RegionalGeoBlocking, false), + RemapText: copyStringIfNotNil(ds.RemapText), + RoutingName: coalesceString(ds.RoutingName, ""), + ServiceCategory: copyStringIfNotNil(ds.ServiceCategory), + Signed: ds.Signed, + SigningAlgorithm: copyStringIfNotNil(ds.SigningAlgorithm), + SSLKeyVersion: copyIntIfNotNil(ds.SSLKeyVersion), + Tenant: copyStringIfNotNil(ds.Tenant), + TenantID: coalesceInt(ds.TenantID, -1), + TLSVersions: make([]string, len(ds.TLSVersions)), + Topology: copyStringIfNotNil(ds.Topology), + TRResponseHeaders: copyStringIfNotNil(ds.TRResponseHeaders), + TRRequestHeaders: copyStringIfNotNil(ds.TRRequestHeaders), + Type: copyStringIfNotNil((*string)(ds.Type)), + TypeID: coalesceInt(ds.TypeID, -1), + XMLID: coalesceString(ds.XMLID, ""), + } + + if ds.Active == nil || !*ds.Active { + upgraded.Active = DSActiveStatePrimed + } else { + upgraded.Active = DSActiveStateActive + } + copy(upgraded.ConsistentHashQueryParams, ds.ConsistentHashQueryParams) + if ds.ExampleURLs != nil { + upgraded.ExampleURLs = make([]string, len(ds.ExampleURLs)) + copy(upgraded.ExampleURLs, ds.ExampleURLs) + } + copy(upgraded.GeoLimitCountries, ds.GeoLimitCountries) + if ds.LastUpdated != nil { + upgraded.LastUpdated = ds.LastUpdated.Time + } + if ds.MatchList != nil && len(*ds.MatchList) > 0 { + upgraded.MatchList = make([]DeliveryServiceMatch, len(*ds.MatchList)) + copy(upgraded.MatchList, *ds.MatchList) + } + copy(upgraded.TLSVersions, ds.TLSVersions) + + return upgraded +} + +// DeliveryServicesResponseV5 is the type of a response from the +// /deliveryservices Traffic Ops endpoint in version 5 of its API. +type DeliveryServicesResponseV5 struct { + Alerts + Response []DeliveryServiceV5 `json:"response"` +} + +// DeliveryServiceResponseV5 is the type of a response for API endponts +// returning a single Delivery Service in Traffic Ops API version 5. +type DeliveryServiceResponseV5 struct { + Alerts + Response DeliveryServiceV5 `json:"response"` +} diff --git a/lib/go-tc/deliveryservices_test.go b/lib/go-tc/deliveryservices_test.go index 55179041d1..03f6e05721 100644 --- a/lib/go-tc/deliveryservices_test.go +++ b/lib/go-tc/deliveryservices_test.go @@ -15,7 +15,9 @@ package tc */ import ( + "encoding/json" "fmt" + "reflect" "strings" "testing" ) @@ -432,6 +434,13 @@ func dsUpgradeAndDowngradeTestingPair() (DeliveryServiceNullableV30, DeliverySer longDesc := "longDesc" longDesc1 := "longDesc1" longDesc2 := "longDesc2" + matchList := []DeliveryServiceMatch{ + { + SetNumber: 1, + Type: DSMatchTypeHostRegex, + Pattern: "this is a testing pattern", + }, + } maxDNSAnswers := -76675 maxOriginConnections := 6514684 maxRequestHeaderBytes := 555 @@ -504,7 +513,7 @@ func dsUpgradeAndDowngradeTestingPair() (DeliveryServiceNullableV30, DeliverySer newDS.LongDesc = &longDesc newDS.LongDesc1 = &longDesc1 newDS.LongDesc2 = &longDesc2 - newDS.MatchList = nil + newDS.MatchList = &matchList newDS.MaxDNSAnswers = &maxDNSAnswers newDS.MaxOriginConnections = &maxOriginConnections newDS.MaxRequestHeaderBytes = &maxRequestHeaderBytes @@ -578,7 +587,7 @@ func dsUpgradeAndDowngradeTestingPair() (DeliveryServiceNullableV30, DeliverySer LongDesc: &longDesc, LongDesc1: &longDesc1, LongDesc2: &longDesc2, - MatchList: nil, + MatchList: &matchList, MaxDNSAnswers: &maxDNSAnswers, MidHeaderRewrite: &midHeaderRewrite, MissLat: &missLat, @@ -681,6 +690,59 @@ func TestDeliveryServiceUpgradeAndDowngrade(t *testing.T) { } } +func TestDeliveryServiceV4UpgradeAndV5Downgrade(t *testing.T) { + _, ds := dsUpgradeAndDowngradeTestingPair() + ds.RemoveLD1AndLD2() + upDowned := ds.Upgrade().Downgrade() + if !reflect.DeepEqual(ds, upDowned) { + bts, err := json.MarshalIndent(ds, "", "\t") + if err != nil { + t.Fatalf("failed to encode original DS after upgrade/downgrade comparison failed: %v", err) + } + t.Logf("original: %s", bts) + bts, err = json.MarshalIndent(upDowned, "", "\t") + if err != nil { + t.Fatalf("failed to encode upgraded-then-downgraded DS after upgrade/downgrade comparison failed: %v", err) + } + t.Logf("upgraded-then-downgraded: %s", bts) + t.Error("Delivery Service upgrade followed by downgrade should result in exact copy") + } + + ds.OrgServerFQDN = new(string) + *ds.OrgServerFQDN = "testquest.org" + if upDowned.OrgServerFQDN != nil && *upDowned.OrgServerFQDN == *ds.OrgServerFQDN { + t.Error("Modifying a reference in the original should leave the copy unchanged") + } + + ds.Active = new(bool) + upgraded := ds.Upgrade() + if upgraded.Active != DSActiveStatePrimed { + t.Fatalf("Upgrading an Active=false APIv4 DS should yield Active='%s', got: %s", DSActiveStatePrimed, upgraded.Active) + } + *ds.Active = true + if upgraded = ds.Upgrade(); upgraded.Active != DSActiveStateActive { + t.Fatalf("Upgrading an Active=true APIv4 DS should yield Active='%s', got: %s", DSActiveStateActive, upgraded.Active) + } + + if downgraded := upgraded.Downgrade(); downgraded.Active == nil { + t.Error("Unexpected nil active state after downgrading APIv5 DS to APIv4") + } else if !*downgraded.Active { + t.Errorf("Downgrading an Active='%s' APIv5 DS should yield Active=true, got: false", DSActiveStateActive) + } + upgraded.Active = DSActiveStatePrimed + if downgraded := upgraded.Downgrade(); downgraded.Active == nil { + t.Error("Unexpected nil active state after downgrading APIv5 DS to APIv4") + } else if *downgraded.Active { + t.Errorf("Downgrading an Active='%s' APIv5 DS should yield Active=false, got: true", DSActiveStatePrimed) + } + upgraded.Active = DSActiveStateInactive + if downgraded := upgraded.Downgrade(); downgraded.Active == nil { + t.Error("Unexpected nil active state after downgrading APIv5 DS to APIv4") + } else if *downgraded.Active { + t.Errorf("Downgrading an Active='%s' APIv5 DS should yield Active=false, got: true", DSActiveStateInactive) + } +} + func expectOnlyWarnings(a Alerts) func(*testing.T) { return func(t *testing.T) { found := 0 From 8cb6e708574bafc6fbb851ac41540eb10427aaa5 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Wed, 21 Sep 2022 09:29:26 -0600 Subject: [PATCH 08/48] Add DSRv5 model and tests for upgrade/downgrade to/from it --- lib/go-tc/deliveryservice_requests.go | 262 +++++++++++++++++++-- lib/go-tc/deliveryservice_requests_test.go | 82 ++++++- 2 files changed, 308 insertions(+), 36 deletions(-) diff --git a/lib/go-tc/deliveryservice_requests.go b/lib/go-tc/deliveryservice_requests.go index 91ff66e454..e2bfbd7419 100644 --- a/lib/go-tc/deliveryservice_requests.go +++ b/lib/go-tc/deliveryservice_requests.go @@ -268,7 +268,7 @@ func (d DeliveryServiceRequestDetails) Format() (string, error) { b := &strings.Builder{} if err := EmailTemplate.Execute(b, d); err != nil { - return "", fmt.Errorf("Failed to apply template: %w", err) + return "", fmt.Errorf("failed to apply template: %w", err) } return b.String(), nil } @@ -822,62 +822,88 @@ func (dsr DeliveryServiceRequestV40) Downgrade() DeliveryServiceRequestNullable return downgraded } -// String encodes the DeliveryServiceRequestV40 as a string, in the format -// "DeliveryServiceRequestV40({{Property}}={{Value}}[, {{Property}}={{Value}}]+)". -// -// If a property is a pointer value, then its dereferenced value is used - -// unless it's nil, in which case "" is used as the value. DeliveryService -// is omitted, because of how large it is. Times are formatted in RFC3339 format. -func (dsr DeliveryServiceRequestV40) String() string { +// dsrString renders a string for a DSR at either v4 or v5. The first argument +// should be the name of the struct being rendered, the remainder are all +// properties of DSRs. +func dsrString( + structName, author, lastEditedBy, changeType, status string, + assignee *string, + createdAt, lastUpdated time.Time, + assigneeID, authorID, id, lastEditedByID *int, +) string { var builder strings.Builder - builder.Write([]byte("DeliveryServiceRequestV40(Assignee=")) - if dsr.Assignee != nil { + builder.WriteString(structName) + builder.Write([]byte("(Assignee=")) + if assignee != nil { builder.WriteRune('"') - builder.WriteString(*dsr.Assignee) + builder.WriteString(*assignee) builder.WriteRune('"') } else { builder.Write([]byte("")) } builder.Write([]byte(", AssigneeID=")) - if dsr.AssigneeID != nil { - builder.WriteString(strconv.Itoa(*dsr.AssigneeID)) + if assigneeID != nil { + builder.WriteString(strconv.Itoa(*assigneeID)) } else { builder.Write([]byte("")) } builder.Write([]byte(`, Author="`)) - builder.WriteString(dsr.Author) + builder.WriteString(author) builder.Write([]byte(`", AuthorID=`)) - if dsr.AuthorID != nil { - builder.WriteString(strconv.Itoa(*dsr.AuthorID)) + if authorID != nil { + builder.WriteString(strconv.Itoa(*authorID)) } else { builder.Write([]byte("")) } builder.Write([]byte(`, ChangeType="`)) - builder.WriteString(dsr.ChangeType.String()) + builder.WriteString(changeType) builder.Write([]byte(`", CreatedAt=`)) - builder.WriteString(dsr.CreatedAt.Format(time.RFC3339)) + builder.WriteString(createdAt.Format(time.RFC3339)) builder.Write([]byte(", ID=")) - if dsr.ID != nil { - builder.WriteString(strconv.Itoa(*dsr.ID)) + if id != nil { + builder.WriteString(strconv.Itoa(*id)) } else { builder.Write([]byte("")) } builder.Write([]byte(`, LastEditedBy="`)) - builder.WriteString(dsr.LastEditedBy) + builder.WriteString(lastEditedBy) builder.Write([]byte(`", LastEditedByID=`)) - if dsr.LastEditedByID != nil { - builder.WriteString(strconv.Itoa(*dsr.LastEditedByID)) + if lastEditedByID != nil { + builder.WriteString(strconv.Itoa(*lastEditedByID)) } else { builder.Write([]byte("")) } builder.Write([]byte(`, LastUpdated=`)) - builder.WriteString(dsr.LastUpdated.Format(time.RFC3339)) + builder.WriteString(lastUpdated.Format(time.RFC3339)) builder.Write([]byte(`, Status="`)) - builder.WriteString(dsr.Status.String()) + builder.WriteString(status) builder.Write([]byte(`")`)) return builder.String() } +// String encodes the DeliveryServiceRequestV40 as a string, in the format +// "DeliveryServiceRequestV40({{Property}}={{Value}}[, {{Property}}={{Value}}]+)". +// +// If a property is a pointer value, then its dereferenced value is used - +// unless it's nil, in which case "" is used as the value. DeliveryService +// is omitted, because of how large it is. Times are formatted in RFC3339 format. +func (dsr DeliveryServiceRequestV40) String() string { + return dsrString( + "DeliveryServiceRequestV40", + dsr.Author, + dsr.LastEditedBy, + dsr.ChangeType.String(), + dsr.Status.String(), + dsr.Assignee, + dsr.CreatedAt, + dsr.LastUpdated, + dsr.AssigneeID, + dsr.AuthorID, + dsr.ID, + dsr.LastEditedByID, + ) +} + // SetXMLID sets the DeliveryServiceRequestV40's XMLID based on its DeliveryService. func (dsr *DeliveryServiceRequestV40) SetXMLID() { if dsr == nil { @@ -894,6 +920,176 @@ func (dsr *DeliveryServiceRequestV40) SetXMLID() { } } +// DeliveryServiceRequestV50 is the type of a Delivery Service Request in +// Traffic Ops API version 5.0. +type DeliveryServiceRequestV50 struct { + // Assignee is the username of the user assigned to the Delivery Service + // Request, if any. + Assignee *string `json:"assignee"` + // AssigneeID is the integral, unique identifier of the user assigned to the + // Delivery Service Request, if any. + AssigneeID *int `json:"-" db:"assignee_id"` + // Author is the username of the user who created the Delivery Service + // Request. + Author string `json:"author"` + // AuthorID is the integral, unique identifier of the user who created the + // Delivery Service Request, if/when it is known. + AuthorID *int `json:"-" db:"author_id"` + // ChangeType represents the type of change being made, must be one of + // "create", "change" or "delete". + ChangeType DSRChangeType `json:"changeType" db:"change_type"` + // CreatedAt is the date/time at which the Delivery Service Request was + // created. + CreatedAt time.Time `json:"createdAt" db:"created_at"` + // ID is the integral, unique identifier for the Delivery Service Request + // if/when it is known. + ID *int `json:"id" db:"id"` + // LastEditedBy is the username of the user by whom the Delivery Service + // Request was last edited. + LastEditedBy string `json:"lastEditedBy"` + // LastEditedByID is the integral, unique identifier of the user by whom the + // Delivery Service Request was last edited, if/when it is known. + LastEditedByID *int `json:"-" db:"last_edited_by_id"` + // LastUpdated is the date/time at which the Delivery Service was last + // modified. + LastUpdated time.Time `json:"lastUpdated" db:"last_updated"` + // Original is the original Delivery Service for which changes are + // requested. This is present in responses only for ChangeTypes 'change' and + // 'delete', and is only required in requests where ChangeType is 'delete'. + Original *DeliveryServiceV5 `json:"original,omitempty" db:"original"` + // Requested is the set of requested changes. This is present in responses + // only for ChangeTypes 'change' and 'create', and is only required in + // requests in those cases. + Requested *DeliveryServiceV5 `json:"requested,omitempty" db:"deliveryservice"` + // Status is the status of the Delivery Service Request. + Status RequestStatus `json:"status" db:"status"` + // Used internally to define the affected Delivery Service. + XMLID string `json:"-"` +} + +// DeliveryServiceRequestV5 is the type of a Delivery Service Request as it +// appears in API version 5. +type DeliveryServiceRequestV5 = DeliveryServiceRequestV50 + +// Downgrade coerces the DeliveryServiceRequestV50 to the older +// DeliveryServiceRequestV40 structure. +// +// "XMLID" will be copied directly, not determined from Requested or Original. +// +// All reference properties are "deep"-copied so they may be modified without +// affecting the original. Delivery Service properties (i.e. Requested and +// Original) are copied using the DeliveryServiceV5.Downgrade method (which is +// also deep). +func (dsr DeliveryServiceRequestV5) Downgrade() DeliveryServiceRequestV4 { + downgraded := DeliveryServiceRequestV4{ + Assignee: copyStringIfNotNil(dsr.Assignee), + AssigneeID: copyIntIfNotNil(dsr.AssigneeID), + Author: dsr.Author, + AuthorID: copyIntIfNotNil(dsr.AuthorID), + ChangeType: dsr.ChangeType, + CreatedAt: dsr.CreatedAt, + ID: copyIntIfNotNil(dsr.ID), + LastEditedBy: dsr.LastEditedBy, + LastEditedByID: copyIntIfNotNil(dsr.LastEditedByID), + LastUpdated: dsr.LastUpdated, + Status: dsr.Status, + XMLID: dsr.XMLID, + } + if dsr.Requested != nil { + downgraded.Requested = new(DeliveryServiceV4) + *downgraded.Requested = dsr.Requested.Downgrade() + } else if dsr.Original != nil { + downgraded.Original = new(DeliveryServiceV4) + *downgraded.Original = dsr.Original.Downgrade() + } + return downgraded +} + +// Upgrade coerces the DeliveryServiceRequestV4 to the newer +// DeliveryServiceRequestV5 structure. +// +// "XMLID" will be copied directly, not determined from Requested or Original. +// +// All reference properties are "deep"-copied so they may be modified without +// affecting the original. Delivery Service properties (i.e. Requested and +// Original) are copied using the DeliveryServiceV4.Upgrade method (which is +// also deep). +func (dsr DeliveryServiceRequestV4) Upgrade() DeliveryServiceRequestV5 { + downgraded := DeliveryServiceRequestV5{ + Assignee: copyStringIfNotNil(dsr.Assignee), + AssigneeID: copyIntIfNotNil(dsr.AssigneeID), + Author: dsr.Author, + AuthorID: copyIntIfNotNil(dsr.AuthorID), + ChangeType: dsr.ChangeType, + CreatedAt: dsr.CreatedAt, + ID: copyIntIfNotNil(dsr.ID), + LastEditedBy: dsr.LastEditedBy, + LastEditedByID: copyIntIfNotNil(dsr.LastEditedByID), + LastUpdated: dsr.LastUpdated, + Status: dsr.Status, + XMLID: dsr.XMLID, + } + if dsr.Requested != nil { + downgraded.Requested = new(DeliveryServiceV5) + *downgraded.Requested = dsr.Requested.Upgrade() + } else if dsr.Original != nil { + downgraded.Original = new(DeliveryServiceV5) + *downgraded.Original = dsr.Original.Upgrade() + } + return downgraded +} + +// IsOpen returns whether or not the Delivery Service Request is still "open" - +// i.e. has not been rejected or completed. +func (dsr DeliveryServiceRequestV5) IsOpen() bool { + return !dsr.IsClosed() +} + +// IsClosed returns whether or not the Delivery Service Request has been +// "closed", by being either rejected or completed. +func (dsr DeliveryServiceRequestV5) IsClosed() bool { + return dsr.Status == RequestStatusComplete || dsr.Status == RequestStatusRejected || dsr.Status == RequestStatusPending +} + +// String encodes the DeliveryServiceRequestV5 as a string, in the format +// "DeliveryServiceRequestV5({{Property}}={{Value}}[, {{Property}}={{Value}}]+)". +// +// If a property is a pointer value, then its dereferenced value is used - +// unless it's nil, in which case "" is used as the value. DeliveryService +// is omitted, because of how large it is. Times are formatted in RFC3339 format. +func (dsr DeliveryServiceRequestV5) String() string { + return dsrString( + "DeliveryServiceRequestV5", + dsr.Author, + dsr.LastEditedBy, + dsr.ChangeType.String(), + dsr.Status.String(), + dsr.Assignee, + dsr.CreatedAt, + dsr.LastUpdated, + dsr.AssigneeID, + dsr.AuthorID, + dsr.ID, + dsr.LastEditedByID, + ) +} + +// SetXMLID sets the DeliveryServiceRequestV5's XMLID based on its DeliveryService. +func (dsr *DeliveryServiceRequestV5) SetXMLID() { + if dsr == nil { + return + } + + if dsr.ChangeType == DSRChangeTypeDelete && dsr.Original != nil { + dsr.XMLID = dsr.Original.XMLID + return + } + + if dsr.Requested != nil { + dsr.XMLID = dsr.Requested.XMLID + } +} + // StatusChangeRequest is the form of a PUT request body to // /deliveryservice_requests/{{ID}}/status. type StatusChangeRequest struct { @@ -932,3 +1128,19 @@ type DeliveryServiceRequestsResponseV40 struct { // for Delivery Service Requests using the latest minor version of API version // 4. type DeliveryServiceRequestsResponseV4 = DeliveryServiceRequestsResponseV40 + +// DeliveryServiceRequestResponseV50 is the type of a response from +// Traffic Ops when creating, updating, or deleting a Delivery Service Request +// using the latest minor version of API version 5. +type DeliveryServiceRequestResponseV5 struct { + Response DeliveryServiceRequestV5 `json:"response"` + Alerts +} + +// DeliveryServiceRequestsResponseV5 is the type of a response from Traffic Ops +// for Delivery Service Requests using the latest minor version of API version +// 5. +type DeliveryServiceRequestsResponseV5 struct { + Response []DeliveryServiceRequestV5 `json:"response"` + Alerts +} diff --git a/lib/go-tc/deliveryservice_requests_test.go b/lib/go-tc/deliveryservice_requests_test.go index 2a6b00d07f..44b62f8b93 100644 --- a/lib/go-tc/deliveryservice_requests_test.go +++ b/lib/go-tc/deliveryservice_requests_test.go @@ -24,8 +24,11 @@ import ( "encoding/json" "errors" "fmt" + "reflect" "testing" "time" + + "github.com/apache/trafficcontrol/lib/go-util" ) func TestStatus(t *testing.T) { @@ -34,12 +37,12 @@ func TestStatus(t *testing.T) { name string } tests := []tester{ - tester{RequestStatus("foo"), "invalid"}, - tester{RequestStatusDraft, "draft"}, - tester{RequestStatusSubmitted, "submitted"}, - tester{RequestStatusRejected, "rejected"}, - tester{RequestStatusPending, "pending"}, - tester{RequestStatusComplete, "complete"}, + {RequestStatus("foo"), "invalid"}, + {RequestStatusDraft, "draft"}, + {RequestStatusSubmitted, "submitted"}, + {RequestStatusRejected, "rejected"}, + {RequestStatusPending, "pending"}, + {RequestStatusComplete, "complete"}, } for _, tst := range tests { @@ -54,11 +57,11 @@ func TestStatusTransition(t *testing.T) { bad := errors.New("bad error") var validTests = [][]error{ // To: Dra Sub Rej Pen Com // From: - []error{nil, nil, bad, bad, bad}, // Draft - []error{nil, nil, nil, nil, nil}, // Submitted - []error{bad, bad, bad, bad, bad}, // Rejected - []error{bad, bad, bad, nil, nil}, // Pending - []error{bad, bad, bad, bad, bad}, // Complete + {nil, nil, bad, bad, bad}, // Draft + {nil, nil, nil, nil, nil}, // Submitted + {bad, bad, bad, bad, bad}, // Rejected + {bad, bad, bad, nil, nil}, // Pending + {bad, bad, bad, bad, bad}, // Complete } // test all transitions @@ -223,3 +226,60 @@ func ExampleDeliveryServiceRequestV40_SetXMLID() { // Output: true // test } + +func ExampleDeliveryServiceRequestV5_String() { + var dsr DeliveryServiceRequestV50 + fmt.Println(dsr.String()) + + // Output: DeliveryServiceRequestV5(Assignee=, AssigneeID=, Author="", AuthorID=, ChangeType="", CreatedAt=0001-01-01T00:00:00Z, ID=, LastEditedBy="", LastEditedByID=, LastUpdated=0001-01-01T00:00:00Z, Status="") +} + +func ExampleDeliveryServiceRequestV5_SetXMLID() { + var dsr DeliveryServiceRequestV5 + fmt.Println(dsr.XMLID == "") + + dsr.Requested = new(DeliveryServiceV5) + dsr.Requested.XMLID = "test" + dsr.SetXMLID() + + fmt.Println(dsr.XMLID) + + // Output: true + // test +} + +func TestDeliveryServiceRequestV4UpgradeAndV5Downgrade(t *testing.T) { + _, ds := dsUpgradeAndDowngradeTestingPair() + ds.RemoveLD1AndLD2() + + dsr := DeliveryServiceRequestV4{ + Assignee: util.StrPtr("assignee"), + AssigneeID: util.IntPtr(1), + Author: "author", + AuthorID: util.IntPtr(2), + ChangeType: DSRChangeTypeCreate, + CreatedAt: time.Time{}, + ID: util.IntPtr(3), + LastEditedBy: "last edited by", + LastEditedByID: util.IntPtr(4), + LastUpdated: time.Now(), + Requested: &ds, + Status: RequestStatusComplete, + } + cpy := dsr.Upgrade().Downgrade() + + if !reflect.DeepEqual(dsr, cpy) { + bts, err := json.MarshalIndent(dsr, "", "\t") + if err != nil { + t.Fatalf("failed to encode original DSR after upgrade/downgrade comparison failed: %v", err) + } + t.Logf("original: %s", bts) + bts, err = json.MarshalIndent(cpy, "", "\t") + if err != nil { + t.Fatalf("failed to encode upgraded-then-downgraded DSR after upgrade/downgrade comparison failed: %v", err) + } + t.Logf("upgraded-then-downgraded: %s", bts) + t.Error("Delivery Service Request upgrade followed by downgrade should result in exact copy") + + } +} From eab0ec04b7a9ccf062f138c8af0b414d02397fa2 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Thu, 22 Sep 2022 10:46:05 -0600 Subject: [PATCH 09/48] Fix atc dev environment default DS --- dev/traffic_ops/seed.psql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev/traffic_ops/seed.psql b/dev/traffic_ops/seed.psql index 5f30def8e8..679cb7f5b3 100644 --- a/dev/traffic_ops/seed.psql +++ b/dev/traffic_ops/seed.psql @@ -294,7 +294,7 @@ INSERT INTO deliveryservice ( miss_long ) VALUES ( 'dev-ds', - TRUE, + 'ACTIVE', 1, 0, (SELECT id FROM "type" WHERE "name" = 'HTTP'), From 61cb18f85d6b9605c1a31251115c6123f2339c4f Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Thu, 22 Sep 2022 10:48:27 -0600 Subject: [PATCH 10/48] Add API testing utils package GoDoc comments Also made FindNeedle generic for no particular reason --- traffic_ops/testing/api/utils/utils.go | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/traffic_ops/testing/api/utils/utils.go b/traffic_ops/testing/api/utils/utils.go index 6315d5af66..ec7c318348 100644 --- a/traffic_ops/testing/api/utils/utils.go +++ b/traffic_ops/testing/api/utils/utils.go @@ -1,3 +1,9 @@ +// Package utils provides helpful utilities for easing the process of testing +// Traffic Ops API clients. The functions here don't depend on any particular +// API version, so they need not be copy/pasted along with the entire testing +// suites. +package utils + /* Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,8 +19,6 @@ limitations under the License. */ -package utils - import ( "encoding/json" "net/http" @@ -37,7 +41,9 @@ type ErrorAndMessage struct { Message string } -func FindNeedle(needle string, haystack []string) bool { +// FindNeedle searches a "haystack" slice of values for the the "needle" value, +// returning true if the value is in the haystack, false otherwise. +func FindNeedle[T comparable](needle T, haystack []T) bool { found := false for _, s := range haystack { if s == needle { @@ -48,6 +54,8 @@ func FindNeedle(needle string, haystack []string) bool { return found } +// ErrorsToStrings converts a slice of errors to a slice of their error +// messages. func ErrorsToStrings(errs []error) []string { errorStrs := []string{} for _, errType := range errs { @@ -57,6 +65,11 @@ func ErrorsToStrings(errs []error) []string { return errorStrs } +// Compare compares a set of expected alert messages to those actually received. +// It checks for the existence of each expected alert, not that they appear in +// any particular order. It also checks that no unexpected alert strings exist. +// Note that this isn't particularly efficient, which is fine because it's only +// meant to be used in testing. func Compare(t *testing.T, expected []string, alertsStrs []string) { sort.Strings(alertsStrs) expectedFmt, _ := json.MarshalIndent(expected, "", " ") @@ -100,8 +113,8 @@ func CreateV4Session(t *testing.T, TrafficOpsURL string, username string, passwo } // CreateV5Session creates a session for client v5 using the passed in username and password. -func CreateV5Session(t *testing.T, TrafficOpsURL, username, password string, toReqTimeout int) *v5client.Session { - userSession, _, err := v5client.LoginWithAgent(TrafficOpsURL, username, password, true, "to-api-v5-client-tests", false, time.Second*time.Duration(toReqTimeout)) +func CreateV5Session(t *testing.T, trafficOpsURL, username, password string, toReqTimeout int) *v5client.Session { + userSession, _, err := v5client.LoginWithAgent(trafficOpsURL, username, password, true, "to-api-v5-client-tests", false, time.Second*time.Duration(toReqTimeout)) assert.RequireNoError(t, err, "Could not login with user %v: %v", username, err) return userSession } From cbd367bc0b49fc74c09a57e97dbbb992b1e8e2bb Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Thu, 22 Sep 2022 10:48:45 -0600 Subject: [PATCH 11/48] Remove unused testing utility structure --- traffic_ops/testing/api/utils/utils.go | 5 ----- 1 file changed, 5 deletions(-) diff --git a/traffic_ops/testing/api/utils/utils.go b/traffic_ops/testing/api/utils/utils.go index ec7c318348..274c647195 100644 --- a/traffic_ops/testing/api/utils/utils.go +++ b/traffic_ops/testing/api/utils/utils.go @@ -36,11 +36,6 @@ import ( v5client "github.com/apache/trafficcontrol/traffic_ops/v5-client" ) -type ErrorAndMessage struct { - Error error - Message string -} - // FindNeedle searches a "haystack" slice of values for the the "needle" value, // returning true if the value is in the haystack, false otherwise. func FindNeedle[T comparable](needle T, haystack []T) bool { From e7d83fdf16919fda75a0f54bacc033a5cfa99cd4 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Thu, 22 Sep 2022 10:50:16 -0600 Subject: [PATCH 12/48] Fix helper functions not calling testing.T.Helper() Also slight performance improvement to ErrorsToStrings --- traffic_ops/testing/api/utils/utils.go | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/traffic_ops/testing/api/utils/utils.go b/traffic_ops/testing/api/utils/utils.go index 274c647195..33c20a6ec5 100644 --- a/traffic_ops/testing/api/utils/utils.go +++ b/traffic_ops/testing/api/utils/utils.go @@ -52,10 +52,9 @@ func FindNeedle[T comparable](needle T, haystack []T) bool { // ErrorsToStrings converts a slice of errors to a slice of their error // messages. func ErrorsToStrings(errs []error) []string { - errorStrs := []string{} - for _, errType := range errs { - et := errType.Error() - errorStrs = append(errorStrs, et) + errorStrs := make([]string, 0, len(errs)) + for _, err := range errs { + errorStrs = append(errorStrs, err.Error()) } return errorStrs } @@ -66,6 +65,7 @@ func ErrorsToStrings(errs []error) []string { // Note that this isn't particularly efficient, which is fine because it's only // meant to be used in testing. func Compare(t *testing.T, expected []string, alertsStrs []string) { + t.Helper() sort.Strings(alertsStrs) expectedFmt, _ := json.MarshalIndent(expected, "", " ") errorsFmt, _ := json.MarshalIndent(alertsStrs, "", " ") @@ -96,6 +96,7 @@ func Compare(t *testing.T, expected []string, alertsStrs []string) { // CreateV3Session creates a session for client v4 using the passed in username and password. func CreateV3Session(t *testing.T, TrafficOpsURL string, username string, password string, toReqTimeout int) *v3client.Session { userSession, _, err := v3client.LoginWithAgent(TrafficOpsURL, username, password, true, "to-api-v3-client-tests", false, time.Second*time.Duration(toReqTimeout)) + t.Helper() assert.RequireNoError(t, err, "Could not login with user %v: %v", username, err) return userSession } @@ -103,12 +104,14 @@ func CreateV3Session(t *testing.T, TrafficOpsURL string, username string, passwo // CreateV4Session creates a session for client v4 using the passed in username and password. func CreateV4Session(t *testing.T, TrafficOpsURL string, username string, password string, toReqTimeout int) *v4client.Session { userSession, _, err := v4client.LoginWithAgent(TrafficOpsURL, username, password, true, "to-api-v4-client-tests", false, time.Second*time.Duration(toReqTimeout)) + t.Helper() assert.RequireNoError(t, err, "Could not login with user %v: %v", username, err) return userSession } // CreateV5Session creates a session for client v5 using the passed in username and password. func CreateV5Session(t *testing.T, trafficOpsURL, username, password string, toReqTimeout int) *v5client.Session { + t.Helper() userSession, _, err := v5client.LoginWithAgent(trafficOpsURL, username, password, true, "to-api-v5-client-tests", false, time.Second*time.Duration(toReqTimeout)) assert.RequireNoError(t, err, "Could not login with user %v: %v", username, err) return userSession @@ -204,6 +207,7 @@ func CkRequest(c ...CkReqFunc) []CkReqFunc { // NoError checks that no error was returned (i.e. `nil`). func NoError() CkReqFunc { return func(t *testing.T, _ toclientlib.ReqInf, _ interface{}, _ tc.Alerts, err error) { + t.Helper() assert.NoError(t, err, "Expected no error. Got: %v", err) } } @@ -211,6 +215,7 @@ func NoError() CkReqFunc { // HasError checks that an error was returned (i.e. not `nil`). func HasError() CkReqFunc { return func(t *testing.T, _ toclientlib.ReqInf, _ interface{}, alerts tc.Alerts, err error) { + t.Helper() assert.Error(t, err, "Expected error. Got: %v", alerts) } } @@ -218,6 +223,7 @@ func HasError() CkReqFunc { // HasStatus checks that the status code from the request is as expected. func HasStatus(expectedStatus int) CkReqFunc { return func(t *testing.T, reqInf toclientlib.ReqInf, _ interface{}, _ tc.Alerts, _ error) { + t.Helper() assert.Equal(t, expectedStatus, reqInf.StatusCode, "Expected Status Code: %d Got: %d", expectedStatus, reqInf.StatusCode) } } @@ -225,6 +231,7 @@ func HasStatus(expectedStatus int) CkReqFunc { // HasAlertLevel checks that the alert from the request matches the expected level. func HasAlertLevel(expectedAlertLevel string) CkReqFunc { return func(t *testing.T, _ toclientlib.ReqInf, _ interface{}, alerts tc.Alerts, _ error) { + t.Helper() assert.RequireNotNil(t, alerts, "Expected alerts to not be nil.") found := false for _, alert := range alerts.Alerts { @@ -240,6 +247,7 @@ func HasAlertLevel(expectedAlertLevel string) CkReqFunc { // Determines that response is a slice before checking the length of the reflected value. func ResponseHasLength(expected int) CkReqFunc { return func(t *testing.T, _ toclientlib.ReqInf, resp interface{}, _ tc.Alerts, _ error) { + t.Helper() rt := reflect.TypeOf(resp) switch rt.Kind() { case reflect.Slice: @@ -255,6 +263,7 @@ func ResponseHasLength(expected int) CkReqFunc { // Determines that response is a slice before checking the length of the reflected value. func ResponseLengthGreaterOrEqual(expected int) CkReqFunc { return func(t *testing.T, _ toclientlib.ReqInf, resp interface{}, _ tc.Alerts, _ error) { + t.Helper() rt := reflect.TypeOf(resp) switch rt.Kind() { case reflect.Slice: From 8507f014b341497e17e02df4150f42a01b7d6229 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Thu, 22 Sep 2022 11:01:07 -0600 Subject: [PATCH 13/48] Fix non-idiomatic name case in testing utilities Also fixed some import ordering, specifically in types_test.go --- traffic_ops/testing/api/utils/utils.go | 18 ++--- traffic_ops/testing/api/v3/asns_test.go | 4 +- .../testing/api/v3/cachegroups_test.go | 14 ++-- .../v3/cachegroupsdeliveryservices_test.go | 6 +- .../testing/api/v3/cdn_federations_test.go | 10 +-- traffic_ops/testing/api/v3/cdns_test.go | 10 +-- .../testing/api/v3/coordinates_test.go | 10 +-- .../deliveryservice_request_comments_test.go | 12 +-- .../api/v3/deliveryservice_requests_test.go | 14 ++-- ...veryservices_required_capabilities_test.go | 8 +- .../testing/api/v3/deliveryservices_test.go | 46 +++++------ .../api/v3/deliveryserviceservers_test.go | 8 +- .../api/v3/deliveryservicesideligible_test.go | 4 +- .../api/v3/deliveryservicesregexes_test.go | 10 +-- traffic_ops/testing/api/v3/divisions_test.go | 12 +-- .../v3/federation_deliveryservices_test.go | 12 +-- .../federation_federation_resolvers_test.go | 16 ++-- .../api/v3/federation_resolvers_test.go | 4 +- .../testing/api/v3/federation_users_test.go | 20 ++--- traffic_ops/testing/api/v3/jobs_test.go | 2 +- traffic_ops/testing/api/v3/loginfail_test.go | 4 +- traffic_ops/testing/api/v3/origins_test.go | 18 ++--- traffic_ops/testing/api/v3/parameters_test.go | 10 +-- .../testing/api/v3/phys_locations_test.go | 14 ++-- .../testing/api/v3/profile_parameters_test.go | 4 +- .../testing/api/v3/profiles_export_test.go | 6 +- traffic_ops/testing/api/v3/profiles_test.go | 10 +-- traffic_ops/testing/api/v3/regions_test.go | 8 +- traffic_ops/testing/api/v3/roles_test.go | 20 ++--- .../v3/servers_id_deliveryservices_test.go | 20 ++--- .../api/v3/servers_id_queue_update_test.go | 8 +- .../testing/api/v3/servers_id_status_test.go | 18 ++--- traffic_ops/testing/api/v3/servers_test.go | 30 +++---- .../testing/api/v3/staticdnsentries_test.go | 18 ++--- traffic_ops/testing/api/v3/statuses_test.go | 10 +-- .../testing/api/v3/steeringtargets_test.go | 10 +-- traffic_ops/testing/api/v3/tenants_test.go | 14 ++-- traffic_ops/testing/api/v3/types_test.go | 15 ++-- traffic_ops/testing/api/v3/users_test.go | 12 +-- traffic_ops/testing/api/v4/asns_test.go | 4 +- .../testing/api/v4/cachegroups_test.go | 20 ++--- .../v4/cachegroupsdeliveryservices_test.go | 6 +- .../testing/api/v4/cdn_federations_test.go | 10 +-- traffic_ops/testing/api/v4/cdn_locks_test.go | 78 +++++++++---------- .../testing/api/v4/cdn_queue_updates_test.go | 10 +-- traffic_ops/testing/api/v4/cdns_test.go | 12 +-- .../testing/api/v4/coordinates_test.go | 14 ++-- .../deliveryservice_request_comments_test.go | 8 +- .../api/v4/deliveryservice_requests_test.go | 16 ++-- .../testing/api/v4/deliveryservices_test.go | 54 ++++++------- .../api/v4/deliveryserviceservers_test.go | 4 +- .../api/v4/deliveryservicesideligible_test.go | 4 +- .../api/v4/deliveryservicesregexes_test.go | 10 +-- traffic_ops/testing/api/v4/divisions_test.go | 14 ++-- .../v4/federation_deliveryservices_test.go | 28 +++---- .../federation_federation_resolvers_test.go | 16 ++-- .../api/v4/federation_resolvers_test.go | 4 +- .../testing/api/v4/federation_users_test.go | 36 ++++----- traffic_ops/testing/api/v4/jobs_test.go | 4 +- traffic_ops/testing/api/v4/origins_test.go | 36 ++++----- traffic_ops/testing/api/v4/parameters_test.go | 18 ++--- .../testing/api/v4/phys_locations_test.go | 12 +-- .../testing/api/v4/profile_parameters_test.go | 4 +- .../testing/api/v4/profiles_export_test.go | 6 +- traffic_ops/testing/api/v4/profiles_test.go | 10 +-- traffic_ops/testing/api/v4/regions_test.go | 8 +- .../v4/servers_id_deliveryservices_test.go | 22 +++--- .../api/v4/servers_id_queue_update_test.go | 8 +- .../testing/api/v4/servers_id_status_test.go | 20 ++--- traffic_ops/testing/api/v4/servers_test.go | 32 ++++---- .../testing/api/v4/staticdnsentries_test.go | 18 ++--- traffic_ops/testing/api/v4/statuses_test.go | 10 +-- .../testing/api/v4/steeringtargets_test.go | 10 +-- traffic_ops/testing/api/v4/tenants_test.go | 14 ++-- traffic_ops/testing/api/v4/types_test.go | 15 ++-- traffic_ops/testing/api/v4/users_test.go | 12 +-- traffic_ops/testing/api/v5/asns_test.go | 4 +- .../testing/api/v5/cachegroups_test.go | 20 ++--- .../v5/cachegroupsdeliveryservices_test.go | 6 +- .../testing/api/v5/cdn_federations_test.go | 10 +-- traffic_ops/testing/api/v5/cdn_locks_test.go | 78 +++++++++---------- .../testing/api/v5/cdn_queue_updates_test.go | 10 +-- traffic_ops/testing/api/v5/cdns_test.go | 12 +-- .../testing/api/v5/coordinates_test.go | 14 ++-- .../deliveryservice_request_comments_test.go | 8 +- .../api/v5/deliveryservice_requests_test.go | 16 ++-- .../testing/api/v5/deliveryservices_test.go | 54 ++++++------- .../api/v5/deliveryserviceservers_test.go | 10 +-- .../api/v5/deliveryservicesideligible_test.go | 4 +- .../api/v5/deliveryservicesregexes_test.go | 10 +-- traffic_ops/testing/api/v5/divisions_test.go | 14 ++-- .../v5/federation_deliveryservices_test.go | 28 +++---- .../federation_federation_resolvers_test.go | 16 ++-- .../api/v5/federation_resolvers_test.go | 4 +- .../testing/api/v5/federation_users_test.go | 36 ++++----- traffic_ops/testing/api/v5/jobs_test.go | 4 +- traffic_ops/testing/api/v5/origins_test.go | 36 ++++----- traffic_ops/testing/api/v5/parameters_test.go | 18 ++--- .../testing/api/v5/phys_locations_test.go | 12 +-- .../testing/api/v5/profile_parameters_test.go | 4 +- .../testing/api/v5/profiles_export_test.go | 6 +- traffic_ops/testing/api/v5/profiles_test.go | 10 +-- traffic_ops/testing/api/v5/regions_test.go | 8 +- .../v5/servers_id_deliveryservices_test.go | 22 +++--- .../api/v5/servers_id_queue_update_test.go | 8 +- .../testing/api/v5/servers_id_status_test.go | 20 ++--- traffic_ops/testing/api/v5/servers_test.go | 32 ++++---- .../testing/api/v5/staticdnsentries_test.go | 18 ++--- traffic_ops/testing/api/v5/statuses_test.go | 10 +-- .../testing/api/v5/steeringtargets_test.go | 10 +-- traffic_ops/testing/api/v5/tenants_test.go | 14 ++-- traffic_ops/testing/api/v5/types_test.go | 15 ++-- traffic_ops/testing/api/v5/users_test.go | 12 +-- 113 files changed, 853 insertions(+), 856 deletions(-) diff --git a/traffic_ops/testing/api/utils/utils.go b/traffic_ops/testing/api/utils/utils.go index 33c20a6ec5..8ada052298 100644 --- a/traffic_ops/testing/api/utils/utils.go +++ b/traffic_ops/testing/api/utils/utils.go @@ -94,17 +94,17 @@ func Compare(t *testing.T, expected []string, alertsStrs []string) { } // CreateV3Session creates a session for client v4 using the passed in username and password. -func CreateV3Session(t *testing.T, TrafficOpsURL string, username string, password string, toReqTimeout int) *v3client.Session { - userSession, _, err := v3client.LoginWithAgent(TrafficOpsURL, username, password, true, "to-api-v3-client-tests", false, time.Second*time.Duration(toReqTimeout)) +func CreateV3Session(t *testing.T, trafficOpsURL string, username string, password string, toReqTimeout int) *v3client.Session { t.Helper() + userSession, _, err := v3client.LoginWithAgent(trafficOpsURL, username, password, true, "to-api-v3-client-tests", false, time.Second*time.Duration(toReqTimeout)) assert.RequireNoError(t, err, "Could not login with user %v: %v", username, err) return userSession } // CreateV4Session creates a session for client v4 using the passed in username and password. -func CreateV4Session(t *testing.T, TrafficOpsURL string, username string, password string, toReqTimeout int) *v4client.Session { - userSession, _, err := v4client.LoginWithAgent(TrafficOpsURL, username, password, true, "to-api-v4-client-tests", false, time.Second*time.Duration(toReqTimeout)) +func CreateV4Session(t *testing.T, trafficOpsURL string, username string, password string, toReqTimeout int) *v4client.Session { t.Helper() + userSession, _, err := v4client.LoginWithAgent(trafficOpsURL, username, password, true, "to-api-v4-client-tests", false, time.Second*time.Duration(toReqTimeout)) assert.RequireNoError(t, err, "Could not login with user %v: %v", username, err) return userSession } @@ -119,7 +119,7 @@ func CreateV5Session(t *testing.T, trafficOpsURL, username, password string, toR // V3TestData represents the data needed for testing the v3 api endpoints. type V3TestData struct { - EndpointId func() int + EndpointID func() int ClientSession *v3client.Session RequestParams url.Values RequestHeaders http.Header @@ -130,7 +130,7 @@ type V3TestData struct { // V3TestDataT represents the data needed for testing the v3 api endpoints. type V3TestDataT[B any] struct { - EndpointId func() int + EndpointID func() int ClientSession *v3client.Session RequestParams url.Values RequestHeaders http.Header @@ -140,7 +140,7 @@ type V3TestDataT[B any] struct { // V4TestData represents the data needed for testing the v4 api endpoints. type V4TestData struct { - EndpointId func() int + EndpointID func() int ClientSession *v4client.Session RequestOpts v4client.RequestOptions RequestBody map[string]interface{} @@ -150,7 +150,7 @@ type V4TestData struct { // V5TestData represents the data needed for testing the v5 api endpoints. type V5TestData struct { - EndpointId func() int + EndpointID func() int ClientSession *v5client.Session RequestOpts v5client.RequestOptions RequestBody map[string]interface{} @@ -168,7 +168,7 @@ type requestOpts interface { // TestData represents the data needed for testing the api endpoints. type TestData[C clientSession, R requestOpts, B any] struct { - EndpointId func() int + EndpointID func() int ClientSession *C RequestOpts R RequestBody B diff --git a/traffic_ops/testing/api/v3/asns_test.go b/traffic_ops/testing/api/v3/asns_test.go index 5d27015c22..715eec7a98 100644 --- a/traffic_ops/testing/api/v3/asns_test.go +++ b/traffic_ops/testing/api/v3/asns_test.go @@ -63,7 +63,7 @@ func TestASN(t *testing.T) { }, "PUT": { "OK when VALID request": { - ClientSession: TOSession, EndpointId: GetASNID(t, "8888"), + ClientSession: TOSession, EndpointID: GetASNID(t, "8888"), RequestBody: map[string]interface{}{ "asn": 7777, "cachegroupName": "originCachegroup", @@ -97,7 +97,7 @@ func TestASN(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateASNByID(testCase.EndpointId(), asn) + alerts, reqInf, err := testCase.ClientSession.UpdateASNByID(testCase.EndpointID(), asn) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/cachegroups_test.go b/traffic_ops/testing/api/v3/cachegroups_test.go index fe2faae568..8e8a08e731 100644 --- a/traffic_ops/testing/api/v3/cachegroups_test.go +++ b/traffic_ops/testing/api/v3/cachegroups_test.go @@ -94,7 +94,7 @@ func TestCacheGroups(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetCacheGroupId(t, "cachegroup1"), + EndpointID: GetCacheGroupId(t, "cachegroup1"), ClientSession: TOSession, RequestBody: tc.CacheGroupNullable{ Latitude: util.Ptr(17.5), @@ -109,7 +109,7 @@ func TestCacheGroups(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetCacheGroupId(t, "cachegroup1"), ClientSession: TOSession, + EndpointID: GetCacheGroupId(t, "cachegroup1"), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}, RequestBody: tc.CacheGroupNullable{ Name: util.Ptr("cachegroup1"), @@ -120,7 +120,7 @@ func TestCacheGroups(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetCacheGroupId(t, "cachegroup1"), + EndpointID: GetCacheGroupId(t, "cachegroup1"), ClientSession: TOSession, RequestBody: tc.CacheGroupNullable{ Name: util.Ptr("cachegroup1"), @@ -132,14 +132,14 @@ func TestCacheGroups(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "UNAUTHORIZED when NOT LOGGED IN": { - EndpointId: GetCacheGroupId(t, "cachegroup1"), + EndpointID: GetCacheGroupId(t, "cachegroup1"), ClientSession: NoAuthTOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusUnauthorized)), }, }, "DELETE": { "UNAUTHORIZED when NOT LOGGED IN": { - EndpointId: GetCacheGroupId(t, "cachegroup1"), + EndpointID: GetCacheGroupId(t, "cachegroup1"), ClientSession: NoAuthTOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusUnauthorized)), }, @@ -166,14 +166,14 @@ func TestCacheGroups(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.UpdateCacheGroupNullableByIDWithHdr(testCase.EndpointId(), testCase.RequestBody, testCase.RequestHeaders) + resp, reqInf, err := testCase.ClientSession.UpdateCacheGroupNullableByIDWithHdr(testCase.EndpointID(), testCase.RequestBody, testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteCacheGroupByID(testCase.EndpointId()) + alerts, reqInf, err := testCase.ClientSession.DeleteCacheGroupByID(testCase.EndpointID()) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/cachegroupsdeliveryservices_test.go b/traffic_ops/testing/api/v3/cachegroupsdeliveryservices_test.go index a78ff2246e..7534cdb217 100644 --- a/traffic_ops/testing/api/v3/cachegroupsdeliveryservices_test.go +++ b/traffic_ops/testing/api/v3/cachegroupsdeliveryservices_test.go @@ -33,13 +33,13 @@ func TestCacheGroupsDeliveryServices(t *testing.T) { methodTests := utils.V3TestCaseT[[]int]{ "POST": { "BAD REQUEST assigning TOPOLOGY-BASED DS to CACHEGROUP": { - EndpointId: GetCacheGroupId(t, "cachegroup3"), + EndpointID: GetCacheGroupId(t, "cachegroup3"), ClientSession: TOSession, RequestBody: []int{GetDeliveryServiceId(t, "top-ds-in-cdn1")()}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "OK when valid request": { - EndpointId: GetCacheGroupId(t, "cachegroup3"), + EndpointID: GetCacheGroupId(t, "cachegroup3"), ClientSession: TOSession, RequestBody: []int{ GetDeliveryServiceId(t, "ds1")(), @@ -58,7 +58,7 @@ func TestCacheGroupsDeliveryServices(t *testing.T) { switch method { case "POST": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.SetCachegroupDeliveryServices(testCase.EndpointId(), testCase.RequestBody) + resp, reqInf, err := testCase.ClientSession.SetCachegroupDeliveryServices(testCase.EndpointID(), testCase.RequestBody) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v3/cdn_federations_test.go b/traffic_ops/testing/api/v3/cdn_federations_test.go index 2d8165e0bb..592b5c5ccd 100644 --- a/traffic_ops/testing/api/v3/cdn_federations_test.go +++ b/traffic_ops/testing/api/v3/cdn_federations_test.go @@ -69,7 +69,7 @@ func TestCDNFederations(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetFederationID(t, "google.com."), + EndpointID: GetFederationID(t, "google.com."), ClientSession: TOSession, RequestBody: tc.CDNFederation{ CName: util.Ptr("new.cname."), @@ -79,7 +79,7 @@ func TestCDNFederations(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateCDNFederationUpdateFields(map[string]interface{}{"CName": "new.cname."})), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetFederationID(t, "booya.com."), + EndpointID: GetFederationID(t, "booya.com."), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}, RequestBody: tc.CDNFederation{ @@ -90,7 +90,7 @@ func TestCDNFederations(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetFederationID(t, "booya.com."), + EndpointID: GetFederationID(t, "booya.com."), ClientSession: TOSession, RequestBody: tc.CDNFederation{ CName: util.Ptr("new.cname."), @@ -136,14 +136,14 @@ func TestCDNFederations(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.UpdateCDNFederationsByIDWithHdr(testCase.RequestBody, cdnName, testCase.EndpointId(), testCase.RequestHeaders) + resp, reqInf, err := testCase.ClientSession.UpdateCDNFederationsByIDWithHdr(testCase.RequestBody, cdnName, testCase.EndpointID(), testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteCDNFederationByID(cdnName, testCase.EndpointId()) + alerts, reqInf, err := testCase.ClientSession.DeleteCDNFederationByID(cdnName, testCase.EndpointID()) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts.Alerts, err) } diff --git a/traffic_ops/testing/api/v3/cdns_test.go b/traffic_ops/testing/api/v3/cdns_test.go index 610307f393..d98785d7ff 100644 --- a/traffic_ops/testing/api/v3/cdns_test.go +++ b/traffic_ops/testing/api/v3/cdns_test.go @@ -74,7 +74,7 @@ func TestCDNs(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetCDNID(t, "cdn1"), + EndpointID: GetCDNID(t, "cdn1"), ClientSession: TOSession, RequestBody: tc.CDN{ DNSSECEnabled: false, @@ -85,7 +85,7 @@ func TestCDNs(t *testing.T) { validateCDNUpdateFields("cdn1", map[string]interface{}{"DomainName": "domain2"})), }, "PRECONDITION FAILED when updating with IF-UNMODIFIED-SINCE Headers": { - EndpointId: GetCDNID(t, "cdn1"), + EndpointID: GetCDNID(t, "cdn1"), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}, RequestBody: tc.CDN{ @@ -96,7 +96,7 @@ func TestCDNs(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetCDNID(t, "cdn1"), + EndpointID: GetCDNID(t, "cdn1"), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfMatch: {rfc.ETag(currentTime)}}, RequestBody: tc.CDN{ @@ -135,14 +135,14 @@ func TestCDNs(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateCDNByIDWithHdr(testCase.EndpointId(), testCase.RequestBody, testCase.RequestHeaders) + alerts, reqInf, err := testCase.ClientSession.UpdateCDNByIDWithHdr(testCase.EndpointID(), testCase.RequestBody, testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteCDNByID(testCase.EndpointId()) + alerts, reqInf, err := testCase.ClientSession.DeleteCDNByID(testCase.EndpointID()) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/coordinates_test.go b/traffic_ops/testing/api/v3/coordinates_test.go index ca6d91265c..403c360e17 100644 --- a/traffic_ops/testing/api/v3/coordinates_test.go +++ b/traffic_ops/testing/api/v3/coordinates_test.go @@ -61,7 +61,7 @@ func TestCoordinates(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetCoordinateID(t, "coordinate2"), + EndpointID: GetCoordinateID(t, "coordinate2"), ClientSession: TOSession, RequestBody: tc.Coordinate{ Latitude: 7.7, @@ -72,7 +72,7 @@ func TestCoordinates(t *testing.T) { validateCoordinateUpdateCreateFields("coordinate2", map[string]interface{}{"Latitude": 7.7, "Longitude": 8.8})), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetCoordinateID(t, "coordinate1"), + EndpointID: GetCoordinateID(t, "coordinate1"), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}, RequestBody: tc.Coordinate{ @@ -83,7 +83,7 @@ func TestCoordinates(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetCoordinateID(t, "coordinate1"), + EndpointID: GetCoordinateID(t, "coordinate1"), ClientSession: TOSession, RequestBody: tc.Coordinate{ Latitude: 1.1, @@ -123,14 +123,14 @@ func TestCoordinates(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateCoordinateByIDWithHdr(testCase.EndpointId(), testCase.RequestBody, testCase.RequestHeaders) + alerts, reqInf, err := testCase.ClientSession.UpdateCoordinateByIDWithHdr(testCase.EndpointID(), testCase.RequestBody, testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteCoordinateByID(testCase.EndpointId()) + alerts, reqInf, err := testCase.ClientSession.DeleteCoordinateByID(testCase.EndpointID()) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/deliveryservice_request_comments_test.go b/traffic_ops/testing/api/v3/deliveryservice_request_comments_test.go index d837786596..12c85fee91 100644 --- a/traffic_ops/testing/api/v3/deliveryservice_request_comments_test.go +++ b/traffic_ops/testing/api/v3/deliveryservice_request_comments_test.go @@ -47,7 +47,7 @@ func TestDeliveryServiceRequestComments(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when VALID ID parameter": { - EndpointId: GetDSRequestCommentId(t), + EndpointID: GetDSRequestCommentId(t), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseHasLength(1)), }, @@ -63,7 +63,7 @@ func TestDeliveryServiceRequestComments(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetDSRequestCommentId(t), + EndpointID: GetDSRequestCommentId(t), ClientSession: TOSession, RequestBody: tc.DeliveryServiceRequestComment{ DeliveryServiceRequestID: GetDSRequestId(t, "test-ds1")(), @@ -72,14 +72,14 @@ func TestDeliveryServiceRequestComments(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "PRECONDITION FAILED when updating with IF-UNMODIFIED-SINCE Header": { - EndpointId: GetDSRequestCommentId(t), + EndpointID: GetDSRequestCommentId(t), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}, RequestBody: tc.DeliveryServiceRequestComment{}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetDSRequestCommentId(t), + EndpointID: GetDSRequestCommentId(t), ClientSession: TOSession, RequestBody: tc.DeliveryServiceRequestComment{}, RequestHeaders: http.Header{rfc.IfMatch: {rfc.ETag(currentTime)}}, @@ -95,7 +95,7 @@ func TestDeliveryServiceRequestComments(t *testing.T) { case "GET": t.Run(name, func(t *testing.T) { if name == "OK when VALID ID parameter" { - resp, reqInf, err := testCase.ClientSession.GetDeliveryServiceRequestCommentByIDWithHdr(testCase.EndpointId(), testCase.RequestHeaders) + resp, reqInf, err := testCase.ClientSession.GetDeliveryServiceRequestCommentByIDWithHdr(testCase.EndpointID(), testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, resp, tc.Alerts{}, err) } @@ -108,7 +108,7 @@ func TestDeliveryServiceRequestComments(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateDeliveryServiceRequestCommentByIDWithHdr(testCase.EndpointId(), testCase.RequestBody, testCase.RequestHeaders) + alerts, reqInf, err := testCase.ClientSession.UpdateDeliveryServiceRequestCommentByIDWithHdr(testCase.EndpointID(), testCase.RequestBody, testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/deliveryservice_requests_test.go b/traffic_ops/testing/api/v3/deliveryservice_requests_test.go index c60813840b..2e43843fa9 100644 --- a/traffic_ops/testing/api/v3/deliveryservice_requests_test.go +++ b/traffic_ops/testing/api/v3/deliveryservice_requests_test.go @@ -53,7 +53,7 @@ func TestDeliveryServiceRequests(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetDeliveryServiceRequestId(t, "test-ds1"), + EndpointID: GetDeliveryServiceRequestId(t, "test-ds1"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "changeType": "create", @@ -67,7 +67,7 @@ func TestDeliveryServiceRequests(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when UPDATING STATUS FROM DRAFT TO SUBMITTED": { - EndpointId: GetDeliveryServiceRequestId(t, "test-ds1"), + EndpointID: GetDeliveryServiceRequestId(t, "test-ds1"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "changeType": "create", @@ -80,14 +80,14 @@ func TestDeliveryServiceRequests(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "PRECONDITION FAILED when updating with IF-UNMODIFIED-SINCE Header": { - EndpointId: GetDeliveryServiceRequestId(t, "test-ds1"), + EndpointID: GetDeliveryServiceRequestId(t, "test-ds1"), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}, RequestBody: map[string]interface{}{}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetDeliveryServiceRequestId(t, "test-ds1"), + EndpointID: GetDeliveryServiceRequestId(t, "test-ds1"), ClientSession: TOSession, RequestBody: map[string]interface{}{}, RequestHeaders: http.Header{rfc.IfMatch: {rfc.ETag(currentTime)}}, @@ -224,7 +224,7 @@ func TestDeliveryServiceRequests(t *testing.T) { }, "DELETE": { "OK when VALID request": { - EndpointId: GetDeliveryServiceRequestId(t, "test-deletion"), + EndpointID: GetDeliveryServiceRequestId(t, "test-deletion"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, @@ -274,14 +274,14 @@ func TestDeliveryServiceRequests(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateDeliveryServiceRequestByIDWithHdr(testCase.EndpointId(), dsReq, testCase.RequestHeaders) + alerts, reqInf, err := testCase.ClientSession.UpdateDeliveryServiceRequestByIDWithHdr(testCase.EndpointID(), dsReq, testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteDeliveryServiceRequestByID(testCase.EndpointId()) + alerts, reqInf, err := testCase.ClientSession.DeleteDeliveryServiceRequestByID(testCase.EndpointID()) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/deliveryservices_required_capabilities_test.go b/traffic_ops/testing/api/v3/deliveryservices_required_capabilities_test.go index caeeb7107e..0edaa64132 100644 --- a/traffic_ops/testing/api/v3/deliveryservices_required_capabilities_test.go +++ b/traffic_ops/testing/api/v3/deliveryservices_required_capabilities_test.go @@ -138,7 +138,7 @@ func TestDeliveryServicesRequiredCapabilities(t *testing.T) { }, "DELETE": { "OK when VALID request": { - EndpointId: GetDeliveryServiceId(t, "ds-top-req-cap"), + EndpointID: GetDeliveryServiceId(t, "ds-top-req-cap"), ClientSession: TOSession, RequestBody: tc.DeliveryServicesRequiredCapability{ RequiredCapability: util.Ptr("ram"), @@ -146,7 +146,7 @@ func TestDeliveryServicesRequiredCapabilities(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "NOT FOUND when NON-EXISTENT DELIVERYSERVICEID parameter": { - EndpointId: func() int { return -1 }, + EndpointID: func() int { return -1 }, ClientSession: TOSession, RequestBody: tc.DeliveryServicesRequiredCapability{ RequiredCapability: util.Ptr("foo"), @@ -154,7 +154,7 @@ func TestDeliveryServicesRequiredCapabilities(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "NOT FOUND when NON-EXISTENT REQUIREDCAPABILITY parameter": { - EndpointId: GetDeliveryServiceId(t, "ds1"), + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: tc.DeliveryServicesRequiredCapability{ RequiredCapability: util.Ptr("bogus"), @@ -201,7 +201,7 @@ func TestDeliveryServicesRequiredCapabilities(t *testing.T) { }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteDeliveryServicesRequiredCapability(testCase.EndpointId(), *testCase.RequestBody.RequiredCapability) + alerts, reqInf, err := testCase.ClientSession.DeleteDeliveryServicesRequiredCapability(testCase.EndpointID(), *testCase.RequestBody.RequiredCapability) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/deliveryservices_test.go b/traffic_ops/testing/api/v3/deliveryservices_test.go index bd4e994b67..975df24669 100644 --- a/traffic_ops/testing/api/v3/deliveryservices_test.go +++ b/traffic_ops/testing/api/v3/deliveryservices_test.go @@ -124,7 +124,7 @@ func TestDeliveryServices(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "longDesc": "changed long desc", "maxDNSAnswers": 500, @@ -139,7 +139,7 @@ func TestDeliveryServices(t *testing.T) { })), }, "OK when UPDATING MINOR VERSION FIELDS": { - EndpointId: GetDeliveryServiceId(t, "ds-test-minor-versions"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds-test-minor-versions"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "consistentHashQueryParams": []string{"d", "e", "f"}, "consistentHashRegex": "foo", @@ -161,21 +161,21 @@ func TestDeliveryServices(t *testing.T) { })), }, "BAD REQUEST when INVALID REMAP TEXT": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "remapText": "@plugin=tslua.so @pparam=/opt/trafficserver/etc/trafficserver/remapPlugin1.lua\nline2", }), Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when MISSING SLICE PLUGIN SIZE": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "rangeRequestHandling": 3, }), Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when SLICE PLUGIN SIZE SET with INVALID RANGE REQUEST SETTING": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "rangeRequestHandling": 1, "rangeSliceBlockSize": 262144, @@ -183,7 +183,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when SLICE PLUGIN SIZE TOO SMALL": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "rangeRequestHandling": 3, "rangeSliceBlockSize": 0, @@ -191,7 +191,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when SLICE PLUGIN SIZE TOO LARGE": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "rangeRequestHandling": 3, "rangeSliceBlockSize": 40000000, @@ -199,7 +199,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when CHANGING TOPOLOGY of DS with ORG SERVERS ASSIGNED": { - EndpointId: GetDeliveryServiceId(t, "ds-top"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds-top"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "topology": "another-topology", "xmlId": "ds-top", @@ -207,7 +207,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when ADDING TOPOLOGY to CLIENT STEERING DS": { - EndpointId: GetDeliveryServiceId(t, "ds-client-steering"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds-client-steering"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "topology": "mso-topology", "xmlId": "ds-client-steering", @@ -216,7 +216,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when TOPOLOGY DOESNT EXIST": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "topology": "", "xmlId": "ds1", @@ -224,7 +224,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when ADDING TOPOLOGY to DS with DS REQUIRED CAPABILITY": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "topology": "top-for-ds-req", "xmlId": "ds1", @@ -232,7 +232,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when ADDING TOPOLOGY to DS when NO CACHES in SAME CDN as DS": { - EndpointId: GetDeliveryServiceId(t, "top-ds-in-cdn2"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "top-ds-in-cdn2"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "cdnId": GetCDNID(t, "cdn2")(), "topology": "top-with-caches-in-cdn1", @@ -241,7 +241,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "OK when REMOVING TOPOLOGY": { - EndpointId: GetDeliveryServiceId(t, "ds-based-top-with-no-mids"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds-based-top-with-no-mids"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "topology": nil, "xmlId": "ds-based-top-with-no-mids", @@ -249,7 +249,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when DS with TOPOLOGY updates HEADER REWRITE FIELDS": { - EndpointId: GetDeliveryServiceId(t, "ds-top"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds-top"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "firstHeaderRewrite": "foo", "innerHeaderRewrite": "bar", @@ -260,7 +260,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "BAD REQUEST when DS with NO TOPOLOGY updates HEADER REWRITE FIELDS": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "firstHeaderRewrite": "foo", "innerHeaderRewrite": "bar", @@ -269,18 +269,18 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when UPDATING DS OUTSIDE TENANCY": { - EndpointId: GetDeliveryServiceId(t, "ds3"), ClientSession: tenant4UserSession, + EndpointID: GetDeliveryServiceId(t, "ds3"), ClientSession: tenant4UserSession, RequestBody: generateDeliveryService(t, map[string]interface{}{"xmlId": "ds3"}), Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}, RequestBody: generateDeliveryService(t, map[string]interface{}{"xmlId": "ds1"}), Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{"xmlId": "ds1"}), RequestHeaders: http.Header{rfc.IfMatch: {rfc.ETag(currentTime)}}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), @@ -288,7 +288,7 @@ func TestDeliveryServices(t *testing.T) { }, "DELETE": { "ERROR when DELETING DS OUTSIDE TENANCY": { - EndpointId: GetDeliveryServiceId(t, "ds3"), ClientSession: tenant4UserSession, + EndpointID: GetDeliveryServiceId(t, "ds3"), ClientSession: tenant4UserSession, Expectations: utils.CkRequest(utils.HasError()), }, }, @@ -300,7 +300,7 @@ func TestDeliveryServices(t *testing.T) { }, "DELIVERY SERVICES CAPACITY": { "OK when VALID request": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, }, @@ -361,14 +361,14 @@ func TestDeliveryServices(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.UpdateDeliveryServiceV30WithHdr(testCase.EndpointId(), ds, testCase.RequestHeaders) + resp, reqInf, err := testCase.ClientSession.UpdateDeliveryServiceV30WithHdr(testCase.EndpointID(), ds, testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, resp, tc.Alerts{}, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - resp, err := testCase.ClientSession.DeleteDeliveryService(strconv.Itoa(testCase.EndpointId())) + resp, err := testCase.ClientSession.DeleteDeliveryService(strconv.Itoa(testCase.EndpointID())) for _, check := range testCase.Expectations { if resp != nil { check(t, toclientlib.ReqInf{}, nil, resp.Alerts, err) @@ -377,7 +377,7 @@ func TestDeliveryServices(t *testing.T) { }) case "DELIVERY SERVICES CAPACITY": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetDeliveryServiceCapacityWithHdr(strconv.Itoa(testCase.EndpointId()), testCase.RequestHeaders) + resp, reqInf, err := testCase.ClientSession.GetDeliveryServiceCapacityWithHdr(strconv.Itoa(testCase.EndpointID()), testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, resp, tc.Alerts{}, err) } diff --git a/traffic_ops/testing/api/v3/deliveryserviceservers_test.go b/traffic_ops/testing/api/v3/deliveryserviceservers_test.go index 1f984592bb..4863783274 100644 --- a/traffic_ops/testing/api/v3/deliveryserviceservers_test.go +++ b/traffic_ops/testing/api/v3/deliveryserviceservers_test.go @@ -111,7 +111,7 @@ func TestDeliveryServiceServers(t *testing.T) { }, "SERVER STATUS PUT": { "BAD REQUEST when UPDATING SERVER STATUS when ONLY EDGE SERVER ASSIGNED": { - EndpointId: GetServerID(t, "test-ds-server-assignments"), ClientSession: TOSession, + EndpointID: GetServerID(t, "test-ds-server-assignments"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "status": "ADMIN_DOWN", "offlineReason": "admin down", @@ -163,7 +163,7 @@ func TestDeliveryServiceServers(t *testing.T) { }) case "SERVER STATUS PUT": t.Run(name, func(t *testing.T) { - _, reqInf, err := testCase.ClientSession.UpdateServerStatus(testCase.EndpointId(), status) + _, reqInf, err := testCase.ClientSession.UpdateServerStatus(testCase.EndpointID(), status) for _, check := range testCase.Expectations { check(t, reqInf, nil, tc.Alerts{}, err) } @@ -230,7 +230,7 @@ func TestDeliveryServicesIDServers(t *testing.T) { dsIDServersTests := utils.V3TestCase{ "GET": { "OK when VALID request": { - EndpointId: GetDeliveryServiceId(t, "test-ds-server-assignments"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "test-ds-server-assignments"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseHasLength(1)), }, @@ -242,7 +242,7 @@ func TestDeliveryServicesIDServers(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetServersByDeliveryService(testCase.EndpointId()) + resp, reqInf, err := testCase.ClientSession.GetServersByDeliveryService(testCase.EndpointID()) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v3/deliveryservicesideligible_test.go b/traffic_ops/testing/api/v3/deliveryservicesideligible_test.go index 671384b698..9172cb870d 100644 --- a/traffic_ops/testing/api/v3/deliveryservicesideligible_test.go +++ b/traffic_ops/testing/api/v3/deliveryservicesideligible_test.go @@ -29,7 +29,7 @@ func TestDeliveryServicesEligible(t *testing.T) { methodTests := utils.V3TestCaseT[struct{}]{ "GET": { "OK when VALID request": { - EndpointId: GetDeliveryServiceId(t, "ds1"), + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseLengthGreaterOrEqual(1)), }, @@ -41,7 +41,7 @@ func TestDeliveryServicesEligible(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetDeliveryServicesEligibleWithHdr(testCase.EndpointId(), testCase.RequestHeaders) + resp, reqInf, err := testCase.ClientSession.GetDeliveryServicesEligibleWithHdr(testCase.EndpointID(), testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, resp, tc.Alerts{}, err) } diff --git a/traffic_ops/testing/api/v3/deliveryservicesregexes_test.go b/traffic_ops/testing/api/v3/deliveryservicesregexes_test.go index b9f0cd3a68..fddf938f14 100644 --- a/traffic_ops/testing/api/v3/deliveryservicesregexes_test.go +++ b/traffic_ops/testing/api/v3/deliveryservicesregexes_test.go @@ -33,12 +33,12 @@ func TestDeliveryServicesRegexes(t *testing.T) { methodTests := utils.V3TestCaseT[tc.DeliveryServiceRegexPost]{ "GET": { "OK when VALID request": { - EndpointId: GetDeliveryServiceId(t, "ds1"), + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseHasLength(3)), }, "OK when VALID ID parameter": { - EndpointId: GetDeliveryServiceId(t, "ds1"), + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestParams: url.Values{"id": {strconv.Itoa(getDSRegexID(t, "ds1"))}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseHasLength(1)), @@ -46,7 +46,7 @@ func TestDeliveryServicesRegexes(t *testing.T) { }, "POST": { "BAD REQUEST when MISSING REGEX PATTERN": { - EndpointId: GetDeliveryServiceId(t, "ds1"), + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: tc.DeliveryServiceRegexPost{ Type: GetTypeId(t, "HOST_REGEXP"), @@ -71,14 +71,14 @@ func TestDeliveryServicesRegexes(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetDeliveryServiceRegexesByDSID(testCase.EndpointId(), params) + resp, reqInf, err := testCase.ClientSession.GetDeliveryServiceRegexesByDSID(testCase.EndpointID(), params) for _, check := range testCase.Expectations { check(t, reqInf, resp, tc.Alerts{}, err) } }) case "POST": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.PostDeliveryServiceRegexesByDSID(testCase.EndpointId(), testCase.RequestBody) + alerts, reqInf, err := testCase.ClientSession.PostDeliveryServiceRegexesByDSID(testCase.EndpointID(), testCase.RequestBody) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/divisions_test.go b/traffic_ops/testing/api/v3/divisions_test.go index e7aedf1533..a3a1e68bde 100644 --- a/traffic_ops/testing/api/v3/divisions_test.go +++ b/traffic_ops/testing/api/v3/divisions_test.go @@ -61,7 +61,7 @@ func TestDivisions(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetDivisionID(t, "cdn-div2"), + EndpointID: GetDivisionID(t, "cdn-div2"), ClientSession: TOSession, RequestBody: tc.Division{ Name: "testdivision", @@ -70,7 +70,7 @@ func TestDivisions(t *testing.T) { validateDivisionUpdateCreateFields("testdivision", map[string]interface{}{"Name": "testdivision"})), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetDivisionID(t, "division1"), + EndpointID: GetDivisionID(t, "division1"), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}, RequestBody: tc.Division{ @@ -79,7 +79,7 @@ func TestDivisions(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetDivisionID(t, "division1"), + EndpointID: GetDivisionID(t, "division1"), ClientSession: TOSession, RequestBody: tc.Division{ Name: "division1", @@ -90,7 +90,7 @@ func TestDivisions(t *testing.T) { }, "DELETE": { "BAD REQUEST when DIVISION in use by REGION": { - EndpointId: GetDivisionID(t, "division1"), + EndpointID: GetDivisionID(t, "division1"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, @@ -124,14 +124,14 @@ func TestDivisions(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateDivisionByIDWithHdr(testCase.EndpointId(), testCase.RequestBody, testCase.RequestHeaders) + alerts, reqInf, err := testCase.ClientSession.UpdateDivisionByIDWithHdr(testCase.EndpointID(), testCase.RequestBody, testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteDivisionByID(testCase.EndpointId()) + alerts, reqInf, err := testCase.ClientSession.DeleteDivisionByID(testCase.EndpointID()) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/federation_deliveryservices_test.go b/traffic_ops/testing/api/v3/federation_deliveryservices_test.go index 1f4ad20afc..849b0def57 100644 --- a/traffic_ops/testing/api/v3/federation_deliveryservices_test.go +++ b/traffic_ops/testing/api/v3/federation_deliveryservices_test.go @@ -33,20 +33,20 @@ func TestFederationsDeliveryServices(t *testing.T) { methodTests := utils.V3TestCaseT[tc.FederationDSPost]{ "GET": { "OK when VALID request": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseLengthGreaterOrEqual(1)), }, }, "DELETE": { "OK when VALID request": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestParams: url.Values{"dsID": {strconv.Itoa(GetDeliveryServiceId(t, "ds1")())}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "BAD REQUEST when LAST DELIVERY SERVICE": { - EndpointId: GetFederationID(t, "google.com."), + EndpointID: GetFederationID(t, "google.com."), ClientSession: TOSession, RequestParams: url.Values{"dsID": {strconv.Itoa(GetDeliveryServiceId(t, "ds2")())}}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), @@ -60,14 +60,14 @@ func TestFederationsDeliveryServices(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetFederationDeliveryServicesWithHdr(testCase.EndpointId(), testCase.RequestHeaders) + resp, reqInf, err := testCase.ClientSession.GetFederationDeliveryServicesWithHdr(testCase.EndpointID(), testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, resp, tc.Alerts{}, err) } }) case "POST": t.Run(name, func(t *testing.T) { - reqInf, err := testCase.ClientSession.CreateFederationDeliveryServices(testCase.EndpointId(), testCase.RequestBody.DSIDs, *testCase.RequestBody.Replace) + reqInf, err := testCase.ClientSession.CreateFederationDeliveryServices(testCase.EndpointID(), testCase.RequestBody.DSIDs, *testCase.RequestBody.Replace) for _, check := range testCase.Expectations { check(t, reqInf, nil, tc.Alerts{}, err) } @@ -80,7 +80,7 @@ func TestFederationsDeliveryServices(t *testing.T) { assert.RequireNoError(t, err, "Failed to convert dsID to an integer.") dsID = id } - alerts, reqInf, err := testCase.ClientSession.DeleteFederationDeliveryService(testCase.EndpointId(), dsID) + alerts, reqInf, err := testCase.ClientSession.DeleteFederationDeliveryService(testCase.EndpointID(), dsID) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/federation_federation_resolvers_test.go b/traffic_ops/testing/api/v3/federation_federation_resolvers_test.go index 17b3eaf4f1..0265f79403 100644 --- a/traffic_ops/testing/api/v3/federation_federation_resolvers_test.go +++ b/traffic_ops/testing/api/v3/federation_federation_resolvers_test.go @@ -30,19 +30,19 @@ func TestFederationFederationResolvers(t *testing.T) { methodTests := utils.V3TestCaseT[tc.AssignFederationResolversRequest]{ "GET": { "OK when VALID request AND RESOLVERS ASSIGNED": { - EndpointId: GetFederationID(t, "booya.com."), + EndpointID: GetFederationID(t, "booya.com."), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseLengthGreaterOrEqual(1)), }, "OK when VALID request AND NO RESOLVERS ASSIGNED": { - EndpointId: GetFederationID(t, "google.com."), + EndpointID: GetFederationID(t, "google.com."), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseHasLength(0)), }, }, "POST": { "OK when ASSIGNING ONE FEDERATION RESOLVER": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestBody: tc.AssignFederationResolversRequest{ FedResolverIDs: []int{GetFederationResolverID(t, "1.2.3.4")()}, @@ -51,7 +51,7 @@ func TestFederationFederationResolvers(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when ASSIGNING MULTIPLE FEDERATION RESOLVERS": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestBody: tc.AssignFederationResolversRequest{ FedResolverIDs: []int{ @@ -64,7 +64,7 @@ func TestFederationFederationResolvers(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when REPLACING ALL FEDERATION RESOLVERS": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestBody: tc.AssignFederationResolversRequest{ FedResolverIDs: []int{GetFederationResolverID(t, "dead::babe")()}, @@ -73,7 +73,7 @@ func TestFederationFederationResolvers(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "BAD REQUEST when FEDERATION DOESNT EXIST": { - EndpointId: func() int { return -1 }, + EndpointID: func() int { return -1 }, ClientSession: TOSession, RequestBody: tc.AssignFederationResolversRequest{ FedResolverIDs: []int{GetFederationResolverID(t, "1.2.3.4")()}, @@ -90,14 +90,14 @@ func TestFederationFederationResolvers(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetFederationFederationResolversByID(testCase.EndpointId()) + resp, reqInf, err := testCase.ClientSession.GetFederationFederationResolversByID(testCase.EndpointID()) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } }) case "POST": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.AssignFederationFederationResolver(testCase.EndpointId(), testCase.RequestBody.FedResolverIDs, testCase.RequestBody.Replace) + resp, reqInf, err := testCase.ClientSession.AssignFederationFederationResolver(testCase.EndpointID(), testCase.RequestBody.FedResolverIDs, testCase.RequestBody.Replace) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v3/federation_resolvers_test.go b/traffic_ops/testing/api/v3/federation_resolvers_test.go index c69f50a5d5..d7892b8348 100644 --- a/traffic_ops/testing/api/v3/federation_resolvers_test.go +++ b/traffic_ops/testing/api/v3/federation_resolvers_test.go @@ -83,7 +83,7 @@ func TestFederationResolvers(t *testing.T) { }, "DELETE": { "NOT FOUND when INVALID ID": { - EndpointId: func() int { return 0 }, + EndpointID: func() int { return 0 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, @@ -129,7 +129,7 @@ func TestFederationResolvers(t *testing.T) { }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteFederationResolver(uint(testCase.EndpointId())) + alerts, reqInf, err := testCase.ClientSession.DeleteFederationResolver(uint(testCase.EndpointID())) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/federation_users_test.go b/traffic_ops/testing/api/v3/federation_users_test.go index 8e013d8d7d..4e739a6565 100644 --- a/traffic_ops/testing/api/v3/federation_users_test.go +++ b/traffic_ops/testing/api/v3/federation_users_test.go @@ -37,20 +37,20 @@ func TestFederationUsers(t *testing.T) { methodTests := utils.V3TestCaseT[tc.FederationUserPost]{ "GET": { "NOT MODIFIED when NO CHANGES made": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfModifiedSince: {tomorrow}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusNotModified)), }, "BAD REQUEST when INVALID FEDERATION ID": { - EndpointId: func() int { return -1 }, + EndpointID: func() int { return -1 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, }, "POST": { "OK when VALID request": { - EndpointId: GetFederationID(t, "google.com."), + EndpointID: GetFederationID(t, "google.com."), ClientSession: TOSession, RequestBody: tc.FederationUserPost{ IDs: []int{GetUserID(t, "readonlyuser")(), GetUserID(t, "disalloweduser")()}, @@ -59,7 +59,7 @@ func TestFederationUsers(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when REPLACING USERS": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestBody: tc.FederationUserPost{ IDs: []int{GetUserID(t, "readonlyuser")()}, @@ -68,7 +68,7 @@ func TestFederationUsers(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when ADDING USER": { - EndpointId: GetFederationID(t, "booya.com."), + EndpointID: GetFederationID(t, "booya.com."), ClientSession: TOSession, RequestBody: tc.FederationUserPost{ IDs: []int{GetUserID(t, "disalloweduser")()}, @@ -77,7 +77,7 @@ func TestFederationUsers(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "BAD REQUEST when INVALID FEDERATION ID": { - EndpointId: func() int { return -1 }, + EndpointID: func() int { return -1 }, ClientSession: TOSession, RequestBody: tc.FederationUserPost{ IDs: []int{}, @@ -86,7 +86,7 @@ func TestFederationUsers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "BAD REQUEST when INVALID USER ID": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestBody: tc.FederationUserPost{ IDs: []int{-1}, @@ -97,7 +97,7 @@ func TestFederationUsers(t *testing.T) { }, "GET AFTER CHANGES": { "OK when CHANGES made": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfModifiedSince: {currentTimeRFC}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), @@ -111,14 +111,14 @@ func TestFederationUsers(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetFederationUsersWithHdr(testCase.EndpointId(), testCase.RequestHeaders) + resp, reqInf, err := testCase.ClientSession.GetFederationUsersWithHdr(testCase.EndpointID(), testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, resp, tc.Alerts{}, err) } }) case "POST": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.CreateFederationUsers(testCase.EndpointId(), testCase.RequestBody.IDs, *testCase.RequestBody.Replace) + alerts, reqInf, err := testCase.ClientSession.CreateFederationUsers(testCase.EndpointID(), testCase.RequestBody.IDs, *testCase.RequestBody.Replace) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/jobs_test.go b/traffic_ops/testing/api/v3/jobs_test.go index 135060e64e..29ea99afe1 100644 --- a/traffic_ops/testing/api/v3/jobs_test.go +++ b/traffic_ops/testing/api/v3/jobs_test.go @@ -140,7 +140,7 @@ func TestJobs(t *testing.T) { }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteInvalidationJob(uint64(testCase.EndpointId())) + alerts, reqInf, err := testCase.ClientSession.DeleteInvalidationJob(uint64(testCase.EndpointID())) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/loginfail_test.go b/traffic_ops/testing/api/v3/loginfail_test.go index fd4fedd298..077c3e289c 100644 --- a/traffic_ops/testing/api/v3/loginfail_test.go +++ b/traffic_ops/testing/api/v3/loginfail_test.go @@ -23,9 +23,9 @@ import ( "time" "github.com/apache/trafficcontrol/traffic_ops/testing/api/assert" - "golang.org/x/net/publicsuffix" - toclient "github.com/apache/trafficcontrol/traffic_ops/v3-client" + + "golang.org/x/net/publicsuffix" ) func TestLoginFail(t *testing.T) { diff --git a/traffic_ops/testing/api/v3/origins_test.go b/traffic_ops/testing/api/v3/origins_test.go index 2b2d570324..126fb0116b 100644 --- a/traffic_ops/testing/api/v3/origins_test.go +++ b/traffic_ops/testing/api/v3/origins_test.go @@ -88,7 +88,7 @@ func TestOrigins(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin2"), @@ -107,7 +107,7 @@ func TestOrigins(t *testing.T) { "FQDN": "originupdated.example.com", "IPAddress": "1.2.3.4", "IP6Address": "0000::1111", "Port": 1234, "Protocol": "http", "Tenant": "tenant2"})), }, "FORBIDDEN when CHILD TENANT updates PARENT TENANT ORIGIN": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: tenant4UserSession, RequestBody: tc.Origin{ Name: util.Ptr("testtenancy"), @@ -119,7 +119,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, "NOT FOUND when ORIGIN DOESNT EXIST": { - EndpointId: func() int { return 1111111 }, + EndpointID: func() int { return 1111111 }, ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("testid"), @@ -131,7 +131,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}, RequestBody: tc.Origin{ @@ -145,7 +145,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin2"), @@ -161,12 +161,12 @@ func TestOrigins(t *testing.T) { }, "DELETE": { "NOT FOUND when DOESNT EXIST": { - EndpointId: func() int { return 11111111 }, + EndpointID: func() int { return 11111111 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "FORBIDDEN when CHILD TENANT deletes PARENT TENANT ORIGIN": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: tenant4UserSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, @@ -208,14 +208,14 @@ func TestOrigins(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.UpdateOriginByIDWithHdr(testCase.EndpointId(), testCase.RequestBody, testCase.RequestHeaders) + resp, reqInf, err := testCase.ClientSession.UpdateOriginByIDWithHdr(testCase.EndpointID(), testCase.RequestBody, testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteOriginByID(testCase.EndpointId()) + alerts, reqInf, err := testCase.ClientSession.DeleteOriginByID(testCase.EndpointID()) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/parameters_test.go b/traffic_ops/testing/api/v3/parameters_test.go index 7f709723d1..e9a54de772 100644 --- a/traffic_ops/testing/api/v3/parameters_test.go +++ b/traffic_ops/testing/api/v3/parameters_test.go @@ -60,7 +60,7 @@ func TestParameters(t *testing.T) { }, "PUT": { "OK when VALID REQUEST": { - EndpointId: GetParameterID(t, "LogObject.Format", "logs_xml.config", "custom_ats_2"), + EndpointID: GetParameterID(t, "LogObject.Format", "logs_xml.config", "custom_ats_2"), ClientSession: TOSession, RequestBody: tc.Parameter{ ConfigFile: "updated.config", @@ -73,7 +73,7 @@ func TestParameters(t *testing.T) { map[string]interface{}{"ConfigFile": "updated.config", "Name": "updated name", "Secure": true, "Value": "updated value"})), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetParameterID(t, "LogFormat.Name", "logs_xml.config", "custom_ats_2"), + EndpointID: GetParameterID(t, "LogFormat.Name", "logs_xml.config", "custom_ats_2"), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}, RequestBody: tc.Parameter{ @@ -84,7 +84,7 @@ func TestParameters(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetParameterID(t, "LogFormat.Name", "logs_xml.config", "custom_ats_2"), + EndpointID: GetParameterID(t, "LogFormat.Name", "logs_xml.config", "custom_ats_2"), ClientSession: TOSession, RequestBody: tc.Parameter{ ConfigFile: "logs_xml.config", @@ -124,14 +124,14 @@ func TestParameters(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateParameterByIDWithHdr(testCase.EndpointId(), testCase.RequestBody, testCase.RequestHeaders) + alerts, reqInf, err := testCase.ClientSession.UpdateParameterByIDWithHdr(testCase.EndpointID(), testCase.RequestBody, testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteParameterByID(testCase.EndpointId()) + alerts, reqInf, err := testCase.ClientSession.DeleteParameterByID(testCase.EndpointID()) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/phys_locations_test.go b/traffic_ops/testing/api/v3/phys_locations_test.go index b4b73ba87f..03842656b9 100644 --- a/traffic_ops/testing/api/v3/phys_locations_test.go +++ b/traffic_ops/testing/api/v3/phys_locations_test.go @@ -114,7 +114,7 @@ func TestPhysLocations(t *testing.T) { validatePhysicalLocationUpdateCreateFields("testPhysicalLocation", map[string]interface{}{"Name": "testPhysicalLocation"})), }, "BAD REQUEST when REGION ID does NOT MATCH REGION NAME": { - EndpointId: GetPhysicalLocationID(t, "HotAtlanta"), + EndpointID: GetPhysicalLocationID(t, "HotAtlanta"), ClientSession: TOSession, RequestBody: tc.PhysLocation{ Address: "1234 southern way", @@ -132,7 +132,7 @@ func TestPhysLocations(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetPhysicalLocationID(t, "HotAtlanta"), + EndpointID: GetPhysicalLocationID(t, "HotAtlanta"), ClientSession: TOSession, RequestBody: tc.PhysLocation{ Address: "1234 southern way", @@ -148,7 +148,7 @@ func TestPhysLocations(t *testing.T) { validatePhysicalLocationUpdateCreateFields("HotAtlanta", map[string]interface{}{"City": "NewCity"})), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetPhysicalLocationID(t, "HotAtlanta"), + EndpointID: GetPhysicalLocationID(t, "HotAtlanta"), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}, RequestBody: tc.PhysLocation{ @@ -163,7 +163,7 @@ func TestPhysLocations(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetPhysicalLocationID(t, "HotAtlanta"), + EndpointID: GetPhysicalLocationID(t, "HotAtlanta"), ClientSession: TOSession, RequestBody: tc.PhysLocation{ Address: "1234 southern way", @@ -180,7 +180,7 @@ func TestPhysLocations(t *testing.T) { }, "DELETE": { "OK when VALID request": { - EndpointId: GetPhysicalLocationID(t, "testDelete"), + EndpointID: GetPhysicalLocationID(t, "testDelete"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, @@ -215,14 +215,14 @@ func TestPhysLocations(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdatePhysLocationByIDWithHdr(testCase.EndpointId(), testCase.RequestBody, testCase.RequestHeaders) + alerts, reqInf, err := testCase.ClientSession.UpdatePhysLocationByIDWithHdr(testCase.EndpointID(), testCase.RequestBody, testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeletePhysLocationByID(testCase.EndpointId()) + alerts, reqInf, err := testCase.ClientSession.DeletePhysLocationByID(testCase.EndpointID()) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/profile_parameters_test.go b/traffic_ops/testing/api/v3/profile_parameters_test.go index 4d78d1ac21..b2931a7cec 100644 --- a/traffic_ops/testing/api/v3/profile_parameters_test.go +++ b/traffic_ops/testing/api/v3/profile_parameters_test.go @@ -105,7 +105,7 @@ func TestProfileParameters(t *testing.T) { }, "DELETE": { "OK when VALID request": { - EndpointId: GetProfileID(t, "ATS_EDGE_TIER_CACHE"), + EndpointID: GetProfileID(t, "ATS_EDGE_TIER_CACHE"), ClientSession: TOSession, RequestParams: url.Values{ "parameterId": {strconv.Itoa(GetParameterID(t, "location", "set_dscp_37.config", "/etc/trafficserver/dscp")())}, @@ -151,7 +151,7 @@ func TestProfileParameters(t *testing.T) { case "DELETE": t.Run(name, func(t *testing.T) { parameterId, _ := strconv.Atoi(testCase.RequestParams["parameterId"][0]) - alerts, reqInf, err := testCase.ClientSession.DeleteParameterByProfileParameter(testCase.EndpointId(), parameterId) + alerts, reqInf, err := testCase.ClientSession.DeleteParameterByProfileParameter(testCase.EndpointID(), parameterId) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/profiles_export_test.go b/traffic_ops/testing/api/v3/profiles_export_test.go index f362298cb7..8e37fda773 100644 --- a/traffic_ops/testing/api/v3/profiles_export_test.go +++ b/traffic_ops/testing/api/v3/profiles_export_test.go @@ -32,14 +32,14 @@ func TestProfilesExport(t *testing.T) { methodTests := utils.V3TestCaseT[struct{}]{ "GET": { "OK when VALID request": { - EndpointId: GetProfileID(t, "EDGE1"), + EndpointID: GetProfileID(t, "EDGE1"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateProfilesExportFields(map[string]interface{}{"CDNName": "cdn1", "Name": "EDGE1", "Description": "edge1 description", "Type": "ATS_PROFILE"})), }, "NOT FOUND when PROFILE DOESNT EXIST": { - EndpointId: func() int { return 1111111111 }, + EndpointID: func() int { return 1111111111 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, @@ -52,7 +52,7 @@ func TestProfilesExport(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.ExportProfile(testCase.EndpointId()) + resp, reqInf, err := testCase.ClientSession.ExportProfile(testCase.EndpointID()) for _, check := range testCase.Expectations { check(t, reqInf, resp, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v3/profiles_test.go b/traffic_ops/testing/api/v3/profiles_test.go index ee5d0434ed..ceccea4fbb 100644 --- a/traffic_ops/testing/api/v3/profiles_test.go +++ b/traffic_ops/testing/api/v3/profiles_test.go @@ -131,7 +131,7 @@ func TestProfiles(t *testing.T) { }, "PUT": { "OK when VALID REQUEST": { - EndpointId: GetProfileID(t, "EDGE2"), + EndpointID: GetProfileID(t, "EDGE2"), ClientSession: TOSession, RequestBody: tc.Profile{ CDNID: GetCDNID(t, "cdn2")(), @@ -146,7 +146,7 @@ func TestProfiles(t *testing.T) { "Name": "EDGE2UPDATED", "RoutingDisabled": false, "Type": "TR_PROFILE"})), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetProfileID(t, "CCR1"), + EndpointID: GetProfileID(t, "CCR1"), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}, RequestBody: tc.Profile{ @@ -159,7 +159,7 @@ func TestProfiles(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetProfileID(t, "CCR1"), + EndpointID: GetProfileID(t, "CCR1"), ClientSession: TOSession, RequestBody: tc.Profile{ CDNID: GetCDNID(t, "cdn1")(), @@ -219,14 +219,14 @@ func TestProfiles(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateProfileByIDWithHdr(testCase.EndpointId(), testCase.RequestBody, testCase.RequestHeaders) + alerts, reqInf, err := testCase.ClientSession.UpdateProfileByIDWithHdr(testCase.EndpointID(), testCase.RequestBody, testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteProfileByID(testCase.EndpointId()) + alerts, reqInf, err := testCase.ClientSession.DeleteProfileByID(testCase.EndpointID()) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/regions_test.go b/traffic_ops/testing/api/v3/regions_test.go index 0338c61988..fbcaccd42d 100644 --- a/traffic_ops/testing/api/v3/regions_test.go +++ b/traffic_ops/testing/api/v3/regions_test.go @@ -74,7 +74,7 @@ func TestRegions(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetRegionID(t, "cdn-region2"), + EndpointID: GetRegionID(t, "cdn-region2"), ClientSession: TOSession, RequestBody: tc.Region{ Name: "newName", @@ -85,7 +85,7 @@ func TestRegions(t *testing.T) { validateRegionsUpdateCreateFields("newName", map[string]interface{}{"Name": "newName"})), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetRegionID(t, "region1"), + EndpointID: GetRegionID(t, "region1"), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}, RequestBody: tc.Region{ @@ -96,7 +96,7 @@ func TestRegions(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetRegionID(t, "region1"), + EndpointID: GetRegionID(t, "region1"), ClientSession: TOSession, RequestBody: tc.Region{ Name: "newName", @@ -153,7 +153,7 @@ func TestRegions(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateRegionByIDWithHdr(testCase.EndpointId(), testCase.RequestBody, testCase.RequestHeaders) + alerts, reqInf, err := testCase.ClientSession.UpdateRegionByIDWithHdr(testCase.EndpointID(), testCase.RequestBody, testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/roles_test.go b/traffic_ops/testing/api/v3/roles_test.go index ca4376ac1e..8c3ff339f5 100644 --- a/traffic_ops/testing/api/v3/roles_test.go +++ b/traffic_ops/testing/api/v3/roles_test.go @@ -128,7 +128,7 @@ func TestRoles(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetRoleID(t, "update_role"), + EndpointID: GetRoleID(t, "update_role"), ClientSession: TOSession, RequestBody: tc.Role{ RoleV11: tc.RoleV11{ @@ -145,7 +145,7 @@ func TestRoles(t *testing.T) { validateRoleUpdateCreateFields("new_name", map[string]interface{}{"Name": "new_name", "Description": "new updated description"})), }, "BAD REQUEST when MISSING NAME": { - EndpointId: GetRoleID(t, "another_role"), + EndpointID: GetRoleID(t, "another_role"), ClientSession: TOSession, RequestBody: tc.Role{ RoleV11: tc.RoleV11{ @@ -160,7 +160,7 @@ func TestRoles(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when MISSING DESCRIPTION": { - EndpointId: GetRoleID(t, "another_role"), + EndpointID: GetRoleID(t, "another_role"), ClientSession: TOSession, RequestBody: tc.Role{ RoleV11: tc.RoleV11{ @@ -175,7 +175,7 @@ func TestRoles(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when ADMIN ROLE": { - EndpointId: GetRoleID(t, "admin"), + EndpointID: GetRoleID(t, "admin"), ClientSession: TOSession, RequestBody: tc.Role{ RoleV11: tc.RoleV11{ @@ -191,7 +191,7 @@ func TestRoles(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "NOT FOUND when ROLE DOESNT EXIST": { - EndpointId: func() int { return 9999999 }, + EndpointID: func() int { return 9999999 }, ClientSession: TOSession, RequestBody: tc.Role{ RoleV11: tc.RoleV11{ @@ -207,7 +207,7 @@ func TestRoles(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "BAD REQUEST when ROLE NAME ALREADY EXISTS": { - EndpointId: GetRoleID(t, "another_role"), + EndpointID: GetRoleID(t, "another_role"), ClientSession: TOSession, RequestBody: tc.Role{ RoleV11: tc.RoleV11{ @@ -223,7 +223,7 @@ func TestRoles(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetRoleID(t, "another_role"), + EndpointID: GetRoleID(t, "another_role"), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}, RequestBody: tc.Role{ @@ -239,7 +239,7 @@ func TestRoles(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetRoleID(t, "another_role"), + EndpointID: GetRoleID(t, "another_role"), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfMatch: {rfc.ETag(currentTime)}}, RequestBody: tc.Role{ @@ -285,14 +285,14 @@ func TestRoles(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, _, err := testCase.ClientSession.UpdateRoleByIDWithHdr(testCase.EndpointId(), testCase.RequestBody, testCase.RequestHeaders) + alerts, reqInf, _, err := testCase.ClientSession.UpdateRoleByIDWithHdr(testCase.EndpointID(), testCase.RequestBody, testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, _, err := testCase.ClientSession.DeleteRoleByID(testCase.EndpointId()) + alerts, reqInf, _, err := testCase.ClientSession.DeleteRoleByID(testCase.EndpointID()) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/servers_id_deliveryservices_test.go b/traffic_ops/testing/api/v3/servers_id_deliveryservices_test.go index 88eab13383..99e720c3bc 100644 --- a/traffic_ops/testing/api/v3/servers_id_deliveryservices_test.go +++ b/traffic_ops/testing/api/v3/servers_id_deliveryservices_test.go @@ -35,20 +35,20 @@ func TestServersIDDeliveryServices(t *testing.T) { methodTests := utils.V3TestCaseT[map[string]interface{}]{ "GET": { "NOT MODIFIED when NO CHANGES made": { - EndpointId: GetServerID(t, "atlanta-edge-14"), + EndpointID: GetServerID(t, "atlanta-edge-14"), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfModifiedSince: {tomorrow}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusNotModified)), }, "OK when VALID request": { - EndpointId: GetServerID(t, "atlanta-edge-14"), + EndpointID: GetServerID(t, "atlanta-edge-14"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, }, "POST": { "OK when VALID request": { - EndpointId: GetServerID(t, "atlanta-edge-01"), + EndpointID: GetServerID(t, "atlanta-edge-01"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "dsIds": []int{GetDeliveryServiceId(t, "ds1")()}, @@ -58,7 +58,7 @@ func TestServersIDDeliveryServices(t *testing.T) { validateServersDeliveryServicesPost(GetServerID(t, "atlanta-edge-01")(), GetDeliveryServiceId(t, "ds1")())), }, "OK when ASSIGNING EDGE to TOPOLOGY BASED DELIVERY SERVICE": { - EndpointId: GetServerID(t, "atlanta-edge-03"), + EndpointID: GetServerID(t, "atlanta-edge-03"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "dsIds": []int{GetDeliveryServiceId(t, "top-ds-in-cdn1")()}, @@ -68,7 +68,7 @@ func TestServersIDDeliveryServices(t *testing.T) { validateServersDeliveryServicesPost(GetServerID(t, "atlanta-edge-03")(), GetDeliveryServiceId(t, "top-ds-in-cdn1")())), }, "OK when ASSIGNING ORIGIN to TOPOLOGY BASED DELIVERY SERVICE": { - EndpointId: GetServerID(t, "denver-mso-org-01"), + EndpointID: GetServerID(t, "denver-mso-org-01"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "dsIds": []int{GetDeliveryServiceId(t, "ds-top")()}, @@ -78,7 +78,7 @@ func TestServersIDDeliveryServices(t *testing.T) { validateServersDeliveryServicesPost(GetServerID(t, "denver-mso-org-01")(), GetDeliveryServiceId(t, "ds-top")())), }, "CONFLICT when SERVER NOT IN SAME CDN as DELIVERY SERVICE": { - EndpointId: GetServerID(t, "cdn2-test-edge"), + EndpointID: GetServerID(t, "cdn2-test-edge"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "dsIds": []int{GetDeliveryServiceId(t, "ds1")()}, @@ -87,7 +87,7 @@ func TestServersIDDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusConflict)), }, "BAD REQUEST when ORIGIN'S CACHEGROUP IS NOT A PART OF TOPOLOGY BASED DELIVERY SERVICE": { - EndpointId: GetServerID(t, "denver-mso-org-01"), + EndpointID: GetServerID(t, "denver-mso-org-01"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "dsIds": []int{GetDeliveryServiceId(t, "ds-top-req-cap")()}, @@ -96,7 +96,7 @@ func TestServersIDDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "CONFLICT when REMOVING ONLY EDGE SERVER ASSIGNMENT": { - EndpointId: GetServerID(t, "test-ds-server-assignments"), + EndpointID: GetServerID(t, "test-ds-server-assignments"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "dsIds": []int{}, @@ -126,14 +126,14 @@ func TestServersIDDeliveryServices(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetServerIDDeliveryServicesWithHdr(testCase.EndpointId(), testCase.RequestHeaders) + resp, reqInf, err := testCase.ClientSession.GetServerIDDeliveryServicesWithHdr(testCase.EndpointID(), testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, resp, tc.Alerts{}, err) } }) case "POST": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.AssignDeliveryServiceIDsToServerID(testCase.EndpointId(), dsIds, replace) + alerts, reqInf, err := testCase.ClientSession.AssignDeliveryServiceIDsToServerID(testCase.EndpointID(), dsIds, replace) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/servers_id_queue_update_test.go b/traffic_ops/testing/api/v3/servers_id_queue_update_test.go index 9925e81ea8..0de6c80606 100644 --- a/traffic_ops/testing/api/v3/servers_id_queue_update_test.go +++ b/traffic_ops/testing/api/v3/servers_id_queue_update_test.go @@ -32,7 +32,7 @@ func TestServersIDQueueUpdate(t *testing.T) { methodTests := utils.V3TestCaseT[bool]{ "POST": { "OK when VALID QUEUE request": { - EndpointId: GetServerID(t, "atlanta-edge-01"), + EndpointID: GetServerID(t, "atlanta-edge-01"), ClientSession: TOSession, RequestBody: true, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), @@ -40,7 +40,7 @@ func TestServersIDQueueUpdate(t *testing.T) { validateUpdPendingSpecificServers(map[string]bool{"atlanta-edge-01": true})), }, "OK when VALID DEQUEUE request": { - EndpointId: GetServerID(t, "atlanta-edge-01"), + EndpointID: GetServerID(t, "atlanta-edge-01"), ClientSession: TOSession, RequestBody: false, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), @@ -51,7 +51,7 @@ func TestServersIDQueueUpdate(t *testing.T) { https://github.com/apache/trafficcontrol/issues/6691 https://github.com/apache/trafficcontrol/issues/6801 "NOT FOUND when NON-EXISTENT SERVER": { - EndpointId: func() int { return 999999 }, + EndpointID: func() int { return 999999 }, ClientSession: TOSession, RequestBody: true, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), @@ -65,7 +65,7 @@ func TestServersIDQueueUpdate(t *testing.T) { switch method { case "POST": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.SetServerQueueUpdate(testCase.EndpointId(), testCase.RequestBody) + resp, reqInf, err := testCase.ClientSession.SetServerQueueUpdate(testCase.EndpointID(), testCase.RequestBody) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v3/servers_id_status_test.go b/traffic_ops/testing/api/v3/servers_id_status_test.go index 988e050313..c895e05cbc 100644 --- a/traffic_ops/testing/api/v3/servers_id_status_test.go +++ b/traffic_ops/testing/api/v3/servers_id_status_test.go @@ -33,7 +33,7 @@ func TestServersIDStatus(t *testing.T) { methodTests := utils.V3TestCaseT[tc.ServerPutStatus]{ "PUT": { "OK when VALID request": { - EndpointId: GetServerID(t, "atlanta-mid-01"), + EndpointID: GetServerID(t, "atlanta-mid-01"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{ID: util.Ptr(GetStatusID(t, "OFFLINE")())}, @@ -42,7 +42,7 @@ func TestServersIDStatus(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateUpdPending("atlanta-mid-01")), }, "OK when using STATUS ID FIELD": { - EndpointId: GetServerID(t, "atlanta-mid-16"), + EndpointID: GetServerID(t, "atlanta-mid-16"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{ID: util.Ptr(GetStatusID(t, "OFFLINE")())}, @@ -51,7 +51,7 @@ func TestServersIDStatus(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateUpdPending("atlanta-mid-16")), }, "VALIDATE TOPOLOGY DESCENDANTS receive STATUS UPDATES": { - EndpointId: GetServerID(t, "topology-mid-04"), + EndpointID: GetServerID(t, "topology-mid-04"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{ID: util.Ptr(GetStatusID(t, "OFFLINE")())}, @@ -63,7 +63,7 @@ func TestServersIDStatus(t *testing.T) { validateParentPendingSpecificServers(map[string]bool{"topology-edge-01": true, "edgeInTopologyEdgeCg02": false})), }, "NOT FOUND when SERVER DOESNT EXIST": { - EndpointId: func() int { return 11111111 }, + EndpointID: func() int { return 11111111 }, ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{Name: util.Ptr("OFFLINE")}, @@ -72,7 +72,7 @@ func TestServersIDStatus(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "BAD REQUEST when STATUS DOESNT EXIST": { - EndpointId: GetServerID(t, "atlanta-mid-16"), + EndpointID: GetServerID(t, "atlanta-mid-16"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{Name: util.Ptr("NOT_A_REAL_STATUS")}, @@ -81,7 +81,7 @@ func TestServersIDStatus(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when MISSING OFFLINE REASON when OFFLINE STATUS": { - EndpointId: GetServerID(t, "atlanta-mid-16"), + EndpointID: GetServerID(t, "atlanta-mid-16"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{Name: util.Ptr("OFFLINE")}, @@ -89,7 +89,7 @@ func TestServersIDStatus(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when MISSING OFFLINE REASON when ADMIN_DOWN STATUS": { - EndpointId: GetServerID(t, "atlanta-mid-16"), + EndpointID: GetServerID(t, "atlanta-mid-16"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{Name: util.Ptr("ADMIN_DOWN")}, @@ -97,7 +97,7 @@ func TestServersIDStatus(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "CONFLICT when SERVER STATUS OFFLINE when ONLY EDGE SERVER ASSIGNED": { - EndpointId: GetServerID(t, "test-ds-server-assignments"), + EndpointID: GetServerID(t, "test-ds-server-assignments"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{Name: util.Ptr("OFFLINE")}, @@ -115,7 +115,7 @@ func TestServersIDStatus(t *testing.T) { case "PUT": t.Run(name, func(t *testing.T) { clearUpdates(t) - alerts, reqInf, err := testCase.ClientSession.UpdateServerStatus(testCase.EndpointId(), testCase.RequestBody) + alerts, reqInf, err := testCase.ClientSession.UpdateServerStatus(testCase.EndpointID(), testCase.RequestBody) for _, check := range testCase.Expectations { if alerts != nil { check(t, reqInf, nil, *alerts, err) diff --git a/traffic_ops/testing/api/v3/servers_test.go b/traffic_ops/testing/api/v3/servers_test.go index 39311ea146..705732dcee 100644 --- a/traffic_ops/testing/api/v3/servers_test.go +++ b/traffic_ops/testing/api/v3/servers_test.go @@ -126,7 +126,7 @@ func TestServers(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetServerID(t, "atlanta-edge-03"), + EndpointID: GetServerID(t, "atlanta-edge-03"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "id": GetServerID(t, "atlanta-edge-03")(), @@ -170,7 +170,7 @@ func TestServers(t *testing.T) { })), }, "BAD REQUEST when CHANGING XMPPID": { - EndpointId: GetServerID(t, "atlanta-edge-16"), + EndpointID: GetServerID(t, "atlanta-edge-16"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "atlanta-edge-16")(), @@ -179,7 +179,7 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "CONFLICT when UPDATING SERVER TYPE when ASSIGNED to DS": { - EndpointId: GetServerID(t, "test-ds-server-assignments"), + EndpointID: GetServerID(t, "test-ds-server-assignments"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "test-ds-server-assignments")(), @@ -189,7 +189,7 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusConflict)), }, "CONFLICT when UPDATING SERVER STATUS when its the ONLY EDGE SERVER ASSIGNED": { - EndpointId: GetServerID(t, "test-ds-server-assignments"), + EndpointID: GetServerID(t, "test-ds-server-assignments"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "test-ds-server-assignments")(), @@ -198,7 +198,7 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusConflict)), }, "BAD REQUEST when UPDATING CDN when LAST SERVER IN CACHEGROUP IN TOPOLOGY": { - EndpointId: GetServerID(t, "midInTopologyMidCg01"), + EndpointID: GetServerID(t, "midInTopologyMidCg01"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "midInTopologyMidCg01")(), @@ -209,7 +209,7 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when UPDATING CACHEGROUP when LAST SERVER IN CACHEGROUP IN TOPOLOGY": { - EndpointId: GetServerID(t, "midInTopologyMidCg01"), + EndpointID: GetServerID(t, "midInTopologyMidCg01"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "midInTopologyMidCg01")(), @@ -221,7 +221,7 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when IPADDRESS EXISTS with SAME PROFILE": { - EndpointId: GetServerID(t, "atlanta-edge-16"), + EndpointID: GetServerID(t, "atlanta-edge-16"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "profileNames": []string{"EDGE1"}, @@ -237,19 +237,19 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when BLANK HOSTNAME": { - EndpointId: GetServerID(t, "atlanta-edge-16"), + EndpointID: GetServerID(t, "atlanta-edge-16"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{"hostName": ""}), Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when BLANK DOMAINNAME": { - EndpointId: GetServerID(t, "atlanta-edge-16"), + EndpointID: GetServerID(t, "atlanta-edge-16"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{"domainName": ""}), Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetServerID(t, "atlanta-edge-01"), + EndpointID: GetServerID(t, "atlanta-edge-01"), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}, RequestBody: generateServer(t, map[string]interface{}{ @@ -258,7 +258,7 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetServerID(t, "atlanta-edge-01"), + EndpointID: GetServerID(t, "atlanta-edge-01"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "atlanta-edge-01")(), @@ -269,12 +269,12 @@ func TestServers(t *testing.T) { }, "DELETE": { "BAD REQUEST when LAST SERVER in CACHE GROUP": { - EndpointId: GetServerID(t, "midInTopologyMidCg01"), + EndpointID: GetServerID(t, "midInTopologyMidCg01"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "CONFLICT when DELETING SERVER when its the ONLY EDGE SERVER ASSIGNED": { - EndpointId: GetServerID(t, "test-ds-server-assignments"), + EndpointID: GetServerID(t, "test-ds-server-assignments"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusConflict)), }, @@ -317,14 +317,14 @@ func TestServers(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateServerByIDWithHdr(testCase.EndpointId(), server, testCase.RequestHeaders) + alerts, reqInf, err := testCase.ClientSession.UpdateServerByIDWithHdr(testCase.EndpointID(), server, testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteServerByID(testCase.EndpointId()) + alerts, reqInf, err := testCase.ClientSession.DeleteServerByID(testCase.EndpointID()) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/staticdnsentries_test.go b/traffic_ops/testing/api/v3/staticdnsentries_test.go index 9dc70bc398..fef5273e75 100644 --- a/traffic_ops/testing/api/v3/staticdnsentries_test.go +++ b/traffic_ops/testing/api/v3/staticdnsentries_test.go @@ -50,7 +50,7 @@ func TestStaticDNSEntries(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetStaticDNSEntryID(t, "host2"), + EndpointID: GetStaticDNSEntryID(t, "host2"), ClientSession: TOSession, RequestBody: tc.StaticDNSEntry{ Address: "192.168.0.2", @@ -64,7 +64,7 @@ func TestStaticDNSEntries(t *testing.T) { validateStaticDNSEntriesUpdateCreateFields("host2", map[string]interface{}{"Address": "192.168.0.2"})), }, "BAD REQUEST when INVALID IPV4 ADDRESS for A_RECORD": { - EndpointId: GetStaticDNSEntryID(t, "host2"), + EndpointID: GetStaticDNSEntryID(t, "host2"), ClientSession: TOSession, RequestBody: tc.StaticDNSEntry{ Address: "test.testdomain.net.", @@ -77,7 +77,7 @@ func TestStaticDNSEntries(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when INVALID DNS for CNAME_RECORD": { - EndpointId: GetStaticDNSEntryID(t, "host1"), + EndpointID: GetStaticDNSEntryID(t, "host1"), ClientSession: TOSession, RequestBody: tc.StaticDNSEntry{ Address: "2001:0db8:85a3:0000:0000:8a2e:0370:7334", @@ -90,7 +90,7 @@ func TestStaticDNSEntries(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when MISSING TRAILING PERIOD for CNAME_RECORD": { - EndpointId: GetStaticDNSEntryID(t, "host1"), + EndpointID: GetStaticDNSEntryID(t, "host1"), ClientSession: TOSession, RequestBody: tc.StaticDNSEntry{ Address: "cdn.test.com", @@ -103,7 +103,7 @@ func TestStaticDNSEntries(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when INVALID IPV6 ADDRESS for AAAA_RECORD": { - EndpointId: GetStaticDNSEntryID(t, "host3"), + EndpointID: GetStaticDNSEntryID(t, "host3"), ClientSession: TOSession, RequestBody: tc.StaticDNSEntry{ Address: "192.168.0.1", @@ -116,7 +116,7 @@ func TestStaticDNSEntries(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetStaticDNSEntryID(t, "host3"), + EndpointID: GetStaticDNSEntryID(t, "host3"), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}, RequestBody: tc.StaticDNSEntry{ @@ -130,7 +130,7 @@ func TestStaticDNSEntries(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetStaticDNSEntryID(t, "host3"), + EndpointID: GetStaticDNSEntryID(t, "host3"), ClientSession: TOSession, RequestBody: tc.StaticDNSEntry{ Address: "2001:0db8:85a3:0000:0000:8a2e:0370:7334", @@ -166,14 +166,14 @@ func TestStaticDNSEntries(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, _, err := testCase.ClientSession.UpdateStaticDNSEntryByIDWithHdr(testCase.EndpointId(), testCase.RequestBody, testCase.RequestHeaders) + alerts, reqInf, _, err := testCase.ClientSession.UpdateStaticDNSEntryByIDWithHdr(testCase.EndpointID(), testCase.RequestBody, testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteStaticDNSEntryByID(testCase.EndpointId()) + alerts, reqInf, err := testCase.ClientSession.DeleteStaticDNSEntryByID(testCase.EndpointID()) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/statuses_test.go b/traffic_ops/testing/api/v3/statuses_test.go index 6fa79e6780..c9fc4f6a9c 100644 --- a/traffic_ops/testing/api/v3/statuses_test.go +++ b/traffic_ops/testing/api/v3/statuses_test.go @@ -61,7 +61,7 @@ func TestStatuses(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetStatusID(t, "TEST_NULL_DESCRIPTION"), + EndpointID: GetStatusID(t, "TEST_NULL_DESCRIPTION"), ClientSession: TOSession, RequestBody: tc.Status{ Description: "new description", @@ -71,7 +71,7 @@ func TestStatuses(t *testing.T) { validateStatusesUpdateCreateFields("TEST_NULL_DESCRIPTION", map[string]interface{}{"Description": "new description"})), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetStatusID(t, "TEST_NULL_DESCRIPTION"), + EndpointID: GetStatusID(t, "TEST_NULL_DESCRIPTION"), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}, RequestBody: tc.Status{ @@ -81,7 +81,7 @@ func TestStatuses(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetStatusID(t, "TEST_NULL_DESCRIPTION"), + EndpointID: GetStatusID(t, "TEST_NULL_DESCRIPTION"), ClientSession: TOSession, RequestBody: tc.Status{ Description: "new description", @@ -113,14 +113,14 @@ func TestStatuses(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateStatusByIDWithHdr(testCase.EndpointId(), testCase.RequestBody, testCase.RequestHeaders) + alerts, reqInf, err := testCase.ClientSession.UpdateStatusByIDWithHdr(testCase.EndpointID(), testCase.RequestBody, testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteStatusByID(testCase.EndpointId()) + alerts, reqInf, err := testCase.ClientSession.DeleteStatusByID(testCase.EndpointID()) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/steeringtargets_test.go b/traffic_ops/testing/api/v3/steeringtargets_test.go index b9e24c5396..7f7605ab91 100644 --- a/traffic_ops/testing/api/v3/steeringtargets_test.go +++ b/traffic_ops/testing/api/v3/steeringtargets_test.go @@ -41,20 +41,20 @@ func TestSteeringTargets(t *testing.T) { methodTests := utils.V3TestCaseT[tc.SteeringTargetNullable]{ "GET": { "NOT MODIFIED when NO CHANGES made": { - EndpointId: GetDeliveryServiceId(t, "ds1"), + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: steeringUserSession, RequestHeaders: http.Header{rfc.IfModifiedSince: {tomorrow}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusNotModified)), }, "OK when VALID request": { - EndpointId: GetDeliveryServiceId(t, "ds1"), + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: steeringUserSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseHasLength(1), validateSteeringTargetFields(map[string]interface{}{"DeliveryService": "ds1", "DeliveryServiceID": uint64(GetDeliveryServiceId(t, "ds1")()), "Target": "ds2", "TargetID": uint64(GetDeliveryServiceId(t, "ds2")()), "Type": "STEERING_WEIGHT", "TypeID": GetTypeID(t, "STEERING_WEIGHT")(), "Value": util.JSONIntStr(42)})), }, "OK when CHANGES made": { - EndpointId: GetDeliveryServiceId(t, "ds1"), + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: steeringUserSession, RequestHeaders: http.Header{rfc.IfModifiedSince: {currentTimeRFC}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), @@ -108,7 +108,7 @@ func TestSteeringTargets(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetSteeringTargetsWithHdr(testCase.EndpointId(), testCase.RequestHeaders) + resp, reqInf, err := testCase.ClientSession.GetSteeringTargetsWithHdr(testCase.EndpointID(), testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, resp, tc.Alerts{}, err) } @@ -137,7 +137,7 @@ func TestSteeringTargets(t *testing.T) { assert.RequireNoError(t, err, "Expected no error converting targetID to an integer: %v", err) } } - alerts, reqInf, err := testCase.ClientSession.DeleteSteeringTarget(testCase.EndpointId(), targetID) + alerts, reqInf, err := testCase.ClientSession.DeleteSteeringTarget(testCase.EndpointID(), targetID) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/tenants_test.go b/traffic_ops/testing/api/v3/tenants_test.go index 60c86f15ce..19ca023572 100644 --- a/traffic_ops/testing/api/v3/tenants_test.go +++ b/traffic_ops/testing/api/v3/tenants_test.go @@ -63,7 +63,7 @@ func TestTenants(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetTenantID(t, "tenant4"), + EndpointID: GetTenantID(t, "tenant4"), ClientSession: TOSession, RequestBody: tc.Tenant{ Active: false, @@ -75,7 +75,7 @@ func TestTenants(t *testing.T) { validateTenantCreateUpdateFields(map[string]interface{}{"Name": "newname", "Active": false})), }, "BAD REQUEST when ROOT TENANT": { - EndpointId: GetTenantID(t, "root"), + EndpointID: GetTenantID(t, "root"), ClientSession: TOSession, RequestBody: tc.Tenant{ Active: false, @@ -85,7 +85,7 @@ func TestTenants(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetTenantID(t, "tenant2"), + EndpointID: GetTenantID(t, "tenant2"), ClientSession: TOSession, RequestHeaders: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}, RequestBody: tc.Tenant{ @@ -97,7 +97,7 @@ func TestTenants(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetTenantID(t, "tenant2"), + EndpointID: GetTenantID(t, "tenant2"), ClientSession: TOSession, RequestBody: tc.Tenant{ Active: false, @@ -111,7 +111,7 @@ func TestTenants(t *testing.T) { }, "DELETE": { "ERROR when TENANT HAS CHILDREN": { - EndpointId: GetTenantID(t, "tenant1"), + EndpointID: GetTenantID(t, "tenant1"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError()), }, @@ -140,7 +140,7 @@ func TestTenants(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.UpdateTenantWithHdr(strconv.Itoa(testCase.EndpointId()), &testCase.RequestBody, testCase.RequestHeaders) + resp, reqInf, err := testCase.ClientSession.UpdateTenantWithHdr(strconv.Itoa(testCase.EndpointID()), &testCase.RequestBody, testCase.RequestHeaders) for _, check := range testCase.Expectations { if resp != nil { check(t, reqInf, resp.Response, resp.Alerts, err) @@ -149,7 +149,7 @@ func TestTenants(t *testing.T) { }) case "DELETE": t.Run(name, func(t *testing.T) { - _, err := testCase.ClientSession.DeleteTenant(strconv.Itoa(testCase.EndpointId())) + _, err := testCase.ClientSession.DeleteTenant(strconv.Itoa(testCase.EndpointID())) for _, check := range testCase.Expectations { check(t, toclientlib.ReqInf{}, nil, tc.Alerts{}, err) } diff --git a/traffic_ops/testing/api/v3/types_test.go b/traffic_ops/testing/api/v3/types_test.go index 2e3d86f874..318430d546 100644 --- a/traffic_ops/testing/api/v3/types_test.go +++ b/traffic_ops/testing/api/v3/types_test.go @@ -23,13 +23,12 @@ import ( "testing" "time" + "github.com/apache/trafficcontrol/lib/go-rfc" + tc "github.com/apache/trafficcontrol/lib/go-tc" "github.com/apache/trafficcontrol/traffic_ops/testing/api/assert" "github.com/apache/trafficcontrol/traffic_ops/testing/api/utils" "github.com/apache/trafficcontrol/traffic_ops/toclientlib" client "github.com/apache/trafficcontrol/traffic_ops/v4-client" - - "github.com/apache/trafficcontrol/lib/go-rfc" - tc "github.com/apache/trafficcontrol/lib/go-tc" ) func TestTypes(t *testing.T) { @@ -86,7 +85,7 @@ func TestTypes(t *testing.T) { }, "PUT": { "BAD REQUEST when useInTable NOT server": { - EndpointId: GetTypeID(t, "ACTIVE_DIRECTORY"), + EndpointID: GetTypeID(t, "ACTIVE_DIRECTORY"), ClientSession: TOSession, RequestBody: tc.Type{ Description: "Active Directory User", @@ -96,7 +95,7 @@ func TestTypes(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "OK when VALID request when useInTable=server": { - EndpointId: GetTypeID(t, "RIAK"), + EndpointID: GetTypeID(t, "RIAK"), ClientSession: TOSession, RequestBody: tc.Type{ Description: "riak type", @@ -109,7 +108,7 @@ func TestTypes(t *testing.T) { }, "DELETE": { "OK when VALID request": { - EndpointId: GetTypeID(t, "INFLUXDB"), + EndpointID: GetTypeID(t, "INFLUXDB"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, @@ -151,14 +150,14 @@ func TestTypes(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateTypeByIDWithHdr(testCase.EndpointId(), testCase.RequestBody, testCase.RequestHeaders) + alerts, reqInf, err := testCase.ClientSession.UpdateTypeByIDWithHdr(testCase.EndpointID(), testCase.RequestBody, testCase.RequestHeaders) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteTypeByID(testCase.EndpointId()) + alerts, reqInf, err := testCase.ClientSession.DeleteTypeByID(testCase.EndpointID()) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v3/users_test.go b/traffic_ops/testing/api/v3/users_test.go index 3d6f6d92f8..ff1085d13c 100644 --- a/traffic_ops/testing/api/v3/users_test.go +++ b/traffic_ops/testing/api/v3/users_test.go @@ -84,7 +84,7 @@ func TestUsers(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetUserID(t, "steering"), + EndpointID: GetUserID(t, "steering"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "addressLine1": "updated line 1", @@ -108,7 +108,7 @@ func TestUsers(t *testing.T) { "Country": "US", "Email": "steeringupdated@example.com", "FullName": "Steering User Updated"})), }, "OK when UPDATING SELF": { - EndpointId: GetUserID(t, "opsuser"), + EndpointID: GetUserID(t, "opsuser"), ClientSession: opsUserSession, RequestBody: map[string]interface{}{ "addressLine1": "address of ops", @@ -129,7 +129,7 @@ func TestUsers(t *testing.T) { validateUsersUpdateCreateFields(map[string]interface{}{"Email": "ops-updated@example.com", "FullName": "Operations User Updated"})), }, "BAD REQUEST when updating OWN ROLE": { - EndpointId: GetUserID(t, "opsuser"), + EndpointID: GetUserID(t, "opsuser"), ClientSession: opsUserSession, RequestBody: map[string]interface{}{ "addressLine1": "address of ops", @@ -149,7 +149,7 @@ func TestUsers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "FORBIDDEN when OPERATIONS USER updates ADMIN USER": { - EndpointId: GetUserID(t, "admin"), + EndpointID: GetUserID(t, "admin"), ClientSession: opsUserSession, RequestBody: map[string]interface{}{ "email": "oops@ops.net", @@ -164,7 +164,7 @@ func TestUsers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, "FORBIDDEN when CHILD TENANT USER updates PARENT TENANT USER": { - EndpointId: GetUserID(t, "tenant3user"), + EndpointID: GetUserID(t, "tenant3user"), ClientSession: tenant4UserSession, RequestBody: map[string]interface{}{ "email": "tenant3user@example.com", @@ -210,7 +210,7 @@ func TestUsers(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.UpdateUserByID(testCase.EndpointId(), &user) + resp, reqInf, err := testCase.ClientSession.UpdateUserByID(testCase.EndpointID(), &user) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v4/asns_test.go b/traffic_ops/testing/api/v4/asns_test.go index 13d34f9bfb..16b9fd3ea4 100644 --- a/traffic_ops/testing/api/v4/asns_test.go +++ b/traffic_ops/testing/api/v4/asns_test.go @@ -64,7 +64,7 @@ func TestASN(t *testing.T) { }, "PUT": { "OK when VALID request": { - ClientSession: TOSession, EndpointId: GetASNID(t, "8888"), + ClientSession: TOSession, EndpointID: GetASNID(t, "8888"), RequestBody: map[string]interface{}{ "asn": 7777, "cachegroupName": "originCachegroup", @@ -98,7 +98,7 @@ func TestASN(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateASN(testCase.EndpointId(), asn, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateASN(testCase.EndpointID(), asn, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/cachegroups_test.go b/traffic_ops/testing/api/v4/cachegroups_test.go index 07172e5694..44c32a0aa3 100644 --- a/traffic_ops/testing/api/v4/cachegroups_test.go +++ b/traffic_ops/testing/api/v4/cachegroups_test.go @@ -151,7 +151,7 @@ func TestCacheGroups(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetCacheGroupId(t, "cachegroup1"), ClientSession: TOSession, + EndpointID: GetCacheGroupId(t, "cachegroup1"), ClientSession: TOSession, RequestBody: tc.CacheGroupNullable{ Latitude: util.Ptr(17.5), Longitude: util.Ptr(17.5), @@ -165,7 +165,7 @@ func TestCacheGroups(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when updating CG with null Lat/Long": { - EndpointId: GetCacheGroupId(t, "nullLatLongCG"), ClientSession: TOSession, + EndpointID: GetCacheGroupId(t, "nullLatLongCG"), ClientSession: TOSession, RequestBody: tc.CacheGroupNullable{ Name: util.Ptr("nullLatLongCG"), ShortName: util.Ptr("null-ll"), @@ -176,7 +176,7 @@ func TestCacheGroups(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "BAD REQUEST when updating TYPE of CG in TOPOLOGY": { - EndpointId: GetCacheGroupId(t, "topology-edge-cg-01"), ClientSession: TOSession, + EndpointID: GetCacheGroupId(t, "topology-edge-cg-01"), ClientSession: TOSession, RequestBody: tc.CacheGroupNullable{ Latitude: util.Ptr(0.0), Longitude: util.Ptr(0.0), @@ -188,7 +188,7 @@ func TestCacheGroups(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetCacheGroupId(t, "cachegroup1"), ClientSession: TOSession, + EndpointID: GetCacheGroupId(t, "cachegroup1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.CacheGroupNullable{ Name: util.Ptr("cachegroup1"), @@ -199,7 +199,7 @@ func TestCacheGroups(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetCacheGroupId(t, "cachegroup1"), ClientSession: TOSession, + EndpointID: GetCacheGroupId(t, "cachegroup1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfMatch: {rfc.ETag(currentTime)}}}, RequestBody: tc.CacheGroupNullable{ Name: util.Ptr("cachegroup1"), @@ -210,19 +210,19 @@ func TestCacheGroups(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "UNAUTHORIZED when NOT LOGGED IN": { - EndpointId: GetCacheGroupId(t, "cachegroup1"), + EndpointID: GetCacheGroupId(t, "cachegroup1"), ClientSession: NoAuthTOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusUnauthorized)), }, }, "DELETE": { "NOT FOUND when INVALID ID parameter": { - EndpointId: func() int { return 111111 }, + EndpointID: func() int { return 111111 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "UNAUTHORIZED when NOT LOGGED IN": { - EndpointId: GetCacheGroupId(t, "cachegroup1"), + EndpointID: GetCacheGroupId(t, "cachegroup1"), ClientSession: NoAuthTOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusUnauthorized)), }, @@ -249,14 +249,14 @@ func TestCacheGroups(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.UpdateCacheGroup(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.UpdateCacheGroup(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteCacheGroup(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteCacheGroup(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/cachegroupsdeliveryservices_test.go b/traffic_ops/testing/api/v4/cachegroupsdeliveryservices_test.go index 29f7d188a2..00be63a0d0 100644 --- a/traffic_ops/testing/api/v4/cachegroupsdeliveryservices_test.go +++ b/traffic_ops/testing/api/v4/cachegroupsdeliveryservices_test.go @@ -33,13 +33,13 @@ func TestCacheGroupsDeliveryServices(t *testing.T) { methodTests := utils.TestCase[client.Session, client.RequestOptions, []int]{ "POST": { "BAD REQUEST assigning TOPOLOGY-BASED DS to CACHEGROUP": { - EndpointId: GetCacheGroupId(t, "cachegroup3"), + EndpointID: GetCacheGroupId(t, "cachegroup3"), ClientSession: TOSession, RequestBody: []int{GetDeliveryServiceId(t, "top-ds-in-cdn1")()}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "OK when valid request": { - EndpointId: GetCacheGroupId(t, "cachegroup3"), + EndpointID: GetCacheGroupId(t, "cachegroup3"), ClientSession: TOSession, RequestBody: []int{ GetDeliveryServiceId(t, "ds1")(), @@ -59,7 +59,7 @@ func TestCacheGroupsDeliveryServices(t *testing.T) { switch method { case "POST": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.SetCacheGroupDeliveryServices(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.SetCacheGroupDeliveryServices(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v4/cdn_federations_test.go b/traffic_ops/testing/api/v4/cdn_federations_test.go index 64bc7027e7..fbdd910895 100644 --- a/traffic_ops/testing/api/v4/cdn_federations_test.go +++ b/traffic_ops/testing/api/v4/cdn_federations_test.go @@ -105,7 +105,7 @@ func TestCDNFederations(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetFederationID(t, "google.com."), + EndpointID: GetFederationID(t, "google.com."), ClientSession: TOSession, RequestBody: tc.CDNFederation{ CName: util.Ptr("new.cname."), @@ -115,7 +115,7 @@ func TestCDNFederations(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateCDNFederationUpdateFields(map[string]interface{}{"CName": "new.cname."})), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetFederationID(t, "booya.com."), + EndpointID: GetFederationID(t, "booya.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.CDNFederation{ @@ -126,7 +126,7 @@ func TestCDNFederations(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetFederationID(t, "booya.com."), + EndpointID: GetFederationID(t, "booya.com."), ClientSession: TOSession, RequestBody: tc.CDNFederation{ CName: util.Ptr("new.cname."), @@ -159,14 +159,14 @@ func TestCDNFederations(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.UpdateCDNFederation(testCase.RequestBody, cdnName, testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.UpdateCDNFederation(testCase.RequestBody, cdnName, testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteCDNFederation(cdnName, testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteCDNFederation(cdnName, testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts.Alerts, err) } diff --git a/traffic_ops/testing/api/v4/cdn_locks_test.go b/traffic_ops/testing/api/v4/cdn_locks_test.go index fe6ca993d9..463df60cbd 100644 --- a/traffic_ops/testing/api/v4/cdn_locks_test.go +++ b/traffic_ops/testing/api/v4/cdn_locks_test.go @@ -110,11 +110,11 @@ func TestCDNLocks(t *testing.T) { }, "SERVERS QUEUE UPDATES": { "OK when USER OWNS LOCK": { - EndpointId: GetServerID(t, "cdn2-test-edge"), ClientSession: opsUserWithLockSession, + EndpointID: GetServerID(t, "cdn2-test-edge"), ClientSession: opsUserWithLockSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetServerID(t, "cdn2-test-edge"), ClientSession: TOSession, + EndpointID: GetServerID(t, "cdn2-test-edge"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, }, @@ -169,7 +169,7 @@ func TestCDNLocks(t *testing.T) { }, "CDN UPDATE": { "OK when USER OWNS LOCK": { - EndpointId: GetCDNID(t, "cdn2"), ClientSession: opsUserWithLockSession, + EndpointID: GetCDNID(t, "cdn2"), ClientSession: opsUserWithLockSession, RequestBody: map[string]interface{}{ "dnssecEnabled": false, "domainName": "newdomain", @@ -178,7 +178,7 @@ func TestCDNLocks(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetCDNID(t, "cdn2"), ClientSession: TOSession, + EndpointID: GetCDNID(t, "cdn2"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "dnssecEnabled": false, "domainName": "newdomaintest", @@ -189,17 +189,17 @@ func TestCDNLocks(t *testing.T) { }, "CDN DELETE": { "OK when USER OWNS LOCK": { - EndpointId: GetCDNID(t, "cdndelete"), ClientSession: opsUserWithLockSession, + EndpointID: GetCDNID(t, "cdndelete"), ClientSession: opsUserWithLockSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetCDNID(t, "cdn2"), ClientSession: TOSession, + EndpointID: GetCDNID(t, "cdn2"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, }, "CACHE GROUP UPDATE": { "OK when USER OWNS LOCK": { - EndpointId: GetCacheGroupId(t, "cachegroup1"), ClientSession: opsUserWithLockSession, + EndpointID: GetCacheGroupId(t, "cachegroup1"), ClientSession: opsUserWithLockSession, RequestBody: map[string]interface{}{ "name": "cachegroup1", "shortName": "newShortName", @@ -209,7 +209,7 @@ func TestCDNLocks(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetCacheGroupId(t, "cachegroup1"), ClientSession: TOSession, + EndpointID: GetCacheGroupId(t, "cachegroup1"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "name": "cachegroup1", "shortName": "newShortName", @@ -232,24 +232,24 @@ func TestCDNLocks(t *testing.T) { }, "DELIVERY SERVICE PUT": { "OK when USER OWNS LOCK": { - EndpointId: GetDeliveryServiceId(t, "basic-ds-in-cdn2"), ClientSession: opsUserWithLockSession, + EndpointID: GetDeliveryServiceId(t, "basic-ds-in-cdn2"), ClientSession: opsUserWithLockSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "xmlId": "basic-ds-in-cdn2", "cdnId": GetCDNID(t, "cdn2")(), "cdnName": "cdn2", "routingName": "cdn"}), Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetDeliveryServiceId(t, "basic-ds-in-cdn2"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "basic-ds-in-cdn2"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{}), Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, }, "DELIVERY SERVICE DELETE": { "OK when USER OWNS LOCK": { - EndpointId: GetDeliveryServiceId(t, "ds-forked-topology"), ClientSession: opsUserWithLockSession, + EndpointID: GetDeliveryServiceId(t, "ds-forked-topology"), ClientSession: opsUserWithLockSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetDeliveryServiceId(t, "top-ds-in-cdn2"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "top-ds-in-cdn2"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, }, @@ -281,7 +281,7 @@ func TestCDNLocks(t *testing.T) { }, "PROFILE PUT": { "OK when USER OWNS LOCK": { - EndpointId: GetProfileID(t, "CDN2_EDGE"), + EndpointID: GetProfileID(t, "CDN2_EDGE"), ClientSession: opsUserWithLockSession, RequestBody: map[string]interface{}{ "cdn": GetCDNID(t, "cdn2")(), @@ -294,7 +294,7 @@ func TestCDNLocks(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetProfileID(t, "EDGEInCDN2"), + EndpointID: GetProfileID(t, "EDGEInCDN2"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "cdn": GetCDNID(t, "cdn2")(), @@ -309,12 +309,12 @@ func TestCDNLocks(t *testing.T) { }, "PROFILE DELETE": { "OK when USER OWNS LOCK": { - EndpointId: GetProfileID(t, "CCR2"), + EndpointID: GetProfileID(t, "CCR2"), ClientSession: opsUserWithLockSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetProfileID(t, "MID2"), + EndpointID: GetProfileID(t, "MID2"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, @@ -339,7 +339,7 @@ func TestCDNLocks(t *testing.T) { }, "PROFILE PARAMETER DELETE": { "OK when USER OWNS LOCK": { - EndpointId: GetProfileID(t, "OKwhenUserOwnLocks"), + EndpointID: GetProfileID(t, "OKwhenUserOwnLocks"), ClientSession: opsUserWithLockSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{ "parameterId": {strconv.Itoa(GetParameterID(t, "test.cdnlock.delete", "rascal.properties", "25.0")())}, @@ -347,7 +347,7 @@ func TestCDNLocks(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetProfileID(t, "FORBIDDENwhenDoesntOwnLock"), + EndpointID: GetProfileID(t, "FORBIDDENwhenDoesntOwnLock"), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{ "parameterId": {strconv.Itoa(GetParameterID(t, "test.cdnlock.forbidden.delete", "rascal.properties", "25.0")())}, @@ -382,7 +382,7 @@ func TestCDNLocks(t *testing.T) { }, "SERVER PUT": { "OK when USER OWNS LOCK": { - EndpointId: GetServerID(t, "edge1-cdn2"), + EndpointID: GetServerID(t, "edge1-cdn2"), ClientSession: opsUserWithLockSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "edge1-cdn2")(), @@ -399,7 +399,7 @@ func TestCDNLocks(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetServerID(t, "dtrc-edge-07"), + EndpointID: GetServerID(t, "dtrc-edge-07"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "dtrc-edge-07")(), @@ -419,12 +419,12 @@ func TestCDNLocks(t *testing.T) { }, "SERVER DELETE": { "OK when USER OWNS LOCK": { - EndpointId: GetServerID(t, "atlanta-mid-17"), + EndpointID: GetServerID(t, "atlanta-mid-17"), ClientSession: opsUserWithLockSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetServerID(t, "denver-mso-org-02"), + EndpointID: GetServerID(t, "denver-mso-org-02"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, @@ -455,7 +455,7 @@ func TestCDNLocks(t *testing.T) { }, "STATIC DNS ENTRIES PUT": { "OK when USER OWNS LOCK": { - EndpointId: GetStaticDNSEntryID(t, "host2"), + EndpointID: GetStaticDNSEntryID(t, "host2"), ClientSession: opsUserWithLockSession, RequestBody: map[string]interface{}{ "address": "192.168.0.2", @@ -467,7 +467,7 @@ func TestCDNLocks(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetStaticDNSEntryID(t, "cdnlock-test-delete-host"), + EndpointID: GetStaticDNSEntryID(t, "cdnlock-test-delete-host"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "address": "192.168.0.2", @@ -481,12 +481,12 @@ func TestCDNLocks(t *testing.T) { }, "STATIC DNS ENTRIES DELETE": { "OK when USER OWNS LOCK": { - EndpointId: GetStaticDNSEntryID(t, "host3"), + EndpointID: GetStaticDNSEntryID(t, "host3"), ClientSession: opsUserWithLockSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetStaticDNSEntryID(t, "cdnlock-negtest-delete-host"), + EndpointID: GetStaticDNSEntryID(t, "cdnlock-negtest-delete-host"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, @@ -533,7 +533,7 @@ func TestCDNLocks(t *testing.T) { } }, "SERVERS QUEUE UPDATES": func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.SetServerQueueUpdate(testCase.EndpointId(), true, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.SetServerQueueUpdate(testCase.EndpointID(), true, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } @@ -571,7 +571,7 @@ func TestCDNLocks(t *testing.T) { cacheGroup := tc.CacheGroupNullable{} err = json.Unmarshal(dat, &cacheGroup) assert.NoError(t, err, "Error occurred when unmarshalling request body: %v", err) - resp, reqInf, err := testCase.ClientSession.UpdateCacheGroup(testCase.EndpointId(), cacheGroup, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.UpdateCacheGroup(testCase.EndpointID(), cacheGroup, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, resp.Alerts, err) } @@ -580,13 +580,13 @@ func TestCDNLocks(t *testing.T) { cdn := tc.CDN{} err = json.Unmarshal(dat, &cdn) assert.NoError(t, err, "Error occurred when unmarshalling request body: %v", err) - alerts, reqInf, err := testCase.ClientSession.UpdateCDN(testCase.EndpointId(), cdn, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateCDN(testCase.EndpointID(), cdn, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }, "CDN DELETE": func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteCDN(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteCDN(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } @@ -604,13 +604,13 @@ func TestCDNLocks(t *testing.T) { ds := tc.DeliveryServiceV4{} err = json.Unmarshal(dat, &ds) assert.NoError(t, err, "Error occurred when unmarshalling request body: %v", err) - resp, reqInf, err := testCase.ClientSession.UpdateDeliveryService(testCase.EndpointId(), ds, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.UpdateDeliveryService(testCase.EndpointID(), ds, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, resp.Alerts, err) } }, "DELIVERY SERVICE DELETE": func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.DeleteDeliveryService(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.DeleteDeliveryService(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, resp.Alerts, err) } @@ -628,13 +628,13 @@ func TestCDNLocks(t *testing.T) { profile := tc.Profile{} err = json.Unmarshal(dat, &profile) assert.NoError(t, err, "Error occurred when unmarshalling request body: %v", err) - alerts, reqInf, err := testCase.ClientSession.UpdateProfile(testCase.EndpointId(), profile, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateProfile(testCase.EndpointID(), profile, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }, "PROFILE DELETE": func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteProfile(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteProfile(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } @@ -650,7 +650,7 @@ func TestCDNLocks(t *testing.T) { }, "PROFILE PARAMETER DELETE": func(t *testing.T) { parameterId, _ := strconv.Atoi(testCase.RequestOpts.QueryParameters["parameterId"][0]) - alerts, reqInf, err := testCase.ClientSession.DeleteProfileParameter(testCase.EndpointId(), parameterId, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteProfileParameter(testCase.EndpointID(), parameterId, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } @@ -668,13 +668,13 @@ func TestCDNLocks(t *testing.T) { server := tc.ServerV4{} err = json.Unmarshal(dat, &server) assert.NoError(t, err, "Error occurred when unmarshalling request body: %v", err) - alerts, reqInf, err := testCase.ClientSession.UpdateServer(testCase.EndpointId(), server, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateServer(testCase.EndpointID(), server, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }, "SERVER DELETE": func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteServer(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteServer(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } @@ -692,13 +692,13 @@ func TestCDNLocks(t *testing.T) { staticDNSEntry := tc.StaticDNSEntry{} err = json.Unmarshal(dat, &staticDNSEntry) assert.NoError(t, err, "Error occurred when unmarshalling request body: %v", err) - alerts, reqInf, err := testCase.ClientSession.UpdateStaticDNSEntry(testCase.EndpointId(), staticDNSEntry, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateStaticDNSEntry(testCase.EndpointID(), staticDNSEntry, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }, "STATIC DNS ENTRIES DELETE": func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteStaticDNSEntry(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteStaticDNSEntry(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/cdn_queue_updates_test.go b/traffic_ops/testing/api/v4/cdn_queue_updates_test.go index fb8e3bd243..704d579874 100644 --- a/traffic_ops/testing/api/v4/cdn_queue_updates_test.go +++ b/traffic_ops/testing/api/v4/cdn_queue_updates_test.go @@ -34,7 +34,7 @@ func TestCDNQueueUpdates(t *testing.T) { methodTests := utils.TestCase[client.Session, client.RequestOptions, bool]{ "POST": { "OK when VALID TYPE parameter": { - EndpointId: GetCDNID(t, "cdn1"), + EndpointID: GetCDNID(t, "cdn1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"type": {"EDGE"}}}, RequestBody: true, @@ -42,7 +42,7 @@ func TestCDNQueueUpdates(t *testing.T) { validateServersUpdatePending(GetCDNID(t, "cdn1")(), map[string]string{"type": "EDGE"})), }, "OK when VALID PROFILE parameter": { - EndpointId: GetCDNID(t, "cdn1"), + EndpointID: GetCDNID(t, "cdn1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"profile": {"EDGE1"}}}, RequestBody: true, @@ -58,9 +58,9 @@ func TestCDNQueueUpdates(t *testing.T) { case "POST": t.Run(name, func(t *testing.T) { // Clear updates on all associated cdn servers to begin with - _, _, err := TOSession.QueueUpdatesForCDN(testCase.EndpointId(), false, client.RequestOptions{}) - assert.RequireNoError(t, err, "Failed to clear updates for cdn %d", testCase.EndpointId()) - resp, reqInf, err := testCase.ClientSession.QueueUpdatesForCDN(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + _, _, err := TOSession.QueueUpdatesForCDN(testCase.EndpointID(), false, client.RequestOptions{}) + assert.RequireNoError(t, err, "Failed to clear updates for cdn %d", testCase.EndpointID()) + resp, reqInf, err := testCase.ClientSession.QueueUpdatesForCDN(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp, tc.Alerts{}, err) } diff --git a/traffic_ops/testing/api/v4/cdns_test.go b/traffic_ops/testing/api/v4/cdns_test.go index c8c1248767..670409a9a1 100644 --- a/traffic_ops/testing/api/v4/cdns_test.go +++ b/traffic_ops/testing/api/v4/cdns_test.go @@ -150,7 +150,7 @@ func TestCDNs(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetCDNID(t, "cdn1"), + EndpointID: GetCDNID(t, "cdn1"), ClientSession: TOSession, RequestBody: tc.CDN{ DNSSECEnabled: false, @@ -161,7 +161,7 @@ func TestCDNs(t *testing.T) { validateCDNUpdateFields("cdn1", map[string]interface{}{"DomainName": "domain2"})), }, "PRECONDITION FAILED when updating with IF-UNMODIFIED-SINCE Headers": { - EndpointId: GetCDNID(t, "cdn1"), + EndpointID: GetCDNID(t, "cdn1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.CDN{ @@ -172,7 +172,7 @@ func TestCDNs(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetCDNID(t, "cdn1"), + EndpointID: GetCDNID(t, "cdn1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfMatch: {rfc.ETag(currentTime)}}}, RequestBody: tc.CDN{ @@ -185,7 +185,7 @@ func TestCDNs(t *testing.T) { }, "DELETE": { "NOT FOUND when INVALID ID parameter": { - EndpointId: func() int { return 111111 }, + EndpointID: func() int { return 111111 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, @@ -211,14 +211,14 @@ func TestCDNs(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateCDN(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateCDN(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteCDN(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteCDN(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/coordinates_test.go b/traffic_ops/testing/api/v4/coordinates_test.go index a1dbefddbe..0426f363be 100644 --- a/traffic_ops/testing/api/v4/coordinates_test.go +++ b/traffic_ops/testing/api/v4/coordinates_test.go @@ -137,7 +137,7 @@ func TestCoordinates(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetCoordinateID(t, "coordinate2"), + EndpointID: GetCoordinateID(t, "coordinate2"), ClientSession: TOSession, RequestBody: tc.Coordinate{ Latitude: 7.7, @@ -148,7 +148,7 @@ func TestCoordinates(t *testing.T) { validateCoordinateUpdateCreateFields("coordinate2", map[string]interface{}{"Latitude": 7.7, "Longitude": 8.8})), }, "NOT FOUND when INVALID ID parameter": { - EndpointId: func() int { return 111111 }, + EndpointID: func() int { return 111111 }, RequestBody: tc.Coordinate{ Latitude: 1.1, Longitude: 2.2, @@ -158,7 +158,7 @@ func TestCoordinates(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetCoordinateID(t, "coordinate1"), + EndpointID: GetCoordinateID(t, "coordinate1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.Coordinate{ @@ -169,7 +169,7 @@ func TestCoordinates(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetCoordinateID(t, "coordinate1"), + EndpointID: GetCoordinateID(t, "coordinate1"), ClientSession: TOSession, RequestBody: tc.Coordinate{ Latitude: 1.1, @@ -182,7 +182,7 @@ func TestCoordinates(t *testing.T) { }, "DELETE": { "NOT FOUND when INVALID ID parameter": { - EndpointId: func() int { return 12345 }, + EndpointID: func() int { return 12345 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, @@ -209,14 +209,14 @@ func TestCoordinates(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateCoordinate(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateCoordinate(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteCoordinate(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteCoordinate(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/deliveryservice_request_comments_test.go b/traffic_ops/testing/api/v4/deliveryservice_request_comments_test.go index d0384b56b4..5b16d33451 100644 --- a/traffic_ops/testing/api/v4/deliveryservice_request_comments_test.go +++ b/traffic_ops/testing/api/v4/deliveryservice_request_comments_test.go @@ -66,7 +66,7 @@ func TestDeliveryServiceRequestComments(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetDSRequestCommentId(t, "admin"), + EndpointID: GetDSRequestCommentId(t, "admin"), ClientSession: TOSession, RequestBody: tc.DeliveryServiceRequestComment{ DeliveryServiceRequestID: GetDSRequestId(t, "test-ds1")(), @@ -75,14 +75,14 @@ func TestDeliveryServiceRequestComments(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "PRECONDITION FAILED when updating with IF-UNMODIFIED-SINCE Header": { - EndpointId: GetDSRequestCommentId(t, "admin"), + EndpointID: GetDSRequestCommentId(t, "admin"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.DeliveryServiceRequestComment{}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetDSRequestCommentId(t, "admin"), + EndpointID: GetDSRequestCommentId(t, "admin"), ClientSession: TOSession, RequestBody: tc.DeliveryServiceRequestComment{}, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfMatch: {rfc.ETag(currentTime)}}}, @@ -104,7 +104,7 @@ func TestDeliveryServiceRequestComments(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateDeliveryServiceRequestComment(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateDeliveryServiceRequestComment(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/deliveryservice_requests_test.go b/traffic_ops/testing/api/v4/deliveryservice_requests_test.go index 07e2e12111..042296e420 100644 --- a/traffic_ops/testing/api/v4/deliveryservice_requests_test.go +++ b/traffic_ops/testing/api/v4/deliveryservice_requests_test.go @@ -76,7 +76,7 @@ func TestDeliveryServiceRequests(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetDeliveryServiceRequestId(t, "test-ds1"), + EndpointID: GetDeliveryServiceRequestId(t, "test-ds1"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "changeType": "create", @@ -90,7 +90,7 @@ func TestDeliveryServiceRequests(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when UPDATING STATUS FROM DRAFT TO SUBMITTED": { - EndpointId: GetDeliveryServiceRequestId(t, "test-ds1"), + EndpointID: GetDeliveryServiceRequestId(t, "test-ds1"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "changeType": "create", @@ -104,7 +104,7 @@ func TestDeliveryServiceRequests(t *testing.T) { validatePutDSRequestFields(map[string]interface{}{"STATUS": tc.RequestStatusSubmitted})), }, "BAD REQUEST when using LONG DESCRIPTION 2 and 3 fields": { - EndpointId: GetDeliveryServiceRequestId(t, "test-ds1"), + EndpointID: GetDeliveryServiceRequestId(t, "test-ds1"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "changeType": "create", @@ -119,14 +119,14 @@ func TestDeliveryServiceRequests(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "PRECONDITION FAILED when updating with IF-UNMODIFIED-SINCE Header": { - EndpointId: GetDeliveryServiceRequestId(t, "test-ds1"), + EndpointID: GetDeliveryServiceRequestId(t, "test-ds1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: map[string]interface{}{}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetDeliveryServiceRequestId(t, "test-ds1"), + EndpointID: GetDeliveryServiceRequestId(t, "test-ds1"), ClientSession: TOSession, RequestBody: map[string]interface{}{}, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfMatch: {rfc.ETag(currentTime)}}}, @@ -263,7 +263,7 @@ func TestDeliveryServiceRequests(t *testing.T) { }, "DELETE": { "OK when VALID request": { - EndpointId: GetDeliveryServiceRequestId(t, "test-deletion"), + EndpointID: GetDeliveryServiceRequestId(t, "test-deletion"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, @@ -306,14 +306,14 @@ func TestDeliveryServiceRequests(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.UpdateDeliveryServiceRequest(testCase.EndpointId(), dsReq, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.UpdateDeliveryServiceRequest(testCase.EndpointID(), dsReq, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.DeleteDeliveryServiceRequest(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.DeleteDeliveryServiceRequest(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v4/deliveryservices_test.go b/traffic_ops/testing/api/v4/deliveryservices_test.go index 98446dff88..d5c68acd6e 100644 --- a/traffic_ops/testing/api/v4/deliveryservices_test.go +++ b/traffic_ops/testing/api/v4/deliveryservices_test.go @@ -254,7 +254,7 @@ func TestDeliveryServices(t *testing.T) { }, "PUT": { "BAD REQUEST when using LONG DESCRIPTION 2 and 3 fields": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "longDesc1": "long desc 1", "longDesc2": "long desc 2", @@ -263,7 +263,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "OK when VALID request": { - EndpointId: GetDeliveryServiceId(t, "ds2"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds2"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "maxRequestHeaderBytes": 131080, "longDesc": "something different", @@ -297,21 +297,21 @@ func TestDeliveryServices(t *testing.T) { })), }, "BAD REQUEST when INVALID REMAP TEXT": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "remapText": "@plugin=tslua.so @pparam=/opt/trafficserver/etc/trafficserver/remapPlugin1.lua\nline2", }), Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when MISSING SLICE PLUGIN SIZE": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "rangeRequestHandling": 3, }), Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when SLICE PLUGIN SIZE SET with INVALID RANGE REQUEST SETTING": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "rangeRequestHandling": 1, "rangeSliceBlockSize": 262144, @@ -319,7 +319,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when SLICE PLUGIN SIZE TOO SMALL": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "rangeRequestHandling": 3, "rangeSliceBlockSize": 0, @@ -327,7 +327,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when SLICE PLUGIN SIZE TOO LARGE": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "rangeRequestHandling": 3, "rangeSliceBlockSize": 40000000, @@ -335,7 +335,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when ADDING TOPOLOGY to CLIENT STEERING DS": { - EndpointId: GetDeliveryServiceId(t, "ds-client-steering"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds-client-steering"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "topology": "mso-topology", "xmlId": "ds-client-steering", @@ -344,7 +344,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when TOPOLOGY DOESNT EXIST": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "topology": "", "xmlId": "ds1", @@ -352,7 +352,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when ADDING TOPOLOGY to DS with DS REQUIRED CAPABILITY": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "topology": "top-for-ds-req", "xmlId": "ds1", @@ -360,7 +360,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when ADDING TOPOLOGY to DS when NO CACHES in SAME CDN as DS": { - EndpointId: GetDeliveryServiceId(t, "top-ds-in-cdn2"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "top-ds-in-cdn2"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "cdnId": GetCDNID(t, "cdn2")(), "topology": "top-with-caches-in-cdn1", @@ -369,7 +369,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "OK when REMOVING TOPOLOGY": { - EndpointId: GetDeliveryServiceId(t, "ds-based-top-with-no-mids"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds-based-top-with-no-mids"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "topology": nil, "xmlId": "ds-based-top-with-no-mids", @@ -377,7 +377,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when DS with TOPOLOGY updates HEADER REWRITE FIELDS": { - EndpointId: GetDeliveryServiceId(t, "ds-top"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds-top"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "firstHeaderRewrite": "foo", "innerHeaderRewrite": "bar", @@ -388,7 +388,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "BAD REQUEST when DS with NO TOPOLOGY updates HEADER REWRITE FIELDS": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "firstHeaderRewrite": "foo", "innerHeaderRewrite": "bar", @@ -397,7 +397,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when DS with TOPOLOGY updates LEGACY HEADER REWRITE FIELDS": { - EndpointId: GetDeliveryServiceId(t, "ds-top"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds-top"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "edgeHeaderRewrite": "foo", "midHeaderRewrite": "bar", @@ -407,7 +407,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "OK when DS with NO TOPOLOGY updates LEGACY HEADER REWRITE FIELDS": { - EndpointId: GetDeliveryServiceId(t, "ds2"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds2"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "profileId": GetProfileID(t, "ATS_EDGE_TIER_CACHE")(), "edgeHeaderRewrite": "foo", @@ -418,7 +418,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when UPDATING MINOR VERSION FIELDS": { - EndpointId: GetDeliveryServiceId(t, "ds-test-minor-versions"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds-test-minor-versions"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "consistentHashQueryParams": []string{"d", "e", "f"}, "consistentHashRegex": "foo", @@ -440,7 +440,7 @@ func TestDeliveryServices(t *testing.T) { })), }, "BAD REQUEST when INVALID COUNTRY CODE": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "geoLimit": 2, "geoLimitCountries": []string{"US", "CA", "12"}, @@ -449,7 +449,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when CHANGING TOPOLOGY of DS with ORG SERVERS ASSIGNED": { - EndpointId: GetDeliveryServiceId(t, "ds-top"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds-top"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "topology": "another-topology", "xmlId": "ds-top", @@ -457,18 +457,18 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when UPDATING DS OUTSIDE TENANCY": { - EndpointId: GetDeliveryServiceId(t, "ds3"), ClientSession: tenant4UserSession, + EndpointID: GetDeliveryServiceId(t, "ds3"), ClientSession: tenant4UserSession, RequestBody: generateDeliveryService(t, map[string]interface{}{"xmlId": "ds3"}), Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: generateDeliveryService(t, map[string]interface{}{"xmlId": "ds1"}), Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{"xmlId": "ds1"}), RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfMatch: {rfc.ETag(currentTime)}}}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), @@ -476,7 +476,7 @@ func TestDeliveryServices(t *testing.T) { }, "DELETE": { "BAD REQUEST when DELETING DS OUTSIDE TENANCY": { - EndpointId: GetDeliveryServiceId(t, "ds3"), ClientSession: tenant4UserSession, + EndpointID: GetDeliveryServiceId(t, "ds3"), ClientSession: tenant4UserSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, }, @@ -489,7 +489,7 @@ func TestDeliveryServices(t *testing.T) { }, "DELIVERY SERVICES CAPACITY": { "OK when VALID request": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, }, @@ -550,21 +550,21 @@ func TestDeliveryServices(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.UpdateDeliveryService(testCase.EndpointId(), ds, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.UpdateDeliveryService(testCase.EndpointID(), ds, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.DeleteDeliveryService(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.DeleteDeliveryService(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, resp.Alerts, err) } }) case "DELIVERY SERVICES CAPACITY": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetDeliveryServiceCapacity(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.GetDeliveryServiceCapacity(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v4/deliveryserviceservers_test.go b/traffic_ops/testing/api/v4/deliveryserviceservers_test.go index e03fc7c15c..da0561ced4 100644 --- a/traffic_ops/testing/api/v4/deliveryserviceservers_test.go +++ b/traffic_ops/testing/api/v4/deliveryserviceservers_test.go @@ -224,7 +224,7 @@ func TestDeliveryServicesIDServers(t *testing.T) { dsIDServersTests := utils.V4TestCase{ "GET": { "OK when VALID request": { - EndpointId: GetDeliveryServiceId(t, "test-ds-server-assignments"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "test-ds-server-assignments"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseHasLength(2)), }, @@ -236,7 +236,7 @@ func TestDeliveryServicesIDServers(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetServersByDeliveryService(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.GetServersByDeliveryService(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v4/deliveryservicesideligible_test.go b/traffic_ops/testing/api/v4/deliveryservicesideligible_test.go index 8aa516c2cb..b19612ca39 100644 --- a/traffic_ops/testing/api/v4/deliveryservicesideligible_test.go +++ b/traffic_ops/testing/api/v4/deliveryservicesideligible_test.go @@ -29,7 +29,7 @@ func TestDeliveryServicesEligible(t *testing.T) { methodTests := utils.TestCase[client.Session, client.RequestOptions, struct{}]{ "GET": { "OK when VALID request": { - EndpointId: GetDeliveryServiceId(t, "ds1"), + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseLengthGreaterOrEqual(1)), }, @@ -41,7 +41,7 @@ func TestDeliveryServicesEligible(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetDeliveryServicesEligible(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.GetDeliveryServicesEligible(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v4/deliveryservicesregexes_test.go b/traffic_ops/testing/api/v4/deliveryservicesregexes_test.go index afad9dd622..6fd0cfc216 100644 --- a/traffic_ops/testing/api/v4/deliveryservicesregexes_test.go +++ b/traffic_ops/testing/api/v4/deliveryservicesregexes_test.go @@ -34,12 +34,12 @@ func TestDeliveryServicesRegexes(t *testing.T) { methodTests := utils.TestCase[client.Session, client.RequestOptions, tc.DeliveryServiceRegexPost]{ "GET": { "OK when VALID request": { - EndpointId: GetDeliveryServiceId(t, "ds1"), + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseHasLength(3)), }, "OK when VALID ID parameter": { - EndpointId: GetDeliveryServiceId(t, "ds1"), + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"id": {strconv.Itoa(getDSRegexID(t, "ds1"))}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseHasLength(1)), @@ -47,7 +47,7 @@ func TestDeliveryServicesRegexes(t *testing.T) { }, "POST": { "BAD REQUEST when MISSING REGEX PATTERN": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: tc.DeliveryServiceRegexPost{ Type: GetTypeId(t, "HOST_REGEXP"), SetNumber: 3, @@ -64,14 +64,14 @@ func TestDeliveryServicesRegexes(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetDeliveryServiceRegexesByDSID(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.GetDeliveryServiceRegexesByDSID(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } }) case "POST": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.PostDeliveryServiceRegexesByDSID(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.PostDeliveryServiceRegexesByDSID(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/divisions_test.go b/traffic_ops/testing/api/v4/divisions_test.go index f3b4ece4f8..0f39c11bec 100644 --- a/traffic_ops/testing/api/v4/divisions_test.go +++ b/traffic_ops/testing/api/v4/divisions_test.go @@ -108,7 +108,7 @@ func TestDivisions(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetDivisionID(t, "cdn-div2"), + EndpointID: GetDivisionID(t, "cdn-div2"), ClientSession: TOSession, RequestBody: tc.Division{ Name: "testdivision", @@ -117,7 +117,7 @@ func TestDivisions(t *testing.T) { validateDivisionUpdateCreateFields("testdivision", map[string]interface{}{"Name": "testdivision"})), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetDivisionID(t, "division1"), + EndpointID: GetDivisionID(t, "division1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.Division{ @@ -126,7 +126,7 @@ func TestDivisions(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetDivisionID(t, "division1"), + EndpointID: GetDivisionID(t, "division1"), ClientSession: TOSession, RequestBody: tc.Division{ Name: "division1", @@ -137,12 +137,12 @@ func TestDivisions(t *testing.T) { }, "DELETE": { "BAD REQUEST when DIVISION in use by REGION": { - EndpointId: GetDivisionID(t, "division1"), + EndpointID: GetDivisionID(t, "division1"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "NOT FOUND when INVALID ID parameter": { - EndpointId: func() int { return 111111 }, + EndpointID: func() int { return 111111 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, @@ -169,14 +169,14 @@ func TestDivisions(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateDivision(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateDivision(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteDivision(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteDivision(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/federation_deliveryservices_test.go b/traffic_ops/testing/api/v4/federation_deliveryservices_test.go index 9873b46789..f3983fe97c 100644 --- a/traffic_ops/testing/api/v4/federation_deliveryservices_test.go +++ b/traffic_ops/testing/api/v4/federation_deliveryservices_test.go @@ -36,57 +36,57 @@ func TestFederationsDeliveryServices(t *testing.T) { methodTests := utils.TestCase[client.Session, client.RequestOptions, tc.FederationDSPost]{ "GET": { "OK when VALID request": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseLengthGreaterOrEqual(1)), }, "SORTED when ORDERBY=DSID parameter": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"orderby": {"dsID"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateFederationDeliveryServicesSort(false)), }, "SORTED when ORDERBY=DSID and SORTORDER=DESC parameter": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"orderby": {"dsID"}, "sortOrder": {"desc"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateFederationDeliveryServicesSort(true)), }, "FIRST RESULT when LIMIT=1": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"orderby": {"dsID"}, "limit": {"1"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateFederationDeliveryServicesPagination(GetFederationID(t, "the.cname.com.")(), "limit")), }, "SECOND RESULT when LIMIT=1 OFFSET=1": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"orderby": {"dsID"}, "limit": {"1"}, "offset": {"1"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateFederationDeliveryServicesPagination(GetFederationID(t, "the.cname.com.")(), "offset")), }, "SECOND RESULT when LIMIT=1 PAGE=2": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"orderby": {"dsID"}, "limit": {"1"}, "page": {"2"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateFederationDeliveryServicesPagination(GetFederationID(t, "the.cname.com.")(), "page")), }, "BAD REQUEST when INVALID LIMIT parameter": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"limit": {"-2"}}}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when INVALID OFFSET parameter": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"limit": {"1"}, "offset": {"0"}}}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when INVALID PAGE parameter": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"limit": {"1"}, "page": {"0"}}}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), @@ -94,13 +94,13 @@ func TestFederationsDeliveryServices(t *testing.T) { }, "DELETE": { "OK when VALID request": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"dsID": {strconv.Itoa(GetDeliveryServiceId(t, "ds1")())}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "BAD REQUEST when LAST DELIVERY SERVICE": { - EndpointId: GetFederationID(t, "google.com."), + EndpointID: GetFederationID(t, "google.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"dsID": {strconv.Itoa(GetDeliveryServiceId(t, "ds2")())}}}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), @@ -114,7 +114,7 @@ func TestFederationsDeliveryServices(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetFederationDeliveryServices(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.GetFederationDeliveryServices(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } @@ -122,7 +122,7 @@ func TestFederationsDeliveryServices(t *testing.T) { case "POST": t.Run(name, func(t *testing.T) { fedDS := testCase.RequestBody - alerts, reqInf, err := testCase.ClientSession.CreateFederationDeliveryServices(testCase.EndpointId(), fedDS.DSIDs, *fedDS.Replace, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.CreateFederationDeliveryServices(testCase.EndpointID(), fedDS.DSIDs, *fedDS.Replace, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } @@ -135,7 +135,7 @@ func TestFederationsDeliveryServices(t *testing.T) { assert.RequireNoError(t, err, "Failed to convert dsID to an integer.") dsID = id } - alerts, reqInf, err := testCase.ClientSession.DeleteFederationDeliveryService(testCase.EndpointId(), dsID, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteFederationDeliveryService(testCase.EndpointID(), dsID, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/federation_federation_resolvers_test.go b/traffic_ops/testing/api/v4/federation_federation_resolvers_test.go index 339add0c13..3d0515eaf0 100644 --- a/traffic_ops/testing/api/v4/federation_federation_resolvers_test.go +++ b/traffic_ops/testing/api/v4/federation_federation_resolvers_test.go @@ -31,19 +31,19 @@ func TestFederationFederationResolvers(t *testing.T) { methodTests := utils.TestCase[client.Session, client.RequestOptions, tc.AssignFederationResolversRequest]{ "GET": { "OK when VALID request AND RESOLVERS ASSIGNED": { - EndpointId: GetFederationID(t, "booya.com."), + EndpointID: GetFederationID(t, "booya.com."), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseLengthGreaterOrEqual(1)), }, "OK when VALID request AND NO RESOLVERS ASSIGNED": { - EndpointId: GetFederationID(t, "google.com."), + EndpointID: GetFederationID(t, "google.com."), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseHasLength(0)), }, }, "POST": { "OK when ASSIGNING ONE FEDERATION RESOLVER": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestBody: tc.AssignFederationResolversRequest{ FedResolverIDs: []int{GetFederationResolverID(t, "1.2.3.4")()}, @@ -52,7 +52,7 @@ func TestFederationFederationResolvers(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when ASSIGNING MULTIPLE FEDERATION RESOLVERS": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestBody: tc.AssignFederationResolversRequest{ FedResolverIDs: []int{ @@ -65,7 +65,7 @@ func TestFederationFederationResolvers(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when REPLACING ALL FEDERATION RESOLVERS": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestBody: tc.AssignFederationResolversRequest{ FedResolverIDs: []int{GetFederationResolverID(t, "dead::babe")()}, @@ -74,7 +74,7 @@ func TestFederationFederationResolvers(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "BAD REQUEST when FEDERATION DOESNT EXIST": { - EndpointId: func() int { return -1 }, + EndpointID: func() int { return -1 }, ClientSession: TOSession, RequestBody: tc.AssignFederationResolversRequest{ FedResolverIDs: []int{GetFederationResolverID(t, "1.2.3.4")()}, @@ -91,7 +91,7 @@ func TestFederationFederationResolvers(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetFederationFederationResolvers(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.GetFederationFederationResolvers(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } @@ -99,7 +99,7 @@ func TestFederationFederationResolvers(t *testing.T) { case "POST": t.Run(name, func(t *testing.T) { frAssignment := testCase.RequestBody - resp, reqInf, err := testCase.ClientSession.AssignFederationFederationResolver(testCase.EndpointId(), frAssignment.FedResolverIDs, frAssignment.Replace, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.AssignFederationFederationResolver(testCase.EndpointID(), frAssignment.FedResolverIDs, frAssignment.Replace, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v4/federation_resolvers_test.go b/traffic_ops/testing/api/v4/federation_resolvers_test.go index 503af5faf5..ba92f3cb17 100644 --- a/traffic_ops/testing/api/v4/federation_resolvers_test.go +++ b/traffic_ops/testing/api/v4/federation_resolvers_test.go @@ -125,7 +125,7 @@ func TestFederationResolvers(t *testing.T) { }, "DELETE": { "NOT FOUND when INVALID ID": { - EndpointId: func() int { return 0 }, + EndpointID: func() int { return 0 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, @@ -152,7 +152,7 @@ func TestFederationResolvers(t *testing.T) { }) case "DELETE": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.DeleteFederationResolver(uint(testCase.EndpointId()), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.DeleteFederationResolver(uint(testCase.EndpointID()), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v4/federation_users_test.go b/traffic_ops/testing/api/v4/federation_users_test.go index 351759bb42..f7ccfe5644 100644 --- a/traffic_ops/testing/api/v4/federation_users_test.go +++ b/traffic_ops/testing/api/v4/federation_users_test.go @@ -41,69 +41,69 @@ func TestFederationUsers(t *testing.T) { methodTests := utils.TestCase[client.Session, client.RequestOptions, tc.FederationUserPost]{ "GET": { "NOT MODIFIED when NO CHANGES made": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfModifiedSince: {tomorrow}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusNotModified)), }, "BAD REQUEST when INVALID FEDERATION ID": { - EndpointId: func() int { return -1 }, + EndpointID: func() int { return -1 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "SORTED by ID when ORDERBY=USERID parameter": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"orderby": {"userID"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateFederationUserIDSort(false)), }, "VALID when SORTORDER param is DESC": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"orderby": {"userID"}, "sortOrder": {"desc"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateFederationUserIDSort(true)), }, "FIRST RESULT when LIMIT=1": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"orderby": {"userID"}, "limit": {"1"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateFederationUsersPagination(GetFederationID(t, "the.cname.com.")(), "limit")), }, "SECOND RESULT when LIMIT=1 OFFSET=1": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"orderby": {"userID"}, "limit": {"1"}, "offset": {"1"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateFederationUsersPagination(GetFederationID(t, "the.cname.com.")(), "offset")), }, "SECOND RESULT when LIMIT=1 PAGE=2": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"orderby": {"userID"}, "limit": {"1"}, "page": {"2"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateFederationUsersPagination(GetFederationID(t, "the.cname.com.")(), "page")), }, "BAD REQUEST when INVALID LIMIT parameter": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"limit": {"-2"}}}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when INVALID OFFSET parameter": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"limit": {"1"}, "offset": {"0"}}}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when INVALID PAGE parameter": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"limit": {"1"}, "page": {"0"}}}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "OK when CHANGES made": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfModifiedSince: {currentTimeRFC}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), @@ -111,7 +111,7 @@ func TestFederationUsers(t *testing.T) { }, "POST": { "OK when VALID request": { - EndpointId: GetFederationID(t, "google.com."), + EndpointID: GetFederationID(t, "google.com."), ClientSession: TOSession, RequestBody: tc.FederationUserPost{ IDs: []int{ @@ -123,7 +123,7 @@ func TestFederationUsers(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when REPLACING USERS": { - EndpointId: GetFederationID(t, "booya.com."), + EndpointID: GetFederationID(t, "booya.com."), ClientSession: TOSession, RequestBody: tc.FederationUserPost{ IDs: []int{GetUserID(t, "readonlyuser")()}, @@ -132,7 +132,7 @@ func TestFederationUsers(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when ADDING USER": { - EndpointId: GetFederationID(t, "booya.com."), + EndpointID: GetFederationID(t, "booya.com."), ClientSession: TOSession, RequestBody: tc.FederationUserPost{ IDs: []int{GetUserID(t, "disalloweduser")()}, @@ -141,7 +141,7 @@ func TestFederationUsers(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "BAD REQUEST when INVALID FEDERATION ID": { - EndpointId: func() int { return -1 }, + EndpointID: func() int { return -1 }, ClientSession: TOSession, RequestBody: tc.FederationUserPost{ IDs: []int{}, @@ -150,7 +150,7 @@ func TestFederationUsers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "BAD REQUEST when INVALID USER ID": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestBody: tc.FederationUserPost{ IDs: []int{-1}, @@ -167,7 +167,7 @@ func TestFederationUsers(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetFederationUsers(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.GetFederationUsers(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } @@ -175,7 +175,7 @@ func TestFederationUsers(t *testing.T) { case "POST": t.Run(name, func(t *testing.T) { federationUser := testCase.RequestBody - alerts, reqInf, err := testCase.ClientSession.CreateFederationUsers(testCase.EndpointId(), federationUser.IDs, *federationUser.Replace, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.CreateFederationUsers(testCase.EndpointID(), federationUser.IDs, *federationUser.Replace, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/jobs_test.go b/traffic_ops/testing/api/v4/jobs_test.go index efc5aa150c..d73673c4a4 100644 --- a/traffic_ops/testing/api/v4/jobs_test.go +++ b/traffic_ops/testing/api/v4/jobs_test.go @@ -498,7 +498,7 @@ func TestJobs(t *testing.T) { }, "DELETE": { "NOT FOUND when JOB DOESNT EXIST": { - EndpointId: func() int { return 1111111111 }, + EndpointID: func() int { return 1111111111 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, @@ -547,7 +547,7 @@ func TestJobs(t *testing.T) { }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteInvalidationJob(uint64(testCase.EndpointId()), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteInvalidationJob(uint64(testCase.EndpointID()), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/origins_test.go b/traffic_ops/testing/api/v4/origins_test.go index 3ed2801362..0eed7229ee 100644 --- a/traffic_ops/testing/api/v4/origins_test.go +++ b/traffic_ops/testing/api/v4/origins_test.go @@ -275,7 +275,7 @@ func TestOrigins(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin2"), @@ -294,7 +294,7 @@ func TestOrigins(t *testing.T) { "FQDN": "originupdated.example.com", "IPAddress": "1.2.3.4", "IP6Address": "0000::1111", "Port": 1234, "Protocol": "http", "Tenant": "tenant2"})), }, "FORBIDDEN when CHILD TENANT updates PARENT TENANT ORIGIN": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: tenant4UserSession, RequestBody: tc.Origin{ Name: util.Ptr("testtenancy"), @@ -306,7 +306,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, "NOT FOUND when ORIGIN DOESNT EXIST": { - EndpointId: func() int { return 1111111 }, + EndpointID: func() int { return 1111111 }, ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("testid"), @@ -318,7 +318,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "BAD REQUEST when DELIVERY SERVICE DOESNT EXIST": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin2"), @@ -330,7 +330,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "NOT FOUND when CACHEGROUP DOESNT EXIST": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin2"), @@ -343,7 +343,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "NOT FOUND when PROFILEID DOESNT EXIST": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin2"), @@ -357,7 +357,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "NOT FOUND when COORDINATE DOESNT EXIST": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin2"), @@ -371,7 +371,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "FORBIDDEN when INVALID TENANT": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin1"), @@ -384,7 +384,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, "BAD REQUEST when INVALID PROTOCOL": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin2"), @@ -397,7 +397,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when INVALID IPV4 ADDRESS": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin2"), @@ -411,7 +411,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when INVALID IPV6 ADDRESS": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin2"), @@ -425,7 +425,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when INVALID PORT": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin2"), @@ -439,7 +439,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.Origin{ @@ -453,7 +453,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin2"), @@ -469,12 +469,12 @@ func TestOrigins(t *testing.T) { }, "DELETE": { "NOT FOUND when DOESNT EXIST": { - EndpointId: func() int { return 11111111 }, + EndpointID: func() int { return 11111111 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "FORBIDDEN when CHILD TENANT deletes PARENT TENANT ORIGIN": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: tenant4UserSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, @@ -501,14 +501,14 @@ func TestOrigins(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.UpdateOrigin(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.UpdateOrigin(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteOrigin(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteOrigin(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/parameters_test.go b/traffic_ops/testing/api/v4/parameters_test.go index fbbdfbc1c0..4d5877ead1 100644 --- a/traffic_ops/testing/api/v4/parameters_test.go +++ b/traffic_ops/testing/api/v4/parameters_test.go @@ -191,7 +191,7 @@ func TestParameters(t *testing.T) { }, "PUT": { "OK when VALID REQUEST": { - EndpointId: GetParameterID(t, "LogObject.Format", "logs_xml.config", "custom_ats_2"), + EndpointID: GetParameterID(t, "LogObject.Format", "logs_xml.config", "custom_ats_2"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "configFile": "updated.config", @@ -204,7 +204,7 @@ func TestParameters(t *testing.T) { map[string]interface{}{"ConfigFile": "updated.config", "Name": "updated name", "Secure": true, "Value": "updated value"})), }, "OK when MISSING VALUE FIELD": { - EndpointId: GetParameterID(t, "LogObject.Filename", "logs_xml.config", "custom_ats_2"), + EndpointID: GetParameterID(t, "LogObject.Filename", "logs_xml.config", "custom_ats_2"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "configFile": "logs_new.config", @@ -217,7 +217,7 @@ func TestParameters(t *testing.T) { map[string]interface{}{"ConfigFile": "logs_new.config", "Secure": true, "Value": ""})), }, "BAD REQUEST when MISSING NAME FIELD": { - EndpointId: GetParameterID(t, "astats_over_http.so", "plugin.config", ""), + EndpointID: GetParameterID(t, "astats_over_http.so", "plugin.config", ""), ClientSession: TOSession, RequestBody: map[string]interface{}{ "configFile": "missingname.config", @@ -228,7 +228,7 @@ func TestParameters(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when MISSING CONFIGFILE FIELD": { - EndpointId: GetParameterID(t, "astats_over_http.so", "plugin.config", ""), + EndpointID: GetParameterID(t, "astats_over_http.so", "plugin.config", ""), ClientSession: TOSession, RequestBody: map[string]interface{}{ "configFile": "", @@ -239,7 +239,7 @@ func TestParameters(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetParameterID(t, "LogFormat.Name", "logs_xml.config", "custom_ats_2"), + EndpointID: GetParameterID(t, "LogFormat.Name", "logs_xml.config", "custom_ats_2"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: map[string]interface{}{ @@ -250,7 +250,7 @@ func TestParameters(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetParameterID(t, "LogFormat.Name", "logs_xml.config", "custom_ats_2"), + EndpointID: GetParameterID(t, "LogFormat.Name", "logs_xml.config", "custom_ats_2"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "configFile": "logs_xml.config", @@ -263,7 +263,7 @@ func TestParameters(t *testing.T) { }, "DELETE": { "BAD REQUEST when DOESNT EXIST": { - EndpointId: func() int { return 100000 }, + EndpointID: func() int { return 100000 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, @@ -313,14 +313,14 @@ func TestParameters(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateParameter(testCase.EndpointId(), parameter, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateParameter(testCase.EndpointID(), parameter, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteParameter(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteParameter(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/phys_locations_test.go b/traffic_ops/testing/api/v4/phys_locations_test.go index 13f988fcc9..61a6fcf705 100644 --- a/traffic_ops/testing/api/v4/phys_locations_test.go +++ b/traffic_ops/testing/api/v4/phys_locations_test.go @@ -133,7 +133,7 @@ func TestPhysLocations(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetPhysicalLocationID(t, "HotAtlanta"), + EndpointID: GetPhysicalLocationID(t, "HotAtlanta"), ClientSession: TOSession, RequestBody: tc.PhysLocation{ Address: "1234 southern way", @@ -149,7 +149,7 @@ func TestPhysLocations(t *testing.T) { validatePhysicalLocationUpdateCreateFields("HotAtlanta", map[string]interface{}{"City": "NewCity"})), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetPhysicalLocationID(t, "HotAtlanta"), + EndpointID: GetPhysicalLocationID(t, "HotAtlanta"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.PhysLocation{ @@ -164,7 +164,7 @@ func TestPhysLocations(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetPhysicalLocationID(t, "HotAtlanta"), + EndpointID: GetPhysicalLocationID(t, "HotAtlanta"), ClientSession: TOSession, RequestBody: tc.PhysLocation{ Address: "1234 southern way", @@ -181,7 +181,7 @@ func TestPhysLocations(t *testing.T) { }, "DELETE": { "OK when VALID request": { - EndpointId: GetPhysicalLocationID(t, "testDelete"), + EndpointID: GetPhysicalLocationID(t, "testDelete"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, @@ -208,14 +208,14 @@ func TestPhysLocations(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdatePhysLocation(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdatePhysLocation(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeletePhysLocation(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeletePhysLocation(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/profile_parameters_test.go b/traffic_ops/testing/api/v4/profile_parameters_test.go index d70ba04478..efa620533e 100644 --- a/traffic_ops/testing/api/v4/profile_parameters_test.go +++ b/traffic_ops/testing/api/v4/profile_parameters_test.go @@ -106,7 +106,7 @@ func TestProfileParameters(t *testing.T) { }, "DELETE": { "OK when VALID request": { - EndpointId: GetProfileID(t, "ATS_EDGE_TIER_CACHE"), + EndpointID: GetProfileID(t, "ATS_EDGE_TIER_CACHE"), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{ "parameterId": {strconv.Itoa(GetParameterID(t, "location", "set_dscp_37.config", "/etc/trafficserver/dscp")())}, @@ -160,7 +160,7 @@ func TestProfileParameters(t *testing.T) { case "DELETE": t.Run(name, func(t *testing.T) { parameterId, _ := strconv.Atoi(testCase.RequestOpts.QueryParameters["parameterId"][0]) - alerts, reqInf, err := testCase.ClientSession.DeleteProfileParameter(testCase.EndpointId(), parameterId, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteProfileParameter(testCase.EndpointID(), parameterId, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/profiles_export_test.go b/traffic_ops/testing/api/v4/profiles_export_test.go index c02efcc5cb..453c594f28 100644 --- a/traffic_ops/testing/api/v4/profiles_export_test.go +++ b/traffic_ops/testing/api/v4/profiles_export_test.go @@ -33,14 +33,14 @@ func TestProfilesExport(t *testing.T) { methodTests := utils.TestCase[client.Session, client.RequestOptions, struct{}]{ "GET": { "OK when VALID request": { - EndpointId: GetProfileID(t, "EDGE1"), + EndpointID: GetProfileID(t, "EDGE1"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateProfilesExportFields(map[string]interface{}{"CDNName": "cdn1", "Name": "EDGE1", "Description": "edge1 description", "Type": "ATS_PROFILE"})), }, "NOT FOUND when PROFILE DOESNT EXIST": { - EndpointId: func() int { return 1111111111 }, + EndpointID: func() int { return 1111111111 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, @@ -53,7 +53,7 @@ func TestProfilesExport(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.ExportProfile(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.ExportProfile(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v4/profiles_test.go b/traffic_ops/testing/api/v4/profiles_test.go index d6a5c93955..7a3ba4d17f 100644 --- a/traffic_ops/testing/api/v4/profiles_test.go +++ b/traffic_ops/testing/api/v4/profiles_test.go @@ -163,7 +163,7 @@ func TestProfiles(t *testing.T) { }, "PUT": { "OK when VALID REQUEST": { - EndpointId: GetProfileID(t, "EDGE2"), + EndpointID: GetProfileID(t, "EDGE2"), ClientSession: TOSession, RequestBody: tc.Profile{ CDNID: GetCDNID(t, "cdn2")(), @@ -178,7 +178,7 @@ func TestProfiles(t *testing.T) { "Name": "EDGE2UPDATED", "RoutingDisabled": false, "Type": "TR_PROFILE"})), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetProfileID(t, "CCR1"), + EndpointID: GetProfileID(t, "CCR1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.Profile{ @@ -191,7 +191,7 @@ func TestProfiles(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetProfileID(t, "CCR1"), + EndpointID: GetProfileID(t, "CCR1"), ClientSession: TOSession, RequestBody: tc.Profile{ CDNID: GetCDNID(t, "cdn1")(), @@ -226,14 +226,14 @@ func TestProfiles(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateProfile(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateProfile(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteProfile(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteProfile(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/regions_test.go b/traffic_ops/testing/api/v4/regions_test.go index 5c45668d6f..5166b0e751 100644 --- a/traffic_ops/testing/api/v4/regions_test.go +++ b/traffic_ops/testing/api/v4/regions_test.go @@ -131,7 +131,7 @@ func TestRegions(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetRegionID(t, "cdn-region2"), + EndpointID: GetRegionID(t, "cdn-region2"), ClientSession: TOSession, RequestBody: tc.Region{ Name: "newName", @@ -142,7 +142,7 @@ func TestRegions(t *testing.T) { validateRegionsUpdateCreateFields("newName", map[string]interface{}{"Name": "newName"})), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetRegionID(t, "region1"), + EndpointID: GetRegionID(t, "region1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.Region{ @@ -153,7 +153,7 @@ func TestRegions(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetRegionID(t, "region1"), + EndpointID: GetRegionID(t, "region1"), ClientSession: TOSession, RequestBody: tc.Region{ Name: "newName", @@ -204,7 +204,7 @@ func TestRegions(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateRegion(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateRegion(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/servers_id_deliveryservices_test.go b/traffic_ops/testing/api/v4/servers_id_deliveryservices_test.go index c8787fabf0..e76d7d7b2c 100644 --- a/traffic_ops/testing/api/v4/servers_id_deliveryservices_test.go +++ b/traffic_ops/testing/api/v4/servers_id_deliveryservices_test.go @@ -36,20 +36,20 @@ func TestServersIDDeliveryServices(t *testing.T) { methodTests := utils.V4TestCase{ "GET": { "NOT MODIFIED when NO CHANGES made": { - EndpointId: GetServerID(t, "atlanta-edge-14"), + EndpointID: GetServerID(t, "atlanta-edge-14"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfModifiedSince: {tomorrow}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusNotModified)), }, "OK when VALID request": { - EndpointId: GetServerID(t, "atlanta-edge-14"), + EndpointID: GetServerID(t, "atlanta-edge-14"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, }, "POST": { "OK when VALID request": { - EndpointId: GetServerID(t, "atlanta-edge-01"), + EndpointID: GetServerID(t, "atlanta-edge-01"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "dsIds": []int{GetDeliveryServiceId(t, "ds1")()}, @@ -59,7 +59,7 @@ func TestServersIDDeliveryServices(t *testing.T) { validateServersDeliveryServicesPost(GetServerID(t, "atlanta-edge-01")(), GetDeliveryServiceId(t, "ds1")())), }, "OK when ASSIGNING EDGE to TOPOLOGY BASED DELIVERY SERVICE": { - EndpointId: GetServerID(t, "atlanta-edge-03"), + EndpointID: GetServerID(t, "atlanta-edge-03"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "dsIds": []int{GetDeliveryServiceId(t, "top-ds-in-cdn1")()}, @@ -69,7 +69,7 @@ func TestServersIDDeliveryServices(t *testing.T) { validateServersDeliveryServicesPost(GetServerID(t, "atlanta-edge-03")(), GetDeliveryServiceId(t, "top-ds-in-cdn1")())), }, "OK when ASSIGNING ORIGIN to TOPOLOGY BASED DELIVERY SERVICE": { - EndpointId: GetServerID(t, "denver-mso-org-01"), + EndpointID: GetServerID(t, "denver-mso-org-01"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "dsIds": []int{GetDeliveryServiceId(t, "ds-top")()}, @@ -79,7 +79,7 @@ func TestServersIDDeliveryServices(t *testing.T) { validateServersDeliveryServicesPost(GetServerID(t, "denver-mso-org-01")(), GetDeliveryServiceId(t, "ds-top")())), }, "CONFLICT when SERVER NOT IN SAME CDN as DELIVERY SERVICE": { - EndpointId: GetServerID(t, "cdn2-test-edge"), + EndpointID: GetServerID(t, "cdn2-test-edge"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "dsIds": []int{GetDeliveryServiceId(t, "ds1")()}, @@ -88,7 +88,7 @@ func TestServersIDDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusConflict)), }, "BAD REQUEST when ORIGIN'S CACHEGROUP IS NOT A PART OF TOPOLOGY BASED DELIVERY SERVICE": { - EndpointId: GetServerID(t, "denver-mso-org-01"), + EndpointID: GetServerID(t, "denver-mso-org-01"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "dsIds": []int{GetDeliveryServiceId(t, "ds-top-req-cap")()}, @@ -97,7 +97,7 @@ func TestServersIDDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "CONFLICT when REMOVING ONLY EDGE SERVER ASSIGNMENT": { - EndpointId: GetServerID(t, "test-ds-server-assignments"), + EndpointID: GetServerID(t, "test-ds-server-assignments"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "dsIds": []int{}, @@ -106,7 +106,7 @@ func TestServersIDDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusConflict)), }, "CONFLICT when REMOVING ONLY ORIGIN SERVER ASSIGNMENT": { - EndpointId: GetServerID(t, "test-mso-org-01"), + EndpointID: GetServerID(t, "test-mso-org-01"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "dsIds": []int{}, @@ -136,14 +136,14 @@ func TestServersIDDeliveryServices(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetServerIDDeliveryServices(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.GetServerIDDeliveryServices(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } }) case "POST": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.AssignDeliveryServiceIDsToServerID(testCase.EndpointId(), dsIds, replace, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.AssignDeliveryServiceIDsToServerID(testCase.EndpointID(), dsIds, replace, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/servers_id_queue_update_test.go b/traffic_ops/testing/api/v4/servers_id_queue_update_test.go index e0c86a2064..595e94a543 100644 --- a/traffic_ops/testing/api/v4/servers_id_queue_update_test.go +++ b/traffic_ops/testing/api/v4/servers_id_queue_update_test.go @@ -32,7 +32,7 @@ func TestServersIDQueueUpdate(t *testing.T) { methodTests := utils.TestCase[client.Session, client.RequestOptions, bool]{ "POST": { "OK when VALID QUEUE request": { - EndpointId: GetServerID(t, "atlanta-edge-01"), + EndpointID: GetServerID(t, "atlanta-edge-01"), ClientSession: TOSession, RequestBody: true, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), @@ -40,7 +40,7 @@ func TestServersIDQueueUpdate(t *testing.T) { validateUpdPendingSpecificServers(map[string]bool{"atlanta-edge-01": true})), }, "OK when VALID DEQUEUE request": { - EndpointId: GetServerID(t, "atlanta-edge-01"), + EndpointID: GetServerID(t, "atlanta-edge-01"), ClientSession: TOSession, RequestBody: false, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), @@ -51,7 +51,7 @@ func TestServersIDQueueUpdate(t *testing.T) { https://github.com/apache/trafficcontrol/issues/6691 https://github.com/apache/trafficcontrol/issues/6801 "NOT FOUND when NON-EXISTENT SERVER": { - EndpointId: func() int { return 999999 }, + EndpointID: func() int { return 999999 }, ClientSession: TOSession, RequestBody: true, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), @@ -65,7 +65,7 @@ func TestServersIDQueueUpdate(t *testing.T) { switch method { case "POST": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.SetServerQueueUpdate(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.SetServerQueueUpdate(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v4/servers_id_status_test.go b/traffic_ops/testing/api/v4/servers_id_status_test.go index a0cc40f71c..1085188105 100644 --- a/traffic_ops/testing/api/v4/servers_id_status_test.go +++ b/traffic_ops/testing/api/v4/servers_id_status_test.go @@ -33,7 +33,7 @@ func TestServersIDStatus(t *testing.T) { methodTests := utils.TestCase[client.Session, client.RequestOptions, tc.ServerPutStatus]{ "PUT": { "OK when VALID request": { - EndpointId: GetServerID(t, "atlanta-mid-01"), + EndpointID: GetServerID(t, "atlanta-mid-01"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{ID: util.Ptr(GetStatusID(t, "OFFLINE")())}, @@ -42,7 +42,7 @@ func TestServersIDStatus(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateUpdPending("atlanta-mid-01")), }, "OK when using STATUS ID FIELD": { - EndpointId: GetServerID(t, "atlanta-mid-16"), + EndpointID: GetServerID(t, "atlanta-mid-16"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{ID: util.Ptr(GetStatusID(t, "OFFLINE")())}, @@ -51,7 +51,7 @@ func TestServersIDStatus(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateUpdPending("atlanta-mid-16")), }, "VALIDATE TOPOLOGY DESCENDANTS receive STATUS UPDATES": { - EndpointId: GetServerID(t, "topology-mid-04"), + EndpointID: GetServerID(t, "topology-mid-04"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{ID: util.Ptr(GetStatusID(t, "OFFLINE")())}, @@ -63,7 +63,7 @@ func TestServersIDStatus(t *testing.T) { validateParentPendingSpecificServers(map[string]bool{"topology-edge-01": true, "edgeInTopologyEdgeCg02": false})), }, "NOT FOUND when SERVER DOESNT EXIST": { - EndpointId: func() int { return 11111111 }, + EndpointID: func() int { return 11111111 }, ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{Name: util.Ptr("OFFLINE")}, @@ -72,7 +72,7 @@ func TestServersIDStatus(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "BAD REQUEST when STATUS DOESNT EXIST": { - EndpointId: GetServerID(t, "atlanta-mid-16"), + EndpointID: GetServerID(t, "atlanta-mid-16"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{Name: util.Ptr("NOT_A_REAL_STATUS")}, @@ -81,7 +81,7 @@ func TestServersIDStatus(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when MISSING OFFLINE REASON when OFFLINE STATUS": { - EndpointId: GetServerID(t, "atlanta-mid-16"), + EndpointID: GetServerID(t, "atlanta-mid-16"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{Name: util.Ptr("OFFLINE")}, @@ -89,7 +89,7 @@ func TestServersIDStatus(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when MISSING OFFLINE REASON when ADMIN_DOWN STATUS": { - EndpointId: GetServerID(t, "atlanta-mid-16"), + EndpointID: GetServerID(t, "atlanta-mid-16"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{Name: util.Ptr("ADMIN_DOWN")}, @@ -97,7 +97,7 @@ func TestServersIDStatus(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "CONFLICT when SERVER STATUS OFFLINE when ONLY EDGE SERVER ASSIGNED": { - EndpointId: GetServerID(t, "test-ds-server-assignments"), + EndpointID: GetServerID(t, "test-ds-server-assignments"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{Name: util.Ptr("OFFLINE")}, @@ -106,7 +106,7 @@ func TestServersIDStatus(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusConflict)), }, "CONFLICT when SERVER STATUS OFFLINE when ONLY ORIGIN SERVER ASSIGNED": { - EndpointId: GetServerID(t, "test-mso-org-01"), + EndpointID: GetServerID(t, "test-mso-org-01"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{Name: util.Ptr("OFFLINE")}, @@ -124,7 +124,7 @@ func TestServersIDStatus(t *testing.T) { case "PUT": t.Run(name, func(t *testing.T) { clearUpdates(t) - alerts, reqInf, err := testCase.ClientSession.UpdateServerStatus(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateServerStatus(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/servers_test.go b/traffic_ops/testing/api/v4/servers_test.go index 42809430a8..cf16a526ac 100644 --- a/traffic_ops/testing/api/v4/servers_test.go +++ b/traffic_ops/testing/api/v4/servers_test.go @@ -161,7 +161,7 @@ func TestServers(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetServerID(t, "atlanta-edge-03"), + EndpointID: GetServerID(t, "atlanta-edge-03"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "id": GetServerID(t, "atlanta-edge-03")(), @@ -205,7 +205,7 @@ func TestServers(t *testing.T) { })), }, "BAD REQUEST when CHANGING XMPPID": { - EndpointId: GetServerID(t, "atlanta-edge-16"), + EndpointID: GetServerID(t, "atlanta-edge-16"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "atlanta-edge-16")(), @@ -214,7 +214,7 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "CONFLICT when UPDATING SERVER TYPE when ASSIGNED to DS": { - EndpointId: GetServerID(t, "test-ds-server-assignments"), + EndpointID: GetServerID(t, "test-ds-server-assignments"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "test-ds-server-assignments")(), @@ -224,7 +224,7 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusConflict)), }, "CONFLICT when UPDATING SERVER STATUS when its the ONLY EDGE SERVER ASSIGNED": { - EndpointId: GetServerID(t, "test-ds-server-assignments"), + EndpointID: GetServerID(t, "test-ds-server-assignments"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "test-ds-server-assignments")(), @@ -233,7 +233,7 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusConflict)), }, "CONFLICT when UPDATING SERVER STATUS when its the ONLY ORG SERVER ASSIGNED": { - EndpointId: GetServerID(t, "test-mso-org-01"), + EndpointID: GetServerID(t, "test-mso-org-01"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "test-mso-org-01")(), @@ -242,7 +242,7 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusConflict)), }, "BAD REQUEST when UPDATING CDN when LAST SERVER IN CACHEGROUP IN TOPOLOGY": { - EndpointId: GetServerID(t, "midInTopologyMidCg01"), + EndpointID: GetServerID(t, "midInTopologyMidCg01"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "midInTopologyMidCg01")(), @@ -253,7 +253,7 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when UPDATING CACHEGROUP when LAST SERVER IN CACHEGROUP IN TOPOLOGY": { - EndpointId: GetServerID(t, "midInTopologyMidCg01"), + EndpointID: GetServerID(t, "midInTopologyMidCg01"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "midInTopologyMidCg01")(), @@ -265,7 +265,7 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when IPADDRESS EXISTS with SAME PROFILE": { - EndpointId: GetServerID(t, "atlanta-edge-16"), + EndpointID: GetServerID(t, "atlanta-edge-16"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "profileNames": []string{"EDGE1"}, @@ -281,19 +281,19 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when BLANK HOSTNAME": { - EndpointId: GetServerID(t, "atlanta-edge-16"), + EndpointID: GetServerID(t, "atlanta-edge-16"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{"hostName": ""}), Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when BLANK DOMAINNAME": { - EndpointId: GetServerID(t, "atlanta-edge-16"), + EndpointID: GetServerID(t, "atlanta-edge-16"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{"domainName": ""}), Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetServerID(t, "atlanta-edge-01"), + EndpointID: GetServerID(t, "atlanta-edge-01"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: generateServer(t, map[string]interface{}{ @@ -302,7 +302,7 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetServerID(t, "atlanta-edge-01"), + EndpointID: GetServerID(t, "atlanta-edge-01"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "atlanta-edge-01")(), @@ -313,12 +313,12 @@ func TestServers(t *testing.T) { }, "DELETE": { "BAD REQUEST when LAST SERVER in CACHE GROUP": { - EndpointId: GetServerID(t, "midInTopologyMidCg01"), + EndpointID: GetServerID(t, "midInTopologyMidCg01"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "CONFLICT when DELETING SERVER when its the ONLY EDGE SERVER ASSIGNED": { - EndpointId: GetServerID(t, "test-ds-server-assignments"), + EndpointID: GetServerID(t, "test-ds-server-assignments"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusConflict)), }, @@ -361,14 +361,14 @@ func TestServers(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateServer(testCase.EndpointId(), server, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateServer(testCase.EndpointID(), server, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteServer(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteServer(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/staticdnsentries_test.go b/traffic_ops/testing/api/v4/staticdnsentries_test.go index f4ba61c70f..570497d11e 100644 --- a/traffic_ops/testing/api/v4/staticdnsentries_test.go +++ b/traffic_ops/testing/api/v4/staticdnsentries_test.go @@ -58,7 +58,7 @@ func TestStaticDNSEntries(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetStaticDNSEntryID(t, "host2"), + EndpointID: GetStaticDNSEntryID(t, "host2"), ClientSession: TOSession, RequestBody: tc.StaticDNSEntry{ Address: "192.168.0.2", @@ -72,7 +72,7 @@ func TestStaticDNSEntries(t *testing.T) { validateStaticDNSEntriesUpdateCreateFields("host2", map[string]interface{}{"Address": "192.168.0.2"})), }, "BAD REQUEST when INVALID IPV4 ADDRESS for A_RECORD": { - EndpointId: GetStaticDNSEntryID(t, "host2"), + EndpointID: GetStaticDNSEntryID(t, "host2"), ClientSession: TOSession, RequestBody: tc.StaticDNSEntry{ Address: "test.testdomain.net.", @@ -85,7 +85,7 @@ func TestStaticDNSEntries(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when INVALID DNS for CNAME_RECORD": { - EndpointId: GetStaticDNSEntryID(t, "host1"), + EndpointID: GetStaticDNSEntryID(t, "host1"), ClientSession: TOSession, RequestBody: tc.StaticDNSEntry{ Address: "2001:0db8:85a3:0000:0000:8a2e:0370:7334", @@ -98,7 +98,7 @@ func TestStaticDNSEntries(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when MISSING TRAILING PERIOD for CNAME_RECORD": { - EndpointId: GetStaticDNSEntryID(t, "host1"), + EndpointID: GetStaticDNSEntryID(t, "host1"), ClientSession: TOSession, RequestBody: tc.StaticDNSEntry{ Address: "cdn.test.com", @@ -111,7 +111,7 @@ func TestStaticDNSEntries(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when INVALID IPV6 ADDRESS for AAAA_RECORD": { - EndpointId: GetStaticDNSEntryID(t, "host3"), + EndpointID: GetStaticDNSEntryID(t, "host3"), ClientSession: TOSession, RequestBody: tc.StaticDNSEntry{ Address: "192.168.0.1", @@ -124,7 +124,7 @@ func TestStaticDNSEntries(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetStaticDNSEntryID(t, "host3"), + EndpointID: GetStaticDNSEntryID(t, "host3"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.StaticDNSEntry{ @@ -138,7 +138,7 @@ func TestStaticDNSEntries(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetStaticDNSEntryID(t, "host3"), + EndpointID: GetStaticDNSEntryID(t, "host3"), ClientSession: TOSession, RequestBody: tc.StaticDNSEntry{ Address: "2001:0db8:85a3:0000:0000:8a2e:0370:7334", @@ -174,14 +174,14 @@ func TestStaticDNSEntries(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateStaticDNSEntry(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateStaticDNSEntry(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteStaticDNSEntry(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteStaticDNSEntry(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/statuses_test.go b/traffic_ops/testing/api/v4/statuses_test.go index 1facba8e58..18ee62b18d 100644 --- a/traffic_ops/testing/api/v4/statuses_test.go +++ b/traffic_ops/testing/api/v4/statuses_test.go @@ -62,7 +62,7 @@ func TestStatuses(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetStatusID(t, "TEST_NULL_DESCRIPTION"), + EndpointID: GetStatusID(t, "TEST_NULL_DESCRIPTION"), ClientSession: TOSession, RequestBody: tc.Status{ Description: "new description", @@ -72,7 +72,7 @@ func TestStatuses(t *testing.T) { validateStatusesUpdateCreateFields("TEST_NULL_DESCRIPTION", map[string]interface{}{"Description": "new description"})), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetStatusID(t, "TEST_NULL_DESCRIPTION"), + EndpointID: GetStatusID(t, "TEST_NULL_DESCRIPTION"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.Status{ @@ -82,7 +82,7 @@ func TestStatuses(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetStatusID(t, "TEST_NULL_DESCRIPTION"), + EndpointID: GetStatusID(t, "TEST_NULL_DESCRIPTION"), ClientSession: TOSession, RequestBody: tc.Status{ Description: "new description", @@ -107,14 +107,14 @@ func TestStatuses(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateStatus(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateStatus(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteStatus(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteStatus(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/steeringtargets_test.go b/traffic_ops/testing/api/v4/steeringtargets_test.go index aa089336cd..9e6c32c830 100644 --- a/traffic_ops/testing/api/v4/steeringtargets_test.go +++ b/traffic_ops/testing/api/v4/steeringtargets_test.go @@ -42,20 +42,20 @@ func TestSteeringTargets(t *testing.T) { methodTests := utils.TestCase[client.Session, client.RequestOptions, tc.SteeringTargetNullable]{ "GET": { "NOT MODIFIED when NO CHANGES made": { - EndpointId: GetDeliveryServiceId(t, "ds1"), + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: steeringUserSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfModifiedSince: {tomorrow}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusNotModified)), }, "OK when VALID request": { - EndpointId: GetDeliveryServiceId(t, "ds1"), + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: steeringUserSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseHasLength(1), validateSteeringTargetFields(map[string]interface{}{"DeliveryService": "ds1", "DeliveryServiceID": uint64(GetDeliveryServiceId(t, "ds1")()), "Target": "ds2", "TargetID": uint64(GetDeliveryServiceId(t, "ds2")()), "Type": "STEERING_WEIGHT", "TypeID": GetTypeID(t, "STEERING_WEIGHT")(), "Value": util.JSONIntStr(42)})), }, "OK when CHANGES made": { - EndpointId: GetDeliveryServiceId(t, "ds1"), + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: steeringUserSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfModifiedSince: {currentTimeRFC}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), @@ -109,7 +109,7 @@ func TestSteeringTargets(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetSteeringTargets(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.GetSteeringTargets(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } @@ -135,7 +135,7 @@ func TestSteeringTargets(t *testing.T) { } targetID, err := strconv.Atoi(testCase.RequestOpts.QueryParameters["targetID"][0]) assert.RequireNoError(t, err, "Expected no error converting string to int for target ID: %v", err) - alerts, reqInf, err := testCase.ClientSession.DeleteSteeringTarget(testCase.EndpointId(), targetID, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteSteeringTarget(testCase.EndpointID(), targetID, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/tenants_test.go b/traffic_ops/testing/api/v4/tenants_test.go index ac47d4d710..55e8100d8d 100644 --- a/traffic_ops/testing/api/v4/tenants_test.go +++ b/traffic_ops/testing/api/v4/tenants_test.go @@ -107,7 +107,7 @@ func TestTenants(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetTenantID(t, "tenant4"), + EndpointID: GetTenantID(t, "tenant4"), ClientSession: TOSession, RequestBody: tc.Tenant{ Active: false, @@ -119,7 +119,7 @@ func TestTenants(t *testing.T) { validateTenantCreateUpdateFields(map[string]interface{}{"Name": "newname", "Active": false})), }, "BAD REQUEST when ROOT TENANT": { - EndpointId: GetTenantID(t, "root"), + EndpointID: GetTenantID(t, "root"), ClientSession: TOSession, RequestBody: tc.Tenant{ Active: false, @@ -129,7 +129,7 @@ func TestTenants(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetTenantID(t, "tenant2"), + EndpointID: GetTenantID(t, "tenant2"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.Tenant{ @@ -141,7 +141,7 @@ func TestTenants(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetTenantID(t, "tenant2"), + EndpointID: GetTenantID(t, "tenant2"), ClientSession: TOSession, RequestBody: tc.Tenant{ Active: false, @@ -155,7 +155,7 @@ func TestTenants(t *testing.T) { }, "DELETE": { "BAD REQUEST when TENANT HAS CHILDREN": { - EndpointId: GetTenantID(t, "tenant1"), + EndpointID: GetTenantID(t, "tenant1"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, @@ -182,14 +182,14 @@ func TestTenants(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.UpdateTenant(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.UpdateTenant(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteTenant(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteTenant(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/types_test.go b/traffic_ops/testing/api/v4/types_test.go index 6cc76be9ee..346e7a318a 100644 --- a/traffic_ops/testing/api/v4/types_test.go +++ b/traffic_ops/testing/api/v4/types_test.go @@ -23,12 +23,11 @@ import ( "testing" "time" - "github.com/apache/trafficcontrol/traffic_ops/testing/api/assert" - "github.com/apache/trafficcontrol/traffic_ops/toclientlib" - "github.com/apache/trafficcontrol/lib/go-rfc" tc "github.com/apache/trafficcontrol/lib/go-tc" + "github.com/apache/trafficcontrol/traffic_ops/testing/api/assert" "github.com/apache/trafficcontrol/traffic_ops/testing/api/utils" + "github.com/apache/trafficcontrol/traffic_ops/toclientlib" client "github.com/apache/trafficcontrol/traffic_ops/v4-client" ) @@ -86,7 +85,7 @@ func TestTypes(t *testing.T) { }, "PUT": { "BAD REQUEST when useInTable NOT server": { - EndpointId: GetTypeID(t, "ACTIVE_DIRECTORY"), + EndpointID: GetTypeID(t, "ACTIVE_DIRECTORY"), ClientSession: TOSession, RequestBody: tc.Type{ Description: "Active Directory User", @@ -96,7 +95,7 @@ func TestTypes(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "OK when VALID request when useInTable=server": { - EndpointId: GetTypeID(t, "RIAK"), + EndpointID: GetTypeID(t, "RIAK"), ClientSession: TOSession, RequestBody: tc.Type{ Description: "riak type", @@ -109,7 +108,7 @@ func TestTypes(t *testing.T) { }, "DELETE": { "OK when VALID request": { - EndpointId: GetTypeID(t, "INFLUXDB"), + EndpointID: GetTypeID(t, "INFLUXDB"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, @@ -136,14 +135,14 @@ func TestTypes(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateType(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateType(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteType(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteType(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v4/users_test.go b/traffic_ops/testing/api/v4/users_test.go index 1819281af4..b386a03ecc 100644 --- a/traffic_ops/testing/api/v4/users_test.go +++ b/traffic_ops/testing/api/v4/users_test.go @@ -86,7 +86,7 @@ func TestUsers(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetUserID(t, "steering"), + EndpointID: GetUserID(t, "steering"), ClientSession: TOSession, RequestBody: tc.UserV4{ AddressLine1: util.Ptr("updated line 1"), @@ -109,7 +109,7 @@ func TestUsers(t *testing.T) { "Country": "US", "Email": "steeringupdated@example.com", "FullName": "Steering User Updated"})), }, "OK when UPDATING SELF": { - EndpointId: GetUserID(t, "opsuser"), + EndpointID: GetUserID(t, "opsuser"), ClientSession: opsUserSession, RequestBody: tc.UserV4{ AddressLine1: util.Ptr("address of ops"), @@ -129,7 +129,7 @@ func TestUsers(t *testing.T) { validateUsersUpdateCreateFields(map[string]interface{}{"Email": "ops-updated@example.com", "FullName": "Operations User Updated"})), }, "NOT FOUND when UPDATING SELF with ROLE that DOESNT EXIST": { - EndpointId: GetUserID(t, "opsuser"), + EndpointID: GetUserID(t, "opsuser"), ClientSession: opsUserSession, RequestBody: tc.UserV4{ AddressLine1: util.Ptr("address of ops"), @@ -148,7 +148,7 @@ func TestUsers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "FORBIDDEN when OPERATIONS USER updates ADMIN USER": { - EndpointId: GetUserID(t, "admin"), + EndpointID: GetUserID(t, "admin"), ClientSession: opsUserSession, RequestBody: tc.UserV4{ Email: util.Ptr("oops@ops.net"), @@ -162,7 +162,7 @@ func TestUsers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, "FORBIDDEN when CHILD TENANT USER updates PARENT TENANT USER": { - EndpointId: GetUserID(t, "tenant3user"), + EndpointID: GetUserID(t, "tenant3user"), ClientSession: tenant4UserSession, RequestBody: tc.UserV4{ Email: util.Ptr("tenant3user@example.com"), @@ -198,7 +198,7 @@ func TestUsers(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.UpdateUser(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.UpdateUser(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v5/asns_test.go b/traffic_ops/testing/api/v5/asns_test.go index bef797f8c5..81e9fa0520 100644 --- a/traffic_ops/testing/api/v5/asns_test.go +++ b/traffic_ops/testing/api/v5/asns_test.go @@ -54,7 +54,7 @@ func TestASN(t *testing.T) { }, "PUT": { "OK when VALID request": { - ClientSession: TOSession, EndpointId: GetASNId(t, "8888"), + ClientSession: TOSession, EndpointID: GetASNId(t, "8888"), RequestBody: map[string]interface{}{ "asn": 7777, "cachegroupName": "originCachegroup", @@ -105,7 +105,7 @@ func TestASN(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateASN(testCase.EndpointId(), asn, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateASN(testCase.EndpointID(), asn, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/cachegroups_test.go b/traffic_ops/testing/api/v5/cachegroups_test.go index 538009a537..9c6f8d3039 100644 --- a/traffic_ops/testing/api/v5/cachegroups_test.go +++ b/traffic_ops/testing/api/v5/cachegroups_test.go @@ -151,7 +151,7 @@ func TestCacheGroups(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetCacheGroupId(t, "cachegroup1"), ClientSession: TOSession, + EndpointID: GetCacheGroupId(t, "cachegroup1"), ClientSession: TOSession, RequestBody: tc.CacheGroupNullable{ Latitude: util.Ptr(17.5), Longitude: util.Ptr(17.5), @@ -165,7 +165,7 @@ func TestCacheGroups(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when updating CG with null Lat/Long": { - EndpointId: GetCacheGroupId(t, "nullLatLongCG"), ClientSession: TOSession, + EndpointID: GetCacheGroupId(t, "nullLatLongCG"), ClientSession: TOSession, RequestBody: tc.CacheGroupNullable{ Name: util.Ptr("nullLatLongCG"), ShortName: util.Ptr("null-ll"), @@ -176,7 +176,7 @@ func TestCacheGroups(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "BAD REQUEST when updating TYPE of CG in TOPOLOGY": { - EndpointId: GetCacheGroupId(t, "topology-edge-cg-01"), ClientSession: TOSession, + EndpointID: GetCacheGroupId(t, "topology-edge-cg-01"), ClientSession: TOSession, RequestBody: tc.CacheGroupNullable{ Latitude: util.Ptr(0.0), Longitude: util.Ptr(0.0), @@ -188,7 +188,7 @@ func TestCacheGroups(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetCacheGroupId(t, "cachegroup1"), ClientSession: TOSession, + EndpointID: GetCacheGroupId(t, "cachegroup1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.CacheGroupNullable{ Name: util.Ptr("cachegroup1"), @@ -199,7 +199,7 @@ func TestCacheGroups(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetCacheGroupId(t, "cachegroup1"), ClientSession: TOSession, + EndpointID: GetCacheGroupId(t, "cachegroup1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfMatch: {rfc.ETag(currentTime)}}}, RequestBody: tc.CacheGroupNullable{ Name: util.Ptr("cachegroup1"), @@ -210,19 +210,19 @@ func TestCacheGroups(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "UNAUTHORIZED when NOT LOGGED IN": { - EndpointId: GetCacheGroupId(t, "cachegroup1"), + EndpointID: GetCacheGroupId(t, "cachegroup1"), ClientSession: NoAuthTOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusUnauthorized)), }, }, "DELETE": { "NOT FOUND when INVALID ID parameter": { - EndpointId: func() int { return 111111 }, + EndpointID: func() int { return 111111 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "UNAUTHORIZED when NOT LOGGED IN": { - EndpointId: GetCacheGroupId(t, "cachegroup1"), + EndpointID: GetCacheGroupId(t, "cachegroup1"), ClientSession: NoAuthTOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusUnauthorized)), }, @@ -249,14 +249,14 @@ func TestCacheGroups(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.UpdateCacheGroup(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.UpdateCacheGroup(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteCacheGroup(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteCacheGroup(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/cachegroupsdeliveryservices_test.go b/traffic_ops/testing/api/v5/cachegroupsdeliveryservices_test.go index ab11171c98..db7ffc5117 100644 --- a/traffic_ops/testing/api/v5/cachegroupsdeliveryservices_test.go +++ b/traffic_ops/testing/api/v5/cachegroupsdeliveryservices_test.go @@ -33,13 +33,13 @@ func TestCacheGroupsDeliveryServices(t *testing.T) { methodTests := utils.TestCase[client.Session, client.RequestOptions, []int]{ "POST": { "BAD REQUEST assigning TOPOLOGY-BASED DS to CACHEGROUP": { - EndpointId: GetCacheGroupId(t, "cachegroup3"), + EndpointID: GetCacheGroupId(t, "cachegroup3"), ClientSession: TOSession, RequestBody: []int{GetDeliveryServiceId(t, "top-ds-in-cdn1")()}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "OK when valid request": { - EndpointId: GetCacheGroupId(t, "cachegroup3"), + EndpointID: GetCacheGroupId(t, "cachegroup3"), ClientSession: TOSession, RequestBody: []int{ GetDeliveryServiceId(t, "ds1")(), @@ -59,7 +59,7 @@ func TestCacheGroupsDeliveryServices(t *testing.T) { switch method { case "POST": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.SetCacheGroupDeliveryServices(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.SetCacheGroupDeliveryServices(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v5/cdn_federations_test.go b/traffic_ops/testing/api/v5/cdn_federations_test.go index 6d916c4f2d..60ba8a7c4d 100644 --- a/traffic_ops/testing/api/v5/cdn_federations_test.go +++ b/traffic_ops/testing/api/v5/cdn_federations_test.go @@ -105,7 +105,7 @@ func TestCDNFederations(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetFederationID(t, "google.com."), + EndpointID: GetFederationID(t, "google.com."), ClientSession: TOSession, RequestBody: tc.CDNFederation{ CName: util.Ptr("new.cname."), @@ -115,7 +115,7 @@ func TestCDNFederations(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateCDNFederationUpdateFields(map[string]interface{}{"CName": "new.cname."})), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetFederationID(t, "booya.com."), + EndpointID: GetFederationID(t, "booya.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.CDNFederation{ @@ -126,7 +126,7 @@ func TestCDNFederations(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetFederationID(t, "booya.com."), + EndpointID: GetFederationID(t, "booya.com."), ClientSession: TOSession, RequestBody: tc.CDNFederation{ CName: util.Ptr("new.cname."), @@ -159,14 +159,14 @@ func TestCDNFederations(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.UpdateCDNFederation(testCase.RequestBody, cdnName, testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.UpdateCDNFederation(testCase.RequestBody, cdnName, testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteCDNFederation(cdnName, testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteCDNFederation(cdnName, testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts.Alerts, err) } diff --git a/traffic_ops/testing/api/v5/cdn_locks_test.go b/traffic_ops/testing/api/v5/cdn_locks_test.go index c03338a2c3..47011b8d82 100644 --- a/traffic_ops/testing/api/v5/cdn_locks_test.go +++ b/traffic_ops/testing/api/v5/cdn_locks_test.go @@ -110,11 +110,11 @@ func TestCDNLocks(t *testing.T) { }, "SERVERS QUEUE UPDATES": { "OK when USER OWNS LOCK": { - EndpointId: GetServerID(t, "cdn2-test-edge"), ClientSession: opsUserWithLockSession, + EndpointID: GetServerID(t, "cdn2-test-edge"), ClientSession: opsUserWithLockSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetServerID(t, "cdn2-test-edge"), ClientSession: TOSession, + EndpointID: GetServerID(t, "cdn2-test-edge"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, }, @@ -169,7 +169,7 @@ func TestCDNLocks(t *testing.T) { }, "CDN UPDATE": { "OK when USER OWNS LOCK": { - EndpointId: GetCDNID(t, "cdn2"), ClientSession: opsUserWithLockSession, + EndpointID: GetCDNID(t, "cdn2"), ClientSession: opsUserWithLockSession, RequestBody: map[string]interface{}{ "dnssecEnabled": false, "domainName": "newdomain", @@ -178,7 +178,7 @@ func TestCDNLocks(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetCDNID(t, "cdn2"), ClientSession: TOSession, + EndpointID: GetCDNID(t, "cdn2"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "dnssecEnabled": false, "domainName": "newdomaintest", @@ -189,17 +189,17 @@ func TestCDNLocks(t *testing.T) { }, "CDN DELETE": { "OK when USER OWNS LOCK": { - EndpointId: GetCDNID(t, "cdndelete"), ClientSession: opsUserWithLockSession, + EndpointID: GetCDNID(t, "cdndelete"), ClientSession: opsUserWithLockSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetCDNID(t, "cdn2"), ClientSession: TOSession, + EndpointID: GetCDNID(t, "cdn2"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, }, "CACHE GROUP UPDATE": { "OK when USER OWNS LOCK": { - EndpointId: GetCacheGroupId(t, "cachegroup1"), ClientSession: opsUserWithLockSession, + EndpointID: GetCacheGroupId(t, "cachegroup1"), ClientSession: opsUserWithLockSession, RequestBody: map[string]interface{}{ "name": "cachegroup1", "shortName": "newShortName", @@ -209,7 +209,7 @@ func TestCDNLocks(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetCacheGroupId(t, "cachegroup1"), ClientSession: TOSession, + EndpointID: GetCacheGroupId(t, "cachegroup1"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "name": "cachegroup1", "shortName": "newShortName", @@ -232,24 +232,24 @@ func TestCDNLocks(t *testing.T) { }, "DELIVERY SERVICE PUT": { "OK when USER OWNS LOCK": { - EndpointId: GetDeliveryServiceId(t, "basic-ds-in-cdn2"), ClientSession: opsUserWithLockSession, + EndpointID: GetDeliveryServiceId(t, "basic-ds-in-cdn2"), ClientSession: opsUserWithLockSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "xmlId": "basic-ds-in-cdn2", "cdnId": GetCDNID(t, "cdn2")(), "cdnName": "cdn2", "routingName": "cdn"}), Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetDeliveryServiceId(t, "basic-ds-in-cdn2"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "basic-ds-in-cdn2"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{}), Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, }, "DELIVERY SERVICE DELETE": { "OK when USER OWNS LOCK": { - EndpointId: GetDeliveryServiceId(t, "ds-forked-topology"), ClientSession: opsUserWithLockSession, + EndpointID: GetDeliveryServiceId(t, "ds-forked-topology"), ClientSession: opsUserWithLockSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetDeliveryServiceId(t, "top-ds-in-cdn2"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "top-ds-in-cdn2"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, }, @@ -281,7 +281,7 @@ func TestCDNLocks(t *testing.T) { }, "PROFILE PUT": { "OK when USER OWNS LOCK": { - EndpointId: GetProfileID(t, "CDN2_EDGE"), + EndpointID: GetProfileID(t, "CDN2_EDGE"), ClientSession: opsUserWithLockSession, RequestBody: map[string]interface{}{ "cdn": GetCDNID(t, "cdn2")(), @@ -294,7 +294,7 @@ func TestCDNLocks(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetProfileID(t, "EDGEInCDN2"), + EndpointID: GetProfileID(t, "EDGEInCDN2"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "cdn": GetCDNID(t, "cdn2")(), @@ -309,12 +309,12 @@ func TestCDNLocks(t *testing.T) { }, "PROFILE DELETE": { "OK when USER OWNS LOCK": { - EndpointId: GetProfileID(t, "CCR2"), + EndpointID: GetProfileID(t, "CCR2"), ClientSession: opsUserWithLockSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetProfileID(t, "MID2"), + EndpointID: GetProfileID(t, "MID2"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, @@ -339,7 +339,7 @@ func TestCDNLocks(t *testing.T) { }, "PROFILE PARAMETER DELETE": { "OK when USER OWNS LOCK": { - EndpointId: GetProfileID(t, "OKwhenUserOwnLocks"), + EndpointID: GetProfileID(t, "OKwhenUserOwnLocks"), ClientSession: opsUserWithLockSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{ "parameterId": {strconv.Itoa(GetParameterID(t, "test.cdnlock.delete", "rascal.properties", "25.0")())}, @@ -347,7 +347,7 @@ func TestCDNLocks(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetProfileID(t, "FORBIDDENwhenDoesntOwnLock"), + EndpointID: GetProfileID(t, "FORBIDDENwhenDoesntOwnLock"), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{ "parameterId": {strconv.Itoa(GetParameterID(t, "test.cdnlock.forbidden.delete", "rascal.properties", "25.0")())}, @@ -382,7 +382,7 @@ func TestCDNLocks(t *testing.T) { }, "SERVER PUT": { "OK when USER OWNS LOCK": { - EndpointId: GetServerID(t, "edge1-cdn2"), + EndpointID: GetServerID(t, "edge1-cdn2"), ClientSession: opsUserWithLockSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "edge1-cdn2")(), @@ -399,7 +399,7 @@ func TestCDNLocks(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetServerID(t, "dtrc-edge-07"), + EndpointID: GetServerID(t, "dtrc-edge-07"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "dtrc-edge-07")(), @@ -419,12 +419,12 @@ func TestCDNLocks(t *testing.T) { }, "SERVER DELETE": { "OK when USER OWNS LOCK": { - EndpointId: GetServerID(t, "atlanta-mid-17"), + EndpointID: GetServerID(t, "atlanta-mid-17"), ClientSession: opsUserWithLockSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetServerID(t, "denver-mso-org-02"), + EndpointID: GetServerID(t, "denver-mso-org-02"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, @@ -455,7 +455,7 @@ func TestCDNLocks(t *testing.T) { }, "STATIC DNS ENTRIES PUT": { "OK when USER OWNS LOCK": { - EndpointId: GetStaticDNSEntryID(t, "host2"), + EndpointID: GetStaticDNSEntryID(t, "host2"), ClientSession: opsUserWithLockSession, RequestBody: map[string]interface{}{ "address": "192.168.0.2", @@ -467,7 +467,7 @@ func TestCDNLocks(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetStaticDNSEntryID(t, "cdnlock-test-delete-host"), + EndpointID: GetStaticDNSEntryID(t, "cdnlock-test-delete-host"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "address": "192.168.0.2", @@ -481,12 +481,12 @@ func TestCDNLocks(t *testing.T) { }, "STATIC DNS ENTRIES DELETE": { "OK when USER OWNS LOCK": { - EndpointId: GetStaticDNSEntryID(t, "host3"), + EndpointID: GetStaticDNSEntryID(t, "host3"), ClientSession: opsUserWithLockSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "FORBIDDEN when ADMIN USER DOESNT OWN LOCK": { - EndpointId: GetStaticDNSEntryID(t, "cdnlock-negtest-delete-host"), + EndpointID: GetStaticDNSEntryID(t, "cdnlock-negtest-delete-host"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, @@ -533,7 +533,7 @@ func TestCDNLocks(t *testing.T) { } }, "SERVERS QUEUE UPDATES": func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.SetServerQueueUpdate(testCase.EndpointId(), true, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.SetServerQueueUpdate(testCase.EndpointID(), true, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } @@ -571,7 +571,7 @@ func TestCDNLocks(t *testing.T) { cacheGroup := tc.CacheGroupNullable{} err = json.Unmarshal(dat, &cacheGroup) assert.NoError(t, err, "Error occurred when unmarshalling request body: %v", err) - resp, reqInf, err := testCase.ClientSession.UpdateCacheGroup(testCase.EndpointId(), cacheGroup, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.UpdateCacheGroup(testCase.EndpointID(), cacheGroup, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, resp.Alerts, err) } @@ -580,13 +580,13 @@ func TestCDNLocks(t *testing.T) { cdn := tc.CDN{} err = json.Unmarshal(dat, &cdn) assert.NoError(t, err, "Error occurred when unmarshalling request body: %v", err) - alerts, reqInf, err := testCase.ClientSession.UpdateCDN(testCase.EndpointId(), cdn, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateCDN(testCase.EndpointID(), cdn, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }, "CDN DELETE": func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteCDN(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteCDN(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } @@ -604,13 +604,13 @@ func TestCDNLocks(t *testing.T) { ds := tc.DeliveryServiceV4{} err = json.Unmarshal(dat, &ds) assert.NoError(t, err, "Error occurred when unmarshalling request body: %v", err) - resp, reqInf, err := testCase.ClientSession.UpdateDeliveryService(testCase.EndpointId(), ds, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.UpdateDeliveryService(testCase.EndpointID(), ds, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, resp.Alerts, err) } }, "DELIVERY SERVICE DELETE": func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.DeleteDeliveryService(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.DeleteDeliveryService(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, resp.Alerts, err) } @@ -628,13 +628,13 @@ func TestCDNLocks(t *testing.T) { profile := tc.Profile{} err = json.Unmarshal(dat, &profile) assert.NoError(t, err, "Error occurred when unmarshalling request body: %v", err) - alerts, reqInf, err := testCase.ClientSession.UpdateProfile(testCase.EndpointId(), profile, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateProfile(testCase.EndpointID(), profile, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }, "PROFILE DELETE": func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteProfile(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteProfile(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } @@ -650,7 +650,7 @@ func TestCDNLocks(t *testing.T) { }, "PROFILE PARAMETER DELETE": func(t *testing.T) { parameterId, _ := strconv.Atoi(testCase.RequestOpts.QueryParameters["parameterId"][0]) - alerts, reqInf, err := testCase.ClientSession.DeleteProfileParameter(testCase.EndpointId(), parameterId, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteProfileParameter(testCase.EndpointID(), parameterId, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } @@ -668,13 +668,13 @@ func TestCDNLocks(t *testing.T) { server := tc.ServerV4{} err = json.Unmarshal(dat, &server) assert.NoError(t, err, "Error occurred when unmarshalling request body: %v", err) - alerts, reqInf, err := testCase.ClientSession.UpdateServer(testCase.EndpointId(), server, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateServer(testCase.EndpointID(), server, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }, "SERVER DELETE": func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteServer(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteServer(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } @@ -692,13 +692,13 @@ func TestCDNLocks(t *testing.T) { staticDNSEntry := tc.StaticDNSEntry{} err = json.Unmarshal(dat, &staticDNSEntry) assert.NoError(t, err, "Error occurred when unmarshalling request body: %v", err) - alerts, reqInf, err := testCase.ClientSession.UpdateStaticDNSEntry(testCase.EndpointId(), staticDNSEntry, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateStaticDNSEntry(testCase.EndpointID(), staticDNSEntry, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }, "STATIC DNS ENTRIES DELETE": func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteStaticDNSEntry(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteStaticDNSEntry(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/cdn_queue_updates_test.go b/traffic_ops/testing/api/v5/cdn_queue_updates_test.go index 650759cda4..50a880d442 100644 --- a/traffic_ops/testing/api/v5/cdn_queue_updates_test.go +++ b/traffic_ops/testing/api/v5/cdn_queue_updates_test.go @@ -34,7 +34,7 @@ func TestCDNQueueUpdates(t *testing.T) { methodTests := utils.TestCase[client.Session, client.RequestOptions, bool]{ "POST": { "OK when VALID TYPE parameter": { - EndpointId: GetCDNID(t, "cdn1"), + EndpointID: GetCDNID(t, "cdn1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"type": {"EDGE"}}}, RequestBody: true, @@ -42,7 +42,7 @@ func TestCDNQueueUpdates(t *testing.T) { validateServersUpdatePending(GetCDNID(t, "cdn1")(), map[string]string{"type": "EDGE"})), }, "OK when VALID PROFILE parameter": { - EndpointId: GetCDNID(t, "cdn1"), + EndpointID: GetCDNID(t, "cdn1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"profile": {"EDGE1"}}}, RequestBody: true, @@ -58,9 +58,9 @@ func TestCDNQueueUpdates(t *testing.T) { case "POST": t.Run(name, func(t *testing.T) { // Clear updates on all associated cdn servers to begin with - _, _, err := TOSession.QueueUpdatesForCDN(testCase.EndpointId(), false, client.RequestOptions{}) - assert.RequireNoError(t, err, "Failed to clear updates for cdn %d", testCase.EndpointId()) - resp, reqInf, err := testCase.ClientSession.QueueUpdatesForCDN(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + _, _, err := TOSession.QueueUpdatesForCDN(testCase.EndpointID(), false, client.RequestOptions{}) + assert.RequireNoError(t, err, "Failed to clear updates for cdn %d", testCase.EndpointID()) + resp, reqInf, err := testCase.ClientSession.QueueUpdatesForCDN(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp, tc.Alerts{}, err) } diff --git a/traffic_ops/testing/api/v5/cdns_test.go b/traffic_ops/testing/api/v5/cdns_test.go index 5d163917a5..17ccfa8ef0 100644 --- a/traffic_ops/testing/api/v5/cdns_test.go +++ b/traffic_ops/testing/api/v5/cdns_test.go @@ -150,7 +150,7 @@ func TestCDNs(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetCDNID(t, "cdn1"), + EndpointID: GetCDNID(t, "cdn1"), ClientSession: TOSession, RequestBody: tc.CDN{ DNSSECEnabled: false, @@ -161,7 +161,7 @@ func TestCDNs(t *testing.T) { validateCDNUpdateFields("cdn1", map[string]interface{}{"DomainName": "domain2"})), }, "PRECONDITION FAILED when updating with IF-UNMODIFIED-SINCE Headers": { - EndpointId: GetCDNID(t, "cdn1"), + EndpointID: GetCDNID(t, "cdn1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.CDN{ @@ -172,7 +172,7 @@ func TestCDNs(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetCDNID(t, "cdn1"), + EndpointID: GetCDNID(t, "cdn1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfMatch: {rfc.ETag(currentTime)}}}, RequestBody: tc.CDN{ @@ -185,7 +185,7 @@ func TestCDNs(t *testing.T) { }, "DELETE": { "NOT FOUND when INVALID ID parameter": { - EndpointId: func() int { return 111111 }, + EndpointID: func() int { return 111111 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, @@ -211,14 +211,14 @@ func TestCDNs(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateCDN(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateCDN(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteCDN(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteCDN(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/coordinates_test.go b/traffic_ops/testing/api/v5/coordinates_test.go index 46f363170f..6c4bd8cb6d 100644 --- a/traffic_ops/testing/api/v5/coordinates_test.go +++ b/traffic_ops/testing/api/v5/coordinates_test.go @@ -137,7 +137,7 @@ func TestCoordinates(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetCoordinateID(t, "coordinate2"), + EndpointID: GetCoordinateID(t, "coordinate2"), ClientSession: TOSession, RequestBody: tc.Coordinate{ Latitude: 7.7, @@ -148,7 +148,7 @@ func TestCoordinates(t *testing.T) { validateCoordinateUpdateCreateFields("coordinate2", map[string]interface{}{"Latitude": 7.7, "Longitude": 8.8})), }, "NOT FOUND when INVALID ID parameter": { - EndpointId: func() int { return 111111 }, + EndpointID: func() int { return 111111 }, RequestBody: tc.Coordinate{ Latitude: 1.1, Longitude: 2.2, @@ -158,7 +158,7 @@ func TestCoordinates(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetCoordinateID(t, "coordinate1"), + EndpointID: GetCoordinateID(t, "coordinate1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.Coordinate{ @@ -169,7 +169,7 @@ func TestCoordinates(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetCoordinateID(t, "coordinate1"), + EndpointID: GetCoordinateID(t, "coordinate1"), ClientSession: TOSession, RequestBody: tc.Coordinate{ Latitude: 1.1, @@ -182,7 +182,7 @@ func TestCoordinates(t *testing.T) { }, "DELETE": { "NOT FOUND when INVALID ID parameter": { - EndpointId: func() int { return 12345 }, + EndpointID: func() int { return 12345 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, @@ -209,14 +209,14 @@ func TestCoordinates(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateCoordinate(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateCoordinate(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteCoordinate(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteCoordinate(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/deliveryservice_request_comments_test.go b/traffic_ops/testing/api/v5/deliveryservice_request_comments_test.go index 74f651fa86..9e09b6afca 100644 --- a/traffic_ops/testing/api/v5/deliveryservice_request_comments_test.go +++ b/traffic_ops/testing/api/v5/deliveryservice_request_comments_test.go @@ -66,7 +66,7 @@ func TestDeliveryServiceRequestComments(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetDSRequestCommentId(t, "admin"), + EndpointID: GetDSRequestCommentId(t, "admin"), ClientSession: TOSession, RequestBody: tc.DeliveryServiceRequestComment{ DeliveryServiceRequestID: GetDSRequestId(t, "test-ds1")(), @@ -75,14 +75,14 @@ func TestDeliveryServiceRequestComments(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "PRECONDITION FAILED when updating with IF-UNMODIFIED-SINCE Header": { - EndpointId: GetDSRequestCommentId(t, "admin"), + EndpointID: GetDSRequestCommentId(t, "admin"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.DeliveryServiceRequestComment{}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetDSRequestCommentId(t, "admin"), + EndpointID: GetDSRequestCommentId(t, "admin"), ClientSession: TOSession, RequestBody: tc.DeliveryServiceRequestComment{}, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfMatch: {rfc.ETag(currentTime)}}}, @@ -104,7 +104,7 @@ func TestDeliveryServiceRequestComments(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateDeliveryServiceRequestComment(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateDeliveryServiceRequestComment(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/deliveryservice_requests_test.go b/traffic_ops/testing/api/v5/deliveryservice_requests_test.go index c6e478a152..b38ab23429 100644 --- a/traffic_ops/testing/api/v5/deliveryservice_requests_test.go +++ b/traffic_ops/testing/api/v5/deliveryservice_requests_test.go @@ -76,7 +76,7 @@ func TestDeliveryServiceRequests(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetDeliveryServiceRequestId(t, "test-ds1"), + EndpointID: GetDeliveryServiceRequestId(t, "test-ds1"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "changeType": "create", @@ -90,7 +90,7 @@ func TestDeliveryServiceRequests(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when UPDATING STATUS FROM DRAFT TO SUBMITTED": { - EndpointId: GetDeliveryServiceRequestId(t, "test-ds1"), + EndpointID: GetDeliveryServiceRequestId(t, "test-ds1"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "changeType": "create", @@ -104,7 +104,7 @@ func TestDeliveryServiceRequests(t *testing.T) { validatePutDSRequestFields(map[string]interface{}{"STATUS": tc.RequestStatusSubmitted})), }, "BAD REQUEST when using LONG DESCRIPTION 2 and 3 fields": { - EndpointId: GetDeliveryServiceRequestId(t, "test-ds1"), + EndpointID: GetDeliveryServiceRequestId(t, "test-ds1"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "changeType": "create", @@ -119,14 +119,14 @@ func TestDeliveryServiceRequests(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "PRECONDITION FAILED when updating with IF-UNMODIFIED-SINCE Header": { - EndpointId: GetDeliveryServiceRequestId(t, "test-ds1"), + EndpointID: GetDeliveryServiceRequestId(t, "test-ds1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: map[string]interface{}{}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetDeliveryServiceRequestId(t, "test-ds1"), + EndpointID: GetDeliveryServiceRequestId(t, "test-ds1"), ClientSession: TOSession, RequestBody: map[string]interface{}{}, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfMatch: {rfc.ETag(currentTime)}}}, @@ -263,7 +263,7 @@ func TestDeliveryServiceRequests(t *testing.T) { }, "DELETE": { "OK when VALID request": { - EndpointId: GetDeliveryServiceRequestId(t, "test-deletion"), + EndpointID: GetDeliveryServiceRequestId(t, "test-deletion"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, @@ -306,14 +306,14 @@ func TestDeliveryServiceRequests(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.UpdateDeliveryServiceRequest(testCase.EndpointId(), dsReq, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.UpdateDeliveryServiceRequest(testCase.EndpointID(), dsReq, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.DeleteDeliveryServiceRequest(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.DeleteDeliveryServiceRequest(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v5/deliveryservices_test.go b/traffic_ops/testing/api/v5/deliveryservices_test.go index 5e400b0be4..fcd953f628 100644 --- a/traffic_ops/testing/api/v5/deliveryservices_test.go +++ b/traffic_ops/testing/api/v5/deliveryservices_test.go @@ -254,7 +254,7 @@ func TestDeliveryServices(t *testing.T) { }, "PUT": { "BAD REQUEST when using LONG DESCRIPTION 2 and 3 fields": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "longDesc1": "long desc 1", "longDesc2": "long desc 2", @@ -263,7 +263,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "OK when VALID request": { - EndpointId: GetDeliveryServiceId(t, "ds2"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds2"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "maxRequestHeaderBytes": 131080, "longDesc": "something different", @@ -297,21 +297,21 @@ func TestDeliveryServices(t *testing.T) { })), }, "BAD REQUEST when INVALID REMAP TEXT": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "remapText": "@plugin=tslua.so @pparam=/opt/trafficserver/etc/trafficserver/remapPlugin1.lua\nline2", }), Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when MISSING SLICE PLUGIN SIZE": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "rangeRequestHandling": 3, }), Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when SLICE PLUGIN SIZE SET with INVALID RANGE REQUEST SETTING": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "rangeRequestHandling": 1, "rangeSliceBlockSize": 262144, @@ -319,7 +319,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when SLICE PLUGIN SIZE TOO SMALL": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "rangeRequestHandling": 3, "rangeSliceBlockSize": 0, @@ -327,7 +327,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when SLICE PLUGIN SIZE TOO LARGE": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "rangeRequestHandling": 3, "rangeSliceBlockSize": 40000000, @@ -335,7 +335,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when ADDING TOPOLOGY to CLIENT STEERING DS": { - EndpointId: GetDeliveryServiceId(t, "ds-client-steering"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds-client-steering"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "topology": "mso-topology", "xmlId": "ds-client-steering", @@ -344,7 +344,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when TOPOLOGY DOESNT EXIST": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "topology": "", "xmlId": "ds1", @@ -352,7 +352,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when ADDING TOPOLOGY to DS with DS REQUIRED CAPABILITY": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "topology": "top-for-ds-req", "xmlId": "ds1", @@ -360,7 +360,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when ADDING TOPOLOGY to DS when NO CACHES in SAME CDN as DS": { - EndpointId: GetDeliveryServiceId(t, "top-ds-in-cdn2"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "top-ds-in-cdn2"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "cdnId": GetCDNID(t, "cdn2")(), "topology": "top-with-caches-in-cdn1", @@ -369,7 +369,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "OK when REMOVING TOPOLOGY": { - EndpointId: GetDeliveryServiceId(t, "ds-based-top-with-no-mids"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds-based-top-with-no-mids"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "topology": nil, "xmlId": "ds-based-top-with-no-mids", @@ -377,7 +377,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when DS with TOPOLOGY updates HEADER REWRITE FIELDS": { - EndpointId: GetDeliveryServiceId(t, "ds-top"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds-top"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "firstHeaderRewrite": "foo", "innerHeaderRewrite": "bar", @@ -388,7 +388,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "BAD REQUEST when DS with NO TOPOLOGY updates HEADER REWRITE FIELDS": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "firstHeaderRewrite": "foo", "innerHeaderRewrite": "bar", @@ -397,7 +397,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when DS with TOPOLOGY updates LEGACY HEADER REWRITE FIELDS": { - EndpointId: GetDeliveryServiceId(t, "ds-top"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds-top"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "edgeHeaderRewrite": "foo", "midHeaderRewrite": "bar", @@ -407,7 +407,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "OK when DS with NO TOPOLOGY updates LEGACY HEADER REWRITE FIELDS": { - EndpointId: GetDeliveryServiceId(t, "ds2"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds2"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "profileId": GetProfileID(t, "ATS_EDGE_TIER_CACHE")(), "edgeHeaderRewrite": "foo", @@ -418,7 +418,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when UPDATING MINOR VERSION FIELDS": { - EndpointId: GetDeliveryServiceId(t, "ds-test-minor-versions"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds-test-minor-versions"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "consistentHashQueryParams": []string{"d", "e", "f"}, "consistentHashRegex": "foo", @@ -440,7 +440,7 @@ func TestDeliveryServices(t *testing.T) { })), }, "BAD REQUEST when INVALID COUNTRY CODE": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "geoLimit": 2, "geoLimitCountries": []string{"US", "CA", "12"}, @@ -449,7 +449,7 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when CHANGING TOPOLOGY of DS with ORG SERVERS ASSIGNED": { - EndpointId: GetDeliveryServiceId(t, "ds-top"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds-top"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ "topology": "another-topology", "xmlId": "ds-top", @@ -457,18 +457,18 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when UPDATING DS OUTSIDE TENANCY": { - EndpointId: GetDeliveryServiceId(t, "ds3"), ClientSession: tenant4UserSession, + EndpointID: GetDeliveryServiceId(t, "ds3"), ClientSession: tenant4UserSession, RequestBody: generateDeliveryService(t, map[string]interface{}{"xmlId": "ds3"}), Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: generateDeliveryService(t, map[string]interface{}{"xmlId": "ds1"}), Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{"xmlId": "ds1"}), RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfMatch: {rfc.ETag(currentTime)}}}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), @@ -476,7 +476,7 @@ func TestDeliveryServices(t *testing.T) { }, "DELETE": { "BAD REQUEST when DELETING DS OUTSIDE TENANCY": { - EndpointId: GetDeliveryServiceId(t, "ds3"), ClientSession: tenant4UserSession, + EndpointID: GetDeliveryServiceId(t, "ds3"), ClientSession: tenant4UserSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, }, @@ -489,7 +489,7 @@ func TestDeliveryServices(t *testing.T) { }, "DELIVERY SERVICES CAPACITY": { "OK when VALID request": { - EndpointId: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, }, @@ -550,21 +550,21 @@ func TestDeliveryServices(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.UpdateDeliveryService(testCase.EndpointId(), ds, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.UpdateDeliveryService(testCase.EndpointID(), ds, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.DeleteDeliveryService(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.DeleteDeliveryService(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, resp.Alerts, err) } }) case "DELIVERY SERVICES CAPACITY": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetDeliveryServiceCapacity(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.GetDeliveryServiceCapacity(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v5/deliveryserviceservers_test.go b/traffic_ops/testing/api/v5/deliveryserviceservers_test.go index f82e903582..4f69ba8b6a 100644 --- a/traffic_ops/testing/api/v5/deliveryserviceservers_test.go +++ b/traffic_ops/testing/api/v5/deliveryserviceservers_test.go @@ -124,7 +124,7 @@ func TestDeliveryServiceServers(t *testing.T) { }, "SERVER STATUS PUT": { "BAD REQUEST when UPDATING SERVER STATUS when ONLY EDGE SERVER ASSIGNED": { - EndpointId: GetServerID(t, "test-ds-server-assignments"), ClientSession: TOSession, + EndpointID: GetServerID(t, "test-ds-server-assignments"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "status": "ADMIN_DOWN", "offlineReason": "admin down", @@ -132,7 +132,7 @@ func TestDeliveryServiceServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusConflict)), }, "BAD REQUEST when UPDATING SERVER STATUS when ONLY ORIGIN SERVER ASSIGNED": { - EndpointId: GetServerID(t, "test-mso-org-01"), ClientSession: TOSession, + EndpointID: GetServerID(t, "test-mso-org-01"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "status": "ADMIN_DOWN", "offlineReason": "admin down", @@ -184,7 +184,7 @@ func TestDeliveryServiceServers(t *testing.T) { }) case "SERVER STATUS PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateServerStatus(testCase.EndpointId(), status, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateServerStatus(testCase.EndpointID(), status, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } @@ -258,7 +258,7 @@ func TestDeliveryServicesIDServers(t *testing.T) { dsIDServersTests := utils.V5TestCase{ "GET": { "OK when VALID request": { - EndpointId: GetDeliveryServiceId(t, "test-ds-server-assignments"), ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "test-ds-server-assignments"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseHasLength(2)), }, @@ -270,7 +270,7 @@ func TestDeliveryServicesIDServers(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetServersByDeliveryService(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.GetServersByDeliveryService(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v5/deliveryservicesideligible_test.go b/traffic_ops/testing/api/v5/deliveryservicesideligible_test.go index dcfd36d842..3ae0e1c8b0 100644 --- a/traffic_ops/testing/api/v5/deliveryservicesideligible_test.go +++ b/traffic_ops/testing/api/v5/deliveryservicesideligible_test.go @@ -29,7 +29,7 @@ func TestDeliveryServicesEligible(t *testing.T) { methodTests := utils.TestCase[client.Session, client.RequestOptions, struct{}]{ "GET": { "OK when VALID request": { - EndpointId: GetDeliveryServiceId(t, "ds1"), + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseLengthGreaterOrEqual(1)), }, @@ -41,7 +41,7 @@ func TestDeliveryServicesEligible(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetDeliveryServicesEligible(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.GetDeliveryServicesEligible(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v5/deliveryservicesregexes_test.go b/traffic_ops/testing/api/v5/deliveryservicesregexes_test.go index bdfe00405d..bfc5d68eba 100644 --- a/traffic_ops/testing/api/v5/deliveryservicesregexes_test.go +++ b/traffic_ops/testing/api/v5/deliveryservicesregexes_test.go @@ -34,12 +34,12 @@ func TestDeliveryServicesRegexes(t *testing.T) { methodTests := utils.TestCase[client.Session, client.RequestOptions, tc.DeliveryServiceRegexPost]{ "GET": { "OK when VALID request": { - EndpointId: GetDeliveryServiceId(t, "ds1"), + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseHasLength(3)), }, "OK when VALID ID parameter": { - EndpointId: GetDeliveryServiceId(t, "ds1"), + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"id": {strconv.Itoa(getDSRegexID(t, "ds1"))}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseHasLength(1)), @@ -47,7 +47,7 @@ func TestDeliveryServicesRegexes(t *testing.T) { }, "POST": { "BAD REQUEST when MISSING REGEX PATTERN": { - EndpointId: GetDeliveryServiceId(t, "ds1"), + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, RequestBody: tc.DeliveryServiceRegexPost{ Type: GetTypeId(t, "HOST_REGEXP"), @@ -65,14 +65,14 @@ func TestDeliveryServicesRegexes(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetDeliveryServiceRegexesByDSID(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.GetDeliveryServiceRegexesByDSID(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } }) case "POST": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.PostDeliveryServiceRegexesByDSID(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.PostDeliveryServiceRegexesByDSID(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/divisions_test.go b/traffic_ops/testing/api/v5/divisions_test.go index bebf4062e5..6022802cf6 100644 --- a/traffic_ops/testing/api/v5/divisions_test.go +++ b/traffic_ops/testing/api/v5/divisions_test.go @@ -108,7 +108,7 @@ func TestDivisions(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetDivisionID(t, "cdn-div2"), + EndpointID: GetDivisionID(t, "cdn-div2"), ClientSession: TOSession, RequestBody: tc.Division{ Name: "testdivision", @@ -117,7 +117,7 @@ func TestDivisions(t *testing.T) { validateDivisionUpdateCreateFields("testdivision", map[string]interface{}{"Name": "testdivision"})), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetDivisionID(t, "division1"), + EndpointID: GetDivisionID(t, "division1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.Division{ @@ -126,7 +126,7 @@ func TestDivisions(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetDivisionID(t, "division1"), + EndpointID: GetDivisionID(t, "division1"), ClientSession: TOSession, RequestBody: tc.Division{ Name: "division1", @@ -137,12 +137,12 @@ func TestDivisions(t *testing.T) { }, "DELETE": { "BAD REQUEST when DIVISION in use by REGION": { - EndpointId: GetDivisionID(t, "division1"), + EndpointID: GetDivisionID(t, "division1"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "NOT FOUND when INVALID ID parameter": { - EndpointId: func() int { return 111111 }, + EndpointID: func() int { return 111111 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, @@ -169,14 +169,14 @@ func TestDivisions(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateDivision(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateDivision(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteDivision(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteDivision(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/federation_deliveryservices_test.go b/traffic_ops/testing/api/v5/federation_deliveryservices_test.go index a3bc260331..f5edc6ff94 100644 --- a/traffic_ops/testing/api/v5/federation_deliveryservices_test.go +++ b/traffic_ops/testing/api/v5/federation_deliveryservices_test.go @@ -36,57 +36,57 @@ func TestFederationsDeliveryServices(t *testing.T) { methodTests := utils.TestCase[client.Session, client.RequestOptions, tc.FederationDSPost]{ "GET": { "OK when VALID request": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseLengthGreaterOrEqual(1)), }, "SORTED when ORDERBY=DSID parameter": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"orderby": {"dsID"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateFederationDeliveryServicesSort(false)), }, "SORTED when ORDERBY=DSID and SORTORDER=DESC parameter": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"orderby": {"dsID"}, "sortOrder": {"desc"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateFederationDeliveryServicesSort(true)), }, "FIRST RESULT when LIMIT=1": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"orderby": {"dsID"}, "limit": {"1"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateFederationDeliveryServicesPagination(GetFederationID(t, "the.cname.com.")(), "limit")), }, "SECOND RESULT when LIMIT=1 OFFSET=1": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"orderby": {"dsID"}, "limit": {"1"}, "offset": {"1"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateFederationDeliveryServicesPagination(GetFederationID(t, "the.cname.com.")(), "offset")), }, "SECOND RESULT when LIMIT=1 PAGE=2": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"orderby": {"dsID"}, "limit": {"1"}, "page": {"2"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateFederationDeliveryServicesPagination(GetFederationID(t, "the.cname.com.")(), "page")), }, "BAD REQUEST when INVALID LIMIT parameter": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"limit": {"-2"}}}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when INVALID OFFSET parameter": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"limit": {"1"}, "offset": {"0"}}}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when INVALID PAGE parameter": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"limit": {"1"}, "page": {"0"}}}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), @@ -94,13 +94,13 @@ func TestFederationsDeliveryServices(t *testing.T) { }, "DELETE": { "OK when VALID request": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"dsID": {strconv.Itoa(GetDeliveryServiceId(t, "ds1")())}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "BAD REQUEST when LAST DELIVERY SERVICE": { - EndpointId: GetFederationID(t, "google.com."), + EndpointID: GetFederationID(t, "google.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"dsID": {strconv.Itoa(GetDeliveryServiceId(t, "ds2")())}}}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), @@ -114,7 +114,7 @@ func TestFederationsDeliveryServices(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetFederationDeliveryServices(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.GetFederationDeliveryServices(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } @@ -122,7 +122,7 @@ func TestFederationsDeliveryServices(t *testing.T) { case "POST": t.Run(name, func(t *testing.T) { fedDS := testCase.RequestBody - alerts, reqInf, err := testCase.ClientSession.CreateFederationDeliveryServices(testCase.EndpointId(), fedDS.DSIDs, *fedDS.Replace, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.CreateFederationDeliveryServices(testCase.EndpointID(), fedDS.DSIDs, *fedDS.Replace, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } @@ -135,7 +135,7 @@ func TestFederationsDeliveryServices(t *testing.T) { assert.RequireNoError(t, err, "Failed to convert dsID to an integer.") dsID = id } - alerts, reqInf, err := testCase.ClientSession.DeleteFederationDeliveryService(testCase.EndpointId(), dsID, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteFederationDeliveryService(testCase.EndpointID(), dsID, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/federation_federation_resolvers_test.go b/traffic_ops/testing/api/v5/federation_federation_resolvers_test.go index 5c040b5c82..ebfd094e66 100644 --- a/traffic_ops/testing/api/v5/federation_federation_resolvers_test.go +++ b/traffic_ops/testing/api/v5/federation_federation_resolvers_test.go @@ -31,19 +31,19 @@ func TestFederationFederationResolvers(t *testing.T) { methodTests := utils.TestCase[client.Session, client.RequestOptions, tc.AssignFederationResolversRequest]{ "GET": { "OK when VALID request AND RESOLVERS ASSIGNED": { - EndpointId: GetFederationID(t, "booya.com."), + EndpointID: GetFederationID(t, "booya.com."), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseLengthGreaterOrEqual(1)), }, "OK when VALID request AND NO RESOLVERS ASSIGNED": { - EndpointId: GetFederationID(t, "google.com."), + EndpointID: GetFederationID(t, "google.com."), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseHasLength(0)), }, }, "POST": { "OK when ASSIGNING ONE FEDERATION RESOLVER": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestBody: tc.AssignFederationResolversRequest{ FedResolverIDs: []int{GetFederationResolverID(t, "1.2.3.4")()}, @@ -52,7 +52,7 @@ func TestFederationFederationResolvers(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when ASSIGNING MULTIPLE FEDERATION RESOLVERS": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestBody: tc.AssignFederationResolversRequest{ FedResolverIDs: []int{ @@ -65,7 +65,7 @@ func TestFederationFederationResolvers(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when REPLACING ALL FEDERATION RESOLVERS": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestBody: tc.AssignFederationResolversRequest{ FedResolverIDs: []int{GetFederationResolverID(t, "dead::babe")()}, @@ -74,7 +74,7 @@ func TestFederationFederationResolvers(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "BAD REQUEST when FEDERATION DOESNT EXIST": { - EndpointId: func() int { return -1 }, + EndpointID: func() int { return -1 }, ClientSession: TOSession, RequestBody: tc.AssignFederationResolversRequest{ FedResolverIDs: []int{GetFederationResolverID(t, "1.2.3.4")()}, @@ -91,7 +91,7 @@ func TestFederationFederationResolvers(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetFederationFederationResolvers(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.GetFederationFederationResolvers(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } @@ -99,7 +99,7 @@ func TestFederationFederationResolvers(t *testing.T) { case "POST": t.Run(name, func(t *testing.T) { frAssignment := testCase.RequestBody - resp, reqInf, err := testCase.ClientSession.AssignFederationFederationResolver(testCase.EndpointId(), frAssignment.FedResolverIDs, frAssignment.Replace, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.AssignFederationFederationResolver(testCase.EndpointID(), frAssignment.FedResolverIDs, frAssignment.Replace, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v5/federation_resolvers_test.go b/traffic_ops/testing/api/v5/federation_resolvers_test.go index a03a89302d..5fae50797d 100644 --- a/traffic_ops/testing/api/v5/federation_resolvers_test.go +++ b/traffic_ops/testing/api/v5/federation_resolvers_test.go @@ -125,7 +125,7 @@ func TestFederationResolvers(t *testing.T) { }, "DELETE": { "NOT FOUND when INVALID ID": { - EndpointId: func() int { return 0 }, + EndpointID: func() int { return 0 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, @@ -152,7 +152,7 @@ func TestFederationResolvers(t *testing.T) { }) case "DELETE": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.DeleteFederationResolver(uint(testCase.EndpointId()), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.DeleteFederationResolver(uint(testCase.EndpointID()), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v5/federation_users_test.go b/traffic_ops/testing/api/v5/federation_users_test.go index 065fbf35ee..ac0c10cc39 100644 --- a/traffic_ops/testing/api/v5/federation_users_test.go +++ b/traffic_ops/testing/api/v5/federation_users_test.go @@ -41,69 +41,69 @@ func TestFederationUsers(t *testing.T) { methodTests := utils.TestCase[client.Session, client.RequestOptions, tc.FederationUserPost]{ "GET": { "NOT MODIFIED when NO CHANGES made": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfModifiedSince: {tomorrow}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusNotModified)), }, "BAD REQUEST when INVALID FEDERATION ID": { - EndpointId: func() int { return -1 }, + EndpointID: func() int { return -1 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "SORTED by ID when ORDERBY=USERID parameter": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"orderby": {"userID"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateFederationUserIDSort(false)), }, "VALID when SORTORDER param is DESC": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"orderby": {"userID"}, "sortOrder": {"desc"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateFederationUserIDSort(true)), }, "FIRST RESULT when LIMIT=1": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"orderby": {"userID"}, "limit": {"1"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateFederationUsersPagination(GetFederationID(t, "the.cname.com.")(), "limit")), }, "SECOND RESULT when LIMIT=1 OFFSET=1": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"orderby": {"userID"}, "limit": {"1"}, "offset": {"1"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateFederationUsersPagination(GetFederationID(t, "the.cname.com.")(), "offset")), }, "SECOND RESULT when LIMIT=1 PAGE=2": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"orderby": {"userID"}, "limit": {"1"}, "page": {"2"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateFederationUsersPagination(GetFederationID(t, "the.cname.com.")(), "page")), }, "BAD REQUEST when INVALID LIMIT parameter": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"limit": {"-2"}}}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when INVALID OFFSET parameter": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"limit": {"1"}, "offset": {"0"}}}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when INVALID PAGE parameter": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"limit": {"1"}, "page": {"0"}}}, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "OK when CHANGES made": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfModifiedSince: {currentTimeRFC}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), @@ -111,7 +111,7 @@ func TestFederationUsers(t *testing.T) { }, "POST": { "OK when VALID request": { - EndpointId: GetFederationID(t, "google.com."), + EndpointID: GetFederationID(t, "google.com."), ClientSession: TOSession, RequestBody: tc.FederationUserPost{ IDs: []int{ @@ -123,7 +123,7 @@ func TestFederationUsers(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when REPLACING USERS": { - EndpointId: GetFederationID(t, "booya.com."), + EndpointID: GetFederationID(t, "booya.com."), ClientSession: TOSession, RequestBody: tc.FederationUserPost{ IDs: []int{GetUserID(t, "readonlyuser")()}, @@ -132,7 +132,7 @@ func TestFederationUsers(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "OK when ADDING USER": { - EndpointId: GetFederationID(t, "booya.com."), + EndpointID: GetFederationID(t, "booya.com."), ClientSession: TOSession, RequestBody: tc.FederationUserPost{ IDs: []int{GetUserID(t, "disalloweduser")()}, @@ -141,7 +141,7 @@ func TestFederationUsers(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, "BAD REQUEST when INVALID FEDERATION ID": { - EndpointId: func() int { return -1 }, + EndpointID: func() int { return -1 }, ClientSession: TOSession, RequestBody: tc.FederationUserPost{ IDs: []int{}, @@ -150,7 +150,7 @@ func TestFederationUsers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "BAD REQUEST when INVALID USER ID": { - EndpointId: GetFederationID(t, "the.cname.com."), + EndpointID: GetFederationID(t, "the.cname.com."), ClientSession: TOSession, RequestBody: tc.FederationUserPost{ IDs: []int{-1}, @@ -167,7 +167,7 @@ func TestFederationUsers(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetFederationUsers(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.GetFederationUsers(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } @@ -175,7 +175,7 @@ func TestFederationUsers(t *testing.T) { case "POST": t.Run(name, func(t *testing.T) { federationUser := testCase.RequestBody - alerts, reqInf, err := testCase.ClientSession.CreateFederationUsers(testCase.EndpointId(), federationUser.IDs, *federationUser.Replace, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.CreateFederationUsers(testCase.EndpointID(), federationUser.IDs, *federationUser.Replace, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/jobs_test.go b/traffic_ops/testing/api/v5/jobs_test.go index 3036012a59..ed1f63eb29 100644 --- a/traffic_ops/testing/api/v5/jobs_test.go +++ b/traffic_ops/testing/api/v5/jobs_test.go @@ -498,7 +498,7 @@ func TestJobs(t *testing.T) { }, "DELETE": { "NOT FOUND when JOB DOESNT EXIST": { - EndpointId: func() int { return 1111111111 }, + EndpointID: func() int { return 1111111111 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, @@ -547,7 +547,7 @@ func TestJobs(t *testing.T) { }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteInvalidationJob(uint64(testCase.EndpointId()), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteInvalidationJob(uint64(testCase.EndpointID()), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/origins_test.go b/traffic_ops/testing/api/v5/origins_test.go index dba6b54f8d..401e1d884e 100644 --- a/traffic_ops/testing/api/v5/origins_test.go +++ b/traffic_ops/testing/api/v5/origins_test.go @@ -275,7 +275,7 @@ func TestOrigins(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin2"), @@ -294,7 +294,7 @@ func TestOrigins(t *testing.T) { "FQDN": "originupdated.example.com", "IPAddress": "1.2.3.4", "IP6Address": "0000::1111", "Port": 1234, "Protocol": "http", "Tenant": "tenant2"})), }, "FORBIDDEN when CHILD TENANT updates PARENT TENANT ORIGIN": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: tenant4UserSession, RequestBody: tc.Origin{ Name: util.Ptr("testtenancy"), @@ -306,7 +306,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, "NOT FOUND when ORIGIN DOESNT EXIST": { - EndpointId: func() int { return 1111111 }, + EndpointID: func() int { return 1111111 }, ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("testid"), @@ -318,7 +318,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "BAD REQUEST when DELIVERY SERVICE DOESNT EXIST": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin2"), @@ -330,7 +330,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "NOT FOUND when CACHEGROUP DOESNT EXIST": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin2"), @@ -343,7 +343,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "NOT FOUND when PROFILEID DOESNT EXIST": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin2"), @@ -357,7 +357,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "NOT FOUND when COORDINATE DOESNT EXIST": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin2"), @@ -371,7 +371,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "FORBIDDEN when INVALID TENANT": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin1"), @@ -384,7 +384,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, "BAD REQUEST when INVALID PROTOCOL": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin2"), @@ -397,7 +397,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when INVALID IPV4 ADDRESS": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin2"), @@ -411,7 +411,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when INVALID IPV6 ADDRESS": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin2"), @@ -425,7 +425,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when INVALID PORT": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin2"), @@ -439,7 +439,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.Origin{ @@ -453,7 +453,7 @@ func TestOrigins(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: TOSession, RequestBody: tc.Origin{ Name: util.Ptr("origin2"), @@ -469,12 +469,12 @@ func TestOrigins(t *testing.T) { }, "DELETE": { "NOT FOUND when DOESNT EXIST": { - EndpointId: func() int { return 11111111 }, + EndpointID: func() int { return 11111111 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "FORBIDDEN when CHILD TENANT deletes PARENT TENANT ORIGIN": { - EndpointId: GetOriginID(t, "origin2"), + EndpointID: GetOriginID(t, "origin2"), ClientSession: tenant4UserSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, @@ -501,14 +501,14 @@ func TestOrigins(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.UpdateOrigin(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.UpdateOrigin(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteOrigin(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteOrigin(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/parameters_test.go b/traffic_ops/testing/api/v5/parameters_test.go index a7879e490d..e169ded18b 100644 --- a/traffic_ops/testing/api/v5/parameters_test.go +++ b/traffic_ops/testing/api/v5/parameters_test.go @@ -191,7 +191,7 @@ func TestParameters(t *testing.T) { }, "PUT": { "OK when VALID REQUEST": { - EndpointId: GetParameterID(t, "LogObject.Format", "logs_xml.config", "custom_ats_2"), + EndpointID: GetParameterID(t, "LogObject.Format", "logs_xml.config", "custom_ats_2"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "configFile": "updated.config", @@ -204,7 +204,7 @@ func TestParameters(t *testing.T) { map[string]interface{}{"ConfigFile": "updated.config", "Name": "updated name", "Secure": true, "Value": "updated value"})), }, "OK when MISSING VALUE FIELD": { - EndpointId: GetParameterID(t, "LogObject.Filename", "logs_xml.config", "custom_ats_2"), + EndpointID: GetParameterID(t, "LogObject.Filename", "logs_xml.config", "custom_ats_2"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "configFile": "logs_new.config", @@ -217,7 +217,7 @@ func TestParameters(t *testing.T) { map[string]interface{}{"ConfigFile": "logs_new.config", "Secure": true, "Value": ""})), }, "BAD REQUEST when MISSING NAME FIELD": { - EndpointId: GetParameterID(t, "astats_over_http.so", "plugin.config", ""), + EndpointID: GetParameterID(t, "astats_over_http.so", "plugin.config", ""), ClientSession: TOSession, RequestBody: map[string]interface{}{ "configFile": "missingname.config", @@ -228,7 +228,7 @@ func TestParameters(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when MISSING CONFIGFILE FIELD": { - EndpointId: GetParameterID(t, "astats_over_http.so", "plugin.config", ""), + EndpointID: GetParameterID(t, "astats_over_http.so", "plugin.config", ""), ClientSession: TOSession, RequestBody: map[string]interface{}{ "configFile": "", @@ -239,7 +239,7 @@ func TestParameters(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetParameterID(t, "LogFormat.Name", "logs_xml.config", "custom_ats_2"), + EndpointID: GetParameterID(t, "LogFormat.Name", "logs_xml.config", "custom_ats_2"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: map[string]interface{}{ @@ -250,7 +250,7 @@ func TestParameters(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetParameterID(t, "LogFormat.Name", "logs_xml.config", "custom_ats_2"), + EndpointID: GetParameterID(t, "LogFormat.Name", "logs_xml.config", "custom_ats_2"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "configFile": "logs_xml.config", @@ -263,7 +263,7 @@ func TestParameters(t *testing.T) { }, "DELETE": { "BAD REQUEST when DOESNT EXIST": { - EndpointId: func() int { return 100000 }, + EndpointID: func() int { return 100000 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, @@ -313,14 +313,14 @@ func TestParameters(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateParameter(testCase.EndpointId(), parameter, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateParameter(testCase.EndpointID(), parameter, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteParameter(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteParameter(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/phys_locations_test.go b/traffic_ops/testing/api/v5/phys_locations_test.go index da77322188..200204454d 100644 --- a/traffic_ops/testing/api/v5/phys_locations_test.go +++ b/traffic_ops/testing/api/v5/phys_locations_test.go @@ -133,7 +133,7 @@ func TestPhysLocations(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetPhysicalLocationID(t, "HotAtlanta"), + EndpointID: GetPhysicalLocationID(t, "HotAtlanta"), ClientSession: TOSession, RequestBody: tc.PhysLocation{ Address: "1234 southern way", @@ -149,7 +149,7 @@ func TestPhysLocations(t *testing.T) { validatePhysicalLocationUpdateCreateFields("HotAtlanta", map[string]interface{}{"City": "NewCity"})), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetPhysicalLocationID(t, "HotAtlanta"), + EndpointID: GetPhysicalLocationID(t, "HotAtlanta"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.PhysLocation{ @@ -164,7 +164,7 @@ func TestPhysLocations(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetPhysicalLocationID(t, "HotAtlanta"), + EndpointID: GetPhysicalLocationID(t, "HotAtlanta"), ClientSession: TOSession, RequestBody: tc.PhysLocation{ Address: "1234 southern way", @@ -181,7 +181,7 @@ func TestPhysLocations(t *testing.T) { }, "DELETE": { "OK when VALID request": { - EndpointId: GetPhysicalLocationID(t, "testDelete"), + EndpointID: GetPhysicalLocationID(t, "testDelete"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, @@ -208,14 +208,14 @@ func TestPhysLocations(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdatePhysLocation(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdatePhysLocation(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeletePhysLocation(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeletePhysLocation(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/profile_parameters_test.go b/traffic_ops/testing/api/v5/profile_parameters_test.go index 5c25c8f5b5..e44ebd7831 100644 --- a/traffic_ops/testing/api/v5/profile_parameters_test.go +++ b/traffic_ops/testing/api/v5/profile_parameters_test.go @@ -106,7 +106,7 @@ func TestProfileParameters(t *testing.T) { }, "DELETE": { "OK when VALID request": { - EndpointId: GetProfileID(t, "ATS_EDGE_TIER_CACHE"), + EndpointID: GetProfileID(t, "ATS_EDGE_TIER_CACHE"), ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{ "parameterId": {strconv.Itoa(GetParameterID(t, "location", "set_dscp_37.config", "/etc/trafficserver/dscp")())}, @@ -160,7 +160,7 @@ func TestProfileParameters(t *testing.T) { case "DELETE": t.Run(name, func(t *testing.T) { parameterId, _ := strconv.Atoi(testCase.RequestOpts.QueryParameters["parameterId"][0]) - alerts, reqInf, err := testCase.ClientSession.DeleteProfileParameter(testCase.EndpointId(), parameterId, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteProfileParameter(testCase.EndpointID(), parameterId, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/profiles_export_test.go b/traffic_ops/testing/api/v5/profiles_export_test.go index 699b8d7c13..8f45e0ff6d 100644 --- a/traffic_ops/testing/api/v5/profiles_export_test.go +++ b/traffic_ops/testing/api/v5/profiles_export_test.go @@ -33,14 +33,14 @@ func TestProfilesExport(t *testing.T) { methodTests := utils.TestCase[client.Session, client.RequestOptions, struct{}]{ "GET": { "OK when VALID request": { - EndpointId: GetProfileID(t, "EDGE1"), + EndpointID: GetProfileID(t, "EDGE1"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateProfilesExportFields(map[string]interface{}{"CDNName": "cdn1", "Name": "EDGE1", "Description": "edge1 description", "Type": "ATS_PROFILE"})), }, "NOT FOUND when PROFILE DOESNT EXIST": { - EndpointId: func() int { return 1111111111 }, + EndpointID: func() int { return 1111111111 }, ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, @@ -53,7 +53,7 @@ func TestProfilesExport(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.ExportProfile(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.ExportProfile(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v5/profiles_test.go b/traffic_ops/testing/api/v5/profiles_test.go index b015ce066e..d1c8c1607e 100644 --- a/traffic_ops/testing/api/v5/profiles_test.go +++ b/traffic_ops/testing/api/v5/profiles_test.go @@ -163,7 +163,7 @@ func TestProfiles(t *testing.T) { }, "PUT": { "OK when VALID REQUEST": { - EndpointId: GetProfileID(t, "EDGE2"), + EndpointID: GetProfileID(t, "EDGE2"), ClientSession: TOSession, RequestBody: tc.Profile{ CDNID: GetCDNID(t, "cdn2")(), @@ -178,7 +178,7 @@ func TestProfiles(t *testing.T) { "Name": "EDGE2UPDATED", "RoutingDisabled": false, "Type": "TR_PROFILE"})), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetProfileID(t, "CCR1"), + EndpointID: GetProfileID(t, "CCR1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.Profile{ @@ -191,7 +191,7 @@ func TestProfiles(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetProfileID(t, "CCR1"), + EndpointID: GetProfileID(t, "CCR1"), ClientSession: TOSession, RequestBody: tc.Profile{ CDNID: GetCDNID(t, "cdn1")(), @@ -226,14 +226,14 @@ func TestProfiles(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateProfile(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateProfile(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteProfile(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteProfile(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/regions_test.go b/traffic_ops/testing/api/v5/regions_test.go index 07b124bd07..35ec09b0ab 100644 --- a/traffic_ops/testing/api/v5/regions_test.go +++ b/traffic_ops/testing/api/v5/regions_test.go @@ -131,7 +131,7 @@ func TestRegions(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetRegionID(t, "cdn-region2"), + EndpointID: GetRegionID(t, "cdn-region2"), ClientSession: TOSession, RequestBody: tc.Region{ Name: "newName", @@ -142,7 +142,7 @@ func TestRegions(t *testing.T) { validateRegionsUpdateCreateFields("newName", map[string]interface{}{"Name": "newName"})), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetRegionID(t, "region1"), + EndpointID: GetRegionID(t, "region1"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.Region{ @@ -153,7 +153,7 @@ func TestRegions(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetRegionID(t, "region1"), + EndpointID: GetRegionID(t, "region1"), ClientSession: TOSession, RequestBody: tc.Region{ Name: "newName", @@ -204,7 +204,7 @@ func TestRegions(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateRegion(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateRegion(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/servers_id_deliveryservices_test.go b/traffic_ops/testing/api/v5/servers_id_deliveryservices_test.go index 50fa745ca4..468b530f97 100644 --- a/traffic_ops/testing/api/v5/servers_id_deliveryservices_test.go +++ b/traffic_ops/testing/api/v5/servers_id_deliveryservices_test.go @@ -36,20 +36,20 @@ func TestServersIDDeliveryServices(t *testing.T) { methodTests := utils.V5TestCase{ "GET": { "NOT MODIFIED when NO CHANGES made": { - EndpointId: GetServerID(t, "atlanta-edge-14"), + EndpointID: GetServerID(t, "atlanta-edge-14"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfModifiedSince: {tomorrow}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusNotModified)), }, "OK when VALID request": { - EndpointId: GetServerID(t, "atlanta-edge-14"), + EndpointID: GetServerID(t, "atlanta-edge-14"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, }, "POST": { "OK when VALID request": { - EndpointId: GetServerID(t, "atlanta-edge-01"), + EndpointID: GetServerID(t, "atlanta-edge-01"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "dsIds": []int{GetDeliveryServiceId(t, "ds1")()}, @@ -59,7 +59,7 @@ func TestServersIDDeliveryServices(t *testing.T) { validateServersDeliveryServicesPost(GetServerID(t, "atlanta-edge-01")(), GetDeliveryServiceId(t, "ds1")())), }, "OK when ASSIGNING EDGE to TOPOLOGY BASED DELIVERY SERVICE": { - EndpointId: GetServerID(t, "atlanta-edge-03"), + EndpointID: GetServerID(t, "atlanta-edge-03"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "dsIds": []int{GetDeliveryServiceId(t, "top-ds-in-cdn1")()}, @@ -69,7 +69,7 @@ func TestServersIDDeliveryServices(t *testing.T) { validateServersDeliveryServicesPost(GetServerID(t, "atlanta-edge-03")(), GetDeliveryServiceId(t, "top-ds-in-cdn1")())), }, "OK when ASSIGNING ORIGIN to TOPOLOGY BASED DELIVERY SERVICE": { - EndpointId: GetServerID(t, "denver-mso-org-01"), + EndpointID: GetServerID(t, "denver-mso-org-01"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "dsIds": []int{GetDeliveryServiceId(t, "ds-top")()}, @@ -79,7 +79,7 @@ func TestServersIDDeliveryServices(t *testing.T) { validateServersDeliveryServicesPost(GetServerID(t, "denver-mso-org-01")(), GetDeliveryServiceId(t, "ds-top")())), }, "CONFLICT when SERVER NOT IN SAME CDN as DELIVERY SERVICE": { - EndpointId: GetServerID(t, "cdn2-test-edge"), + EndpointID: GetServerID(t, "cdn2-test-edge"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "dsIds": []int{GetDeliveryServiceId(t, "ds1")()}, @@ -88,7 +88,7 @@ func TestServersIDDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusConflict)), }, "BAD REQUEST when ORIGIN'S CACHEGROUP IS NOT A PART OF TOPOLOGY BASED DELIVERY SERVICE": { - EndpointId: GetServerID(t, "denver-mso-org-01"), + EndpointID: GetServerID(t, "denver-mso-org-01"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "dsIds": []int{GetDeliveryServiceId(t, "ds-top-req-cap")()}, @@ -97,7 +97,7 @@ func TestServersIDDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "CONFLICT when REMOVING ONLY EDGE SERVER ASSIGNMENT": { - EndpointId: GetServerID(t, "test-ds-server-assignments"), + EndpointID: GetServerID(t, "test-ds-server-assignments"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "dsIds": []int{}, @@ -106,7 +106,7 @@ func TestServersIDDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusConflict)), }, "CONFLICT when REMOVING ONLY ORIGIN SERVER ASSIGNMENT": { - EndpointId: GetServerID(t, "test-mso-org-01"), + EndpointID: GetServerID(t, "test-mso-org-01"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "dsIds": []int{}, @@ -136,14 +136,14 @@ func TestServersIDDeliveryServices(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetServerIDDeliveryServices(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.GetServerIDDeliveryServices(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } }) case "POST": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.AssignDeliveryServiceIDsToServerID(testCase.EndpointId(), dsIds, replace, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.AssignDeliveryServiceIDsToServerID(testCase.EndpointID(), dsIds, replace, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/servers_id_queue_update_test.go b/traffic_ops/testing/api/v5/servers_id_queue_update_test.go index 60268f2426..29ae8a46cf 100644 --- a/traffic_ops/testing/api/v5/servers_id_queue_update_test.go +++ b/traffic_ops/testing/api/v5/servers_id_queue_update_test.go @@ -33,7 +33,7 @@ func TestServersIDQueueUpdate(t *testing.T) { methodTests := utils.TestCase[client.Session, client.RequestOptions, bool]{ "POST": { "OK when VALID QUEUE request": { - EndpointId: GetServerID(t, "atlanta-edge-01"), + EndpointID: GetServerID(t, "atlanta-edge-01"), ClientSession: TOSession, RequestBody: true, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), @@ -41,7 +41,7 @@ func TestServersIDQueueUpdate(t *testing.T) { validateUpdPendingSpecificServers(map[string]bool{"atlanta-edge-01": true})), }, "OK when VALID DEQUEUE request": { - EndpointId: GetServerID(t, "atlanta-edge-01"), + EndpointID: GetServerID(t, "atlanta-edge-01"), ClientSession: TOSession, RequestBody: false, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), @@ -52,7 +52,7 @@ func TestServersIDQueueUpdate(t *testing.T) { https://github.com/apache/trafficcontrol/issues/6691 https://github.com/apache/trafficcontrol/issues/6801 "NOT FOUND when NON-EXISTENT SERVER": { - EndpointId: func() int { return 999999 }, + EndpointID: func() int { return 999999 }, ClientSession: TOSession, RequestBody: true, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), @@ -66,7 +66,7 @@ func TestServersIDQueueUpdate(t *testing.T) { switch method { case "POST": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.SetServerQueueUpdate(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.SetServerQueueUpdate(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } diff --git a/traffic_ops/testing/api/v5/servers_id_status_test.go b/traffic_ops/testing/api/v5/servers_id_status_test.go index 0aa2b4f1ec..b2d2d96274 100644 --- a/traffic_ops/testing/api/v5/servers_id_status_test.go +++ b/traffic_ops/testing/api/v5/servers_id_status_test.go @@ -33,7 +33,7 @@ func TestServersIDStatus(t *testing.T) { methodTests := utils.TestCase[client.Session, client.RequestOptions, tc.ServerPutStatus]{ "PUT": { "OK when VALID request": { - EndpointId: GetServerID(t, "atlanta-mid-01"), + EndpointID: GetServerID(t, "atlanta-mid-01"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{ID: util.Ptr(GetStatusID(t, "OFFLINE")())}, @@ -42,7 +42,7 @@ func TestServersIDStatus(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateUpdPending("atlanta-mid-01")), }, "OK when using STATUS ID FIELD": { - EndpointId: GetServerID(t, "atlanta-mid-16"), + EndpointID: GetServerID(t, "atlanta-mid-16"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{ID: util.Ptr(GetStatusID(t, "OFFLINE")())}, @@ -51,7 +51,7 @@ func TestServersIDStatus(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateUpdPending("atlanta-mid-16")), }, "VALIDATE TOPOLOGY DESCENDANTS receive STATUS UPDATES": { - EndpointId: GetServerID(t, "topology-mid-04"), + EndpointID: GetServerID(t, "topology-mid-04"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{ID: util.Ptr(GetStatusID(t, "OFFLINE")())}, @@ -63,7 +63,7 @@ func TestServersIDStatus(t *testing.T) { validateParentPendingSpecificServers(map[string]bool{"topology-edge-01": true, "edgeInTopologyEdgeCg02": false})), }, "NOT FOUND when SERVER DOESNT EXIST": { - EndpointId: func() int { return 11111111 }, + EndpointID: func() int { return 11111111 }, ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{Name: util.Ptr("OFFLINE")}, @@ -72,7 +72,7 @@ func TestServersIDStatus(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "BAD REQUEST when STATUS DOESNT EXIST": { - EndpointId: GetServerID(t, "atlanta-mid-16"), + EndpointID: GetServerID(t, "atlanta-mid-16"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{Name: util.Ptr("NOT_A_REAL_STATUS")}, @@ -81,7 +81,7 @@ func TestServersIDStatus(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when MISSING OFFLINE REASON when OFFLINE STATUS": { - EndpointId: GetServerID(t, "atlanta-mid-16"), + EndpointID: GetServerID(t, "atlanta-mid-16"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{Name: util.Ptr("OFFLINE")}, @@ -89,7 +89,7 @@ func TestServersIDStatus(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when MISSING OFFLINE REASON when ADMIN_DOWN STATUS": { - EndpointId: GetServerID(t, "atlanta-mid-16"), + EndpointID: GetServerID(t, "atlanta-mid-16"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{Name: util.Ptr("ADMIN_DOWN")}, @@ -97,7 +97,7 @@ func TestServersIDStatus(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "CONFLICT when SERVER STATUS OFFLINE when ONLY EDGE SERVER ASSIGNED": { - EndpointId: GetServerID(t, "test-ds-server-assignments"), + EndpointID: GetServerID(t, "test-ds-server-assignments"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{Name: util.Ptr("OFFLINE")}, @@ -106,7 +106,7 @@ func TestServersIDStatus(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusConflict)), }, "CONFLICT when SERVER STATUS OFFLINE when ONLY ORIGIN SERVER ASSIGNED": { - EndpointId: GetServerID(t, "test-mso-org-01"), + EndpointID: GetServerID(t, "test-mso-org-01"), ClientSession: TOSession, RequestBody: tc.ServerPutStatus{ Status: util.JSONNameOrIDStr{Name: util.Ptr("OFFLINE")}, @@ -124,7 +124,7 @@ func TestServersIDStatus(t *testing.T) { case "PUT": t.Run(name, func(t *testing.T) { clearUpdates(t) - alerts, reqInf, err := testCase.ClientSession.UpdateServerStatus(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateServerStatus(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/servers_test.go b/traffic_ops/testing/api/v5/servers_test.go index 082e3142af..727c6b6e70 100644 --- a/traffic_ops/testing/api/v5/servers_test.go +++ b/traffic_ops/testing/api/v5/servers_test.go @@ -162,7 +162,7 @@ func TestServers(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetServerID(t, "atlanta-edge-03"), + EndpointID: GetServerID(t, "atlanta-edge-03"), ClientSession: TOSession, RequestBody: map[string]interface{}{ "id": GetServerID(t, "atlanta-edge-03")(), @@ -206,7 +206,7 @@ func TestServers(t *testing.T) { })), }, "BAD REQUEST when CHANGING XMPPID": { - EndpointId: GetServerID(t, "atlanta-edge-16"), + EndpointID: GetServerID(t, "atlanta-edge-16"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "atlanta-edge-16")(), @@ -215,7 +215,7 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "CONFLICT when UPDATING SERVER TYPE when ASSIGNED to DS": { - EndpointId: GetServerID(t, "test-ds-server-assignments"), + EndpointID: GetServerID(t, "test-ds-server-assignments"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "test-ds-server-assignments")(), @@ -225,7 +225,7 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusConflict)), }, "CONFLICT when UPDATING SERVER STATUS when its the ONLY EDGE SERVER ASSIGNED": { - EndpointId: GetServerID(t, "test-ds-server-assignments"), + EndpointID: GetServerID(t, "test-ds-server-assignments"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "test-ds-server-assignments")(), @@ -234,7 +234,7 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusConflict)), }, "CONFLICT when UPDATING SERVER STATUS when its the ONLY ORG SERVER ASSIGNED": { - EndpointId: GetServerID(t, "test-mso-org-01"), + EndpointID: GetServerID(t, "test-mso-org-01"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "test-mso-org-01")(), @@ -243,7 +243,7 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusConflict)), }, "BAD REQUEST when UPDATING CDN when LAST SERVER IN CACHEGROUP IN TOPOLOGY": { - EndpointId: GetServerID(t, "midInTopologyMidCg01"), + EndpointID: GetServerID(t, "midInTopologyMidCg01"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "midInTopologyMidCg01")(), @@ -254,7 +254,7 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when UPDATING CACHEGROUP when LAST SERVER IN CACHEGROUP IN TOPOLOGY": { - EndpointId: GetServerID(t, "midInTopologyMidCg01"), + EndpointID: GetServerID(t, "midInTopologyMidCg01"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "midInTopologyMidCg01")(), @@ -266,7 +266,7 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when IPADDRESS EXISTS with SAME PROFILE": { - EndpointId: GetServerID(t, "atlanta-edge-16"), + EndpointID: GetServerID(t, "atlanta-edge-16"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "profileNames": []string{"EDGE1"}, @@ -282,19 +282,19 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when BLANK HOSTNAME": { - EndpointId: GetServerID(t, "atlanta-edge-16"), + EndpointID: GetServerID(t, "atlanta-edge-16"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{"hostName": ""}), Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when BLANK DOMAINNAME": { - EndpointId: GetServerID(t, "atlanta-edge-16"), + EndpointID: GetServerID(t, "atlanta-edge-16"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{"domainName": ""}), Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetServerID(t, "atlanta-edge-01"), + EndpointID: GetServerID(t, "atlanta-edge-01"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: generateServer(t, map[string]interface{}{ @@ -303,7 +303,7 @@ func TestServers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetServerID(t, "atlanta-edge-01"), + EndpointID: GetServerID(t, "atlanta-edge-01"), ClientSession: TOSession, RequestBody: generateServer(t, map[string]interface{}{ "id": GetServerID(t, "atlanta-edge-01")(), @@ -314,12 +314,12 @@ func TestServers(t *testing.T) { }, "DELETE": { "BAD REQUEST when LAST SERVER in CACHE GROUP": { - EndpointId: GetServerID(t, "midInTopologyMidCg01"), + EndpointID: GetServerID(t, "midInTopologyMidCg01"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "CONFLICT when DELETING SERVER when its the ONLY EDGE SERVER ASSIGNED": { - EndpointId: GetServerID(t, "test-ds-server-assignments"), + EndpointID: GetServerID(t, "test-ds-server-assignments"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusConflict)), }, @@ -362,14 +362,14 @@ func TestServers(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateServer(testCase.EndpointId(), server, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateServer(testCase.EndpointID(), server, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteServer(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteServer(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/staticdnsentries_test.go b/traffic_ops/testing/api/v5/staticdnsentries_test.go index fb5c27289b..2ba31a2ab8 100644 --- a/traffic_ops/testing/api/v5/staticdnsentries_test.go +++ b/traffic_ops/testing/api/v5/staticdnsentries_test.go @@ -58,7 +58,7 @@ func TestStaticDNSEntries(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetStaticDNSEntryID(t, "host2"), + EndpointID: GetStaticDNSEntryID(t, "host2"), ClientSession: TOSession, RequestBody: tc.StaticDNSEntry{ Address: "192.168.0.2", @@ -72,7 +72,7 @@ func TestStaticDNSEntries(t *testing.T) { validateStaticDNSEntriesUpdateCreateFields("host2", map[string]interface{}{"Address": "192.168.0.2"})), }, "BAD REQUEST when INVALID IPV4 ADDRESS for A_RECORD": { - EndpointId: GetStaticDNSEntryID(t, "host2"), + EndpointID: GetStaticDNSEntryID(t, "host2"), ClientSession: TOSession, RequestBody: tc.StaticDNSEntry{ Address: "test.testdomain.net.", @@ -85,7 +85,7 @@ func TestStaticDNSEntries(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when INVALID DNS for CNAME_RECORD": { - EndpointId: GetStaticDNSEntryID(t, "host1"), + EndpointID: GetStaticDNSEntryID(t, "host1"), ClientSession: TOSession, RequestBody: tc.StaticDNSEntry{ Address: "2001:0db8:85a3:0000:0000:8a2e:0370:7334", @@ -98,7 +98,7 @@ func TestStaticDNSEntries(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when MISSING TRAILING PERIOD for CNAME_RECORD": { - EndpointId: GetStaticDNSEntryID(t, "host1"), + EndpointID: GetStaticDNSEntryID(t, "host1"), ClientSession: TOSession, RequestBody: tc.StaticDNSEntry{ Address: "cdn.test.com", @@ -111,7 +111,7 @@ func TestStaticDNSEntries(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "BAD REQUEST when INVALID IPV6 ADDRESS for AAAA_RECORD": { - EndpointId: GetStaticDNSEntryID(t, "host3"), + EndpointID: GetStaticDNSEntryID(t, "host3"), ClientSession: TOSession, RequestBody: tc.StaticDNSEntry{ Address: "192.168.0.1", @@ -124,7 +124,7 @@ func TestStaticDNSEntries(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetStaticDNSEntryID(t, "host3"), + EndpointID: GetStaticDNSEntryID(t, "host3"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.StaticDNSEntry{ @@ -138,7 +138,7 @@ func TestStaticDNSEntries(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetStaticDNSEntryID(t, "host3"), + EndpointID: GetStaticDNSEntryID(t, "host3"), ClientSession: TOSession, RequestBody: tc.StaticDNSEntry{ Address: "2001:0db8:85a3:0000:0000:8a2e:0370:7334", @@ -174,14 +174,14 @@ func TestStaticDNSEntries(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateStaticDNSEntry(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateStaticDNSEntry(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteStaticDNSEntry(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteStaticDNSEntry(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/statuses_test.go b/traffic_ops/testing/api/v5/statuses_test.go index 78bc26f388..81e7a71c2a 100644 --- a/traffic_ops/testing/api/v5/statuses_test.go +++ b/traffic_ops/testing/api/v5/statuses_test.go @@ -62,7 +62,7 @@ func TestStatuses(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetStatusID(t, "TEST_NULL_DESCRIPTION"), + EndpointID: GetStatusID(t, "TEST_NULL_DESCRIPTION"), ClientSession: TOSession, RequestBody: tc.Status{ Description: "new description", @@ -72,7 +72,7 @@ func TestStatuses(t *testing.T) { validateStatusesUpdateCreateFields("TEST_NULL_DESCRIPTION", map[string]interface{}{"Description": "new description"})), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetStatusID(t, "TEST_NULL_DESCRIPTION"), + EndpointID: GetStatusID(t, "TEST_NULL_DESCRIPTION"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.Status{ @@ -82,7 +82,7 @@ func TestStatuses(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetStatusID(t, "TEST_NULL_DESCRIPTION"), + EndpointID: GetStatusID(t, "TEST_NULL_DESCRIPTION"), ClientSession: TOSession, RequestBody: tc.Status{ Description: "new description", @@ -107,14 +107,14 @@ func TestStatuses(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateStatus(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateStatus(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteStatus(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteStatus(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/steeringtargets_test.go b/traffic_ops/testing/api/v5/steeringtargets_test.go index 06e558e20d..323535998f 100644 --- a/traffic_ops/testing/api/v5/steeringtargets_test.go +++ b/traffic_ops/testing/api/v5/steeringtargets_test.go @@ -42,20 +42,20 @@ func TestSteeringTargets(t *testing.T) { methodTests := utils.TestCase[client.Session, client.RequestOptions, tc.SteeringTargetNullable]{ "GET": { "NOT MODIFIED when NO CHANGES made": { - EndpointId: GetDeliveryServiceId(t, "ds1"), + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: steeringUserSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfModifiedSince: {tomorrow}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusNotModified)), }, "OK when VALID request": { - EndpointId: GetDeliveryServiceId(t, "ds1"), + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: steeringUserSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseHasLength(1), validateSteeringTargetFields(map[string]interface{}{"DeliveryService": "ds1", "DeliveryServiceID": uint64(GetDeliveryServiceId(t, "ds1")()), "Target": "ds2", "TargetID": uint64(GetDeliveryServiceId(t, "ds2")()), "Type": "STEERING_WEIGHT", "TypeID": GetTypeID(t, "STEERING_WEIGHT")(), "Value": util.JSONIntStr(42)})), }, "OK when CHANGES made": { - EndpointId: GetDeliveryServiceId(t, "ds1"), + EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: steeringUserSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfModifiedSince: {currentTimeRFC}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), @@ -109,7 +109,7 @@ func TestSteeringTargets(t *testing.T) { switch method { case "GET": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.GetSteeringTargets(testCase.EndpointId(), testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.GetSteeringTargets(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } @@ -135,7 +135,7 @@ func TestSteeringTargets(t *testing.T) { } targetID, err := strconv.Atoi(testCase.RequestOpts.QueryParameters["targetID"][0]) assert.RequireNoError(t, err, "Expected no error converting string to int for target ID: %v", err) - alerts, reqInf, err := testCase.ClientSession.DeleteSteeringTarget(testCase.EndpointId(), targetID, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteSteeringTarget(testCase.EndpointID(), targetID, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/tenants_test.go b/traffic_ops/testing/api/v5/tenants_test.go index 165a89271f..9d8800badb 100644 --- a/traffic_ops/testing/api/v5/tenants_test.go +++ b/traffic_ops/testing/api/v5/tenants_test.go @@ -107,7 +107,7 @@ func TestTenants(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetTenantID(t, "tenant4"), + EndpointID: GetTenantID(t, "tenant4"), ClientSession: TOSession, RequestBody: tc.Tenant{ Active: false, @@ -119,7 +119,7 @@ func TestTenants(t *testing.T) { validateTenantCreateUpdateFields(map[string]interface{}{"Name": "newname", "Active": false})), }, "BAD REQUEST when ROOT TENANT": { - EndpointId: GetTenantID(t, "root"), + EndpointID: GetTenantID(t, "root"), ClientSession: TOSession, RequestBody: tc.Tenant{ Active: false, @@ -129,7 +129,7 @@ func TestTenants(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "PRECONDITION FAILED when updating with IMS & IUS Headers": { - EndpointId: GetTenantID(t, "tenant2"), + EndpointID: GetTenantID(t, "tenant2"), ClientSession: TOSession, RequestOpts: client.RequestOptions{Header: http.Header{rfc.IfUnmodifiedSince: {currentTimeRFC}}}, RequestBody: tc.Tenant{ @@ -141,7 +141,7 @@ func TestTenants(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusPreconditionFailed)), }, "PRECONDITION FAILED when updating with IFMATCH ETAG Header": { - EndpointId: GetTenantID(t, "tenant2"), + EndpointID: GetTenantID(t, "tenant2"), ClientSession: TOSession, RequestBody: tc.Tenant{ Active: false, @@ -155,7 +155,7 @@ func TestTenants(t *testing.T) { }, "DELETE": { "BAD REQUEST when TENANT HAS CHILDREN": { - EndpointId: GetTenantID(t, "tenant1"), + EndpointID: GetTenantID(t, "tenant1"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, @@ -182,14 +182,14 @@ func TestTenants(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.UpdateTenant(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.UpdateTenant(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteTenant(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteTenant(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/types_test.go b/traffic_ops/testing/api/v5/types_test.go index 8f8e2ab9da..0b3d2c24ec 100644 --- a/traffic_ops/testing/api/v5/types_test.go +++ b/traffic_ops/testing/api/v5/types_test.go @@ -23,12 +23,11 @@ import ( "testing" "time" - "github.com/apache/trafficcontrol/traffic_ops/testing/api/assert" - "github.com/apache/trafficcontrol/traffic_ops/toclientlib" - "github.com/apache/trafficcontrol/lib/go-rfc" tc "github.com/apache/trafficcontrol/lib/go-tc" + "github.com/apache/trafficcontrol/traffic_ops/testing/api/assert" "github.com/apache/trafficcontrol/traffic_ops/testing/api/utils" + "github.com/apache/trafficcontrol/traffic_ops/toclientlib" client "github.com/apache/trafficcontrol/traffic_ops/v5-client" ) @@ -86,7 +85,7 @@ func TestTypes(t *testing.T) { }, "PUT": { "BAD REQUEST when useInTable NOT server": { - EndpointId: GetTypeID(t, "ACTIVE_DIRECTORY"), + EndpointID: GetTypeID(t, "ACTIVE_DIRECTORY"), ClientSession: TOSession, RequestBody: tc.Type{ Description: "Active Directory User", @@ -96,7 +95,7 @@ func TestTypes(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), }, "OK when VALID request when useInTable=server": { - EndpointId: GetTypeID(t, "RIAK"), + EndpointID: GetTypeID(t, "RIAK"), ClientSession: TOSession, RequestBody: tc.Type{ Description: "riak type", @@ -109,7 +108,7 @@ func TestTypes(t *testing.T) { }, "DELETE": { "OK when VALID request": { - EndpointId: GetTypeID(t, "INFLUXDB"), + EndpointID: GetTypeID(t, "INFLUXDB"), ClientSession: TOSession, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK)), }, @@ -136,14 +135,14 @@ func TestTypes(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.UpdateType(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.UpdateType(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } }) case "DELETE": t.Run(name, func(t *testing.T) { - alerts, reqInf, err := testCase.ClientSession.DeleteType(testCase.EndpointId(), testCase.RequestOpts) + alerts, reqInf, err := testCase.ClientSession.DeleteType(testCase.EndpointID(), testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, nil, alerts, err) } diff --git a/traffic_ops/testing/api/v5/users_test.go b/traffic_ops/testing/api/v5/users_test.go index 7fdd20e60a..9214d6843f 100644 --- a/traffic_ops/testing/api/v5/users_test.go +++ b/traffic_ops/testing/api/v5/users_test.go @@ -86,7 +86,7 @@ func TestUsers(t *testing.T) { }, "PUT": { "OK when VALID request": { - EndpointId: GetUserID(t, "steering"), + EndpointID: GetUserID(t, "steering"), ClientSession: TOSession, RequestBody: tc.UserV4{ AddressLine1: util.Ptr("updated line 1"), @@ -109,7 +109,7 @@ func TestUsers(t *testing.T) { "Country": "US", "Email": "steeringupdated@example.com", "FullName": "Steering User Updated"})), }, "OK when UPDATING SELF": { - EndpointId: GetUserID(t, "opsuser"), + EndpointID: GetUserID(t, "opsuser"), ClientSession: opsUserSession, RequestBody: tc.UserV4{ AddressLine1: util.Ptr("address of ops"), @@ -129,7 +129,7 @@ func TestUsers(t *testing.T) { validateUsersUpdateCreateFields(map[string]interface{}{"Email": "ops-updated@example.com", "FullName": "Operations User Updated"})), }, "NOT FOUND when UPDATING SELF with ROLE that DOESNT EXIST": { - EndpointId: GetUserID(t, "opsuser"), + EndpointID: GetUserID(t, "opsuser"), ClientSession: opsUserSession, RequestBody: tc.UserV4{ AddressLine1: util.Ptr("address of ops"), @@ -148,7 +148,7 @@ func TestUsers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusNotFound)), }, "FORBIDDEN when OPERATIONS USER updates ADMIN USER": { - EndpointId: GetUserID(t, "admin"), + EndpointID: GetUserID(t, "admin"), ClientSession: opsUserSession, RequestBody: tc.UserV4{ Email: util.Ptr("oops@ops.net"), @@ -162,7 +162,7 @@ func TestUsers(t *testing.T) { Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, "FORBIDDEN when CHILD TENANT USER updates PARENT TENANT USER": { - EndpointId: GetUserID(t, "tenant3user"), + EndpointID: GetUserID(t, "tenant3user"), ClientSession: tenant4UserSession, RequestBody: tc.UserV4{ Email: util.Ptr("tenant3user@example.com"), @@ -198,7 +198,7 @@ func TestUsers(t *testing.T) { }) case "PUT": t.Run(name, func(t *testing.T) { - resp, reqInf, err := testCase.ClientSession.UpdateUser(testCase.EndpointId(), testCase.RequestBody, testCase.RequestOpts) + resp, reqInf, err := testCase.ClientSession.UpdateUser(testCase.EndpointID(), testCase.RequestBody, testCase.RequestOpts) for _, check := range testCase.Expectations { check(t, reqInf, resp.Response, resp.Alerts, err) } From 973934028be8d9180038e8290348c6a895b2b910 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Tue, 27 Sep 2022 11:09:07 -0600 Subject: [PATCH 14/48] Fix routing name of hard-coded DS set to invalid value --- traffic_ops/testing/api/v3/tc-fixtures.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/traffic_ops/testing/api/v3/tc-fixtures.json b/traffic_ops/testing/api/v3/tc-fixtures.json index f392b2d5f1..c485f5e5ea 100644 --- a/traffic_ops/testing/api/v3/tc-fixtures.json +++ b/traffic_ops/testing/api/v3/tc-fixtures.json @@ -858,7 +858,7 @@ "regexRemap": null, "regionalGeoBlocking": false, "remapText": null, - "routingName": "cdn", + "routingName": "ccr-ds1", "signed": false, "signingAlgorithm": null, "sslKeyVersion": 0, From 3f15ab56f9d66eecc30f4ac037a9244752423bb0 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Tue, 27 Sep 2022 11:10:28 -0600 Subject: [PATCH 15/48] Update DS SSL generation logic to use latest major version --- .../deliveryservice/sslkeys.go | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/sslkeys.go b/traffic_ops/traffic_ops_golang/deliveryservice/sslkeys.go index d1b1f2e224..f3a133c066 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/sslkeys.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/sslkeys.go @@ -23,6 +23,7 @@ import ( "context" "database/sql" "errors" + "fmt" "net/http" "strconv" "strings" @@ -116,12 +117,12 @@ func generatePutTrafficVaultSSLKeys(req tc.DeliveryServiceGenSSLKeysReq, tx *sql // GeneratePlaceholderSelfSignedCert generates a self-signed SSL certificate as a placeholder when a new HTTPS // delivery service is created or an HTTP delivery service is updated to use HTTPS. -func GeneratePlaceholderSelfSignedCert(ds tc.DeliveryServiceV4, inf *api.APIInfo, context context.Context) (error, int) { +func GeneratePlaceholderSelfSignedCert(ds tc.DeliveryServiceV5, inf *api.APIInfo, context context.Context) (error, int) { tx := inf.Tx.Tx tv := inf.Vault - _, ok, err := tv.GetDeliveryServiceSSLKeys(*ds.XMLID, "", tx, context) + _, ok, err := tv.GetDeliveryServiceSSLKeys(ds.XMLID, "", tx, context) if err != nil { - return errors.New("getting latest ssl keys for xmlId: " + *ds.XMLID + " : " + err.Error()), http.StatusInternalServerError + return fmt.Errorf("getting latest ssl keys for XMLID '%s': %w", ds.XMLID, err), http.StatusInternalServerError } if ok { return nil, http.StatusOK @@ -129,7 +130,7 @@ func GeneratePlaceholderSelfSignedCert(ds tc.DeliveryServiceV4, inf *api.APIInfo version := util.JSONIntStr(1) - cdnName, cdnDomain, err := dbhelpers.GetCDNNameDomain(*ds.CDNID, tx) + cdnName, cdnDomain, err := dbhelpers.GetCDNNameDomain(ds.CDNID, tx) if err != nil { return err, http.StatusInternalServerError } @@ -137,11 +138,11 @@ func GeneratePlaceholderSelfSignedCert(ds tc.DeliveryServiceV4, inf *api.APIInfo cdnNameStr := string(cdnName) if ds.ExampleURLs == nil { - ds.ExampleURLs = MakeExampleURLs(ds.Protocol, *ds.Type, *ds.RoutingName, *ds.MatchList, cdnDomain) + ds.ExampleURLs = MakeExampleURLs(ds.Protocol, tc.DSType(*ds.Type), ds.RoutingName, ds.MatchList, cdnDomain) } hostname := strings.Split(ds.ExampleURLs[0], "://")[1] - if ds.Type.IsHTTP() { + if (*tc.DSType)(ds.Type).IsHTTP() { parts := strings.Split(hostname, ".") parts[0] = "*" hostname = strings.Join(parts, ".") @@ -150,9 +151,9 @@ func GeneratePlaceholderSelfSignedCert(ds tc.DeliveryServiceV4, inf *api.APIInfo req := tc.DeliveryServiceGenSSLKeysReq{ DeliveryServiceSSLKeysReq: tc.DeliveryServiceSSLKeysReq{ CDN: &cdnNameStr, - DeliveryService: ds.XMLID, + DeliveryService: &ds.XMLID, HostName: &hostname, - Key: ds.XMLID, + Key: &ds.XMLID, Version: &version, BusinessUnit: util.StrPtr("Placeholder"), City: util.StrPtr("Placeholder"), @@ -176,10 +177,10 @@ func GeneratePlaceholderSelfSignedCert(ds tc.DeliveryServiceV4, inf *api.APIInfo } if err := generatePutTrafficVaultSSLKeys(req, tx, inf.Vault, context); err != nil { - return errors.New("generating and putting SSL keys: " + err.Error()), http.StatusInternalServerError + return fmt.Errorf("generating and putting SSL keys: %w", err), http.StatusInternalServerError } if err := updateSSLKeyVersion(*req.DeliveryService, req.Version.ToInt64(), tx); err != nil { - return errors.New("generating SSL keys for delivery service '" + *req.DeliveryService + "': " + err.Error()), http.StatusInternalServerError + return fmt.Errorf("generating SSL keys for delivery service '%s': %w", *req.DeliveryService, err), http.StatusInternalServerError } return nil, http.StatusOK From 555c170451ba7677d570f56aad8e2fee623b2db5 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Tue, 27 Sep 2022 11:12:34 -0600 Subject: [PATCH 16/48] Update server/DS assignment logic to V5 --- .../deliveryservice/servers/delete.go | 28 ++++--------------- .../deliveryservice/servers/servers.go | 21 ++++++++------ 2 files changed, 19 insertions(+), 30 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/servers/delete.go b/traffic_ops/traffic_ops_golang/deliveryservice/servers/delete.go index 5d0275bd92..aaa3878e07 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/servers/delete.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/servers/delete.go @@ -141,30 +141,14 @@ func deleteDSS(w http.ResponseWriter, r *http.Request) { return } - ds := dses[0] - if ds.Active == nil { - errCode = http.StatusInternalServerError - sysErr = fmt.Errorf("Delivery Service #%d had nil Active", dsID) - api.HandleErr(w, r, tx, errCode, nil, sysErr) - return - } - - if *ds.Active { - usesMSO := ds.MultiSiteOrigin == nil || *ds.MultiSiteOrigin - hasTopology := ds.Topology != nil - errCode, userErr, sysErr = checkLastAvailableEdgeOrOrigin(dsID, serverID, usesMSO, hasTopology, tx) + ds := dses[0].DS + if ds.Active == tc.DSActiveStateActive { + errCode, userErr, sysErr = checkLastAvailableEdgeOrOrigin(dsID, serverID, ds.MultiSiteOrigin, ds.Topology != nil, tx) if userErr != nil || sysErr != nil { api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr) return } } - if ds.XMLID == nil { - errCode = http.StatusInternalServerError - sysErr = fmt.Errorf("Delivery Service #%d had nil XMLID", dsID) - api.HandleErr(w, r, tx, errCode, nil, sysErr) - return - } - dsName := *ds.XMLID if ds.CDNName != nil { userErr, sysErr, statusCode := dbhelpers.CheckIfCurrentUserCanModifyCDN(inf.Tx.Tx, *ds.CDNName, inf.User.UserName) @@ -175,7 +159,7 @@ func deleteDSS(w http.ResponseWriter, r *http.Request) { } serverName, exists, err := dbhelpers.GetServerNameFromID(tx, int64(serverID)) if err != nil { - api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New("getting server name from id: "+err.Error())) + api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, fmt.Errorf("getting server name from id: %w", err)) return } else if !exists { api.HandleErr(w, r, inf.Tx.Tx, http.StatusNotFound, errors.New("server not found"), nil) @@ -184,14 +168,14 @@ func deleteDSS(w http.ResponseWriter, r *http.Request) { ok, err := deleteDSServer(tx, dsID, serverID) if err != nil { - api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New("deleting delivery service server: "+err.Error())) + api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, fmt.Errorf("deleting delivery service server: %w", err)) return } if !ok { api.HandleErr(w, r, inf.Tx.Tx, http.StatusNotFound, nil, nil) return } - api.CreateChangeLogRawTx(api.ApiChange, "DS: "+string(dsName)+", ID: "+strconv.Itoa(dsID)+", ACTION: Remove server "+string(serverName)+" from delivery service", inf.User, inf.Tx.Tx) + api.CreateChangeLogRawTx(api.ApiChange, "DS: "+ds.XMLID+", ID: "+strconv.Itoa(dsID)+", ACTION: Remove server "+string(serverName)+" from delivery service", inf.User, inf.Tx.Tx) api.WriteRespAlert(w, r, tc.SuccessLevel, "Server unlinked from delivery service.") } diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/servers/servers.go b/traffic_ops/traffic_ops_golang/deliveryservice/servers/servers.go index 06720c3f3d..e5b4463c7b 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/servers/servers.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/servers/servers.go @@ -867,7 +867,6 @@ func (dss *TODSSDeliveryService) Read(h http.Header, useIMS bool) ([]interface{} } var maxTime time.Time var runSecond bool - returnable := []interface{}{} params := dss.APIInfo().Params tx := dss.APIInfo().Tx.Tx user := dss.APIInfo().User @@ -911,7 +910,7 @@ func (dss *TODSSDeliveryService) Read(h http.Header, useIMS bool) ([]interface{} runSecond, maxTime = ims.TryIfModifiedSinceQuery(dss.APIInfo().Tx, h, queryValues, selectMaxLastUpdatedQuery(where)) if !runSecond { log.Debugln("IMS HIT") - return returnable, nil, nil, http.StatusNotModified, &maxTime + return nil, nil, nil, http.StatusNotModified, &maxTime } log.Debugln("IMS MISS") } else { @@ -928,16 +927,20 @@ func (dss *TODSSDeliveryService) Read(h http.Header, useIMS bool) ([]interface{} return nil, userErr, sysErr, http.StatusInternalServerError, nil } - for _, ds := range dses { - if version.Major > 3 && version.Minor >= 0 { - ds = ds.RemoveLD1AndLD2() + returnable := make([]interface{}, 0, len(dses)) + for _, d := range dses { + ds := d.DS + if version.Major > 4 { returnable = append(returnable, ds) + } else if version.Major > 3 && version.Minor >= 0 { + returnable = append(returnable, ds.Downgrade()) } else { + legacyDS := ds.Downgrade() if version.Minor > 0 { - dsV31 := ds.DowngradeToV31() + dsV31 := legacyDS.DowngradeToV31() returnable = append(returnable, dsV31) } else { - dsV30 := ds.DowngradeToV31().DeliveryServiceV30 + dsV30 := legacyDS.DowngradeToV31().DeliveryServiceV30 returnable = append(returnable, dsV30) } } @@ -992,8 +995,9 @@ FROM func scanDSInfoRow(row *sql.Row) (DSInfo, bool, error) { di := DSInfo{} var useMSO *bool + var active tc.DeliveryServiceActiveState if err := row.Scan( - &di.Active, + &active, &di.ID, &di.Name, &di.Type, @@ -1012,6 +1016,7 @@ func scanDSInfoRow(row *sql.Row) (DSInfo, bool, error) { } return DSInfo{}, false, fmt.Errorf("querying delivery service server ds info: %v", err) } + di.Active = active == tc.DSActiveStateActive di.Type = tc.DSTypeFromString(string(di.Type)) if useMSO != nil { di.UseMultiSiteOrigin = *useMSO From f9ba8847ac33819c81e22fb18e304d11bca30f10 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Tue, 27 Sep 2022 11:14:37 -0600 Subject: [PATCH 17/48] Update DS "safe" update logic for V5 --- .../deliveryservice/safe.go | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/safe.go b/traffic_ops/traffic_ops_golang/deliveryservice/safe.go index 0b000a9511..e076982aca 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/safe.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/safe.go @@ -121,7 +121,7 @@ func UpdateSafe(w http.ResponseWriter, r *http.Request) { } else { log.Warnf("Couldn't get config %v", e) } - dses, userErr, sysErr, errCode, _ := readGetDeliveryServices(r.Header, inf.Params, inf.Tx, inf.User, useIMS) + dses, userErr, sysErr, errCode, _ := readGetDeliveryServices(r.Header, inf.Params, inf.Tx, inf.User, useIMS, *version) if userErr != nil || sysErr != nil { api.HandleErr(w, r, tx, errCode, userErr, sysErr) return @@ -132,10 +132,7 @@ func UpdateSafe(w http.ResponseWriter, r *http.Request) { return } - ds := dses[0] - if version.Major > 3 { - ds = ds.RemoveLD1AndLD2() - } + ds := dses[0].DS alertMsg := "Delivery Service safe update successful." if inf.Version == nil { log.Warnln("API version found to be null in DS safe update") @@ -144,23 +141,32 @@ func UpdateSafe(w http.ResponseWriter, r *http.Request) { switch inf.Version.Major { default: fallthrough + case 5: + api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, ds) case 4: if inf.Version.Minor >= 1 { - api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, dses) + api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, []tc.DeliveryServiceV41{}) } else { api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, []tc.DeliveryServiceV40{ds.DeliveryServiceV40}) } case 3: + legacyDS := ds.Downgrade() + legacyDS.LongDesc1 = dses[0].LongDesc1 + legacyDS.LongDesc2 = dses[0].LongDesc2 + ret := legacyDS.DowngradeToV31() if inf.Version.Minor >= 1 { - api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, []tc.DeliveryServiceV31{tc.DeliveryServiceV31(ds.DowngradeToV31())}) + api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, []tc.DeliveryServiceV31{tc.DeliveryServiceV31(ret)}) } - api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, []tc.DeliveryServiceV30{ds.DowngradeToV31().DeliveryServiceV30}) + api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, []tc.DeliveryServiceV30{ret.DeliveryServiceV30}) case 2: - api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, []tc.DeliveryServiceNullableV15{ds.DowngradeToV31().DeliveryServiceNullableV15}) + legacyDS := ds.Downgrade() + legacyDS.LongDesc1 = dses[0].LongDesc1 + legacyDS.LongDesc2 = dses[0].LongDesc2 + api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, []tc.DeliveryServiceNullableV15{legacyDS.DowngradeToV31().DeliveryServiceNullableV15}) } } - api.CreateChangeLogRawTx(api.ApiChange, fmt.Sprintf("DS: %s, ID: %d, ACTION: Updated safe fields", *ds.XMLID, *ds.ID), inf.User, tx) + api.CreateChangeLogRawTx(api.ApiChange, fmt.Sprintf("DS: %s, ID: %d, ACTION: Updated safe fields", ds.XMLID, *ds.ID), inf.User, tx) } // updateDSSafe updates the given delivery service in the database. Returns whether the DS existed, and any error. From 3160b2cff96a3f8113f0949d7e5820cb4483bf2e Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Wed, 28 Sep 2022 10:11:39 -0600 Subject: [PATCH 18/48] Update general DS logic to operate on APIv5 structures --- .../deliveryservice/deliveryservices.go | 797 ++++++++++-------- .../deliveryservice/safe.go | 4 +- 2 files changed, 466 insertions(+), 335 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go index b918638c7a..6d0b25d831 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go @@ -1,3 +1,5 @@ +// Package deliveryservice contains logic and handlers for /deliveryservices and +// related sub-routes (e.g. /deliveryservices/{{ID}}/servers). package deliveryservice /* @@ -53,36 +55,48 @@ const ( edgeTier ) -// we need a type alias to define functions on +// TODeliveryService is a CRUDder implementation for Delivery Services; it's +// only used for GET and DELETE requests. type TODeliveryService struct { api.APIInfoImpl - tc.DeliveryServiceV4 + tc.DeliveryServiceV5 } -// TODeliveryServiceOldDetails is the struct to store the old details while updating a DS. +// TODeliveryServiceOldDetails is used to store the "old" details while +// updating a DS. type TODeliveryServiceOldDetails struct { - OldOrgServerFqdn *string - OldCdnName string - OldCdnId int + OldOrgServerFQDN *string + OldCDNName string + OldCDNID int OldRoutingName string OldSSLKeyVersion *int } +// MarshalJSON implements encoding/json.Marshaler. func (ds TODeliveryService) MarshalJSON() ([]byte, error) { - return json.Marshal(ds.DeliveryServiceV4) + return json.Marshal(ds.DeliveryServiceV5) } +// UnmarshalJSON implements encoding/json.Unmarshaler. func (ds *TODeliveryService) UnmarshalJSON(data []byte) error { - return json.Unmarshal(data, &ds.DeliveryServiceV4) + return json.Unmarshal(data, &ds.DeliveryServiceV5) } +// APIInfo implements +// github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api.APIInfoer. func (ds *TODeliveryService) APIInfo() *api.APIInfo { return ds.ReqInfo } +// SetKeys implements part of the +// github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api.Identifier +// interface. 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. + i, _ := keys["id"].(int) ds.ID = &i } +// GetKeys implements part of the +// github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api.Identifier +// interface. func (ds TODeliveryService) GetKeys() (map[string]interface{}, bool) { if ds.ID == nil { return map[string]interface{}{"id": 0}, false @@ -90,24 +104,32 @@ func (ds TODeliveryService) GetKeys() (map[string]interface{}, bool) { return map[string]interface{}{"id": *ds.ID}, true } +// GetKeyFieldsInfo implements part of the +// github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api.Identifier +// interface. func (ds TODeliveryService) GetKeyFieldsInfo() []api.KeyFieldInfo { return []api.KeyFieldInfo{{Field: "id", Func: api.GetIntKey}} } +// GetAuditName implements part of the +// github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api.Identifier +// interface. func (ds *TODeliveryService) GetAuditName() string { - if ds.XMLID != nil { - return *ds.XMLID - } - return "" + return ds.XMLID } +// GetType implements part of the +// github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api.Identifier +// interface. 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). +// IsTenantAuthorized implements the +// github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api.Tenantable +// interface. func (ds *TODeliveryService) IsTenantAuthorized(user *auth.CurrentUser) (bool, error) { - return isTenantAuthorized(ds.ReqInfo, &ds.DeliveryServiceV4) + return isTenantAuthorized(ds.ReqInfo, &ds.DeliveryServiceV5) } const baseTLSVersionsQuery = `SELECT ARRAY_AGG(tls_version ORDER BY tls_version) FROM deliveryservice_tls_version` @@ -128,6 +150,8 @@ func GetDSTLSVersions(dsID int, tx *sql.Tx) ([]string, error) { return vers, err } +// CreateV30 is used to handle POST requests to create a Delivery Service at +// version 3.0 of the Traffic Ops API. func CreateV30(w http.ResponseWriter, r *http.Request) { inf, userErr, sysErr, errCode := api.NewInfo(r, nil, nil) if userErr != nil || sysErr != nil { @@ -138,7 +162,7 @@ func CreateV30(w http.ResponseWriter, r *http.Request) { 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) + api.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, fmt.Errorf("decoding: %w", err), nil) return } @@ -149,6 +173,9 @@ func CreateV30(w http.ResponseWriter, r *http.Request) { } api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Delivery Service creation was successful", []tc.DeliveryServiceV30{*res}) } + +// CreateV31 is used to handle POST requests to create a Delivery Service at +// version 3.1 of the Traffic Ops API. func CreateV31(w http.ResponseWriter, r *http.Request) { inf, userErr, sysErr, errCode := api.NewInfo(r, nil, nil) if userErr != nil || sysErr != nil { @@ -159,7 +186,7 @@ func CreateV31(w http.ResponseWriter, r *http.Request) { 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) + api.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, fmt.Errorf("decoding: %w", err), nil) return } @@ -170,6 +197,10 @@ func CreateV31(w http.ResponseWriter, r *http.Request) { } api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Delivery Service creation was successful", []tc.DeliveryServiceV31{*res}) } + +// CreateV40 is used to handle POST requests to create a Delivery Service at +// version 4.0 of the Traffic Ops API (and isomorphic API versions thereof, with +// respect to Delivery Service representations). func CreateV40(w http.ResponseWriter, r *http.Request) { inf, userErr, sysErr, errCode := api.NewInfo(r, nil, nil) if userErr != nil || sysErr != nil { @@ -180,7 +211,7 @@ func CreateV40(w http.ResponseWriter, r *http.Request) { 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) + api.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, fmt.Errorf("decoding: %w", err), nil) return } res, status, userErr, sysErr := createV40(w, r, inf, ds, true) @@ -230,6 +261,7 @@ func createV30(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV30 t } 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) @@ -303,25 +335,36 @@ func createV40(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV4 tc // created on insert set. On error, an HTTP status code, user error, and system // error are returned. The status code SHOULD NOT be used, if both errors are // nil. -func createV41(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV4 tc.DeliveryServiceV41, omitExtraLongDescFields bool) (*tc.DeliveryServiceV41, int, error, error) { - user := inf.User +func createV41(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, ds tc.DeliveryServiceV41, omitExtraLongDescFields bool) (*tc.DeliveryServiceV41, int, error, error) { + res, code, userErr, sysErr := createV50(w, r, inf, ds.Upgrade(), omitExtraLongDescFields, ds.LongDesc1, ds.LongDesc2) + if res != nil { + ds := res.Downgrade() + return &ds, code, userErr, sysErr + } + return nil, code, userErr, sysErr +} + +// createV50 creates the given Delivery Service in the database, and returns a +// reference to the Delivery Service with its ID and other fields which are +// created on insert set. On error, an HTTP status code, user error, and system +// error are returned. The status code SHOULD NOT be used, if both errors are +// nil. +func createV50(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, ds tc.DeliveryServiceV5, omitExtraLongDescFields bool, longDesc1, longDesc2 *string) (*tc.DeliveryServiceV5, int, error, error) { tx := inf.Tx.Tx - ds := tc.DeliveryServiceV4(dsV4) err := Validate(tx, &ds) - var geoLimitCountries string if err != nil { - return nil, http.StatusBadRequest, errors.New("invalid request: " + err.Error()), nil + return nil, http.StatusBadRequest, fmt.Errorf("invalid request: %w", err), nil } if authorized, err := isTenantAuthorized(inf, &ds); err != nil { - return nil, http.StatusInternalServerError, nil, errors.New("checking tenant: " + err.Error()) + return nil, http.StatusInternalServerError, nil, fmt.Errorf("checking tenant: %w", err) } 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 { + if ds.DeepCachingType != "" { deepCachingType = ds.DeepCachingType.String() // necessary, because DeepCachingType's default needs to insert the string, not "", and Query doesn't call .String(). } @@ -329,15 +372,15 @@ func createV41(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV4 tc return nil, errCode, userErr, sysErr } - userErr, sysErr, errCode := dbhelpers.CheckIfCurrentUserCanModifyCDNWithID(inf.Tx.Tx, int64(*ds.CDNID), inf.User.UserName) + 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, ",") + + geoLimitCountries := strings.Join(ds.GeoLimitCountries, ",") var resultRows *sql.Rows if omitExtraLongDescFields { - if ds.LongDesc1 != nil || ds.LongDesc2 != nil { + if longDesc1 != nil || 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(), @@ -429,8 +472,8 @@ func createV41(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV4 tc ds.IPV6RoutingEnabled, ds.LogsEnabled, ds.LongDesc, - ds.LongDesc1, - ds.LongDesc2, + longDesc1, + longDesc2, ds.MaxDNSAnswers, ds.MaxOriginConnections, ds.MidHeaderRewrite, @@ -469,15 +512,15 @@ func createV41(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV4 tc usrErr, sysErr, code := api.ParseDBError(err) return nil, code, usrErr, sysErr } - defer resultRows.Close() + defer log.Close(resultRows, "inserting Delivery Service") id := 0 - var lastUpdated tc.TimeNoMod if !resultRows.Next() { return nil, http.StatusInternalServerError, nil, errors.New("no deliveryservice request inserted, no id was returned") } + var lastUpdated time.Time if err := resultRows.Scan(&id, &lastUpdated); err != nil { - return nil, http.StatusInternalServerError, nil, errors.New("could not scan id from insert: " + err.Error()) + return nil, http.StatusInternalServerError, nil, fmt.Errorf("could not scan id from insert: %w", err) } if resultRows.Next() { return nil, http.StatusInternalServerError, nil, errors.New("too many ids returned from deliveryservice request insert") @@ -487,21 +530,12 @@ func createV41(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV4 tc 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) + dsType, err := getTypeFromID(ds.TypeID, tx) if err != nil { - return nil, http.StatusInternalServerError, nil, errors.New("getting delivery service type: " + err.Error()) + return nil, http.StatusInternalServerError, nil, fmt.Errorf("getting delivery service type: %w", err) } - ds.Type = &dsType + ds.Type = (*string)(&dsType) if len(ds.TLSVersions) < 1 { ds.TLSVersions = nil @@ -509,8 +543,8 @@ func createV41(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV4 tc 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 := createDefaultRegex(tx, *ds.ID, ds.XMLID); err != nil { + return nil, http.StatusInternalServerError, nil, fmt.Errorf("creating default regex: %w", err) } if _, err := createConsistentHashQueryParams(tx, *ds.ID, ds.ConsistentHashQueryParams); err != nil { @@ -518,68 +552,68 @@ func createV41(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV4 tc return nil, code, usrErr, sysErr } - matchlists, err := GetDeliveryServicesMatchLists([]string{*ds.XMLID}, tx) + matchlists, err := GetDeliveryServicesMatchLists([]string{ds.XMLID}, tx) if err != nil { - return nil, http.StatusInternalServerError, nil, errors.New("creating DS: reading matchlists: " + err.Error()) + return nil, http.StatusInternalServerError, nil, fmt.Errorf("creating DS: reading matchlists: %w", err) } - if matchlist, ok := matchlists[*ds.XMLID]; !ok { + matchlist, ok := matchlists[ds.XMLID] + if !ok { return nil, http.StatusInternalServerError, nil, errors.New("creating DS: reading matchlists: not found") - } else { - ds.MatchList = &matchlist } + 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()) + return nil, http.StatusInternalServerError, nil, fmt.Errorf("creating DS: getting CDN info: %w", err) } - ds.ExampleURLs = MakeExampleURLs(ds.Protocol, *ds.Type, *ds.RoutingName, *ds.MatchList, cdnDomain) + ds.ExampleURLs = MakeExampleURLs(ds.Protocol, tc.DSType(*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 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, fmt.Errorf("ensuring ds parameters: %w", err) } - if dnssecEnabled && ds.Type.UsesDNSSECKeys() { + if dnssecEnabled && tc.DSType(*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 { + if userErr, sysErr, statusCode := PutDNSSecKeys(tx, ds.XMLID, cdnName, ds.ExampleURLs, inf.Vault, r.Context()); userErr != nil || sysErr != nil { return nil, statusCode, userErr, sysErr } } + user := inf.User if err := createPrimaryOrigin(tx, user, ds); err != nil { - return nil, http.StatusInternalServerError, nil, errors.New("creating delivery service: " + err.Error()) + return nil, http.StatusInternalServerError, nil, fmt.Errorf("creating delivery service: %w", err) } - 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()) + 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, fmt.Errorf("error writing to audit log: %w", err) } - dsV4 = ds - if inf.Config.TrafficVaultEnabled && ds.Protocol != nil && (*ds.Protocol == tc.DSProtocolHTTPS || *ds.Protocol == tc.DSProtocolHTTPAndHTTPS || *ds.Protocol == tc.DSProtocolHTTPToHTTPS) { - err, errCode := GeneratePlaceholderSelfSignedCert(dsV4, inf, r.Context()) + err, errCode := GeneratePlaceholderSelfSignedCert(ds, inf, r.Context()) if err != nil || errCode != http.StatusOK { - return nil, errCode, nil, fmt.Errorf("creating self signed default cert: %v", err) + return nil, errCode, nil, fmt.Errorf("creating self signed default cert: %w", err) } } - return &dsV4, http.StatusOK, nil, nil + return &ds, 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()) + return fmt.Errorf("insert regex: %w", err) } 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 fmt.Errorf("executing parameter query to insert location: %w", err) } return nil } + func createConsistentHashQueryParams(tx *sql.Tx, dsID int, consistentHashQueryParams []string) (int, error) { if len(consistentHashQueryParams) == 0 { return 0, nil @@ -595,33 +629,50 @@ func createConsistentHashQueryParams(tx *sql.Tx, dsID int, consistentHashQueryPa return c, nil } + +// Read implements the +// github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api.Reader +// interface (given that +// github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api.APIInfoer +// is already implemented). 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) + dses, userErr, sysErr, errCode, maxTime := readGetDeliveryServices(h, ds.APIInfo().Params, ds.APIInfo().Tx, ds.APIInfo().User, useIMS, *version) if sysErr != nil { - sysErr = errors.New("reading dses: " + sysErr.Error()) + sysErr = fmt.Errorf("reading dses: %w", sysErr) errCode = http.StatusInternalServerError } if userErr != nil || sysErr != nil { return nil, userErr, sysErr, errCode, nil } - for _, ds := range dses { + returnable := make([]interface{}, 0, len(dses)) + for _, d := range dses { + ds := d.DS switch { - // NOTE: it's required to handle minor version cases in a descending >= manner - case version.Major > 4 || (version.Major == 4 && version.Minor >= 1): - returnable = append(returnable, ds.RemoveLD1AndLD2()) - case version.Major >= 4: - returnable = append(returnable, ds.DeliveryServiceV40.RemoveLD1AndLD2()) + case version.Major > 4: + returnable = append(returnable, ds) + case version.Major == 4: + d := ds.Downgrade() + if version.Minor >= 1 { + returnable = append(returnable, d.RemoveLD1AndLD2()) + } else { + returnable = append(returnable, d.DeliveryServiceV40.RemoveLD1AndLD2()) + } case version.Major >= 3 && version.Minor >= 1: - returnable = append(returnable, ds.DowngradeToV31()) + legacyDS := ds.Downgrade() + legacyDS.LongDesc1 = d.LongDesc1 + legacyDS.LongDesc2 = d.LongDesc2 + returnable = append(returnable, legacyDS.DowngradeToV31()) case version.Major >= 3: - returnable = append(returnable, ds.DowngradeToV31().DeliveryServiceV30) + legacyDS := ds.Downgrade() + legacyDS.LongDesc1 = d.LongDesc1 + legacyDS.LongDesc2 = d.LongDesc2 + returnable = append(returnable, legacyDS.DowngradeToV31().DeliveryServiceV30) default: return nil, nil, fmt.Errorf("TODeliveryService.Read called with invalid API version: %d.%d", version.Major, version.Minor), http.StatusInternalServerError, nil } @@ -629,6 +680,8 @@ func (ds *TODeliveryService) Read(h http.Header, useIMS bool) ([]interface{}, er return returnable, nil, nil, errCode, maxTime } +// UpdateV30 is used to handle PUT requests to update a Delivery Service in +// version 3.0 of the Traffic Ops API. func UpdateV30(w http.ResponseWriter, r *http.Request) { inf, userErr, sysErr, errCode := api.NewInfo(r, nil, []string{"id"}) if userErr != nil || sysErr != nil { @@ -641,7 +694,7 @@ func UpdateV30(w http.ResponseWriter, r *http.Request) { 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) + api.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, fmt.Errorf("malformed JSON: %w", err), nil) return } ds.ID = &id @@ -653,6 +706,9 @@ func UpdateV30(w http.ResponseWriter, r *http.Request) { } api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Delivery Service update was successful", []tc.DeliveryServiceV30{*res}) } + +// UpdateV31 is used to handle PUT requests to update a Delivery Service in +// version 3.1 of the Traffic Ops API. func UpdateV31(w http.ResponseWriter, r *http.Request) { inf, userErr, sysErr, errCode := api.NewInfo(r, nil, []string{"id"}) if userErr != nil || sysErr != nil { @@ -665,7 +721,7 @@ func UpdateV31(w http.ResponseWriter, r *http.Request) { 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) + api.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, fmt.Errorf("malformed JSON: %w", err), nil) return } ds.ID = &id @@ -676,6 +732,10 @@ func UpdateV31(w http.ResponseWriter, r *http.Request) { } api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Delivery Service update was successful", []tc.DeliveryServiceV31{*res}) } + +// UpdateV40 is used to handle PUT requests to update a Delivery Service in +// version 4.0 of the Traffic Ops API (and isomorphic API versions thereof, with +// respect to Delivery Service representations). func UpdateV40(w http.ResponseWriter, r *http.Request) { inf, userErr, sysErr, errCode := api.NewInfo(r, nil, []string{"id"}) if userErr != nil || sysErr != nil { @@ -687,13 +747,13 @@ func UpdateV40(w http.ResponseWriter, r *http.Request) { 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) + api.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, fmt.Errorf("malformed JSON: %w", err), 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())) + api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, fmt.Errorf("deliveryservice update: getting CDN from DS ID %w", err)) return } userErr, sysErr, statusCode := dbhelpers.CheckIfCurrentUserCanModifyCDN(inf.Tx.Tx, string(cdn), inf.User.UserName) @@ -762,10 +822,10 @@ WHERE if err := inf.Tx.Tx.QueryRow(query, *dsV30.ID).Scan( &dsV31.MaxRequestHeaderBytes, ); err != nil { - if err == sql.ErrNoRows { + if errors.Is(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()) + return nil, http.StatusInternalServerError, nil, fmt.Errorf("querying delivery service ID %d: %w", *dsV31.ID, err) } res, status, userErr, sysErr := updateV31(w, r, inf, &dsV31) if res != nil { @@ -773,6 +833,7 @@ WHERE } 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() @@ -793,9 +854,29 @@ func updateV31(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV31 * } ds.DeliveryServiceV40 = *res if dsV31.CacheURL != nil { - _, err := tx.Exec("UPDATE deliveryservice SET cacheurl = $1 WHERE ID = $2", - dsV31.CacheURL, - ds.ID, + _, 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 dsV31.LongDesc1 != nil { + _, err := tx.Exec("UPDATE deliveryservice SET long_desc_1 = $1 WHERE id = $2", + *dsV31.LongDesc1, + *ds.ID, + ) + if err != nil { + usrErr, sysErr, code := api.ParseDBError(err) + return nil, code, usrErr, sysErr + } + } + if dsV31.LongDesc2 != nil { + _, err := tx.Exec("UPDATE deliveryservice SET long_desc_2 = $1 WHERE id = $2", + *dsV31.LongDesc2, + *ds.ID, ) if err != nil { usrErr, sysErr, code := api.ParseDBError(err) @@ -810,6 +891,7 @@ func updateV31(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV31 * 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) { ds, code, userErr, sysErr := updateV41(w, r, inf, &tc.DeliveryServiceV41{DeliveryServiceV40: *dsV40}, omitExtraLongDescFields) if userErr != nil || sysErr != nil || ds == nil { @@ -819,62 +901,63 @@ func updateV40(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV40 * return &d, code, nil, nil } func updateV41(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV4 *tc.DeliveryServiceV41, omitExtraLongDescFields bool) (*tc.DeliveryServiceV41, int, error, error) { + upgraded := dsV4.Upgrade() + res, code, userErr, sysErr := updateV50(w, r, inf, &upgraded, omitExtraLongDescFields, dsV4.LongDesc1, dsV4.LongDesc2) + if userErr != nil || sysErr != nil || res == nil { + return nil, code, userErr, sysErr + } + ds := res.Downgrade() + return &ds, code, userErr, sysErr +} + +func updateV50(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, ds *tc.DeliveryServiceV5, omitExtraLongDescFields bool, longDesc1, longDesc2 *string) (*tc.DeliveryServiceV5, int, error, error) { tx := inf.Tx.Tx user := inf.User - ds := tc.DeliveryServiceV4(*dsV4) - if err := Validate(tx, &ds); err != nil { - return nil, http.StatusBadRequest, errors.New("invalid request: " + err.Error()), nil + if err := Validate(tx, ds); err != nil { + return nil, http.StatusBadRequest, fmt.Errorf("invalid request: %w", err), nil } - if authorized, err := isTenantAuthorized(inf, &ds); err != nil { - return nil, http.StatusInternalServerError, nil, errors.New("checking tenant: " + err.Error()) + if authorized, err := isTenantAuthorized(inf, ds); err != nil { + return nil, http.StatusInternalServerError, nil, fmt.Errorf("checking tenant: %w", err) } 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) + dsType, ok, err := getDSType(tx, ds.XMLID) if !ok { - return nil, http.StatusNotFound, errors.New("delivery service '" + *ds.XMLID + "' not found"), nil + 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()) + return nil, http.StatusInternalServerError, nil, fmt.Errorf("getting delivery service type during update: %w", err) } - errCode := http.StatusOK + var errCode int 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 { + sslKeysExist, err := getSSLVersion(ds.XMLID, tx) + if 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 + errStr := "delivery service has ssl keys that cannot be automatically changed, therefore %s is immutable" + if oldDetails.OldCDNID != ds.CDNID { + return nil, http.StatusBadRequest, fmt.Errorf(errStr, "CDN ID"), nil } - if ds.RoutingName != nil && oldDetails.OldRoutingName != *ds.RoutingName { - cdnRoutingDetailDiff = true + if ds.CDNName != nil && oldDetails.OldCDNName != *ds.CDNName { + return nil, http.StatusBadRequest, fmt.Errorf(errStr, "CDN Name"), nil } - 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 + if oldDetails.OldRoutingName != ds.RoutingName { + return nil, http.StatusBadRequest, fmt.Errorf(errStr, "Routing Name"), nil } ds.SSLKeyVersion = oldDetails.OldSSLKeyVersion } @@ -882,7 +965,7 @@ func updateV41(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV4 *t // 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 { + if ds.DeepCachingType != "" { deepCachingType = ds.DeepCachingType.String() // necessary, because DeepCachingType's default needs to insert the string, not "", and Query doesn't call .String(). } @@ -891,14 +974,14 @@ func updateV41(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV4 *t return nil, errCode, userErr, sysErr } - if errCode, userErr, sysErr = dbhelpers.CheckTopology(inf.Tx, ds); userErr != nil || sysErr != nil { + 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()) + return nil, http.StatusInternalServerError, nil, fmt.Errorf("getting existing DS required capabilities: %w", err) } if len(requiredCapabilities) > 0 { if userErr, sysErr, status := EnsureTopologyBasedRequiredCapabilities(tx, *ds.ID, *ds.Topology, requiredCapabilities); userErr != nil || sysErr != nil { @@ -914,12 +997,11 @@ func updateV41(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV4 *t var geoLimitCountries string if ds.GeoLimitCountries != nil { - geo := ([]string)(ds.GeoLimitCountries) - geoLimitCountries = strings.Join(geo, ",") + geoLimitCountries = strings.Join(ds.GeoLimitCountries, ",") } var resultRows *sql.Rows if omitExtraLongDescFields { - if ds.LongDesc1 != nil || ds.LongDesc2 != nil { + if longDesc1 != nil || 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(), @@ -1010,8 +1092,8 @@ func updateV41(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV4 *t ds.IPV6RoutingEnabled, ds.LogsEnabled, ds.LongDesc, - ds.LongDesc1, - ds.LongDesc2, + longDesc1, + longDesc2, ds.MaxDNSAnswers, ds.MidHeaderRewrite, ds.MissLat, @@ -1053,34 +1135,20 @@ func updateV41(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV4 *t usrErr, sysErr, code := api.ParseDBError(err) return nil, code, usrErr, sysErr } - defer resultRows.Close() + defer log.Close(resultRows, "updating Delivery Service") if !resultRows.Next() { return nil, http.StatusNotFound, errors.New("no delivery service found with this id"), nil } - var lastUpdated tc.TimeNoMod + var lastUpdated time.Time if err := resultRows.Scan(&lastUpdated); err != nil { - return nil, http.StatusInternalServerError, nil, errors.New("scan updating delivery service: " + err.Error()) + return nil, http.StatusInternalServerError, nil, fmt.Errorf("scan updating delivery service: %w", err) } 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") - + return nil, http.StatusInternalServerError, nil, errors.New("updating delivery service " + ds.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 @@ -1090,45 +1158,45 @@ func updateV41(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV4 *t return nil, http.StatusInternalServerError, nil, fmt.Errorf("updating TLS versions for DS #%d: %w", *ds.ID, err) } - newDSType, err := getTypeFromID(*ds.TypeID, tx) + newDSType, err := getTypeFromID(ds.TypeID, tx) if err != nil { - return nil, http.StatusInternalServerError, nil, errors.New("getting delivery service type after update: " + err.Error()) + return nil, http.StatusInternalServerError, nil, fmt.Errorf("getting delivery service type after update: %w", err) } - ds.Type = &newDSType + ds.Type = (*string)(&newDSType) cdnDomain, err := getCDNDomain(*ds.ID, tx) // need to get the domain again, in case it changed. if err != nil { - return nil, http.StatusInternalServerError, nil, errors.New("getting CDN domain: (" + cdnDomain + ") after update: " + err.Error()) + return nil, http.StatusInternalServerError, nil, fmt.Errorf("getting CDN domain: (%s) after update: %w", cdnDomain, err) } - matchLists, err := GetDeliveryServicesMatchLists([]string{*ds.XMLID}, tx) + matchLists, err := GetDeliveryServicesMatchLists([]string{ds.XMLID}, tx) if err != nil { - return nil, http.StatusInternalServerError, nil, errors.New("getting matchlists after update: " + err.Error()) + return nil, http.StatusInternalServerError, nil, fmt.Errorf("getting matchlists after update: %w", err) } - if ml, ok := matchLists[*ds.XMLID]; !ok { + ml, ok := matchLists[ds.XMLID] + if !ok { return nil, http.StatusInternalServerError, nil, errors.New("no matchlists after update") - } else { - ds.MatchList = &ml } + ds.MatchList = ml - if err := EnsureParams(tx, *ds.ID, *ds.XMLID, ds.EdgeHeaderRewrite, ds.MidHeaderRewrite, ds.RegexRemap, ds.SigningAlgorithm, newDSType, ds.MaxOriginConnections); err != nil { - return nil, http.StatusInternalServerError, nil, errors.New("ensuring ds parameters:: " + err.Error()) + if err := EnsureParams(tx, *ds.ID, ds.XMLID, ds.EdgeHeaderRewrite, ds.MidHeaderRewrite, ds.RegexRemap, ds.SigningAlgorithm, newDSType, ds.MaxOriginConnections); err != nil { + return nil, http.StatusInternalServerError, nil, fmt.Errorf("ensuring ds parameters: %w", err) } - if oldDetails.OldOrgServerFqdn != nil && ds.OrgServerFQDN != nil && *oldDetails.OldOrgServerFqdn != *ds.OrgServerFQDN { - if err := updatePrimaryOrigin(tx, user, ds); err != nil { - return nil, http.StatusInternalServerError, nil, errors.New("updating delivery service: " + err.Error()) + if oldDetails.OldOrgServerFQDN != nil && ds.OrgServerFQDN != nil && *oldDetails.OldOrgServerFQDN != *ds.OrgServerFQDN { + if err := updatePrimaryOrigin(tx, user, *ds); err != nil { + return nil, http.StatusInternalServerError, nil, fmt.Errorf("updating delivery service: %w", err) } } - ds.LastUpdated = &lastUpdated + ds.LastUpdated = lastUpdated // the update may change or delete the query params -- delete existing and re-add if any provided q := `DELETE FROM deliveryservice_consistent_hash_query_param WHERE deliveryservice_id = $1` if res, err := tx.Exec(q, *ds.ID); err != nil { - return nil, http.StatusInternalServerError, nil, fmt.Errorf("deleting consistent hash query params for ds %s: %w", *ds.XMLID, err) + return nil, http.StatusInternalServerError, nil, fmt.Errorf("deleting consistent hash query params for ds %s: %w", ds.XMLID, err) } else if c, _ := res.RowsAffected(); c > 0 { - api.CreateChangeLogRawTx(api.ApiChange, "DS: "+*ds.XMLID+", ID: "+strconv.Itoa(*ds.ID)+", ACTION: Deleted "+strconv.FormatInt(c, 10)+" consistent hash query params", user, tx) + api.CreateChangeLogRawTx(api.ApiChange, "DS: "+ds.XMLID+", ID: "+strconv.Itoa(*ds.ID)+", ACTION: Deleted "+strconv.FormatInt(c, 10)+" consistent hash query params", user, tx) } if _, err = createConsistentHashQueryParams(tx, *ds.ID, ds.ConsistentHashQueryParams); err != nil { @@ -1136,23 +1204,27 @@ func updateV41(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV4 *t return nil, code, usrErr, sysErr } - if err := api.CreateChangeLogRawErr(api.ApiChange, "Updated ds: "+*ds.XMLID+" id: "+strconv.Itoa(*ds.ID), user, tx); err != nil { - return nil, http.StatusInternalServerError, nil, errors.New("writing change log entry: " + err.Error()) + if err := api.CreateChangeLogRawErr(api.ApiChange, "Updated ds: "+ds.XMLID+" id: "+strconv.Itoa(*ds.ID), user, tx); err != nil { + return nil, http.StatusInternalServerError, nil, fmt.Errorf("writing change log entry: %w", err) } - dsV4 = &ds - if inf.Config.TrafficVaultEnabled && ds.Protocol != nil && (*ds.Protocol == tc.DSProtocolHTTPS || *ds.Protocol == tc.DSProtocolHTTPAndHTTPS || *ds.Protocol == tc.DSProtocolHTTPToHTTPS) { - err, errCode := GeneratePlaceholderSelfSignedCert(*dsV4, inf, r.Context()) + err, errCode := GeneratePlaceholderSelfSignedCert(*ds, inf, r.Context()) if err != nil || errCode != http.StatusOK { - return nil, errCode, nil, fmt.Errorf("creating self signed default cert: %v", err) + return nil, errCode, nil, fmt.Errorf("creating self signed default cert: %w", err) } } - return dsV4, http.StatusOK, nil, nil + return ds, http.StatusOK, nil, nil } -// Delete is the DeliveryService implementation of the Deleter interface. +// Delete implements the +// github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api.Deleter +// interface (given that the +// github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api.APIInfoer +// and +// github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api.Identifier +// interfaces are already implemented). func (ds *TODeliveryService) Delete() (error, error, int) { if ds.ID == nil { return errors.New("missing id"), nil, http.StatusBadRequest @@ -1160,43 +1232,41 @@ func (ds *TODeliveryService) Delete() (error, error, int) { xmlID, ok, err := GetXMLID(ds.ReqInfo.Tx.Tx, *ds.ID) if err != nil { - return nil, errors.New("ds delete: getting xmlid: " + err.Error()), http.StatusInternalServerError + return nil, fmt.Errorf("ds delete: getting xmlid: %w", err), http.StatusInternalServerError } else if !ok { return errors.New("delivery service not found"), nil, http.StatusNotFound } - ds.XMLID = &xmlID + ds.XMLID = xmlID - if ds.CDNID != nil { - userErr, sysErr, errCode := dbhelpers.CheckIfCurrentUserCanModifyCDNWithID(ds.APIInfo().Tx.Tx, int64(*ds.CDNID), ds.APIInfo().User.UserName) - if userErr != nil || sysErr != nil { - return userErr, sysErr, errCode - } + var userErr error + var sysErr error + var errCode int + if ds.CDNID != 0 { + userErr, sysErr, errCode = dbhelpers.CheckIfCurrentUserCanModifyCDNWithID(ds.APIInfo().Tx.Tx, int64(ds.CDNID), ds.APIInfo().User.UserName) } else if ds.CDNName != nil { - userErr, sysErr, errCode := dbhelpers.CheckIfCurrentUserCanModifyCDN(ds.APIInfo().Tx.Tx, *ds.CDNName, ds.APIInfo().User.UserName) - if userErr != nil || sysErr != nil { - return userErr, sysErr, errCode - } + userErr, sysErr, errCode = dbhelpers.CheckIfCurrentUserCanModifyCDN(ds.APIInfo().Tx.Tx, *ds.CDNName, ds.APIInfo().User.UserName) } else { _, cdnName, _, err := dbhelpers.GetDSNameAndCDNFromID(ds.ReqInfo.Tx.Tx, *ds.ID) if err != nil { - return nil, fmt.Errorf("couldn't get cdn name for DS: %v", err), http.StatusBadRequest - } - userErr, sysErr, errCode := dbhelpers.CheckIfCurrentUserCanModifyCDN(ds.APIInfo().Tx.Tx, string(cdnName), ds.APIInfo().User.UserName) - if userErr != nil || sysErr != nil { - return userErr, sysErr, errCode + return nil, fmt.Errorf("couldn't get cdn name for DS: %w", err), http.StatusBadRequest } + userErr, sysErr, errCode = dbhelpers.CheckIfCurrentUserCanModifyCDN(ds.APIInfo().Tx.Tx, string(cdnName), ds.APIInfo().User.UserName) + } + if userErr != nil || sysErr != nil { + return userErr, sysErr, errCode } + // Note ds regexes MUST be deleted before the ds, because there's a ON DELETE CASCADE on deliveryservice_regex (but not on regex). // Likewise, it MUST happen in a transaction with the later DS delete, so they aren't deleted if the DS delete fails. if _, err := ds.ReqInfo.Tx.Tx.Exec(`DELETE FROM regex WHERE id IN (SELECT regex FROM deliveryservice_regex WHERE deliveryservice=$1)`, *ds.ID); err != nil { - return nil, errors.New("TODeliveryService.Delete deleting regexes for delivery service: " + err.Error()), http.StatusInternalServerError + return nil, fmt.Errorf("TODeliveryService.Delete deleting regexes for delivery service: %w", err), http.StatusInternalServerError } if _, err := ds.ReqInfo.Tx.Tx.Exec(`DELETE FROM deliveryservice_regex WHERE deliveryservice=$1`, *ds.ID); err != nil { - return nil, errors.New("TODeliveryService.Delete deleting delivery service regexes: " + err.Error()), http.StatusInternalServerError + return nil, fmt.Errorf("TODeliveryService.Delete deleting delivery service regexes: %w", err), http.StatusInternalServerError } - userErr, sysErr, errCode := api.GenericDelete(ds) + userErr, sysErr, errCode = api.GenericDelete(ds) if userErr != nil || sysErr != nil { return userErr, sysErr, errCode } @@ -1204,21 +1274,54 @@ func (ds *TODeliveryService) Delete() (error, error, int) { paramConfigFilePrefixes := []string{"hdr_rw_", "hdr_rw_mid_", "regex_remap_", "cacheurl_"} configFiles := []string{} for _, prefix := range paramConfigFilePrefixes { - configFiles = append(configFiles, prefix+*ds.XMLID+".config") + configFiles = append(configFiles, prefix+ds.XMLID+".config") } if _, err := ds.ReqInfo.Tx.Tx.Exec(`DELETE FROM parameter WHERE name = 'location' AND config_file = ANY($1)`, pq.Array(configFiles)); err != nil { - return nil, errors.New("TODeliveryService.Delete deleting delivery service parameteres: " + err.Error()), http.StatusInternalServerError + return nil, fmt.Errorf("TODeliveryService.Delete deleting delivery service parameters: %w", err), http.StatusInternalServerError } return nil, nil, http.StatusOK } -func (v *TODeliveryService) DeleteQuery() string { +// DeleteQuery implements part of the +// github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api.GenericDeleter +// interface. +func (*TODeliveryService) DeleteQuery() string { return `DELETE FROM deliveryservice WHERE id = :id` } -func readGetDeliveryServices(h http.Header, params map[string]string, tx *sqlx.Tx, user *auth.CurrentUser, useIMS bool) ([]tc.DeliveryServiceV4, error, error, int, *time.Time) { +// addActive adds the query parameter for a DS's "active" state for the +// appropriate given API version to the provided 'WHERE' clause, and updates +// queryValues with the client-provided value from params as necessary. +func addActive(where string, params map[string]string, queryValues map[string]interface{}, version api.Version) (string, error) { + active, ok := params["active"] + if !ok { + return where, nil + } + if version.Major < 5 { + b, err := strconv.ParseBool(active) + if err != nil { + return where, fmt.Errorf("active cannot parse to boolean: %w", err) + } + if b { + return dbhelpers.AppendWhere(where, "ds.active = 'ACTIVE'"), nil + } + return dbhelpers.AppendWhere(where, "ds.active <> 'ACTIVE'"), nil + } + switch tc.DeliveryServiceActiveState(active) { + case tc.DSActiveStateActive: + fallthrough + case tc.DSActiveStateInactive: + fallthrough + case tc.DSActiveStatePrimed: + queryValues["active"] = active + return dbhelpers.AppendWhere(where, "ds.active=:active"), nil + } + return where, fmt.Errorf("active illegal value '%s' must be one of '%s', '%s', or '%s'", active, tc.DSActiveStateActive, tc.DSActiveStateInactive, tc.DSActiveStatePrimed) +} + +func readGetDeliveryServices(h http.Header, params map[string]string, tx *sqlx.Tx, user *auth.CurrentUser, useIMS bool, version api.Version) ([]DSWithLegacyFields, error, error, int, *time.Time) { if tx == nil { return nil, nil, errors.New("nil transaction passed to readGetDeliveryServices"), http.StatusInternalServerError, nil } @@ -1231,9 +1334,8 @@ func readGetDeliveryServices(h http.Header, params map[string]string, tx *sqlx.T var maxTime time.Time var runSecond bool - if strings.HasSuffix(params["id"], ".json") { - params["id"] = params["id"][:len(params["id"])-len(".json")] - } + // TODO: is this necessary? + params["id"] = strings.TrimSuffix(params["id"], ".json") if _, ok := params["orderby"]; !ok { params["orderby"] = "xml_id" } @@ -1252,18 +1354,23 @@ func readGetDeliveryServices(h http.Header, params map[string]string, tx *sqlx.T "signingAlgorithm": {Column: "ds.signing_algorithm"}, "topology": {Column: "ds.topology"}, "serviceCategory": {Column: "ds.service_category"}, - "active": {Column: "ds.active", Checker: api.IsBool}, } where, orderBy, pagination, queryValues, errs := dbhelpers.BuildWhereAndOrderByAndPagination(params, queryParamsToSQLCols) if len(errs) > 0 { return nil, util.JoinErrs(errs), nil, http.StatusBadRequest, nil } + + where, err := addActive(where, params, queryValues, version) + if err != nil { + return nil, err, nil, http.StatusBadRequest, nil + } + if useIMS { runSecond, maxTime = ims.TryIfModifiedSinceQuery(tx, h, queryValues, selectMaxLastUpdatedQuery(where)) if !runSecond { log.Debugln("IMS HIT") - return []tc.DeliveryServiceV4{}, nil, nil, http.StatusNotModified, &maxTime + return nil, nil, nil, http.StatusNotModified, &maxTime } log.Debugln("IMS MISS") } else { @@ -1310,6 +1417,8 @@ func requiredIfMatchesTypeName(patterns []string, typeName string) func(interfac if v != nil { return nil } + case bool: + return nil case *string: if v != nil { return nil @@ -1336,7 +1445,14 @@ func requiredIfMatchesTypeName(patterns []string, typeName string) func(interfac var validTLSVersionPattern = regexp.MustCompile(`^\d+\.\d+$`) -func Validate(tx *sql.Tx, ds *tc.DeliveryServiceV4) error { +// Validate checks that the given Delivery Service is valid according to various +// criteria. *It also modifies the given DS under certain circumstances, +// providing default values to some properties when they are zero-valued or nil +// references*. This will panic if either argument is nil. The error returned is +// safe for clients to see. +// +// TODO: return system errors as well. +func Validate(tx *sql.Tx, ds *tc.DeliveryServiceV5) error { sanitize(ds) neverOrAlways := validation.NewStringRule(tovalidate.IsOneOfStringICase("NEVER", "ALWAYS"), "must be one of 'NEVER' or 'ALWAYS'") @@ -1387,7 +1503,7 @@ func Validate(tx *sql.Tx, ds *tc.DeliveryServiceV4) error { errs = append(errs, err) } if err := validateTypeFields(tx, ds); err != nil { - errs = append(errs, errors.New("type fields: "+err.Error())) + errs = append(errs, fmt.Errorf("type fields: %w", err)) } if len(errs) == 0 { return nil @@ -1395,21 +1511,20 @@ func Validate(tx *sql.Tx, ds *tc.DeliveryServiceV4) error { return util.JoinErrs(errs) } -func validateGeoLimitCountries(ds *tc.DeliveryServiceV4) error { +func validateGeoLimitCountries(ds *tc.DeliveryServiceV5) error { var IsLetter = regexp.MustCompile(`^[A-Z]+$`).MatchString - if ds.GeoLimitCountries == nil { + if len(ds.GeoLimitCountries) == 0 { return nil } - countryCodes := ([]string)(ds.GeoLimitCountries) - for _, cc := range countryCodes { + for _, cc := range ds.GeoLimitCountries { if cc != "" && !IsLetter(cc) { - return fmt.Errorf("country codes can only contain alphabets") + return errors.New("country codes can only contain alphabetical characters") } } return nil } -func validateTopologyFields(ds *tc.DeliveryServiceV4) error { +func validateTopologyFields(ds *tc.DeliveryServiceV5) error { if ds.Topology != nil && (ds.EdgeHeaderRewrite != nil || ds.MidHeaderRewrite != nil) { return errors.New("cannot set edgeHeaderRewrite or midHeaderRewrite while a Topology is assigned. Use firstHeaderRewrite, innerHeaderRewrite, and/or lastHeaderRewrite instead") } @@ -1448,7 +1563,7 @@ func validateOrgServerFQDN(orgServerFQDN string) bool { return true } -func validateTypeFields(tx *sql.Tx, ds *tc.DeliveryServiceV4) error { +func validateTypeFields(tx *sql.Tx, ds *tc.DeliveryServiceV5) error { // Validate the TypeName related fields below err := error(nil) DNSRegexType := "^DNS.*$" @@ -1457,7 +1572,7 @@ func validateTypeFields(tx *sql.Tx, ds *tc.DeliveryServiceV4) error { latitudeErr := "Must be a floating point number within the range +-90" longitudeErr := "Must be a floating point number within the range +-180" - typeName, err := tc.ValidateTypeID(tx, ds.TypeID, "deliveryservice") + typeName, err := tc.ValidateTypeID(tx, &ds.TypeID, "deliveryservice") if err != nil { return err } @@ -1465,7 +1580,7 @@ func validateTypeFields(tx *sql.Tx, ds *tc.DeliveryServiceV4) error { errs := validation.Errors{ "consistentHashQueryParams": validation.Validate(ds, validation.By(func(dsi interface{}) error { - ds := dsi.(*tc.DeliveryServiceV4) + ds := dsi.(*tc.DeliveryServiceV5) if len(ds.ConsistentHashQueryParams) == 0 || tc.DSType(typeName).IsHTTP() { return nil } @@ -1491,7 +1606,7 @@ func validateTypeFields(tx *sql.Tx, ds *tc.DeliveryServiceV4) error { validation.NewStringRule(validateOrgServerFQDN, "must start with http:// or https:// and be followed by a valid hostname with an optional port (no trailing slash)")), "rangeSliceBlockSize": validation.Validate(ds, validation.By(func(dsi interface{}) error { - ds := dsi.(*tc.DeliveryServiceV4) + ds := dsi.(*tc.DeliveryServiceV5) if ds.RangeRequestHandling != nil { if *ds.RangeRequestHandling == 3 { return validation.Validate(ds.RangeSliceBlockSize, validation.Required, @@ -1526,7 +1641,7 @@ func validateTypeFields(tx *sql.Tx, ds *tc.DeliveryServiceV4) error { ), "topology": validation.Validate(ds, validation.By(func(dsi interface{}) error { - ds := dsi.(*tc.DeliveryServiceV4) + ds := dsi.(*tc.DeliveryServiceV5) if ds.Topology != nil && tc.DSType(typeName).IsSteering() { return fmt.Errorf("steering deliveryservice types cannot be assigned to a topology") } @@ -1534,7 +1649,7 @@ func validateTypeFields(tx *sql.Tx, ds *tc.DeliveryServiceV4) error { })), "maxRequestHeaderBytes": validation.Validate(ds, validation.By(func(dsi interface{}) error { - ds := dsi.(*tc.DeliveryServiceV4) + ds := dsi.(*tc.DeliveryServiceV5) if ds.MaxRequestHeaderBytes == nil { return errors.New("maxRequestHeaderBytes empty, must be a valid positive value") } @@ -1574,8 +1689,8 @@ JOIN cdn ON ds.cdn_id = cdn.id WHERE ds.id=$1 ` var oldDetails TODeliveryServiceOldDetails - if err := tx.QueryRow(q, id).Scan(&oldDetails.OldRoutingName, &oldDetails.OldSSLKeyVersion, &oldDetails.OldCdnName, &oldDetails.OldCdnId, &oldDetails.OldOrgServerFqdn); err != nil { - if err == sql.ErrNoRows { + if err := tx.QueryRow(q, id).Scan(&oldDetails.OldRoutingName, &oldDetails.OldSSLKeyVersion, &oldDetails.OldCDNName, &oldDetails.OldCDNID, &oldDetails.OldOrgServerFQDN); err != nil { + if errors.Is(err, sql.ErrNoRows) { return oldDetails, fmt.Errorf("querying delivery service %v host name: no such delivery service exists", id), nil, http.StatusNotFound } return oldDetails, nil, fmt.Errorf("querying delivery service %v host name: "+err.Error(), id), http.StatusInternalServerError @@ -1592,11 +1707,11 @@ func getTypeFromID(id int, tx *sql.Tx) (tc.DSType, error) { return tc.DSTypeFromString(name), nil } -func updatePrimaryOrigin(tx *sql.Tx, user *auth.CurrentUser, ds tc.DeliveryServiceV4) error { +func updatePrimaryOrigin(tx *sql.Tx, user *auth.CurrentUser, ds tc.DeliveryServiceV5) error { count := 0 q := `SELECT count(*) FROM origin WHERE deliveryservice = $1 AND is_primary` if err := tx.QueryRow(q, *ds.ID).Scan(&count); err != nil { - return fmt.Errorf("querying existing primary origin for ds %s: %w", *ds.XMLID, err) + return fmt.Errorf("querying existing primary origin for ds %s: %w", ds.XMLID, err) } if ds.OrgServerFQDN == nil || *ds.OrgServerFQDN == "" { @@ -1604,9 +1719,9 @@ func updatePrimaryOrigin(tx *sql.Tx, user *auth.CurrentUser, ds tc.DeliveryServi // the update is removing the existing orgServerFQDN, so the existing row needs to be deleted q = `DELETE FROM origin WHERE deliveryservice = $1 AND is_primary` if _, err := tx.Exec(q, *ds.ID); err != nil { - return fmt.Errorf("deleting primary origin for ds %s: %w", *ds.XMLID, err) + return fmt.Errorf("deleting primary origin for ds %s: %w", ds.XMLID, err) } - api.CreateChangeLogRawTx(api.ApiChange, "DS: "+*ds.XMLID+", ID: "+strconv.Itoa(*ds.ID)+", ACTION: Deleted primary origin", user, tx) + api.CreateChangeLogRawTx(api.ApiChange, "DS: "+ds.XMLID+", ID: "+strconv.Itoa(*ds.ID)+", ACTION: Deleted primary origin", user, tx) } return nil } @@ -1618,37 +1733,37 @@ func updatePrimaryOrigin(tx *sql.Tx, user *auth.CurrentUser, ds tc.DeliveryServi protocol, fqdn, port, err := parseOrgServerFQDN(*ds.OrgServerFQDN) if err != nil { - return fmt.Errorf("updating primary origin: %v", err) + return fmt.Errorf("updating primary origin: %w", err) } name := "" q = `UPDATE origin SET protocol = $1, fqdn = $2, port = $3 WHERE is_primary AND deliveryservice = $4 RETURNING name` if err := tx.QueryRow(q, protocol, fqdn, port, *ds.ID).Scan(&name); err != nil { - return fmt.Errorf("update primary origin for ds %s from '%s': %w", *ds.XMLID, *ds.OrgServerFQDN, err) + return fmt.Errorf("update primary origin for ds %s from '%s': %w", ds.XMLID, *ds.OrgServerFQDN, err) } - api.CreateChangeLogRawTx(api.ApiChange, "DS: "+*ds.XMLID+", ID: "+strconv.Itoa(*ds.ID)+", ACTION: Updated primary origin: "+name, user, tx) + api.CreateChangeLogRawTx(api.ApiChange, "DS: "+ds.XMLID+", ID: "+strconv.Itoa(*ds.ID)+", ACTION: Updated primary origin: "+name, user, tx) return nil } -func createPrimaryOrigin(tx *sql.Tx, user *auth.CurrentUser, ds tc.DeliveryServiceV4) error { +func createPrimaryOrigin(tx *sql.Tx, user *auth.CurrentUser, ds tc.DeliveryServiceV5) error { if ds.OrgServerFQDN == nil { return nil } protocol, fqdn, port, err := parseOrgServerFQDN(*ds.OrgServerFQDN) if err != nil { - return fmt.Errorf("creating primary origin: %v", err) + return fmt.Errorf("creating primary origin: %w", err) } originID := 0 q := `INSERT INTO origin (name, fqdn, protocol, is_primary, port, deliveryservice, tenant) VALUES ($1, $2, $3, TRUE, $4, $5, $6) RETURNING id` if err := tx.QueryRow(q, ds.XMLID, fqdn, protocol, port, ds.ID, ds.TenantID).Scan(&originID); err != nil { - return fmt.Errorf("insert origin from '%s': %s", *ds.OrgServerFQDN, err.Error()) + return fmt.Errorf("insert origin from '%s': %w", *ds.OrgServerFQDN, err) } - api.CreateChangeLogRawTx(api.ApiChange, "DS: "+*ds.XMLID+", ID: "+strconv.Itoa(*ds.ID)+", ACTION: Created primary origin id: "+strconv.Itoa(originID), user, tx) + api.CreateChangeLogRawTx(api.ApiChange, "DS: "+ds.XMLID+", ID: "+strconv.Itoa(*ds.ID)+", ACTION: Created primary origin id: "+strconv.Itoa(originID), user, tx) return nil } @@ -1656,7 +1771,7 @@ func createPrimaryOrigin(tx *sql.Tx, user *auth.CurrentUser, ds tc.DeliveryServi func getDSType(tx *sql.Tx, xmlid string) (tc.DSType, bool, error) { name := "" if err := tx.QueryRow(`SELECT name FROM type WHERE id = (select type from deliveryservice where xml_id = $1)`, xmlid).Scan(&name); err != nil { - if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { return "", false, nil } return "", false, fmt.Errorf("querying deliveryservice type name: " + err.Error()) @@ -1664,14 +1779,27 @@ func getDSType(tx *sql.Tx, xmlid string) (tc.DSType, bool, error) { return tc.DSTypeFromString(name), true, nil } -func GetDeliveryServices(query string, queryValues map[string]interface{}, tx *sqlx.Tx) ([]tc.DeliveryServiceV4, error, error, int) { +// DSWithLegacyFields contains a Delivery Service along with associated fields +// that have been removed from its representation(s). +type DSWithLegacyFields struct { + DS tc.DeliveryServiceV5 + LongDesc1 *string + LongDesc2 *string +} + +// GetDeliveryServices can be used with a valid query and map of values to +// retrieve Delivery Services from the database. Note that Tenancy must be built +// into the query already. The returned Delivery Services come with accompanying +// information about fields that have been removed from the model, in case a +// legacy handler needs that information. +func GetDeliveryServices(query string, queryValues map[string]interface{}, tx *sqlx.Tx) ([]DSWithLegacyFields, error, error, int) { rows, err := tx.NamedQuery(query, queryValues) if err != nil { - return nil, nil, fmt.Errorf("querying: %v", err), http.StatusInternalServerError + return nil, nil, fmt.Errorf("querying: %w", err), http.StatusInternalServerError } - defer rows.Close() + defer log.Close(rows, "getting Delivery Services") - dses := []tc.DeliveryServiceV4{} + dses := []DSWithLegacyFields{} dsCDNDomains := map[string]string{} // ensure json generated from this slice won't come out as `null` if empty @@ -1679,8 +1807,10 @@ func GetDeliveryServices(query string, queryValues map[string]interface{}, tx *s geoLimitCountries := util.StrPtr("") for rows.Next() { - ds := tc.DeliveryServiceV4{} - cdnDomain := "" + var ds tc.DeliveryServiceV5 + var longDesc1 *string + var longDesc2 *string + var cdnDomain string err := rows.Scan( &ds.Active, &ds.AnonymousBlockingEnabled, @@ -1716,8 +1846,8 @@ func GetDeliveryServices(query string, queryValues map[string]interface{}, tx *s &ds.LastUpdated, &ds.LogsEnabled, &ds.LongDesc, - &ds.LongDesc1, - &ds.LongDesc2, + &longDesc1, + &longDesc2, &ds.MaxDNSAnswers, &ds.MaxOriginConnections, &ds.MaxRequestHeaderBytes, @@ -1755,30 +1885,26 @@ func GetDeliveryServices(query string, queryValues map[string]interface{}, tx *s &cdnDomain) if err != nil { - return nil, nil, fmt.Errorf("getting delivery services: %v", err), http.StatusInternalServerError + return nil, nil, fmt.Errorf("getting delivery services: %w", err), http.StatusInternalServerError } if geoLimitCountries != nil && *geoLimitCountries != "" { geo := strings.Split(*geoLimitCountries, ",") ds.GeoLimitCountries = geo } - ds.ConsistentHashQueryParams = []string{} - if len(dsQueryParams) >= 0 { - // ensure unique and in consistent order - m := make(map[string]struct{}, len(dsQueryParams)) - for _, k := range dsQueryParams { - if _, exists := m[k]; exists { - continue - } - m[k] = struct{}{} - ds.ConsistentHashQueryParams = append(ds.ConsistentHashQueryParams, k) + ds.ConsistentHashQueryParams = make([]string, 0, len(dsQueryParams)) + // ensure unique and in consistent order + m := make(map[string]struct{}, len(dsQueryParams)) + for _, k := range dsQueryParams { + if _, exists := m[k]; exists { + continue } + m[k] = struct{}{} + ds.ConsistentHashQueryParams = append(ds.ConsistentHashQueryParams, k) } - dsCDNDomains[*ds.XMLID] = cdnDomain - if ds.DeepCachingType != nil { - *ds.DeepCachingType = tc.DeepCachingTypeFromString(string(*ds.DeepCachingType)) - } + dsCDNDomains[ds.XMLID] = cdnDomain + ds.DeepCachingType = tc.DeepCachingTypeFromString(string(ds.DeepCachingType)) ds.Signed = ds.SigningAlgorithm != nil && *ds.SigningAlgorithm == tc.SigningAlgorithmURLSig @@ -1786,26 +1912,32 @@ func GetDeliveryServices(query string, queryValues map[string]interface{}, tx *s ds.TLSVersions = nil } - dses = append(dses, ds) + dses = append(dses, DSWithLegacyFields{ + DS: ds, + LongDesc1: longDesc1, + LongDesc2: longDesc2, + }) } - dsNames := make([]string, len(dses), len(dses)) + dsNames := make([]string, len(dses)) for i, ds := range dses { - dsNames[i] = *ds.XMLID + dsNames[i] = ds.DS.XMLID } matchLists, err := GetDeliveryServicesMatchLists(dsNames, tx.Tx) if err != nil { - return nil, nil, errors.New("getting delivery service matchlists: " + err.Error()), http.StatusInternalServerError + return nil, nil, fmt.Errorf("getting delivery service matchlists: %w", err), http.StatusInternalServerError } - for i, ds := range dses { - matchList, ok := matchLists[*ds.XMLID] + for i, d := range dses { + ds := d.DS + matchList, ok := matchLists[ds.XMLID] if !ok { continue } - ds.MatchList = &matchList - ds.ExampleURLs = MakeExampleURLs(ds.Protocol, *ds.Type, *ds.RoutingName, *ds.MatchList, dsCDNDomains[*ds.XMLID]) - dses[i] = ds + ds.MatchList = matchList + ds.ExampleURLs = MakeExampleURLs(ds.Protocol, tc.DSType(*ds.Type), ds.RoutingName, ds.MatchList, dsCDNDomains[ds.XMLID]) + d.DS = ds + dses[i] = d } return dses, nil, nil, http.StatusOK @@ -1839,19 +1971,19 @@ func MakeExampleURLs(protocol *int, dsType tc.DSType, routingName string, matchL if protocol != nil { switch *protocol { case 0: - scheme = "http" + scheme = string(tc.ProtocolHTTP) case 1: - scheme = "https" + scheme = string(tc.ProtocolHTTPS) case 2: fallthrough case 3: - scheme = "http" - scheme2 = "https" + scheme = string(tc.ProtocolHTTP) + scheme2 = string(tc.ProtocolHTTPS) default: - scheme = "http" + scheme = string(tc.ProtocolHTTP) } } else { - scheme = "http" + scheme = string(tc.ProtocolHTTP) } dsIsDNS := dsType.IsDNS() regexReplacer := strings.NewReplacer(`\`, ``, `.*`, ``, `.`, ``) @@ -1876,6 +2008,9 @@ func MakeExampleURLs(protocol *int, dsType tc.DSType, routingName string, matchL return examples } +// GetDeliveryServicesMatchLists retrieves "Match Lists" for each of the +// Delivery Services having the provided XMLID(s). The error return value is not +// safe to return to clients. func GetDeliveryServicesMatchLists(dses []string, tx *sql.Tx) (map[string][]tc.DeliveryServiceMatch, error) { // TODO move somewhere generic q := ` @@ -1889,17 +2024,17 @@ ORDER BY dsr.set_number ` rows, err := tx.Query(q, pq.Array(dses)) if err != nil { - return nil, errors.New("getting delivery service regexes: " + err.Error()) + return nil, fmt.Errorf("getting delivery service regexes: %w", err) } - defer rows.Close() + defer log.Close(rows, "getting Delivery Service Match Lists") - matches := map[string][]tc.DeliveryServiceMatch{} + matches := make(map[string][]tc.DeliveryServiceMatch, len(dses)) for rows.Next() { m := tc.DeliveryServiceMatch{} dsName := "" matchTypeStr := "" if err := rows.Scan(&dsName, &matchTypeStr, &m.Pattern, &m.SetNumber); err != nil { - return nil, errors.New("scanning delivery service regexes: " + err.Error()) + return nil, fmt.Errorf("scanning delivery service regexes: %w", err) } matchType := tc.DSMatchTypeFromString(matchTypeStr) if matchType == tc.DSMatchTypeInvalid { @@ -1915,16 +2050,16 @@ ORDER BY dsr.set_number // Note the edgeHeaderRewrite, midHeaderRewrite, regexRemap may be nil, if the delivery service does not have those values. func EnsureParams(tx *sql.Tx, dsID int, xmlID string, edgeHeaderRewrite *string, midHeaderRewrite *string, regexRemap *string, signingAlgorithm *string, dsType tc.DSType, maxOriginConns *int) error { if err := ensureHeaderRewriteParams(tx, dsID, xmlID, edgeHeaderRewrite, edgeTier, dsType, maxOriginConns); err != nil { - return errors.New("creating edge header rewrite parameters: " + err.Error()) + return fmt.Errorf("creating edge header rewrite parameters: %w", err) } if err := ensureHeaderRewriteParams(tx, dsID, xmlID, midHeaderRewrite, midTier, dsType, maxOriginConns); err != nil { - return errors.New("creating mid header rewrite parameters: " + err.Error()) + return fmt.Errorf("creating mid header rewrite parameters: %w", err) } if err := ensureRegexRemapParams(tx, dsID, xmlID, regexRemap); err != nil { - return errors.New("creating mid regex remap parameters: " + err.Error()) + return fmt.Errorf("creating mid regex remap parameters: %w", err) } if err := ensureURLSigParams(tx, dsID, xmlID, signingAlgorithm); err != nil { - return errors.New("creating urlsig parameters: " + err.Error()) + return fmt.Errorf("creating urlsig parameters: %w", err) } return nil } @@ -2010,39 +2145,41 @@ WHERE server.id IN (SELECT server from deliveryservice_server where deliveryserv ON CONFLICT DO NOTHING ` if _, err := tx.Exec(profileParameterQuery, locationParamID, deliveryServiceID); err != nil { - return errors.New("inserting profile_parameters: " + err.Error()) + return fmt.Errorf("inserting profile_parameters: %w", err) } return nil } -// ensureLocation ensures a location parameter exists for the given config file. If not, it creates one, with the same value as the 'remap.config' file parameter. Returns the ID of the location parameter. +// ensureLocation ensures a location parameter exists for the given config file. +// If not, it creates one, with the same value as the 'remap.config' file +// parameter. Returns the ID of the location parameter. func ensureLocation(tx *sql.Tx, configFile string) (int, error) { atsConfigLocation := "" if err := tx.QueryRow(`SELECT value FROM parameter WHERE name = 'location' AND config_file = 'remap.config'`).Scan(&atsConfigLocation); err != nil { - if err == sql.ErrNoRows { - return 0, errors.New("executing parameter query for ATS config location: parameter missing (do you have a name=location config_file=remap.config parameter?") + if errors.Is(err, sql.ErrNoRows) { + return 0, errors.New("executing parameter query for ATS config location: parameter missing (do you have a name=location config_file=remap.config parameter?)") } - return 0, errors.New("executing parameter query for ATS config location: " + err.Error()) + return 0, fmt.Errorf("executing parameter query for ATS config location: %w", err) } atsConfigLocation = strings.TrimRight(atsConfigLocation, `/`) locationParamID := 0 existingLocationErr := tx.QueryRow(`SELECT id FROM parameter WHERE name = 'location' AND config_file = $1`, configFile).Scan(&locationParamID) if existingLocationErr != nil && existingLocationErr != sql.ErrNoRows { - return 0, errors.New("executing parameter query for existing location: " + existingLocationErr.Error()) + return 0, fmt.Errorf("executing parameter query for existing location: %w", existingLocationErr) } - if existingLocationErr == sql.ErrNoRows { + if errors.Is(existingLocationErr, sql.ErrNoRows) { resultRows, err := tx.Query(`INSERT INTO parameter (config_file, name, value) VALUES ($1, 'location', $2) RETURNING id`, configFile, atsConfigLocation) if err != nil { - return 0, errors.New("executing parameter query to insert location: " + err.Error()) + return 0, fmt.Errorf("executing parameter query to insert location: %w", err) } - defer resultRows.Close() + defer log.Close(resultRows, "inserting location parameter for '"+configFile+"'") if !resultRows.Next() { return 0, errors.New("parameter query to insert location didn't return id") } if err := resultRows.Scan(&locationParamID); err != nil { - return 0, errors.New("parameter query to insert location returned id scan: " + err.Error()) + return 0, fmt.Errorf("parameter query to insert location returned id scan: %w", err) } if resultRows.Next() { return 0, errors.New("parameter query to insert location returned too many rows (>1)") @@ -2054,76 +2191,70 @@ func ensureLocation(tx *sql.Tx, configFile string) (int, error) { func deleteLocationParam(tx *sql.Tx, configFile string) error { id := 0 err := tx.QueryRow(`DELETE FROM parameter WHERE name = 'location' AND config_file = $1 RETURNING id`, configFile).Scan(&id) - if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { return nil } if err != nil { log.Errorln("deleting name=location config_file=" + configFile + " parameter: " + err.Error()) - return errors.New("executing parameter delete: " + err.Error()) + return fmt.Errorf("executing parameter delete: %w", err) } if _, err := tx.Exec(`DELETE FROM profile_parameter WHERE parameter = $1`, id); err != nil { log.Errorf("deleting parameter name=location config_file=%v id=%v profile_parameter: %v", configFile, id, err) - return errors.New("executing parameter profile_parameter delete: " + err.Error()) + return fmt.Errorf("executing parameter profile_parameter delete: %w", err) } return nil } -// getTenantID returns the tenant Id of the given delivery service. -// Note it may return a nil id and nil error, if the tenant ID in the database -// is nil. +// getTenantID returns a pointer to the tenant ID of the given Delivery Service, +// or any error encountered while determining said ID. // This will panic if the transaction is nil. -func getTenantID(tx *sql.Tx, ds *tc.DeliveryServiceV4) (*int, error) { - if ds == nil || (ds.ID == nil && ds.XMLID == nil) { - return nil, errors.New("delivery service was nil, or had nil identifiers (ID and XMLID)") - } +func getTenantID(tx *sql.Tx, ds tc.DeliveryServiceV5) (*int, error) { if ds.ID != nil { - existingID, _, err := getDSTenantIDByID(tx, *ds.ID) // ignore exists return - if the DS is new, we only need to check the user input tenant - return existingID, err + id, _, err := getDSTenantIDByID(tx, *ds.ID) + return id, err } - existingID, _, err := getDSTenantIDByName(tx, tc.DeliveryServiceName(*ds.XMLID)) // ignore exists return - if the DS is new, we only need to check the user input tenant - return existingID, err + id, _, err := getDSTenantIDByName(tx, tc.DeliveryServiceName(ds.XMLID)) + return id, err } -func isTenantAuthorized(inf *api.APIInfo, ds *tc.DeliveryServiceV4) (bool, error) { +func isTenantAuthorized(inf *api.APIInfo, ds *tc.DeliveryServiceV5) (bool, error) { tx := inf.Tx.Tx user := inf.User - existingID, err := getTenantID(inf.Tx.Tx, ds) + existingID, err := getTenantID(inf.Tx.Tx, *ds) if err != nil { - return false, errors.New("getting tenant ID: " + err.Error()) + return false, fmt.Errorf("getting tenant ID: %w", err) } - if ds.TenantID == nil { - ds.TenantID = existingID + if ds.TenantID <= 0 { + if existingID == nil { + return false, errors.New("checking Tenant authorization: Delivery Service doesn't have a specified Tenant ID and doesn't already exist") + } + ds.TenantID = *existingID } - if existingID != nil && existingID != ds.TenantID { + if existingID != nil && *existingID != ds.TenantID { userAuthorizedForExistingDSTenant, err := tenant.IsResourceAuthorizedToUserTx(*existingID, user, tx) if err != nil { - return false, errors.New("checking authorization for existing DS ID: " + err.Error()) + return false, fmt.Errorf("checking authorization for existing DS ID: %w", err) } if !userAuthorizedForExistingDSTenant { return false, nil } } - if ds.TenantID != nil { - userAuthorizedForNewDSTenant, err := tenant.IsResourceAuthorizedToUserTx(*ds.TenantID, user, tx) - if err != nil { - return false, errors.New("checking authorization for new DS ID: " + err.Error()) - } - if !userAuthorizedForNewDSTenant { - return false, nil - } + userAuthorizedForNewDSTenant, err := tenant.IsResourceAuthorizedToUserTx(ds.TenantID, user, tx) + if err != nil { + return false, fmt.Errorf("checking authorization for new DS ID: %w", err) } - return true, nil + return userAuthorizedForNewDSTenant, nil } // getDSTenantIDByID returns the tenant ID, whether the delivery service exists, and any error. func getDSTenantIDByID(tx *sql.Tx, id int) (*int, bool, error) { tenantID := (*int)(nil) if err := tx.QueryRow(`SELECT tenant_id FROM deliveryservice where id = $1`, id).Scan(&tenantID); err != nil { - if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { return nil, false, nil } - return nil, false, fmt.Errorf("querying tenant ID for delivery service ID '%v': %v", id, err) + return nil, false, fmt.Errorf("querying tenant ID for delivery service ID '%v': %w", id, err) } return tenantID, true, nil } @@ -2132,10 +2263,10 @@ func getDSTenantIDByID(tx *sql.Tx, id int) (*int, bool, error) { func getDSTenantIDByName(tx *sql.Tx, ds tc.DeliveryServiceName) (*int, bool, error) { tenantID := (*int)(nil) if err := tx.QueryRow(`SELECT tenant_id FROM deliveryservice where xml_id = $1`, ds).Scan(&tenantID); err != nil { - if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { return nil, false, nil } - return nil, false, fmt.Errorf("querying tenant ID for delivery service name '%v': %v", ds, err) + return nil, false, fmt.Errorf("querying tenant ID for delivery service name '%v': %w", ds, err) } return tenantID, true, nil } @@ -2144,15 +2275,16 @@ func getDSTenantIDByName(tx *sql.Tx, ds tc.DeliveryServiceName) (*int, bool, err func GetXMLID(tx *sql.Tx, id int) (string, bool, error) { xmlID := "" if err := tx.QueryRow(`SELECT xml_id FROM deliveryservice where id = $1`, id).Scan(&xmlID); err != nil { - if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { return "", false, nil } - return "", false, fmt.Errorf("querying xml_id for delivery service ID '%v': %v", id, err) + return "", false, fmt.Errorf("querying xml_id for delivery service ID '%v': %w", id, err) } return xmlID, true, nil } -// getSSLVersion reports a boolean value, confirming whether DS has a SSL version or not +// getSSLVersion reports a boolean value, confirming whether DS has a SSL +// version or not. func getSSLVersion(xmlId string, tx *sql.Tx) (bool, error) { var exists bool row := tx.QueryRow(`SELECT EXISTS(SELECT * FROM deliveryservice WHERE xml_id = $1 AND ssl_key_version>=1)`, xmlId) @@ -2168,14 +2300,17 @@ func setNilIfEmpty(ptrs ...**string) { } } -func sanitize(ds *tc.DeliveryServiceV4) { - if ds.GeoLimitCountries != nil { - geo := ([]string)(ds.GeoLimitCountries) - for i, _ := range geo { - geo[i] = strings.ToUpper(strings.Replace(geo[i], " ", "", -1)) - } - ds.GeoLimitCountries = geo +func sanitizeGeoLimitCountries(ds *tc.DeliveryServiceV5) { + if len(ds.GeoLimitCountries) == 0 { + return + } + for i, cc := range ds.GeoLimitCountries { + ds.GeoLimitCountries[i] = strings.ToUpper(strings.ReplaceAll(cc, " ", "")) } +} + +func sanitize(ds *tc.DeliveryServiceV5) { + sanitizeGeoLimitCountries(ds) if ds.ProfileID != nil && *ds.ProfileID == -1 { ds.ProfileID = nil } @@ -2186,11 +2321,8 @@ func sanitize(ds *tc.DeliveryServiceV4) { &ds.InnerHeaderRewrite, &ds.LastHeaderRewrite, ) - if ds.RoutingName == nil || *ds.RoutingName == "" { - ds.RoutingName = util.StrPtr(tc.DefaultRoutingName) - } - if ds.AnonymousBlockingEnabled == nil { - ds.AnonymousBlockingEnabled = util.BoolPtr(false) + if ds.RoutingName == "" { + ds.RoutingName = tc.DefaultRoutingName } signedAlgorithm := tc.SigningAlgorithmURLSig if ds.Signed && (ds.SigningAlgorithm == nil || *ds.SigningAlgorithm == "") { @@ -2202,11 +2334,10 @@ func sanitize(ds *tc.DeliveryServiceV4) { if ds.MaxOriginConnections == nil || *ds.MaxOriginConnections < 0 { ds.MaxOriginConnections = util.IntPtr(0) } - if ds.DeepCachingType == nil { - s := tc.DeepCachingType("") - ds.DeepCachingType = &s + if ds.DeepCachingType == tc.DeepCachingTypeInvalid { + ds.DeepCachingType = tc.DeepCachingTypeNever } - *ds.DeepCachingType = tc.DeepCachingTypeFromString(string(*ds.DeepCachingType)) + ds.DeepCachingType = tc.DeepCachingTypeFromString(string(ds.DeepCachingType)) if ds.MaxRequestHeaderBytes == nil { ds.MaxRequestHeaderBytes = util.IntPtr(tc.DefaultMaxRequestHeaderBytes) } @@ -2249,7 +2380,7 @@ ds.active, ds.last_header_rewrite, ds.last_updated, ds.logs_enabled, - ds.long_desc, + COALESCE(ds.long_desc, '') AS long_desc, ds.long_desc_1, ds.long_desc_2, ds.max_dns_answers, diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/safe.go b/traffic_ops/traffic_ops_golang/deliveryservice/safe.go index e076982aca..74f505d91a 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/safe.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/safe.go @@ -145,9 +145,9 @@ func UpdateSafe(w http.ResponseWriter, r *http.Request) { api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, ds) case 4: if inf.Version.Minor >= 1 { - api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, []tc.DeliveryServiceV41{}) + api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, []tc.DeliveryServiceV41{ds.Downgrade()}) } else { - api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, []tc.DeliveryServiceV40{ds.DeliveryServiceV40}) + api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, []tc.DeliveryServiceV40{ds.Downgrade().DeliveryServiceV40}) } case 3: legacyDS := ds.Downgrade() From 14280446be1b2c5e51e098b0379c93023015e12d Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Wed, 28 Sep 2022 10:12:50 -0600 Subject: [PATCH 19/48] Update DB helper utilities to use latest DS representation --- .../dbhelpers/db_helpers.go | 52 +++++++++---------- 1 file changed, 25 insertions(+), 27 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/dbhelpers/db_helpers.go b/traffic_ops/traffic_ops_golang/dbhelpers/db_helpers.go index f93131ab96..a9531263d7 100644 --- a/traffic_ops/traffic_ops_golang/dbhelpers/db_helpers.go +++ b/traffic_ops/traffic_ops_golang/dbhelpers/db_helpers.go @@ -106,10 +106,10 @@ WHERE tm_user.email = $1 // 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 +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 @@ -320,15 +320,15 @@ func CheckIfCurrentUserCanModifyCDNWithID(tx *sql.Tx, cdnID int64, user string) // 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 +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 + SELECT name FROM cdn WHERE id IN ( - SELECT cdn_id FROM server - WHERE cachegroup = ($1))) + SELECT cdn_id FROM server + WHERE cachegroup = ($1))) GROUP BY c.username, c.cdn, c.soft` var userName string var cdn string @@ -362,14 +362,14 @@ GROUP BY c.username, c.cdn, c.soft` // 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 + 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 + SELECT name FROM cdn WHERE id IN ( - SELECT cdn_id FROM server + SELECT cdn_id FROM server WHERE cachegroup = ANY($1))) GROUP BY c.username, c.cdn, c.soft` var userName string @@ -414,7 +414,7 @@ func parseCriteriaAndQueryValues(queryParamsToSQLCols map[string]WhereColumnInfo err = colInfo.Checker(urlValue) } if err != nil { - errs = append(errs, errors.New(key+" "+err.Error())) + errs = append(errs, fmt.Errorf("%s %w", key, err)) } else { criteria = colInfo.Column + "=:" + key criteriaArgs = append(criteriaArgs, criteria) @@ -617,7 +617,7 @@ 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 = true +AND ds.active = 'ACTIVE' AND dt.name != '` + tc.DSTypeAnyMap.String() + `' AND p.routing_disabled = false AND (st.name = '` + tc.CacheStatusOnline.String() + `' OR st.name = '` + tc.CacheStatusReported.String() + `' OR st.name = '` + tc.CacheStatusAdminDown.String() + `') @@ -1321,26 +1321,24 @@ func TopologyExists(tx *sql.Tx, name string) (bool, error) { // one of the Topology's Cache Groups is empty with respect to the Delivery // Service's CDN. Note that this can panic if ds does not have a properly set // CDNID. -func CheckTopology(tx *sqlx.Tx, ds tc.DeliveryServiceV4) (int, error, error) { - statusCode, userErr, sysErr := http.StatusOK, error(nil), error(nil) - +func CheckTopology(tx *sqlx.Tx, ds tc.DeliveryServiceV5) (int, error, error) { if ds.Topology == nil { - return statusCode, userErr, sysErr + return http.StatusOK, nil, nil } cacheGroupIDs, _, err := GetTopologyCachegroups(tx.Tx, *ds.Topology) if err != nil { - return http.StatusInternalServerError, nil, fmt.Errorf("getting topology cachegroups: %v", err) + return http.StatusInternalServerError, nil, fmt.Errorf("getting topology cachegroups: %w", err) } if len(cacheGroupIDs) == 0 { return http.StatusBadRequest, fmt.Errorf("no such Topology '%s'", *ds.Topology), nil } - if err = topology_validation.CheckForEmptyCacheGroups(tx, cacheGroupIDs, []int{*ds.CDNID}, true, []int{}); err != nil { - return http.StatusBadRequest, fmt.Errorf("empty cachegroups in Topology %s found for CDN %d: %w", *ds.Topology, *ds.CDNID, err), nil + if err = topology_validation.CheckForEmptyCacheGroups(tx, cacheGroupIDs, []int{ds.CDNID}, true, []int{}); err != nil { + return http.StatusBadRequest, fmt.Errorf("empty cachegroups in Topology %s found for CDN %d: %w", *ds.Topology, ds.CDNID, err), nil } - return statusCode, userErr, sysErr + return http.StatusOK, nil, nil } // GetTopologyCachegroups returns an array of cachegroup IDs and an array of cachegroup From f0a2ae9367cfcfa147d9e74aa30bba9f66faa8b5 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Wed, 28 Sep 2022 10:35:44 -0600 Subject: [PATCH 20/48] Update general DSR logic to operate on the latest DS model Note that this means that because the internal representation in the database has changed, it is no longer possible to create a Delivery Service with a Long Description 1 or Long Description 2 with DSRs, and that no DSR can be used to update a DS to have those fields as anything other than null, *and* that all historical DSRs will no longer show what those fields were either before or after its change was made. --- .../deliveryservice/request/requests.go | 151 ++++++++---------- 1 file changed, 65 insertions(+), 86 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go b/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go index 3a927903b5..2967957a7a 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go @@ -1,3 +1,5 @@ +// Package request contains logic and handlers for API routes dealing with +// Delivery Service Requests (DSRs). package request /* @@ -110,7 +112,7 @@ FROM deliveryservice_request WHERE id=$1 ` -// TODO: figure out how to modify 'AddTenancyCheck' so this isn't necessary +// TODO: figure out how to modify 'AddTenancyCheck' so this isn't necessary. const customTenancyCheck = `( CASE r.change_type WHEN 'delete' THEN CAST(r.original->>'tenantId' AS BIGINT) = ANY(CAST(:accessibleTenants AS BIGINT[])) @@ -136,23 +138,20 @@ func selectMaxLastUpdatedQuery(where string) string { // them as originals on the Delivery Services to which each ID maps in // needOriginals. It returns a response code to use if an error occurred, in // which case it also returns a user error and a system error. -func getOriginals(ids []int, tx *sqlx.Tx, needOriginals map[int][]*tc.DeliveryServiceRequestV4, omitExtraLongDescFields bool) (int, error, error) { +func getOriginals(ids []int, tx *sqlx.Tx, needOriginals map[int][]*tc.DeliveryServiceRequestV5) (int, error, error) { if len(ids) > 0 { originals, userErr, sysErr, errCode := deliveryservice.GetDeliveryServices(originalsQuery, map[string]interface{}{"ids": pq.Array(ids)}, tx) if userErr != nil || sysErr != nil { return errCode, userErr, sysErr } - for _, original := range originals { - if original.ID == nil { + for _, ds := range originals { + if original := ds.DS; original.ID == nil { log.Warnf("Trying to fill in originals: found Delivery Service with no ID") } else if need, ok := needOriginals[*original.ID]; ok { for _, n := range need { - n.Original = new(tc.DeliveryServiceV4) + n.Original = new(tc.DeliveryServiceV5) *n.Original = original - if omitExtraLongDescFields { - *n.Original = n.Original.RemoveLD1AndLD2() - } } } else { log.Warnf("Trying to fill in originals: found Delivery Service that wasn't identified by a DSR (#%d)", *original.ID) @@ -201,13 +200,8 @@ func Get(w http.ResponseWriter, r *http.Request) { // TODO: add this functionality to the query builder in dbhelpers if xmlID, ok := inf.Params["xmlId"]; ok { + where = dbhelpers.AppendWhere(where, "(r.deliveryservice->>'xmlId' = :xmlId) OR (r.original->>'xmlId' = :xmlId)") queryValues["xmlId"] = xmlID - if where != "" { - where += " AND " - } else { - where = "WHERE " - } - where += "(r.deliveryservice->>'xmlId' = :xmlId) OR (r.original->>'xmlId' = :xmlId)" } var maxTime *time.Time @@ -227,17 +221,12 @@ func Get(w http.ResponseWriter, r *http.Request) { tenantIDs, err := tenant.GetUserTenantIDListTx(tx, inf.User.TenantID) if err != nil { - sysErr = fmt.Errorf("dsr getting tenant list: %v", err) + sysErr = fmt.Errorf("dsr getting tenant list: %w", err) api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, sysErr) return } - if where == "" { - where = "WHERE " - } else { - where += " AND " - } - where += customTenancyCheck + where = dbhelpers.AppendWhere(where, customTenancyCheck) queryValues["accessibleTenants"] = pq.Array(tenantIDs) query := selectQuery + where + orderBy + pagination @@ -245,19 +234,19 @@ func Get(w http.ResponseWriter, r *http.Request) { rows, err := inf.Tx.NamedQuery(query, queryValues) if err != nil { - sysErr = fmt.Errorf("dsr querying: %v", err) + sysErr = fmt.Errorf("dsr querying: %w", err) api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, sysErr) return } - defer rows.Close() + defer log.Close(rows, "getting DSRs") - dsrs := []tc.DeliveryServiceRequestV40{} - needOriginals := map[int][]*tc.DeliveryServiceRequestV40{} + dsrs := []tc.DeliveryServiceRequestV5{} + needOriginals := map[int][]*tc.DeliveryServiceRequestV5{} var originalIDs []int for rows.Next() { - var dsr tc.DeliveryServiceRequestV40 + var dsr tc.DeliveryServiceRequestV5 if err = rows.StructScan(&dsr); err != nil { - api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, fmt.Errorf("dsr scanning: %v", err)) + api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, fmt.Errorf("dsr scanning: %w", err)) return } dsrs = append(dsrs, dsr) @@ -266,7 +255,7 @@ func Get(w http.ResponseWriter, r *http.Request) { if dsr.ChangeType == tc.DSRChangeTypeUpdate && dsr.Requested != nil && dsr.Requested.ID != nil { id := *dsr.Requested.ID if _, ok := needOriginals[id]; !ok { - needOriginals[id] = []*tc.DeliveryServiceRequestV40{&dsrs[len(dsrs)-1]} + needOriginals[id] = []*tc.DeliveryServiceRequestV5{&dsrs[len(dsrs)-1]} } else { needOriginals[id] = append(needOriginals[id], &dsrs[len(dsrs)-1]) } @@ -274,7 +263,7 @@ func Get(w http.ResponseWriter, r *http.Request) { } else if dsr.ChangeType == tc.DSRChangeTypeDelete && dsr.Original != nil && dsr.Original.ID != nil { id := *dsr.Original.ID if _, ok := needOriginals[id]; !ok { - needOriginals[id] = []*tc.DeliveryServiceRequestV40{&dsrs[len(dsrs)-1]} + needOriginals[id] = []*tc.DeliveryServiceRequestV5{&dsrs[len(dsrs)-1]} } else { needOriginals[id] = append(needOriginals[id], &dsrs[len(dsrs)-1]) } @@ -288,18 +277,26 @@ func Get(w http.ResponseWriter, r *http.Request) { } if version.Major >= 4 { - errCode, userErr, sysErr = getOriginals(originalIDs, inf.Tx, needOriginals, true) + errCode, userErr, sysErr = getOriginals(originalIDs, inf.Tx, needOriginals) if userErr != nil || sysErr != nil { api.HandleErr(w, r, tx, errCode, userErr, sysErr) return } - api.WriteResp(w, r, dsrs) + if version.Major >= 5 { + api.WriteResp(w, r, dsrs) + return + } + downgraded := make([]tc.DeliveryServiceRequestV40, 0, len(dsrs)) + for _, dsr := range dsrs { + downgraded = append(downgraded, dsr.Downgrade()) + } + api.WriteResp(w, r, downgraded) return } downgraded := make([]tc.DeliveryServiceRequestNullable, 0, len(dsrs)) for _, dsr := range dsrs { - downgraded = append(downgraded, dsr.Downgrade()) + downgraded = append(downgraded, dsr.Downgrade().Downgrade()) } api.WriteResp(w, r, downgraded) @@ -307,15 +304,11 @@ func Get(w http.ResponseWriter, r *http.Request) { // isTenantAuthorized ensures the user is authorized on the DSR's // DeliveryService's Tenant, as appropriate to the change type. -func isTenantAuthorized(dsr tc.DeliveryServiceRequestV40, inf *api.APIInfo) (bool, error) { +func isTenantAuthorized(dsr tc.DeliveryServiceRequestV5, inf *api.APIInfo) (bool, error) { if dsr.Requested != nil && (dsr.ChangeType == tc.DSRChangeTypeUpdate || dsr.ChangeType == tc.DSRChangeTypeCreate) { - if dsr.Requested.TenantID == nil { - log.Debugf("requested.tenantID is nil") - return false, errors.New("requested.tenantID is nil") - } - ok, err := tenant.IsResourceAuthorizedToUserTx(*dsr.Requested.TenantID, inf.User, inf.Tx.Tx) + ok, err := tenant.IsResourceAuthorizedToUserTx(dsr.Requested.TenantID, inf.User, inf.Tx.Tx) if err != nil { - err = fmt.Errorf("requested: %v", err) + err = fmt.Errorf("requested: %w", err) } if !ok || err != nil { return ok, err @@ -328,19 +321,15 @@ func isTenantAuthorized(dsr tc.DeliveryServiceRequestV40, inf *api.APIInfo) (boo return true, nil } - if ds.TenantID == nil { - log.Debugf("original.tenantID is nil") - return false, errors.New("original.tenantID is nil") - } - ok, err := tenant.IsResourceAuthorizedToUserTx(*ds.TenantID, inf.User, inf.Tx.Tx) + ok, err := tenant.IsResourceAuthorizedToUserTx(ds.TenantID, inf.User, inf.Tx.Tx) if err != nil { - err = fmt.Errorf("original: %v", err) + err = fmt.Errorf("original: %w", err) } return ok, err } // Warning: this assumes inf isn't nil, and neither is dsr, inf.Tx or inf.User or inf.Tx.Tx. -func insert(dsr *tc.DeliveryServiceRequestV40, inf *api.APIInfo) (int, error, error) { +func insert(dsr *tc.DeliveryServiceRequestV5, inf *api.APIInfo) (int, error, error) { dsr.Author = inf.User.UserName dsr.LastEditedBy = inf.User.UserName if dsr.ChangeType != tc.DSRChangeTypeDelete { @@ -369,14 +358,8 @@ func insert(dsr *tc.DeliveryServiceRequestV40, inf *api.APIInfo) (int, error, er sysErr = fmt.Errorf("too many Delivery Services with XMLID '%s'; want: 1, got: %d", dsr.XMLID, len(originals)) return http.StatusInternalServerError, nil, sysErr } - dsr.Original = new(tc.DeliveryServiceV4) - *dsr.Original = originals[0] - if inf.Version.Major >= 4 && inf.Version.Minor >= 0 { - *dsr.Original = dsr.Original.RemoveLD1AndLD2() - if dsr.Requested != nil { - *dsr.Requested = dsr.Requested.RemoveLD1AndLD2() - } - } + dsr.Original = new(tc.DeliveryServiceV5) + *dsr.Original = originals[0].DS } return http.StatusOK, nil, nil } @@ -422,9 +405,9 @@ func (d dsrManipulationResult) String() string { func createV4(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (result dsrManipulationResult) { tx := inf.Tx.Tx - var dsr tc.DeliveryServiceRequestV40 + var dsr tc.DeliveryServiceRequestV4 if err := json.NewDecoder(r.Body).Decode(&dsr); err != nil { - api.HandleErr(w, r, tx, http.StatusBadRequest, fmt.Errorf("decoding: %v", err), nil) + api.HandleErr(w, r, tx, http.StatusBadRequest, fmt.Errorf("decoding: %w", err), nil) return } if userErr, sysErr := validateV4(dsr, tx); userErr != nil || sysErr != nil { @@ -438,7 +421,8 @@ func createV4(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (result return } - ok, err := isTenantAuthorized(dsr, inf) + upgraded := dsr.Upgrade() + ok, err := isTenantAuthorized(upgraded, inf) if err != nil { api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, err) return @@ -476,7 +460,7 @@ func createV4(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (result dsr.Requested.TLSVersions = nil } } - errCode, userErr, sysErr := insert(&dsr, inf) + errCode, userErr, sysErr := insert(&upgraded, inf) if userErr != nil || sysErr != nil { api.HandleErr(w, r, tx, errCode, userErr, sysErr) return @@ -498,7 +482,7 @@ func createLegacy(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (res tx := inf.Tx.Tx var dsr tc.DeliveryServiceRequestNullable if err := json.NewDecoder(r.Body).Decode(&dsr); err != nil { - userErr := fmt.Errorf("decoding: %v", err) + userErr := fmt.Errorf("decoding: %w", err) api.HandleErr(w, r, tx, http.StatusBadRequest, userErr, nil) return } @@ -507,10 +491,10 @@ func createLegacy(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (res return } - upgraded := dsr.Upgrade() + upgraded := dsr.Upgrade().Upgrade() authorized, err := isTenantAuthorized(upgraded, inf) if err != nil { - sysErr := fmt.Errorf("checking tenant authorized: %v", err) + sysErr := fmt.Errorf("checking tenant authorized: %w", err) api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, sysErr) return } @@ -542,7 +526,7 @@ func createLegacy(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (res XMLID := *ds.XMLID active, err := isActiveRequest(inf.Tx, XMLID) if err != nil { - sysErr := fmt.Errorf("checking request active: %v", err) + sysErr := fmt.Errorf("checking request active: %w", err) api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, sysErr) return } @@ -603,7 +587,6 @@ func Post(w http.ResponseWriter, r *http.Request) { // Delete is the handler for DELETE requests to /deliveryservice_requests. func Delete(w http.ResponseWriter, r *http.Request) { - var omitExtraLongDescFields bool inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"id"}, []string{"id"}) tx := inf.Tx.Tx if userErr != nil || sysErr != nil { @@ -613,8 +596,7 @@ func Delete(w http.ResponseWriter, r *http.Request) { defer inf.Close() // Middleware should've already handled this, so idk why this is a pointer at all tbh - version := inf.Version - if version == nil { + if inf.Version == nil { middleware.NotImplementedHandler().ServeHTTP(w, r) return } @@ -624,12 +606,9 @@ func Delete(w http.ResponseWriter, r *http.Request) { return } - if version.Major >= 4 && version.Minor >= 0 { - omitExtraLongDescFields = true - } - var dsr tc.DeliveryServiceRequestV40 + var dsr tc.DeliveryServiceRequestV5 if err := inf.Tx.QueryRowx(selectQuery+"WHERE r.id=$1", inf.IntParams["id"]).StructScan(&dsr); err != nil { - if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { errCode = http.StatusNotFound userErr = fmt.Errorf("no such Delivery Service Request: #%d", inf.IntParams["id"]) sysErr = nil @@ -653,12 +632,12 @@ func Delete(w http.ResponseWriter, r *http.Request) { result, err := tx.Exec(deleteQuery, inf.IntParams["id"]) if err != nil { - sysErr = fmt.Errorf("deleting DSR #%d: %v", inf.IntParams["id"], err) + sysErr = fmt.Errorf("deleting DSR #%d: %w", inf.IntParams["id"], err) api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, sysErr) return } if affected, err := result.RowsAffected(); err != nil { - sysErr = fmt.Errorf("checking affected rows: %v", err) + sysErr = fmt.Errorf("checking affected rows: %w", err) api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, sysErr) return } else if affected != 1 { @@ -669,9 +648,9 @@ func Delete(w http.ResponseWriter, r *http.Request) { if dsr.IsOpen() && dsr.ChangeType != tc.DSRChangeTypeCreate { if dsr.ChangeType == tc.DSRChangeTypeDelete && dsr.Original != nil && dsr.Original.ID != nil { - errCode, userErr, sysErr = getOriginals([]int{*dsr.Original.ID}, inf.Tx, map[int][]*tc.DeliveryServiceRequestV4{*dsr.Original.ID: {&dsr}}, omitExtraLongDescFields) + errCode, userErr, sysErr = getOriginals([]int{*dsr.Original.ID}, inf.Tx, map[int][]*tc.DeliveryServiceRequestV5{*dsr.Original.ID: {&dsr}}) } else if dsr.ChangeType == tc.DSRChangeTypeUpdate && dsr.Requested != nil && dsr.Requested.ID != nil { - errCode, userErr, sysErr = getOriginals([]int{*dsr.Requested.ID}, inf.Tx, map[int][]*tc.DeliveryServiceRequestV4{*dsr.Requested.ID: {&dsr}}, omitExtraLongDescFields) + errCode, userErr, sysErr = getOriginals([]int{*dsr.Requested.ID}, inf.Tx, map[int][]*tc.DeliveryServiceRequestV5{*dsr.Requested.ID: {&dsr}}) } if userErr != nil || sysErr != nil { @@ -703,7 +682,7 @@ func putV40(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (result ds tx := inf.Tx.Tx var dsr tc.DeliveryServiceRequestV40 if err := json.NewDecoder(r.Body).Decode(&dsr); err != nil { - api.HandleErr(w, r, tx, http.StatusBadRequest, fmt.Errorf("decoding: %v", err), nil) + api.HandleErr(w, r, tx, http.StatusBadRequest, fmt.Errorf("decoding: %w", err), nil) return } if userErr, sysErr := validateV4(dsr, tx); userErr != nil || sysErr != nil { @@ -723,7 +702,8 @@ func putV40(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (result ds dsr.Requested = nil } - authorized, err := isTenantAuthorized(dsr, inf) + upgraded := dsr.Upgrade() + authorized, err := isTenantAuthorized(upgraded, inf) if err != nil { api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, err) return @@ -768,10 +748,10 @@ func putV40(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (result ds if err := tx.QueryRow(updateQuery, args...).Scan(&dsr.CreatedAt, &dsr.LastUpdated); err != nil { var userErr, sysErr error var errCode int - if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { userErr = fmt.Errorf("no such Delivery Service Request: #%d", inf.IntParams["id"]) errCode = http.StatusNotFound - sysErr = fmt.Errorf("running update query for Delivery Service Requests: %v", err) + sysErr = fmt.Errorf("running update query for Delivery Service Requests: %w", err) } else { userErr, sysErr, errCode = api.ParseDBError(err) } @@ -798,7 +778,7 @@ func putV40(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (result ds return } dsr.Original = new(tc.DeliveryServiceV4) - *dsr.Original = originals[0] + *dsr.Original = originals[0].DS.Downgrade() *dsr.Original = dsr.Original.RemoveLD1AndLD2() if dsr.Requested != nil { *dsr.Requested = dsr.Requested.RemoveLD1AndLD2() @@ -818,7 +798,7 @@ func putLegacy(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (result tx := inf.Tx.Tx var dsr tc.DeliveryServiceRequestNullable if err := json.NewDecoder(r.Body).Decode(&dsr); err != nil { - userErr := fmt.Errorf("decoding: %v", err) + userErr := fmt.Errorf("decoding: %w", err) api.HandleErr(w, r, tx, http.StatusBadRequest, userErr, nil) return } @@ -838,7 +818,7 @@ func putLegacy(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (result dsr.LastEditedByID = new(tc.IDNoMod) *dsr.LastEditedByID = tc.IDNoMod(inf.User.ID) - upgraded := dsr.Upgrade() + upgraded := dsr.Upgrade().Upgrade() authorized, err := isTenantAuthorized(upgraded, inf) if err != nil { @@ -862,7 +842,7 @@ func putLegacy(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (result if err := tx.QueryRow(updateQuery, args...).Scan(&dsr.CreatedAt, &dsr.LastUpdated); err != nil { var errCode int var userErr, sysErr error - if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { errCode = http.StatusNotFound userErr = fmt.Errorf("no such Delivery Service Request: #%d", inf.IntParams["id"]) sysErr = nil @@ -894,8 +874,7 @@ func Put(w http.ResponseWriter, r *http.Request) { defer inf.Close() // Middleware should've already handled this, so idk why this is a pointer at all tbh - version := inf.Version - if version == nil { + if inf.Version == nil { middleware.NotImplementedHandler().ServeHTTP(w, r) return } @@ -913,9 +892,9 @@ func Put(w http.ResponseWriter, r *http.Request) { return } - var current tc.DeliveryServiceRequestV40 + var current tc.DeliveryServiceRequestV5 if err := inf.Tx.QueryRowx(selectQuery+"WHERE r.id=$1", id).StructScan(¤t); err != nil { - if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { errCode = http.StatusNotFound userErr = fmt.Errorf("no such Delivery Service Request: #%d", inf.IntParams["id"]) sysErr = nil From 7c73b0de7717e1d24f436d99074aa3ad20f42f5b Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Wed, 28 Sep 2022 10:37:30 -0600 Subject: [PATCH 21/48] Update DSR assignment logic to operate on the latest DS model --- .../deliveryservice/request/assign.go | 41 ++++++++----------- 1 file changed, 16 insertions(+), 25 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/request/assign.go b/traffic_ops/traffic_ops_golang/deliveryservice/request/assign.go index 3f96a28950..d34d138c72 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/request/assign.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/request/assign.go @@ -57,16 +57,16 @@ func GetAssignment(w http.ResponseWriter, r *http.Request) { return } - var dsr tc.DeliveryServiceRequestV40 + var dsr tc.DeliveryServiceRequestV5 if err := inf.Tx.QueryRowx(selectQuery+"WHERE r.id=$1", inf.IntParams["id"]).StructScan(&dsr); err != nil { - if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { errCode = http.StatusNotFound userErr = fmt.Errorf("no such Delivery Service Request: %d", inf.IntParams["id"]) sysErr = nil } else { errCode = http.StatusInternalServerError userErr = nil - sysErr = fmt.Errorf("looking for DSR: %v", err) + sysErr = fmt.Errorf("looking for DSR: %w", err) } api.HandleErr(w, r, tx, errCode, userErr, sysErr) return @@ -109,21 +109,21 @@ func getAssignee(r *assignmentRequest, xmlID string, tx *sql.Tx) (string, int, e var message string if r.AssigneeID != nil { r.Assignee = new(string) - if err := tx.QueryRow(`SELECT username FROM tm_user WHERE id = $1`, *r.AssigneeID).Scan(r.Assignee); err == sql.ErrNoRows { + if err := tx.QueryRow(`SELECT username FROM tm_user WHERE id = $1`, *r.AssigneeID).Scan(r.Assignee); errors.Is(err, sql.ErrNoRows) { userErr := fmt.Errorf("no such user #%d", *r.AssigneeID) return "", http.StatusBadRequest, userErr, nil } else if err != nil { - sysErr := fmt.Errorf("getting username for assignee ID (#%d): %v", *r.AssigneeID, err) + sysErr := fmt.Errorf("getting username for assignee ID (#%d): %w", *r.AssigneeID, err) return "", http.StatusInternalServerError, nil, sysErr } message = fmt.Sprintf("Changed assignee of '%s' Delivery Service Request to '%s'", xmlID, *r.Assignee) } else if r.Assignee != nil { r.AssigneeID = new(int) - if err := tx.QueryRow(`SELECT id FROM tm_user WHERE username=$1`, *r.Assignee).Scan(r.AssigneeID); err == sql.ErrNoRows { + if err := tx.QueryRow(`SELECT id FROM tm_user WHERE username=$1`, *r.Assignee).Scan(r.AssigneeID); errors.Is(err, sql.ErrNoRows) { userErr := fmt.Errorf("no such user '%s'", *r.Assignee) return "", http.StatusBadRequest, userErr, nil } else if err != nil { - sysErr := fmt.Errorf("getting user ID for assignee (%s): %v", *r.Assignee, err) + sysErr := fmt.Errorf("getting user ID for assignee (%s): %w", *r.Assignee, err) return "", http.StatusInternalServerError, nil, sysErr } message = fmt.Sprintf("Changed assignee of '%s' Delivery Service Request to '%s'", xmlID, *r.Assignee) @@ -162,16 +162,16 @@ func PutAssignment(w http.ResponseWriter, r *http.Request) { req.Assignee = nil } - var dsr tc.DeliveryServiceRequestV40 + var dsr tc.DeliveryServiceRequestV5 if err := inf.Tx.QueryRowx(selectQuery+"WHERE r.id=$1", inf.IntParams["id"]).StructScan(&dsr); err != nil { - if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { errCode = http.StatusNotFound userErr = fmt.Errorf("no such Delivery Service Request: %d", inf.IntParams["id"]) sysErr = nil } else { errCode = http.StatusInternalServerError userErr = nil - sysErr = fmt.Errorf("looking for DSR: %v", err) + sysErr = fmt.Errorf("looking for DSR: %w", err) } api.HandleErr(w, r, tx, errCode, userErr, sysErr) return @@ -218,25 +218,16 @@ func PutAssignment(w http.ResponseWriter, r *http.Request) { api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, sysErr) return } - dsr.Original = new(tc.DeliveryServiceV4) - *dsr.Original = originals[0] + dsr.Original = new(tc.DeliveryServiceV5) + *dsr.Original = originals[0].DS } var resp interface{} - if inf.Version.Major >= 4 { - if dsr.Requested != nil && (dsr.Requested.LongDesc1 != nil || dsr.Requested.LongDesc2 != nil) { - api.HandleErr(w, r, tx, http.StatusBadRequest, errors.New("the longDesc1 and longDesc2 fields are no longer supported in API 4.0 onwards"), nil) - return - } - - if dsr.Original != nil { - *dsr.Original = dsr.Original.RemoveLD1AndLD2() - } - if dsr.Requested != nil { - *dsr.Requested = dsr.Requested.RemoveLD1AndLD2() - } + if inf.Version.Major >= 5 { resp = dsr - } else { + } else if inf.Version.Major >= 4 { resp = dsr.Downgrade() + } else { + resp = dsr.Downgrade().Downgrade() } api.WriteRespAlertObj(w, r, tc.SuccessLevel, message, resp) From 43e9a9ea3dfd58aa2e857b7c587dce143279300b Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Wed, 28 Sep 2022 10:39:18 -0600 Subject: [PATCH 22/48] Update DSR status manipulation logic to operate on the latest DS model --- .../deliveryservice/request/status.go | 41 ++++++++----------- 1 file changed, 16 insertions(+), 25 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/request/status.go b/traffic_ops/traffic_ops_golang/deliveryservice/request/status.go index cbbcbe5f0d..d252a3906d 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/request/status.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/request/status.go @@ -57,16 +57,16 @@ func GetStatus(w http.ResponseWriter, r *http.Request) { return } - var dsr tc.DeliveryServiceRequestV40 + var dsr tc.DeliveryServiceRequestV5 if err := inf.Tx.QueryRowx(selectQuery+"WHERE r.id=$1", inf.IntParams["id"]).StructScan(&dsr); err != nil { - if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { errCode = http.StatusNotFound userErr = fmt.Errorf("no such Delivery Service Request: %d", inf.IntParams["id"]) sysErr = nil } else { errCode = http.StatusInternalServerError userErr = nil - sysErr = fmt.Errorf("looking for DSR: %v", err) + sysErr = fmt.Errorf("looking for DSR: %w", err) } api.HandleErr(w, r, tx, errCode, userErr, sysErr) return @@ -102,7 +102,6 @@ RETURNING last_updated // PutStatus is the handler for PUT requests to // /deliveryservice_requests/{{ID}}/status. func PutStatus(w http.ResponseWriter, r *http.Request) { - var omitExtraLongDescFields bool inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"id"}, []string{"id"}) tx := inf.Tx.Tx if userErr != nil || sysErr != nil { @@ -112,8 +111,7 @@ func PutStatus(w http.ResponseWriter, r *http.Request) { defer inf.Close() // Middleware should've already handled this, so idk why this is a pointer at all tbh - version := inf.Version - if version == nil { + if inf.Version == nil { middleware.NotImplementedHandler().ServeHTTP(w, r) return } @@ -124,9 +122,6 @@ func PutStatus(w http.ResponseWriter, r *http.Request) { return } - if inf.Version.Major >= 4 && inf.Version.Minor >= 0 { - omitExtraLongDescFields = true - } var req tc.StatusChangeRequest if err := api.Parse(r.Body, tx, &req); err != nil { api.HandleErr(w, r, tx, http.StatusBadRequest, err, nil) @@ -135,16 +130,16 @@ func PutStatus(w http.ResponseWriter, r *http.Request) { dsrID := inf.IntParams["id"] - var dsr tc.DeliveryServiceRequestV40 + var dsr tc.DeliveryServiceRequestV5 if err := inf.Tx.QueryRowx(selectQuery+"WHERE r.id=$1", dsrID).StructScan(&dsr); err != nil { - if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { errCode = http.StatusNotFound userErr = fmt.Errorf("no such Delivery Service Request: %d", dsrID) sysErr = nil } else { errCode = http.StatusInternalServerError userErr = nil - sysErr = fmt.Errorf("looking for DSR: %v", err) + sysErr = fmt.Errorf("looking for DSR: %w", err) } api.HandleErr(w, r, tx, errCode, userErr, sysErr) return @@ -174,7 +169,7 @@ func PutStatus(w http.ResponseWriter, r *http.Request) { // (and isn't a "create" request) if dsr.IsOpen() && req.Status != tc.RequestStatusDraft && req.Status != tc.RequestStatusSubmitted && dsr.ChangeType != tc.DSRChangeTypeCreate { if dsr.ChangeType == tc.DSRChangeTypeUpdate && dsr.Requested != nil && dsr.Requested.ID != nil { - errCode, userErr, sysErr = getOriginals([]int{*dsr.Requested.ID}, inf.Tx, map[int][]*tc.DeliveryServiceRequestV4{*dsr.Requested.ID: {&dsr}}, omitExtraLongDescFields) + errCode, userErr, sysErr = getOriginals([]int{*dsr.Requested.ID}, inf.Tx, map[int][]*tc.DeliveryServiceRequestV5{*dsr.Requested.ID: {&dsr}}) if userErr != nil || sysErr != nil { api.HandleErr(w, r, tx, errCode, userErr, sysErr) return @@ -183,7 +178,7 @@ func PutStatus(w http.ResponseWriter, r *http.Request) { sysErr = fmt.Errorf("failed to build original from dsr #%d that was to be closed; requested ID: %d", dsrID, *dsr.Requested.ID) } } else if dsr.ChangeType == tc.DSRChangeTypeDelete && dsr.Original != nil && dsr.Original.ID != nil { - errCode, userErr, sysErr = getOriginals([]int{*dsr.Original.ID}, inf.Tx, map[int][]*tc.DeliveryServiceRequestV4{*dsr.Original.ID: {&dsr}}, omitExtraLongDescFields) + errCode, userErr, sysErr = getOriginals([]int{*dsr.Original.ID}, inf.Tx, map[int][]*tc.DeliveryServiceRequestV5{*dsr.Original.ID: {&dsr}}) if userErr != nil || sysErr != nil { api.HandleErr(w, r, tx, errCode, userErr, sysErr) return @@ -200,7 +195,7 @@ func PutStatus(w http.ResponseWriter, r *http.Request) { err := tx.QueryRow(updateStatusAndOriginalQuery, dsr.Original, req.Status, dsr.LastEditedByID, dsrID).Scan(&dsr.LastUpdated) if err != nil { - sysErr = fmt.Errorf("updating original for dsr #%d: %v", dsrID, err) + sysErr = fmt.Errorf("updating original for dsr #%d: %w", dsrID, err) api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, sysErr) return } @@ -216,8 +211,8 @@ func PutStatus(w http.ResponseWriter, r *http.Request) { api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, fmt.Errorf("expected exactly one DS with XMLID '%s', found: %d", dsr.XMLID, len(original))) return } - dsr.Original = new(tc.DeliveryServiceV4) - *dsr.Original = original[0] + dsr.Original = new(tc.DeliveryServiceV5) + *dsr.Original = original[0].DS } } else { userErr, sysErr, errCode = api.ParseDBError(err) @@ -229,16 +224,12 @@ func PutStatus(w http.ResponseWriter, r *http.Request) { dsr.Status = req.Status var resp interface{} - if inf.Version.Major >= 4 { - if dsr.Original != nil { - *dsr.Original = dsr.Original.RemoveLD1AndLD2() - } - if dsr.Requested != nil { - *dsr.Requested = dsr.Requested.RemoveLD1AndLD2() - } + if inf.Version.Major >= 5 { resp = dsr - } else { + } else if inf.Version.Major >= 4 { resp = dsr.Downgrade() + } else { + resp = dsr.Downgrade().Downgrade() } api.WriteRespAlertObj(w, r, tc.SuccessLevel, message, resp) From 62572d8b02f1493ba74a5c56628eb4ffe2fa5836 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Wed, 28 Sep 2022 10:40:09 -0600 Subject: [PATCH 23/48] Update DSR validation logic to operate on the latest DS model --- .../deliveryservice/request/validate.go | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/request/validate.go b/traffic_ops/traffic_ops_golang/deliveryservice/request/validate.go index 8bf4dc604e..47fb24265d 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/request/validate.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/request/validate.go @@ -68,7 +68,7 @@ func validateLegacy(dsr tc.DeliveryServiceRequestNullable, tx *sql.Tx) error { } errs := tovalidate.ToErrors(errMap) // ensure the deliveryservice requested is valid - upgraded := dsr.DeliveryService.UpgradeToV4() + upgraded := dsr.DeliveryService.UpgradeToV4().Upgrade() e := deliveryservice.Validate(tx, &upgraded) errs = append(errs, e) @@ -78,7 +78,13 @@ func validateLegacy(dsr tc.DeliveryServiceRequestNullable, tx *sql.Tx) error { // validateV4 validates a DSR, returning - in order - a user-facing error that // should be shown to the client, and a system error. -func validateV4(dsr tc.DeliveryServiceRequestV40, tx *sql.Tx) (error, error) { +func validateV4(dsr tc.DeliveryServiceRequestV4, tx *sql.Tx) (error, error) { + return validateV5(dsr.Upgrade(), tx) +} + +// validateV4 validates a DSR, returning - in order - a user-facing error that +// should be shown to the client, and a system error. +func validateV5(dsr tc.DeliveryServiceRequestV5, tx *sql.Tx) (error, error) { if tx == nil { return nil, errors.New("nil transaction") } @@ -112,7 +118,7 @@ func validateV4(dsr tc.DeliveryServiceRequestV40, tx *sql.Tx) (error, error) { if r == nil { return fmt.Errorf("required for changeType='%s'", dsr.ChangeType) } - ds, ok := r.(*tc.DeliveryServiceV4) + ds, ok := r.(*tc.DeliveryServiceV5) if !ok { return fmt.Errorf("expected a Delivery Service, got %T", r) } @@ -121,7 +127,7 @@ func validateV4(dsr tc.DeliveryServiceRequestV40, tx *sql.Tx) (error, error) { } err := deliveryservice.Validate(tx, ds) if err == nil { - dsr.XMLID = *ds.XMLID + dsr.XMLID = ds.XMLID } return err }, From f3d16602fb9ef36620b2d7711a6b67e61250250d Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Wed, 28 Sep 2022 10:40:50 -0600 Subject: [PATCH 24/48] Update various queries for DS active state to use new values/type --- traffic_ops/traffic_ops_golang/crconfig/deliveryservice.go | 6 +++--- traffic_ops/traffic_ops_golang/crconfig/servers.go | 2 +- traffic_ops/traffic_ops_golang/monitoring/monitoring.go | 2 +- traffic_ops/traffic_ops_golang/server/servers.go | 2 +- traffic_ops/traffic_ops_golang/server/servers_assignment.go | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/crconfig/deliveryservice.go b/traffic_ops/traffic_ops_golang/crconfig/deliveryservice.go index dfd45ebaa7..b84d98d697 100644 --- a/traffic_ops/traffic_ops_golang/crconfig/deliveryservice.go +++ b/traffic_ops/traffic_ops_golang/crconfig/deliveryservice.go @@ -145,7 +145,7 @@ FROM deliveryservice AS d INNER JOIN type AS t ON t.id = d.type LEFT OUTER JOIN profile AS p ON p.id = d.profile WHERE d.cdn_id = (select id FROM cdn WHERE name = $1) -AND d.active = true +AND d.active = 'ACTIVE' ` q += fmt.Sprintf(" and t.name != '%s'", tc.DSTypeAnyMap) rows, err := tx.Query(q, cdn) @@ -465,7 +465,7 @@ from staticdnsentry as e inner join deliveryservice as d on d.id = e.deliveryservice inner join type as t on t.id = e.type where d.cdn_id = (select id from cdn where name = $1) -and d.active = true +and d.active = 'ACTIVE' ` rows, err := tx.Query(q, cdn) if err != nil { @@ -500,7 +500,7 @@ inner join deliveryservice as d on d.id = dr.deliveryservice inner join type as t on t.id = r.type inner join type as dt on dt.id = d.type where d.cdn_id = (select id from cdn where name = $1) -and d.active = true +and d.active = 'ACTIVE' order by dr.set_number asc ` rows, err := tx.Query(q, cdn) diff --git a/traffic_ops/traffic_ops_golang/crconfig/servers.go b/traffic_ops/traffic_ops_golang/crconfig/servers.go index 16b52ab285..9127939242 100644 --- a/traffic_ops/traffic_ops_golang/crconfig/servers.go +++ b/traffic_ops/traffic_ops_golang/crconfig/servers.go @@ -274,7 +274,7 @@ inner join deliveryservice_regex as dsr on dsr.regex = r.id inner join deliveryservice as ds on ds.id = dsr.deliveryservice inner join type as dt on dt.id = ds.type where ds.cdn_id = (select id from cdn where name = $1) -and ds.active = true` + +and ds.active = 'ACTIVE'` + fmt.Sprintf(" and dt.name != '%s' ", tc.DSTypeAnyMap) + ` and rt.name = 'HOST_REGEXP' order by dsr.set_number asc diff --git a/traffic_ops/traffic_ops_golang/monitoring/monitoring.go b/traffic_ops/traffic_ops_golang/monitoring/monitoring.go index d9be7e5eaa..492653b4b2 100644 --- a/traffic_ops/traffic_ops_golang/monitoring/monitoring.go +++ b/traffic_ops/traffic_ops_golang/monitoring/monitoring.go @@ -502,7 +502,7 @@ func getDeliveryServices(tx *sql.Tx, cdnName string) ([]DeliveryService, error) JOIN cdn ON cdn.id = ds.cdn_id JOIN deliveryservice_regex dsr ON dsr.deliveryservice = ds.id JOIN regex r ON r.id = dsr.regex - WHERE ds.active = true + WHERE ds.active = 'ACTIVE' AND cdn.name=$1 AND r.type = (SELECT id FROM type WHERE name = 'HOST_REGEXP') GROUP BY ds.xml_id, ds.global_max_tps, ds.xml_id, ds.global_max_mbps, t.name, ds.topology diff --git a/traffic_ops/traffic_ops_golang/server/servers.go b/traffic_ops/traffic_ops_golang/server/servers.go index f1a827a278..3a5615ffdf 100644 --- a/traffic_ops/traffic_ops_golang/server/servers.go +++ b/traffic_ops/traffic_ops_golang/server/servers.go @@ -2094,7 +2094,7 @@ FROM deliveryservice_server dss JOIN server s ON dss.server = s.id JOIN type t ON s.type = t.id JOIN deliveryservice ds ON dss.deliveryservice = ds.id -WHERE t.name LIKE $1 AND ds.active +WHERE t.name LIKE $1 AND ds.active = 'ACTIVE' GROUP BY ds.id, ds.multi_site_origin, ds.topology HAVING COUNT(dss.server) = 1 AND $2 = ANY(ARRAY_AGG(dss.server)); ` diff --git a/traffic_ops/traffic_ops_golang/server/servers_assignment.go b/traffic_ops/traffic_ops_golang/server/servers_assignment.go index 0107a9db89..f7edcaddea 100644 --- a/traffic_ops/traffic_ops_golang/server/servers_assignment.go +++ b/traffic_ops/traffic_ops_golang/server/servers_assignment.go @@ -74,7 +74,7 @@ WHERE d.id IN ( FROM deliveryservice_server dss INNER JOIN deliveryservice d ON d.id = dss.deliveryservice WHERE dss.server=$1 - AND d.active + AND d.active = 'ACTIVE' ) AND NOT (dss.deliveryservice = ANY($2::BIGINT[])) AND (st.name = '` + string(tc.CacheStatusOnline) + `' OR st.name = '` + string(tc.CacheStatusReported) + `') From b97a58e5838726221ee364af6abd2f83f4db5021 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Wed, 28 Sep 2022 10:48:41 -0600 Subject: [PATCH 25/48] Fix bug where ID query param is considered invalid when not provided --- .../traffic_ops_golang/deliveryservice/deliveryservices.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go index 6d0b25d831..8b92e8ab1d 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go @@ -1335,7 +1335,9 @@ func readGetDeliveryServices(h http.Header, params map[string]string, tx *sqlx.T var maxTime time.Time var runSecond bool // TODO: is this necessary? - params["id"] = strings.TrimSuffix(params["id"], ".json") + if idParam, ok := params["id"]; ok { + params["id"] = strings.TrimSuffix(idParam, ".json") + } if _, ok := params["orderby"]; !ok { params["orderby"] = "xml_id" } From ec8d259f6798b0459d797a72bf5aa0e194577c67 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Wed, 28 Sep 2022 10:49:27 -0600 Subject: [PATCH 26/48] Update tests for new model --- .../deliveryservice/deliveryservices_test.go | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices_test.go b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices_test.go index 7bfaeaa876..68eced8730 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices_test.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices_test.go @@ -30,6 +30,7 @@ import ( "github.com/apache/trafficcontrol/lib/go-tc" "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/jmoiron/sqlx" @@ -63,20 +64,20 @@ func TestGetDetails(t *testing.T) { if code != http.StatusOK { t.Fatalf("expected status OK 200, but got %d", code) } - if oldDetails.OldOrgServerFqdn == nil { + if oldDetails.OldOrgServerFQDN == nil { t.Fatalf("old org server fqdn is nil") } - if *oldDetails.OldOrgServerFqdn != "http://123.34.32.21:9090" { - t.Errorf("expected old org server fqdn to be http://123.34.32.21:9090, but got %v", *oldDetails.OldOrgServerFqdn) + if *oldDetails.OldOrgServerFQDN != "http://123.34.32.21:9090" { + t.Errorf("expected old org server fqdn to be http://123.34.32.21:9090, but got %v", *oldDetails.OldOrgServerFQDN) } if oldDetails.OldRoutingName != "cdn" { t.Errorf("expected old routing name to be cdn, but got %v", oldDetails.OldRoutingName) } - if oldDetails.OldCdnName != "foo" { - t.Errorf("expected old cdn name to be foo, but got %v", oldDetails.OldCdnName) + if oldDetails.OldCDNName != "foo" { + t.Errorf("expected old cdn name to be foo, but got %v", oldDetails.OldCDNName) } - if oldDetails.OldCdnId != 1 { - t.Errorf("expected old cdn id to be 1, but got %v", oldDetails.OldCdnId) + if oldDetails.OldCDNID != 1 { + t.Errorf("expected old cdn id to be 1, but got %v", oldDetails.OldCDNID) } if *oldDetails.OldSSLKeyVersion != 1 { t.Errorf("expected old ssl_key_version to be 1, but got %v", oldDetails.OldSSLKeyVersion) @@ -264,7 +265,7 @@ func TestReadGetDeliveryServices(t *testing.T) { key string value driver.Value }{ - {"active", true}, + {"active", "ACTIVE"}, {"anonymous_blocking_enabled", false}, {"ccr_dns_ttl", nil}, {"cdn_id", 1}, @@ -352,8 +353,9 @@ func TestReadGetDeliveryServices(t *testing.T) { regexRows := sqlmock.NewRows([]string{"ds_name", "type", "pattern", "set_number"}) regexRows.AddRow("demo1", "hostregexp", "", 0) mock.ExpectQuery("SELECT ds\\.xml_id as ds_name, t\\.name as type, r\\.pattern, COALESCE\\(dsr\\.set_number, 0\\) FROM regex").WillReturnRows(regexRows) + mock.ExpectCommit() - _, userErr, sysErr, _, _ := readGetDeliveryServices(nil, nil, db.MustBegin(), &u, false) + _, userErr, sysErr, _, _ := readGetDeliveryServices(nil, nil, db.MustBegin(), &u, false, api.Version{Major: 4, Minor: 1}) if userErr != nil { t.Errorf("Unexpected user error reading Delivery Services: %v", userErr) } From 085119f5ec6f74fdfde4c877700e0ee3e9a7c6d3 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Thu, 29 Sep 2022 10:12:22 -0600 Subject: [PATCH 27/48] Fix #7094 --- lib/go-tc/deliveryservice_requests.go | 2 -- lib/go-tc/deliveryservices.go | 2 +- traffic_ops/testing/api/v4/tc-fixtures.json | 2 +- .../traffic_ops_golang/deliveryservice/deliveryservices.go | 4 ---- 4 files changed, 2 insertions(+), 8 deletions(-) diff --git a/lib/go-tc/deliveryservice_requests.go b/lib/go-tc/deliveryservice_requests.go index e2bfbd7419..0c6ae2662c 100644 --- a/lib/go-tc/deliveryservice_requests.go +++ b/lib/go-tc/deliveryservice_requests.go @@ -27,7 +27,6 @@ import ( "strings" "time" - "github.com/apache/trafficcontrol/lib/go-log" "github.com/apache/trafficcontrol/lib/go-util" validation "github.com/go-ozzo/ozzo-validation" @@ -561,7 +560,6 @@ func (r RequestStatus) MarshalJSON() ([]byte, error) { // Value implements driver.Valuer. func (r *RequestStatus) Value() (driver.Value, error) { v, err := json.Marshal(r) - log.Debugf("value is %v; err is %v", v, err) v = []byte(strings.Trim(string(v), `"`)) return v, err } diff --git a/lib/go-tc/deliveryservices.go b/lib/go-tc/deliveryservices.go index e9a9c6f658..b3a999ddf6 100644 --- a/lib/go-tc/deliveryservices.go +++ b/lib/go-tc/deliveryservices.go @@ -1643,7 +1643,7 @@ func (ds DeliveryServiceV4) Upgrade() DeliveryServiceV5 { CheckPath: copyStringIfNotNil(ds.CheckPath), ConsistentHashQueryParams: make([]string, len(ds.ConsistentHashQueryParams)), ConsistentHashRegex: copyStringIfNotNil(ds.ConsistentHashRegex), - DeepCachingType: DeepCachingType(coalesceString((*string)(ds.DeepCachingType), string(DeepCachingTypeInvalid))), + DeepCachingType: DeepCachingType(coalesceString((*string)(ds.DeepCachingType), "")), DisplayName: coalesceString(ds.DisplayName, ""), DNSBypassCNAME: copyStringIfNotNil(ds.DNSBypassCNAME), DNSBypassIP: copyStringIfNotNil(ds.DNSBypassIP), diff --git a/traffic_ops/testing/api/v4/tc-fixtures.json b/traffic_ops/testing/api/v4/tc-fixtures.json index f0d73e79c5..6e9b6eaa6e 100644 --- a/traffic_ops/testing/api/v4/tc-fixtures.json +++ b/traffic_ops/testing/api/v4/tc-fixtures.json @@ -907,7 +907,7 @@ "regexRemap": null, "regionalGeoBlocking": false, "remapText": null, - "routingName": "cdn", + "routingName": "ccr-ds1", "signed": false, "signingAlgorithm": null, "sslKeyVersion": 0, diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go index 8b92e8ab1d..6aa5f52a5a 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go @@ -1463,7 +1463,6 @@ func Validate(tx *sql.Tx, ds *tc.DeliveryServiceV5) error { noSpaces := validation.NewStringRule(tovalidate.NoSpaces, "cannot contain spaces") noLineBreaks := validation.NewStringRule(tovalidate.NoLineBreaks, "cannot contain line breaks") errs := tovalidate.ToErrors(validation.Errors{ - "active": validation.Validate(ds.Active, validation.NotNil), "cdnId": validation.Validate(ds.CDNID, validation.Required), "deepCachingType": validation.Validate(ds.DeepCachingType, neverOrAlways), "displayName": validation.Validate(ds.DisplayName, validation.Required, validation.Length(1, 48)), @@ -2336,9 +2335,6 @@ func sanitize(ds *tc.DeliveryServiceV5) { if ds.MaxOriginConnections == nil || *ds.MaxOriginConnections < 0 { ds.MaxOriginConnections = util.IntPtr(0) } - if ds.DeepCachingType == tc.DeepCachingTypeInvalid { - ds.DeepCachingType = tc.DeepCachingTypeNever - } ds.DeepCachingType = tc.DeepCachingTypeFromString(string(ds.DeepCachingType)) if ds.MaxRequestHeaderBytes == nil { ds.MaxRequestHeaderBytes = util.IntPtr(tc.DefaultMaxRequestHeaderBytes) From 16cb079f34ae8ab256ba56a7f5a02246e214d5f2 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Thu, 29 Sep 2022 10:13:19 -0600 Subject: [PATCH 28/48] Fix DSR update using legacy structures to store requested/original --- .../api/v4/deliveryservice_requests_test.go | 6 +-- .../deliveryservice/request/requests.go | 42 +++++++++++-------- 2 files changed, 28 insertions(+), 20 deletions(-) diff --git a/traffic_ops/testing/api/v4/deliveryservice_requests_test.go b/traffic_ops/testing/api/v4/deliveryservice_requests_test.go index 042296e420..9f60632ce4 100644 --- a/traffic_ops/testing/api/v4/deliveryservice_requests_test.go +++ b/traffic_ops/testing/api/v4/deliveryservice_requests_test.go @@ -331,7 +331,7 @@ func GetDeliveryServiceRequestId(t *testing.T, xmlId string) func() int { opts := client.NewRequestOptions() opts.QueryParameters.Set("xmlId", xmlId) resp, _, err := TOSession.GetDeliveryServiceRequests(opts) - assert.RequireNoError(t, err, "Get Delivery Service Requests failed with error: %v", err) + assert.RequireNoError(t, err, "Get Delivery Service Request '%s' failed with error: %v", xmlId, err) assert.RequireGreaterOrEqual(t, len(resp.Response), 1, "Expected delivery service requests response object length of atleast 1, but got %d", len(resp.Response)) assert.RequireNotNil(t, resp.Response[0].ID, "Expected id to not be nil") return *resp.Response[0].ID @@ -381,8 +381,8 @@ func DeleteTestDeliveryServiceRequests(t *testing.T) { resp, _, err := TOSession.GetDeliveryServiceRequests(client.RequestOptions{}) assert.NoError(t, err, "Cannot get Delivery Service Requests: %v - alerts: %+v", err, resp.Alerts) for _, request := range resp.Response { - alert, _, err := TOSession.DeleteDeliveryServiceRequest(*request.ID, client.RequestOptions{}) - assert.NoError(t, err, "Cannot delete Delivery Service Request #%d: %v - alerts: %+v", request.ID, err, alert.Alerts) + _, _, err := TOSession.DeleteDeliveryServiceRequest(*request.ID, client.RequestOptions{}) + assert.NoError(t, err, "Cannot delete Delivery Service Request #%d: %v", request.ID, err) // Retrieve the DeliveryServiceRequest to see if it got deleted opts := client.NewRequestOptions() diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go b/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go index 2967957a7a..f56d735f60 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go @@ -448,7 +448,7 @@ func createV4(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (result return } if len(dsr.Original.TLSVersions) < 1 { - dsr.Original.TLSVersions = nil + upgraded.Original.TLSVersions = nil } } if dsr.Requested != nil { @@ -457,7 +457,7 @@ func createV4(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (result return } if len(dsr.Requested.TLSVersions) < 1 { - dsr.Requested.TLSVersions = nil + upgraded.Requested.TLSVersions = nil } } errCode, userErr, sysErr := insert(&upgraded, inf) @@ -466,6 +466,8 @@ func createV4(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (result return } + dsr = upgraded.Downgrade() + w.Header().Set("Location", fmt.Sprintf("/api/%d.%d/deliveryservice_requests/%d", inf.Version.Major, inf.Version.Minor, *dsr.ID)) w.WriteHeader(http.StatusCreated) api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Delivery Service request created", dsr) @@ -660,10 +662,15 @@ func Delete(w http.ResponseWriter, r *http.Request) { } var resp interface{} - if inf.Version.Major >= 4 { + switch inf.Version.Major { + default: + fallthrough + case 5: resp = dsr - } else { + case 4: resp = dsr.Downgrade() + case 3: + resp = dsr.Downgrade().Downgrade() } api.WriteRespAlertObj(w, r, tc.SuccessLevel, fmt.Sprintf("Delivery Service Request #%d deleted", inf.IntParams["id"]), resp) @@ -713,24 +720,24 @@ func putV40(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (result ds return } - dsr.LastEditedBy = inf.User.UserName - dsr.LastEditedByID = new(int) - *dsr.LastEditedByID = inf.User.ID + upgraded.LastEditedBy = inf.User.UserName + upgraded.LastEditedByID = new(int) + *upgraded.LastEditedByID = inf.User.ID - if dsr.Requested != nil && len(dsr.Requested.TLSVersions) < 1 { - dsr.Requested.TLSVersions = nil + if upgraded.Requested != nil && len(upgraded.Requested.TLSVersions) < 1 { + upgraded.Requested.TLSVersions = nil } - if dsr.Original != nil && len(dsr.Original.TLSVersions) < 1 { - dsr.Original.TLSVersions = nil + if upgraded.Original != nil && len(upgraded.Original.TLSVersions) < 1 { + upgraded.Original.TLSVersions = nil } args := []interface{}{ - dsr.AssigneeID, - dsr.ChangeType, + upgraded.AssigneeID, + upgraded.ChangeType, inf.User.ID, - dsr.Requested, - dsr.Original, - dsr.Status, + upgraded.Requested, + upgraded.Original, + upgraded.Status, inf.IntParams["id"], } if dsr.Original != nil { @@ -745,7 +752,7 @@ func putV40(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (result ds return } } - if err := tx.QueryRow(updateQuery, args...).Scan(&dsr.CreatedAt, &dsr.LastUpdated); err != nil { + if err := tx.QueryRow(updateQuery, args...).Scan(&upgraded.CreatedAt, &upgraded.LastUpdated); err != nil { var userErr, sysErr error var errCode int if errors.Is(err, sql.ErrNoRows) { @@ -758,6 +765,7 @@ func putV40(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (result ds api.HandleErr(w, r, tx, errCode, userErr, sysErr) return } + dsr = upgraded.Downgrade() dsr.SetXMLID() if dsr.ChangeType == tc.DSRChangeTypeUpdate { From 4f1c3809a1f31035ae6c48438051d28b30a67f37 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Thu, 29 Sep 2022 11:28:47 -0600 Subject: [PATCH 29/48] Add type information to assert package comparator --- traffic_ops/testing/api/assert/assertions.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/traffic_ops/testing/api/assert/assertions.go b/traffic_ops/testing/api/assert/assertions.go index 6cce96c415..1267cf9c5f 100644 --- a/traffic_ops/testing/api/assert/assertions.go +++ b/traffic_ops/testing/api/assert/assertions.go @@ -76,7 +76,7 @@ func Error(t *testing.T, err error, msgAndArgs ...interface{}) bool { func Exactly(t *testing.T, a, b interface{}, msgAndArgs ...interface{}) bool { t.Helper() if !reflect.DeepEqual(a, b) { - msg := failureOutput(fmt.Sprintf("Not exactly equal. Expected: %v Actual: %v", a, b), msgAndArgs...) + msg := failureOutput(fmt.Sprintf("Not exactly equal. Expected: %v (%T) Actual: %v (%T)", a, a, b, b), msgAndArgs...) t.Error(msg) return false } From 0ae3aae733c9b9469ad0b3545a8963638ba3c5a4 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Thu, 29 Sep 2022 13:01:44 -0600 Subject: [PATCH 30/48] Update DS methods of client (and associated tests) --- .../v5/cachegroupsdeliveryservices_test.go | 8 +- .../testing/api/v5/cdn_dnsseckeys_test.go | 5 +- traffic_ops/testing/api/v5/cdn_locks_test.go | 4 +- .../api/v5/deliveryservices_keys_test.go | 154 +++++++++--------- .../testing/api/v5/deliveryservices_test.go | 119 ++++++-------- .../api/v5/deliveryserviceservers_test.go | 5 +- traffic_ops/testing/api/v5/tc-fixtures.json | 84 +++++----- .../testing/api/v5/traffic_control_test.go | 2 +- traffic_ops/v5-client/deliveryservice.go | 36 ++-- 9 files changed, 197 insertions(+), 220 deletions(-) diff --git a/traffic_ops/testing/api/v5/cachegroupsdeliveryservices_test.go b/traffic_ops/testing/api/v5/cachegroupsdeliveryservices_test.go index db7ffc5117..dd16737d7f 100644 --- a/traffic_ops/testing/api/v5/cachegroupsdeliveryservices_test.go +++ b/traffic_ops/testing/api/v5/cachegroupsdeliveryservices_test.go @@ -131,12 +131,8 @@ func setInactive(t *testing.T, dsID int) { assert.RequireEqual(t, len(resp.Response), 1, "Expected exactly one Delivery Service to exist with ID %d, found: %d", dsID, len(resp.Response)) ds := resp.Response[0] - if ds.Active == nil { - t.Errorf("Deliver Service #%d had null or undefined 'active'", dsID) - ds.Active = new(bool) - } - if *ds.Active { - *ds.Active = false + if ds.Active == tc.DSActiveStateActive { + ds.Active = tc.DSActiveStateInactive _, _, err = TOSession.UpdateDeliveryService(dsID, ds, client.RequestOptions{}) assert.NoError(t, err, "Failed to set Delivery Service #%d to inactive: %v", dsID, err) } diff --git a/traffic_ops/testing/api/v5/cdn_dnsseckeys_test.go b/traffic_ops/testing/api/v5/cdn_dnsseckeys_test.go index daee11cb24..dabba591a7 100644 --- a/traffic_ops/testing/api/v5/cdn_dnsseckeys_test.go +++ b/traffic_ops/testing/api/v5/cdn_dnsseckeys_test.go @@ -141,8 +141,7 @@ func GenerateDNSSECKeys(t *testing.T) { customDS := getCustomDS(cdn.ID, types.Response[0].ID, dsXMLID, "cdn", "https://testdnssecgen.example.com", dsXMLID) ds, _, err := TOSession.CreateDeliveryService(customDS, client.RequestOptions{}) assert.NoError(t, err, "Unexpected error creating Delivery Service: %v - alerts: %+v", err, ds.Alerts) - assert.RequireEqual(t, len(ds.Response), 1, "Expected creating a Delivery Service to create exactly one Delivery Service, Traffic Ops returned: %d", len(ds.Response)) - assert.RequireNotNil(t, ds.Response[0].ID, nil, "Traffic Ops returned a representation for a created Delivery Service with null or undefined ID") + assert.RequireNotNil(t, ds.Response.ID, nil, "Traffic Ops returned a representation for a created Delivery Service with null or undefined ID") res, _, err = TOSession.GetCDNDNSSECKeys(firstCDN.Name, client.RequestOptions{}) assert.RequireNoError(t, err, "Unexpected error getting CDN DNSSEC keys: %v - alerts: %+v", err, res.Alerts) @@ -150,7 +149,7 @@ func GenerateDNSSECKeys(t *testing.T) { if _, ok := res.Response[dsXMLID]; !ok { t.Error("after creating a new delivery service for a DNSSEC-enabled CDN - expected: DNSSEC keys to be found for the delivery service, actual: no DNSSEC keys found for the delivery service") } - alerts, _, err := TOSession.DeleteDeliveryService(*ds.Response[0].ID, client.RequestOptions{}) + alerts, _, err := TOSession.DeleteDeliveryService(*ds.Response.ID, client.RequestOptions{}) assert.NoError(t, err, "Unexpected error deleting Delivery Service: %v - alerts: %+v", err, alerts.Alerts) delResp, _, err := TOSession.DeleteCDNDNSSECKeys(firstCDN.Name, client.RequestOptions{}) diff --git a/traffic_ops/testing/api/v5/cdn_locks_test.go b/traffic_ops/testing/api/v5/cdn_locks_test.go index 47011b8d82..2e99965b7e 100644 --- a/traffic_ops/testing/api/v5/cdn_locks_test.go +++ b/traffic_ops/testing/api/v5/cdn_locks_test.go @@ -592,7 +592,7 @@ func TestCDNLocks(t *testing.T) { } }, "DELIVERY SERVICE POST": func(t *testing.T) { - ds := tc.DeliveryServiceV4{} + var ds tc.DeliveryServiceV5 err = json.Unmarshal(dat, &ds) assert.NoError(t, err, "Error occurred when unmarshalling request body: %v", err) resp, reqInf, err := testCase.ClientSession.CreateDeliveryService(ds, testCase.RequestOpts) @@ -601,7 +601,7 @@ func TestCDNLocks(t *testing.T) { } }, "DELIVERY SERVICE PUT": func(t *testing.T) { - ds := tc.DeliveryServiceV4{} + var ds tc.DeliveryServiceV5 err = json.Unmarshal(dat, &ds) assert.NoError(t, err, "Error occurred when unmarshalling request body: %v", err) resp, reqInf, err := testCase.ClientSession.UpdateDeliveryService(testCase.EndpointID(), ds, testCase.RequestOpts) diff --git a/traffic_ops/testing/api/v5/deliveryservices_keys_test.go b/traffic_ops/testing/api/v5/deliveryservices_keys_test.go index 207f8a7fc2..3b17f1450d 100644 --- a/traffic_ops/testing/api/v5/deliveryservices_keys_test.go +++ b/traffic_ops/testing/api/v5/deliveryservices_keys_test.go @@ -68,30 +68,29 @@ func createBlankCDN(cdnName string, t *testing.T) tc.CDN { return cdns.Response[0] } -func cleanUp(t *testing.T, ds tc.DeliveryServiceV4, oldCDNID int, newCDNID int, sslKeyVersions []string) { - if ds.ID == nil || ds.XMLID == nil { - t.Error("Cannot clean up Delivery Service with nil ID and/or XMLID") +func cleanUp(t *testing.T, ds tc.DeliveryServiceV5, oldCDNID int, newCDNID int, sslKeyVersions []string) { + if ds.ID == nil { + t.Error("Cannot clean up Delivery Service with nil ID") return } - xmlid := *ds.XMLID id := *ds.ID opts := client.NewRequestOptions() for _, version := range sslKeyVersions { opts.QueryParameters.Set("version", version) - resp, _, err := TOSession.DeleteDeliveryServiceSSLKeys(xmlid, opts) - assert.NoError(t, err, "Unexpected error deleting Delivery Service SSL Keys: %v - alerts: %+v", err, resp.Alerts) + _, _, err := TOSession.DeleteDeliveryServiceSSLKeys(ds.XMLID, opts) + assert.NoError(t, err, "Unexpected error deleting Delivery Service SSL Keys: %v", err) } - resp, _, err := TOSession.DeleteDeliveryService(id, client.RequestOptions{}) - assert.NoError(t, err, "Unexpected error deleting Delivery Service '%s' (#%d) during cleanup: %v - alerts: %+v", xmlid, id, err, resp.Alerts) + _, _, err := TOSession.DeleteDeliveryService(id, client.RequestOptions{}) + assert.NoError(t, err, "Unexpected error deleting Delivery Service '%s' (#%d) during cleanup: %v", ds.XMLID, id, err) if oldCDNID != -1 { - resp2, _, err := TOSession.DeleteCDN(oldCDNID, client.RequestOptions{}) - assert.NoError(t, err, "Unexpected error deleting CDN (#%d) during cleanup: %v - alerts: %+v", oldCDNID, err, resp2.Alerts) + _, _, err := TOSession.DeleteCDN(oldCDNID, client.RequestOptions{}) + assert.NoError(t, err, "Unexpected error deleting CDN (#%d) during cleanup: %v", oldCDNID, err) } if newCDNID != -1 { - resp2, _, err := TOSession.DeleteCDN(newCDNID, client.RequestOptions{}) - assert.NoError(t, err, "Unexpected error deleting CDN (#%d) during cleanup: %v - alerts: %+v", newCDNID, err, resp2.Alerts) + _, _, err := TOSession.DeleteCDN(newCDNID, client.RequestOptions{}) + assert.NoError(t, err, "Unexpected error deleting CDN (#%d) during cleanup: %v", newCDNID, err) } } @@ -121,30 +120,31 @@ func cleanUp(t *testing.T, ds tc.DeliveryServiceV4, oldCDNID int, newCDNID int, // // BUT, will ALWAYS have nil MaxRequestHeaderBytes. // Note that the Tenant is hard-coded to #1. -func getCustomDS(cdnID, typeID int, displayName, routingName, orgFQDN, dsID string) tc.DeliveryServiceV4 { - customDS := tc.DeliveryServiceV4{} - customDS.Active = util.BoolPtr(true) - customDS.CDNID = util.IntPtr(cdnID) - customDS.DSCP = util.IntPtr(0) - customDS.DisplayName = util.StrPtr(displayName) - customDS.RoutingName = util.StrPtr(routingName) - customDS.GeoLimit = util.IntPtr(0) - customDS.GeoProvider = util.IntPtr(0) - customDS.IPV6RoutingEnabled = util.BoolPtr(false) - customDS.InitialDispersion = util.IntPtr(1) - customDS.LogsEnabled = util.BoolPtr(true) - customDS.MissLat = util.FloatPtr(0) - customDS.MissLong = util.FloatPtr(0) - customDS.MultiSiteOrigin = util.BoolPtr(false) - customDS.OrgServerFQDN = util.StrPtr(orgFQDN) - customDS.Protocol = util.IntPtr(2) - customDS.QStringIgnore = util.IntPtr(0) - customDS.RangeRequestHandling = util.IntPtr(0) - customDS.RegionalGeoBlocking = util.BoolPtr(false) - customDS.TenantID = util.IntPtr(1) - customDS.TypeID = util.IntPtr(typeID) - customDS.XMLID = util.StrPtr(dsID) - customDS.MaxRequestHeaderBytes = nil +func getCustomDS(cdnID, typeID int, displayName, routingName, orgFQDN, dsID string) tc.DeliveryServiceV5 { + customDS := tc.DeliveryServiceV5{ + Active: tc.DSActiveStatePrimed, + CDNID: cdnID, + DSCP: 0, + DisplayName: displayName, + RoutingName: routingName, + GeoLimit: 0, + GeoProvider: 0, + IPV6RoutingEnabled: util.BoolPtr(false), + InitialDispersion: util.IntPtr(1), + LogsEnabled: true, + MissLat: util.FloatPtr(0), + MissLong: util.FloatPtr(0), + MultiSiteOrigin: false, + OrgServerFQDN: util.StrPtr(orgFQDN), + Protocol: util.IntPtr(2), + QStringIgnore: util.IntPtr(0), + RangeRequestHandling: util.IntPtr(0), + RegionalGeoBlocking: false, + TenantID: 1, + TypeID: typeID, + XMLID: dsID, + MaxRequestHeaderBytes: nil, + } return customDS } @@ -162,9 +162,8 @@ func DeleteCDNOldSSLKeys(t *testing.T) { resp, _, err := TOSession.CreateDeliveryService(customDS, client.RequestOptions{}) assert.RequireNoError(t, err, "Unexpected error creating a Delivery Service: %v - alerts: %+v", err, resp.Alerts) - assert.RequireEqual(t, len(resp.Response), 1, "Expected Delivery Service creation to return exactly one Delivery Service, got: %d", len(resp.Response)) - ds := resp.Response[0] + ds := resp.Response assert.RequireNotNil(t, ds.XMLID, "Traffic Ops returned a representation for a Delivery Service with null or undefined XMLID") ds.CDNName = &cdn.Name @@ -176,8 +175,8 @@ func DeleteCDNOldSSLKeys(t *testing.T) { Country: util.StrPtr("CO"), State: util.StrPtr("ST"), } - genResp, _, err := TOSession.GenerateSSLKeysForDS(*ds.XMLID, *ds.CDNName, sslKeyRequestFields, client.RequestOptions{}) - assert.RequireNoError(t, err, "Unexpected error generaing SSL Keys for Delivery Service '%s': %v - alerts: %+v", *ds.XMLID, err, genResp.Alerts) + _, _, err = TOSession.GenerateSSLKeysForDS(ds.XMLID, *ds.CDNName, sslKeyRequestFields, client.RequestOptions{}) + assert.RequireNoError(t, err, "Unexpected error generaing SSL Keys for Delivery Service '%s': %v", ds.XMLID, err) defer cleanUp(t, ds, cdn.ID, -1, []string{"1"}) @@ -185,16 +184,15 @@ func DeleteCDNOldSSLKeys(t *testing.T) { customDS2 := getCustomDS(cdn.ID, types.Response[0].ID, "displayName2", "routingName2", "https://test2.com", "dsID2") resp, _, err = TOSession.CreateDeliveryService(customDS2, client.RequestOptions{}) - assert.RequireNoError(t, err, "Unexpected error creating a Delivery Service: %v - alerts: %+v", err, resp.Alerts) - assert.RequireEqual(t, len(resp.Response), 1, "Expected Delivery Service creation to return exactly one Delivery Service, got: %d", len(resp.Response)) + assert.RequireNoError(t, err, "Unexpected error creating a Delivery Service: %v", err) - ds2 := resp.Response[0] + ds2 := resp.Response assert.RequireNotNil(t, ds2.XMLID, "Traffic Ops returned a representation for a Delivery Service with null or undefined XMLID") ds2.CDNName = &cdn.Name sslKeyRequestFields.HostName = util.StrPtr("*.test2.com") - genResp, _, err = TOSession.GenerateSSLKeysForDS(*ds2.XMLID, *ds2.CDNName, sslKeyRequestFields, client.RequestOptions{}) - assert.RequireNoError(t, err, "Unexpected error generaing SSL Keys for Delivery Service '%s': %v - alerts: %+v", *ds2.XMLID, err, genResp.Alerts) + _, _, err = TOSession.GenerateSSLKeysForDS(ds2.XMLID, *ds2.CDNName, sslKeyRequestFields, client.RequestOptions{}) + assert.RequireNoError(t, err, "Unexpected error generaing SSL Keys for Delivery Service '%s': %v", ds2.XMLID, err) var cdnKeys []tc.CDNSSLKeys for tries := 0; tries < 5; tries++ { @@ -249,13 +247,12 @@ func DeliveryServiceSSLKeys(t *testing.T) { resp, _, err := TOSession.CreateDeliveryService(customDS, client.RequestOptions{}) assert.RequireNoError(t, err, "Unexpected error creating a Delivery Service: %v - alerts: %+v", err, resp.Alerts) - assert.RequireEqual(t, len(resp.Response), 1, "Expected Delivery Service creation to return exactly one Delivery Service, got: %d", len(resp.Response)) - ds := resp.Response[0] + ds := resp.Response assert.RequireNotNil(t, ds.XMLID, "Traffic Ops returned a representation for a Delivery Service with null or undefined XMLID") ds.CDNName = &cdn.Name - genResp, _, err := TOSession.GenerateSSLKeysForDS(*ds.XMLID, *ds.CDNName, tc.SSLKeyRequestFields{ + genResp, _, err := TOSession.GenerateSSLKeysForDS(ds.XMLID, *ds.CDNName, tc.SSLKeyRequestFields{ BusinessUnit: util.StrPtr("BU"), City: util.StrPtr("CI"), Organization: util.StrPtr("OR"), @@ -263,7 +260,7 @@ func DeliveryServiceSSLKeys(t *testing.T) { Country: util.StrPtr("CO"), State: util.StrPtr("ST"), }, client.RequestOptions{}) - assert.RequireNoError(t, err, "Unexpected error generating SSL Keys for Delivery Service '%s': %v - alerts: %+v", *ds.XMLID, err, genResp.Alerts) + assert.RequireNoError(t, err, "Unexpected error generating SSL Keys for Delivery Service '%s': %v - alerts: %+v", ds.XMLID, err, genResp.Alerts) defer cleanUp(t, ds, cdn.ID, -1, []string{"1"}) @@ -271,7 +268,7 @@ func DeliveryServiceSSLKeys(t *testing.T) { for tries := 0; tries < 5; tries++ { time.Sleep(time.Second) var sslKeysResp tc.DeliveryServiceSSLKeysResponse - sslKeysResp, _, err = TOSession.GetDeliveryServiceSSLKeys(*ds.XMLID, client.RequestOptions{}) + sslKeysResp, _, err = TOSession.GetDeliveryServiceSSLKeys(ds.XMLID, client.RequestOptions{}) *dsSSLKey = sslKeysResp.Response if err == nil && dsSSLKey != nil { break @@ -279,7 +276,7 @@ func DeliveryServiceSSLKeys(t *testing.T) { } if err != nil || dsSSLKey == nil { - t.Fatalf("unable to get DS %s SSL key: %v", *ds.XMLID, err) + t.Fatalf("unable to get DS %s SSL key: %v", ds.XMLID, err) } if dsSSLKey.Certificate.Key == "" { t.Errorf("expected a valid key but got nothing") @@ -315,7 +312,7 @@ func DeliveryServiceSSLKeys(t *testing.T) { for tries := 0; tries < 5; tries++ { time.Sleep(time.Second) var sslKeysResp tc.DeliveryServiceSSLKeysResponse - sslKeysResp, _, err = TOSession.GetDeliveryServiceSSLKeys(*ds.XMLID, client.RequestOptions{}) + sslKeysResp, _, err = TOSession.GetDeliveryServiceSSLKeys(ds.XMLID, client.RequestOptions{}) *dsSSLKey = sslKeysResp.Response if err == nil && dsSSLKey != nil { break @@ -323,7 +320,7 @@ func DeliveryServiceSSLKeys(t *testing.T) { } if err != nil || dsSSLKey == nil { - t.Fatalf("unable to get DS %s SSL key: %v", *ds.XMLID, err) + t.Fatalf("unable to get DS %s SSL key: %v", ds.XMLID, err) } if dsSSLKey.Certificate.Key == "" { t.Errorf("expected a valid key but got nothing") @@ -345,7 +342,7 @@ func DeliveryServiceSSLKeys(t *testing.T) { for tries := 0; tries < 5; tries++ { time.Sleep(time.Second) var sslKeysResp tc.DeliveryServiceSSLKeysResponse - sslKeysResp, _, err = TOSession.GetDeliveryServiceSSLKeys(*ds.XMLID, client.RequestOptions{}) + sslKeysResp, _, err = TOSession.GetDeliveryServiceSSLKeys(ds.XMLID, client.RequestOptions{}) *dsSSLKey = sslKeysResp.Response if err == nil { break @@ -377,7 +374,7 @@ func VerifySSLKeysOnDsCreationTest(t *testing.T) { for tries := 0; tries < 5; tries++ { time.Sleep(time.Second) var sslKeysResp tc.DeliveryServiceSSLKeysResponse - sslKeysResp, _, err = TOSession.GetDeliveryServiceSSLKeys(*ds.XMLID, client.RequestOptions{}) + sslKeysResp, _, err = TOSession.GetDeliveryServiceSSLKeys(ds.XMLID, client.RequestOptions{}) *dsSSLKey = sslKeysResp.Response if err == nil && dsSSLKey != nil { break @@ -385,7 +382,7 @@ func VerifySSLKeysOnDsCreationTest(t *testing.T) { } if err != nil || dsSSLKey == nil { - t.Fatalf("unable to get DS %s SSL key: %v", *ds.XMLID, err) + t.Fatalf("unable to get DS %s SSL key: %v", ds.XMLID, err) } if dsSSLKey.Certificate.Key == "" { t.Errorf("expected a valid key but got nothing") @@ -420,16 +417,15 @@ func SSLDeliveryServiceCDNUpdateTest(t *testing.T) { resp, _, err := TOSession.CreateDeliveryService(customDS, client.RequestOptions{}) assert.RequireNoError(t, err, "Unexpected error creating a custom Delivery Service: %v - alerts: %+v", err, resp.Alerts) - assert.RequireEqual(t, len(resp.Response), 1, "Expected Delivery Service creation to create exactly one Delivery Service, Traffic Ops indicates %d were created", len(resp.Response)) - ds := resp.Response[0] + ds := resp.Response assert.NotNil(t, ds.XMLID, "Traffic Ops created a Delivery Service with null or undefined XMLID") ds.CDNName = &oldCdn.Name defer cleanUp(t, ds, oldCdn.ID, newCdn.ID, []string{"1"}) - _, _, err = TOSession.GenerateSSLKeysForDS(*ds.XMLID, *ds.CDNName, tc.SSLKeyRequestFields{ + _, _, err = TOSession.GenerateSSLKeysForDS(ds.XMLID, *ds.CDNName, tc.SSLKeyRequestFields{ BusinessUnit: util.StrPtr("BU"), City: util.StrPtr("CI"), Organization: util.StrPtr("OR"), @@ -454,13 +450,13 @@ func SSLDeliveryServiceCDNUpdateTest(t *testing.T) { newCDNKeys, _, err := TOSession.GetCDNSSLKeys(newCdn.Name, client.RequestOptions{}) assert.RequireNoError(t, err, "Unable to get cdn %v keys: %v", newCdn.Name, err) - ds.RoutingName = util.StrPtr("anothername") + ds.RoutingName = "anothername" _, _, err = TOSession.UpdateDeliveryService(*ds.ID, ds, client.RequestOptions{}) assert.RequireNotNil(t, err, "Should not be able to update delivery service (routing name) as it has ssl keys") - ds.RoutingName = util.StrPtr("routingName") + ds.RoutingName = "routingName" - ds.CDNID = &newCdn.ID + ds.CDNID = newCdn.ID ds.CDNName = &newCdn.Name _, _, err = TOSession.UpdateDeliveryService(*ds.ID, ds, client.RequestOptions{}) assert.RequireNotNil(t, err, "Should not be able to update delivery service (cdn) as it has ssl keys") @@ -481,7 +477,7 @@ func GetTestDeliveryServicesURLSignatureKeys(t *testing.T) { firstDS := testData.DeliveryServices[0] assert.RequireNotNil(t, firstDS.XMLID, "Found a Delivery Service in testing data with a null or undefined XMLID") - _, _, err := TOSession.GetDeliveryServiceURLSignatureKeys(*firstDS.XMLID, client.RequestOptions{}) + _, _, err := TOSession.GetDeliveryServiceURLSignatureKeys(firstDS.XMLID, client.RequestOptions{}) assert.RequireNoError(t, err, "Failed to get url sig keys: %v", err) } @@ -490,10 +486,10 @@ func CreateTestDeliveryServicesURLSignatureKeys(t *testing.T) { firstDS := testData.DeliveryServices[0] assert.RequireNotNil(t, firstDS.XMLID, "Found a Delivery Service in testing data with a null or undefined XMLID") - resp, _, err := TOSession.CreateDeliveryServiceURLSignatureKeys(*firstDS.XMLID, client.RequestOptions{}) + resp, _, err := TOSession.CreateDeliveryServiceURLSignatureKeys(firstDS.XMLID, client.RequestOptions{}) assert.NoError(t, err, "Unexpected error creating URL signing keys: %v - alerts: %+v", err, resp.Alerts) - firstKeys, _, err := TOSession.GetDeliveryServiceURLSignatureKeys(*firstDS.XMLID, client.RequestOptions{}) + firstKeys, _, err := TOSession.GetDeliveryServiceURLSignatureKeys(firstDS.XMLID, client.RequestOptions{}) assert.NoError(t, err, "Unexpected error getting URL signing keys: %v - alerts: %+v", err, firstKeys.Alerts) assert.GreaterOrEqual(t, len(firstKeys.Response), 1, "failed to create URL signing keys") @@ -501,10 +497,10 @@ func CreateTestDeliveryServicesURLSignatureKeys(t *testing.T) { assert.RequireEqual(t, ok, true, "Expected to find 'key0' in URL signing keys, but didn't") // Create new keys again and check that they are different - resp, _, err = TOSession.CreateDeliveryServiceURLSignatureKeys(*firstDS.XMLID, client.RequestOptions{}) + resp, _, err = TOSession.CreateDeliveryServiceURLSignatureKeys(firstDS.XMLID, client.RequestOptions{}) assert.NoError(t, err, "Unexpected error creating URL signing keys: %v - alerts: %+v", err, resp.Alerts) - secondKeys, _, err := TOSession.GetDeliveryServiceURLSignatureKeys(*firstDS.XMLID, client.RequestOptions{}) + secondKeys, _, err := TOSession.GetDeliveryServiceURLSignatureKeys(firstDS.XMLID, client.RequestOptions{}) assert.NoError(t, err, "Unexpected error getting URL signing keys: %v - alerts: %+v", err, secondKeys.Alerts) assert.GreaterOrEqual(t, len(secondKeys.Response), 0, "Failed to create url sig keys") @@ -521,7 +517,7 @@ func DeleteTestDeliveryServicesURLSignatureKeys(t *testing.T) { firstDS := testData.DeliveryServices[0] assert.RequireNotNil(t, firstDS.XMLID, "Found a Delivery Service in testing data with a null or undefined XMLID") - resp, _, err := TOSession.DeleteDeliveryServiceURLSignatureKeys(*firstDS.XMLID, client.RequestOptions{}) + resp, _, err := TOSession.DeleteDeliveryServiceURLSignatureKeys(firstDS.XMLID, client.RequestOptions{}) assert.NoError(t, err, "Unexpected error deleting URL signing keys: %v - alerts: %+v", err, resp.Alerts) } @@ -530,8 +526,8 @@ func GetTestDeliveryServicesURISigningKeys(t *testing.T) { firstDS := testData.DeliveryServices[0] assert.RequireNotNil(t, firstDS.XMLID, "Found a Delivery Service in testing data with a null or undefined XMLID") - _, _, err := TOSession.GetDeliveryServiceURISigningKeys(*firstDS.XMLID, client.RequestOptions{}) - assert.NoError(t, err, "Unexpected error getting URI signing keys for Delivery Service '%s': %v", *firstDS.XMLID, err) + _, _, err := TOSession.GetDeliveryServiceURISigningKeys(firstDS.XMLID, client.RequestOptions{}) + assert.NoError(t, err, "Unexpected error getting URI signing keys for Delivery Service '%s': %v", firstDS.XMLID, err) } const ( @@ -575,10 +571,10 @@ func CreateTestDeliveryServicesURISigningKeys(t *testing.T) { err := json.Unmarshal([]byte(keySet1), &keyset) assert.NoError(t, err, "json.UnMarshal(): expected nil error, actual: %v", err) - _, _, err = TOSession.CreateDeliveryServiceURISigningKeys(*firstDS.XMLID, keyset, client.RequestOptions{}) + _, _, err = TOSession.CreateDeliveryServiceURISigningKeys(firstDS.XMLID, keyset, client.RequestOptions{}) assert.NoError(t, err, "failed to create uri sig keys: %v", err) - firstKeysBytes, _, err := TOSession.GetDeliveryServiceURISigningKeys(*firstDS.XMLID, client.RequestOptions{}) + firstKeysBytes, _, err := TOSession.GetDeliveryServiceURISigningKeys(firstDS.XMLID, client.RequestOptions{}) assert.NoError(t, err, "Failed to get uri sig keys: %v", err) firstKeys := tc.JWKSMap{} @@ -595,10 +591,10 @@ func CreateTestDeliveryServicesURISigningKeys(t *testing.T) { err = json.Unmarshal([]byte(keySet2), &keyset2) assert.NoError(t, err, "json.UnMarshal(): expected nil error, actual: %v", err) - alerts, _, err := TOSession.CreateDeliveryServiceURISigningKeys(*firstDS.XMLID, keyset2, client.RequestOptions{}) - assert.NoError(t, err, "Unexpected error creating URI Signature Keys for Delivery Service '%s': %v - alerts: %+v", *firstDS.XMLID, err, alerts.Alerts) + alerts, _, err := TOSession.CreateDeliveryServiceURISigningKeys(firstDS.XMLID, keyset2, client.RequestOptions{}) + assert.NoError(t, err, "Unexpected error creating URI Signature Keys for Delivery Service '%s': %v - alerts: %+v", firstDS.XMLID, err, alerts.Alerts) - secondKeysBytes, _, err := TOSession.GetDeliveryServiceURISigningKeys(*firstDS.XMLID, client.RequestOptions{}) + secondKeysBytes, _, err := TOSession.GetDeliveryServiceURISigningKeys(firstDS.XMLID, client.RequestOptions{}) assert.NoError(t, err, "Failed to get uri sig keys: %v", err) secondKeys := tc.JWKSMap{} err = json.Unmarshal(secondKeysBytes, &secondKeys) @@ -624,11 +620,11 @@ func DeleteTestDeliveryServicesURISigningKeys(t *testing.T) { firstDS := testData.DeliveryServices[0] assert.RequireNotNil(t, firstDS.XMLID, "Found a Delivery Service in testing data with a null or undefined XMLID") - resp, _, err := TOSession.DeleteDeliveryServiceURISigningKeys(*firstDS.XMLID, client.RequestOptions{}) - assert.NoError(t, err, "Unexpected error deleting URI Signing keys for Delivery Service '%s': %v - alerts: %+v", *firstDS.XMLID, err, resp.Alerts) + resp, _, err := TOSession.DeleteDeliveryServiceURISigningKeys(firstDS.XMLID, client.RequestOptions{}) + assert.NoError(t, err, "Unexpected error deleting URI Signing keys for Delivery Service '%s': %v - alerts: %+v", firstDS.XMLID, err, resp.Alerts) - emptyBytes, _, err := TOSession.GetDeliveryServiceURISigningKeys(*firstDS.XMLID, client.RequestOptions{}) - assert.NoError(t, err, "Unexpected error getting URI signing keys for Delivery Service '%s': %v", *firstDS.XMLID, err) + emptyBytes, _, err := TOSession.GetDeliveryServiceURISigningKeys(firstDS.XMLID, client.RequestOptions{}) + assert.NoError(t, err, "Unexpected error getting URI signing keys for Delivery Service '%s': %v", firstDS.XMLID, err) emptyMap := make(map[string]interface{}) err = json.Unmarshal(emptyBytes, &emptyMap) diff --git a/traffic_ops/testing/api/v5/deliveryservices_test.go b/traffic_ops/testing/api/v5/deliveryservices_test.go index fcd953f628..a40f57d644 100644 --- a/traffic_ops/testing/api/v5/deliveryservices_test.go +++ b/traffic_ops/testing/api/v5/deliveryservices_test.go @@ -57,55 +57,60 @@ func TestDeliveryServices(t *testing.T) { ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"accessibleTo": {"1"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseLengthGreaterOrEqual(1)), }, - "OK when ACTIVE=TRUE": { - ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"active": {"true"}}}, + "OK when Active=ACTIVE": { + ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"active": {string(tc.DSActiveStateActive)}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseLengthGreaterOrEqual(1), - validateDSExpectedFields(map[string]interface{}{"Active": true})), + validateDSExpectedFields(map[string]interface{}{"Active": tc.DSActiveStateActive}, true)), }, - "OK when ACTIVE=FALSE": { - ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"active": {"false"}}}, + "OK when Active=PRIMED": { + ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"active": {string(tc.DSActiveStatePrimed)}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseLengthGreaterOrEqual(1), - validateDSExpectedFields(map[string]interface{}{"Active": false})), + validateDSExpectedFields(map[string]interface{}{"Active": tc.DSActiveStatePrimed}, true)), + }, + "OK when Active=INACTIVE": { + ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"active": {string(tc.DSActiveStateInactive)}}}, + Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseLengthGreaterOrEqual(1), + validateDSExpectedFields(map[string]interface{}{"Active": tc.DSActiveStateInactive}, true)), }, "OK when VALID CDN parameter": { ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"cdn": {"cdn1"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseLengthGreaterOrEqual(1), - validateDSExpectedFields(map[string]interface{}{"CDNName": "cdn1"})), + validateDSExpectedFields(map[string]interface{}{"CDNName": "cdn1"}, true)), }, "OK when VALID LOGSENABLED parameter": { ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"logsEnabled": {"false"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseLengthGreaterOrEqual(1), - validateDSExpectedFields(map[string]interface{}{"LogsEnabled": false})), + validateDSExpectedFields(map[string]interface{}{"LogsEnabled": false}, true)), }, "OK when VALID PROFILE parameter": { ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"profile": {"ATS_EDGE_TIER_CACHE"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseLengthGreaterOrEqual(1), - validateDSExpectedFields(map[string]interface{}{"ProfileName": "ATS_EDGE_TIER_CACHE"})), + validateDSExpectedFields(map[string]interface{}{"ProfileName": "ATS_EDGE_TIER_CACHE"}, true)), }, "OK when VALID SERVICECATEGORY parameter": { ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"serviceCategory": {"serviceCategory1"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseLengthGreaterOrEqual(1), - validateDSExpectedFields(map[string]interface{}{"ServiceCategory": "serviceCategory1"})), + validateDSExpectedFields(map[string]interface{}{"ServiceCategory": "serviceCategory1"}, true)), }, "OK when VALID TENANT parameter": { ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"tenant": {"tenant1"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseLengthGreaterOrEqual(1), - validateDSExpectedFields(map[string]interface{}{"Tenant": "tenant1"})), + validateDSExpectedFields(map[string]interface{}{"Tenant": "tenant1"}, true)), }, "OK when VALID TOPOLOGY parameter": { ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"topology": {"mso-topology"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseLengthGreaterOrEqual(1), - validateDSExpectedFields(map[string]interface{}{"Topology": "mso-topology"})), + validateDSExpectedFields(map[string]interface{}{"Topology": "mso-topology"}, true)), }, "OK when VALID TYPE parameter": { ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"type": {"HTTP"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseLengthGreaterOrEqual(1), - validateDSExpectedFields(map[string]interface{}{"Type": tc.DSTypeHTTP})), + validateDSExpectedFields(map[string]interface{}{"Type": string(tc.DSTypeHTTP)}, true)), }, "OK when VALID XMLID parameter": { ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"xmlId": {"ds1"}}}, Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), utils.ResponseHasLength(1), - validateDSExpectedFields(map[string]interface{}{"XMLID": "ds1"})), + validateDSExpectedFields(map[string]interface{}{"XMLID": "ds1"}, true)), }, "EMPTY RESPONSE when INVALID ACCESSIBLETO parameter": { ClientSession: TOSession, RequestOpts: client.RequestOptions{QueryParameters: url.Values{"accessibleTo": {"10000"}}}, @@ -193,17 +198,8 @@ func TestDeliveryServices(t *testing.T) { "geoLimitCountries": []string{"US", "CA"}, "xmlId": "geolimit-test", }), - Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusCreated), utils.ResponseHasLength(1), - validateDSExpectedFields(map[string]interface{}{"GeoLimitCountries": tc.GeoLimitCountriesType{"US", "CA"}})), - }, - "BAD REQUEST when using LONG DESCRIPTION 2 and 3 fields": { - ClientSession: TOSession, - RequestBody: generateDeliveryService(t, map[string]interface{}{ - "longDesc1": "long desc 1", - "longDesc2": "long desc 2", - "xmlId": "ld1-ld2-test", - }), - Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), + Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusCreated), + validateDSExpectedFields(map[string]interface{}{"GeoLimitCountries": []string{"US", "CA"}}, false)), }, "BAD REQUEST when XMLID left EMPTY": { ClientSession: TOSession, @@ -241,7 +237,7 @@ func TestDeliveryServices(t *testing.T) { "tlsVersions": []string{"1.1"}, "xmlId": "test-TLS-creation-http", }), - Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusCreated), utils.ResponseHasLength(1)), + Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusCreated)), }, "BAD REQUEST when creating DS with TENANCY NOT THE SAME AS CURRENT TENANT": { ClientSession: tenant4UserSession, @@ -249,19 +245,10 @@ func TestDeliveryServices(t *testing.T) { "tenantId": GetTenantID(t, "tenant3")(), "xmlId": "test-tenancy", }), - Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden), utils.ResponseHasLength(0)), + Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, }, "PUT": { - "BAD REQUEST when using LONG DESCRIPTION 2 and 3 fields": { - EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, - RequestBody: generateDeliveryService(t, map[string]interface{}{ - "longDesc1": "long desc 1", - "longDesc2": "long desc 2", - "xmlId": "ds1", - }), - Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), - }, "OK when VALID request": { EndpointID: GetDeliveryServiceId(t, "ds2"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ @@ -269,7 +256,7 @@ func TestDeliveryServices(t *testing.T) { "longDesc": "something different", "maxDNSAnswers": 164598, "maxOriginConnections": 100, - "active": false, + "active": tc.DSActiveStatePrimed, "displayName": "newds2displayname", "dscp": 41, "geoLimit": 1, @@ -290,11 +277,11 @@ func TestDeliveryServices(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validateDSExpectedFields(map[string]interface{}{"MaxRequestHeaderSize": 131080, "LongDesc": "something different", "MaxDNSAnswers": 164598, "MaxOriginConnections": 100, - "Active": false, "DisplayName": "newds2displayname", "DSCP": 41, "GeoLimit": 1, + "Active": tc.DSActiveStatePrimed, "DisplayName": "newds2displayname", "DSCP": 41, "GeoLimit": 1, "InitialDispersion": 2, "IPV6RoutingEnabled": false, "LogsEnabled": false, "MissLat": 42.881944, "MissLong": -88.627778, "MultiSiteOrigin": true, "OrgServerFQDN": "http://origin.example.net", "Protocol": 2, "QStringIgnore": 0, "RegionalGeoBlocking": true, - })), + }, false)), }, "BAD REQUEST when INVALID REMAP TEXT": { EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, @@ -437,7 +424,7 @@ func TestDeliveryServices(t *testing.T) { "ConsistentHashRegex": "foo", "DeepCachingType": tc.DeepCachingTypeNever, "FQPacingRate": 41, "MaxOriginConnections": 500, "SigningAlgorithm": "uri_signing", "Tenant": "tenant1", "TRRequestHeaders": "X-ooF\nX-raB", "TRResponseHeaders": "Access-Control-Max-Age: 600\nContent-Type: text/html; charset=utf-8", - })), + }, false)), }, "BAD REQUEST when INVALID COUNTRY CODE": { EndpointID: GetDeliveryServiceId(t, "ds1"), ClientSession: TOSession, @@ -498,7 +485,7 @@ func TestDeliveryServices(t *testing.T) { for method, testCases := range methodTests { t.Run(method, func(t *testing.T) { for name, testCase := range testCases { - ds := tc.DeliveryServiceV4{} + var ds tc.DeliveryServiceV5 if val, ok := testCase.RequestOpts.QueryParameters["accessibleTo"]; ok { if _, err := strconv.Atoi(val[0]); err != nil { @@ -576,16 +563,21 @@ func TestDeliveryServices(t *testing.T) { }) } -func validateDSExpectedFields(expectedResp map[string]interface{}) utils.CkReqFunc { +func validateDSExpectedFields(expectedResp map[string]interface{}, multi bool) utils.CkReqFunc { return func(t *testing.T, _ toclientlib.ReqInf, resp interface{}, _ tc.Alerts, _ error) { - dsResp := resp.([]tc.DeliveryServiceV4) + var dsResp []tc.DeliveryServiceV5 + if multi { + dsResp = resp.([]tc.DeliveryServiceV5) + } else { + dsResp = []tc.DeliveryServiceV5{resp.(tc.DeliveryServiceV5)} + } for field, expected := range expectedResp { for _, ds := range dsResp { switch field { case "Active": - assert.Equal(t, expected, *ds.Active, "Expected Active to be %v, but got %v", expected, *ds.Active) + assert.Equal(t, expected, ds.Active, "Expected Active to be %v, but got %v", expected, ds.Active) case "DeepCachingType": - assert.Equal(t, expected, *ds.DeepCachingType, "Expected DeepCachingType to be %v, but got %v", expected, *ds.DeepCachingType) + assert.Equal(t, expected, ds.DeepCachingType, "Expected DeepCachingType to be %v, but got %v", expected, ds.DeepCachingType) case "CDNName": assert.Equal(t, expected, *ds.CDNName, "Expected CDNName to be %v, but got %v", expected, *ds.CDNName) case "ConsistentHashRegex": @@ -593,13 +585,13 @@ func validateDSExpectedFields(expectedResp map[string]interface{}) utils.CkReqFu case "ConsistentHashQueryParams": assert.Exactly(t, expected, ds.ConsistentHashQueryParams, "Expected ConsistentHashQueryParams to be %v, but got %v", expected, ds.ConsistentHashQueryParams) case "DisplayName": - assert.Equal(t, expected, *ds.DisplayName, "Expected DisplayName to be %v, but got %v", expected, *ds.DisplayName) + assert.Equal(t, expected, ds.DisplayName, "Expected DisplayName to be %v, but got %v", expected, ds.DisplayName) case "DSCP": - assert.Equal(t, expected, *ds.DSCP, "Expected DSCP to be %v, but got %v", expected, *ds.DSCP) + assert.Equal(t, expected, ds.DSCP, "Expected DSCP to be %v, but got %v", expected, ds.DSCP) case "FQPacingRate": assert.Equal(t, expected, *ds.FQPacingRate, "Expected FQPacingRate to be %v, but got %v", expected, *ds.FQPacingRate) case "GeoLimit": - assert.Equal(t, expected, *ds.GeoLimit, "Expected GeoLimit to be %v, but got &v", expected, ds.GeoLimit) + assert.Equal(t, expected, ds.GeoLimit, "Expected GeoLimit to be %v, but got &v", expected, ds.GeoLimit) case "GeoLimitCountries": assert.Exactly(t, expected, ds.GeoLimitCountries, "Expected GeoLimitCountries to be %v, but got &v", expected, ds.GeoLimitCountries) case "InitialDispersion": @@ -607,9 +599,9 @@ func validateDSExpectedFields(expectedResp map[string]interface{}) utils.CkReqFu case "IPV6RoutingEnabled": assert.Equal(t, expected, *ds.IPV6RoutingEnabled, "Expected IPV6RoutingEnabled to be %v, but got &v", expected, ds.IPV6RoutingEnabled) case "LogsEnabled": - assert.Equal(t, expected, *ds.LogsEnabled, "Expected LogsEnabled to be %v, but got %v", expected, *ds.LogsEnabled) + assert.Equal(t, expected, ds.LogsEnabled, "Expected LogsEnabled to be %v, but got %v", expected, ds.LogsEnabled) case "LongDesc": - assert.Equal(t, expected, *ds.LongDesc, "Expected LongDesc to be %v, but got %v", expected, *ds.LongDesc) + assert.Equal(t, expected, ds.LongDesc, "Expected LongDesc to be %v, but got %v", expected, ds.LongDesc) case "MaxDNSAnswers": assert.Equal(t, expected, *ds.MaxDNSAnswers, "Expected MaxDNSAnswers to be %v, but got %v", expected, *ds.MaxDNSAnswers) case "MaxOriginConnections": @@ -621,7 +613,7 @@ func validateDSExpectedFields(expectedResp map[string]interface{}) utils.CkReqFu case "MissLong": assert.Equal(t, expected, *ds.MissLong, "Expected MissLong to be %v, but got %v", expected, *ds.MissLong) case "MultiSiteOrigin": - assert.Equal(t, expected, *ds.MultiSiteOrigin, "Expected MultiSiteOrigin to be %v, but got %v", expected, *ds.MultiSiteOrigin) + assert.Equal(t, expected, ds.MultiSiteOrigin, "Expected MultiSiteOrigin to be %v, but got %v", expected, ds.MultiSiteOrigin) case "OrgServerFQDN": assert.Equal(t, expected, *ds.OrgServerFQDN, "Expected OrgServerFQDN to be %v, but got %v", expected, *ds.OrgServerFQDN) case "ProfileName": @@ -631,7 +623,7 @@ func validateDSExpectedFields(expectedResp map[string]interface{}) utils.CkReqFu case "QStringIgnore": assert.Equal(t, expected, *ds.QStringIgnore, "Expected QStringIgnore to be %v, but got %v", expected, *ds.QStringIgnore) case "RegionalGeoBlocking": - assert.Equal(t, expected, *ds.RegionalGeoBlocking, "Expected QStringIgnore to be %v, but got %v", expected, *ds.RegionalGeoBlocking) + assert.Equal(t, expected, ds.RegionalGeoBlocking, "Expected QStringIgnore to be %v, but got %v", expected, ds.RegionalGeoBlocking) case "ServiceCategory": assert.Equal(t, expected, *ds.ServiceCategory, "Expected ServiceCategory to be %v, but got %v", expected, *ds.ServiceCategory) case "SigningAlgorithm": @@ -647,7 +639,7 @@ func validateDSExpectedFields(expectedResp map[string]interface{}) utils.CkReqFu case "Type": assert.Equal(t, expected, *ds.Type, "Expected Type to be %v, but got %v", expected, *ds.Type) case "XMLID": - assert.Equal(t, expected, *ds.XMLID, "Expected XMLID to be %v, but got %v", expected, *ds.XMLID) + assert.Equal(t, expected, ds.XMLID, "Expected XMLID to be %v, but got %v", expected, ds.XMLID) default: t.Errorf("Expected field: %v, does not exist in response", field) } @@ -658,7 +650,7 @@ func validateDSExpectedFields(expectedResp map[string]interface{}) utils.CkReqFu func validatePagination(paginationParam string) utils.CkReqFunc { return func(t *testing.T, _ toclientlib.ReqInf, resp interface{}, _ tc.Alerts, _ error) { - paginationResp := resp.([]tc.DeliveryServiceV4) + paginationResp := resp.([]tc.DeliveryServiceV5) opts := client.NewRequestOptions() opts.QueryParameters.Set("orderby", "id") @@ -680,7 +672,7 @@ func validatePagination(paginationParam string) utils.CkReqFunc { func validateDescSort() utils.CkReqFunc { return func(t *testing.T, _ toclientlib.ReqInf, resp interface{}, alerts tc.Alerts, _ error) { - dsDescResp := resp.([]tc.DeliveryServiceV4) + dsDescResp := resp.([]tc.DeliveryServiceV5) var descSortedList []string var ascSortedList []string assert.GreaterOrEqual(t, len(dsDescResp), 2, "Need at least 2 XMLIDs in Traffic Ops to test desc sort, found: %d", len(dsDescResp)) @@ -692,11 +684,11 @@ func validateDescSort() utils.CkReqFunc { assert.Equal(t, len(dsAscResp.Response), len(dsDescResp), "Expected descending order response length: %v, to match ascending order response length %v", len(dsAscResp.Response), len(dsDescResp)) // Insert xmlIDs to the front of a new list, so they are now reversed to be in ascending order. for _, ds := range dsDescResp { - descSortedList = append([]string{*ds.XMLID}, descSortedList...) + descSortedList = append([]string{ds.XMLID}, descSortedList...) } // Insert xmlIDs by appending to a new list, so they stay in ascending order. for _, ds := range dsAscResp.Response { - ascSortedList = append(ascSortedList, *ds.XMLID) + ascSortedList = append(ascSortedList, ds.XMLID) } assert.Exactly(t, ascSortedList, descSortedList, "Delivery Service responses are not equal after reversal: %v - %v", ascSortedList, descSortedList) } @@ -719,7 +711,7 @@ func GetDeliveryServiceId(t *testing.T, xmlId string) func() int { func generateDeliveryService(t *testing.T, requestDS map[string]interface{}) map[string]interface{} { // map for the most basic HTTP Delivery Service a user can create genericHTTPDS := map[string]interface{}{ - "active": true, + "active": tc.DSActiveStateActive, "cdnName": "cdn1", "cdnId": GetCDNID(t, "cdn1")(), "displayName": "test ds", @@ -753,13 +745,8 @@ func generateDeliveryService(t *testing.T, requestDS map[string]interface{}) map func CreateTestDeliveryServices(t *testing.T) { for _, ds := range testData.DeliveryServices { - ds = ds.RemoveLD1AndLD2() - if ds.XMLID == nil { - t.Error("Found a Delivery Service in testing data with null or undefined XMLID") - continue - } resp, _, err := TOSession.CreateDeliveryService(ds, client.RequestOptions{}) - assert.NoError(t, err, "Could not create Delivery Service '%s': %v - alerts: %+v", *ds.XMLID, err, resp.Alerts) + assert.NoError(t, err, "Could not create Delivery Service '%s': %v", ds.XMLID, err, resp.Alerts) } } @@ -774,7 +761,7 @@ func DeleteTestDeliveryServices(t *testing.T) { opts := client.NewRequestOptions() opts.QueryParameters.Set("id", strconv.Itoa(*ds.ID)) getDS, _, err := TOSession.GetDeliveryServices(opts) - assert.NoError(t, err, "Error deleting Delivery Service for '%s' : %v - alerts: %+v", *ds.XMLID, err, getDS.Alerts) - assert.Equal(t, 0, len(getDS.Response), "Expected Delivery Service '%s' to be deleted", *ds.XMLID) + assert.NoError(t, err, "Error deleting Delivery Service for '%s' : %v", ds.XMLID, err) + assert.Equal(t, 0, len(getDS.Response), "Expected Delivery Service '%s' to be deleted", ds.XMLID) } } diff --git a/traffic_ops/testing/api/v5/deliveryserviceservers_test.go b/traffic_ops/testing/api/v5/deliveryserviceservers_test.go index 4f69ba8b6a..7b78249824 100644 --- a/traffic_ops/testing/api/v5/deliveryserviceservers_test.go +++ b/traffic_ops/testing/api/v5/deliveryserviceservers_test.go @@ -351,11 +351,10 @@ func DeleteTestDeliveryServiceServers(t *testing.T) { assert.NoError(t, err, "Error retrieving Delivery Service: %v - alerts: %+v", err, getDS.Alerts) assert.Equal(t, 1, len(getDS.Response), "Expected 1 Delivery Service.") // Update active to false in order to remove the server assignment - active := false - getDS.Response[0].Active = &active + getDS.Response[0].Active = tc.DSActiveStateInactive updResp, _, err := TOSession.UpdateDeliveryService(*dss.DeliveryService, getDS.Response[0], client.RequestOptions{}) assert.NoError(t, err, "Error updating Delivery Service: %v - alerts: %+v", err, updResp.Alerts) - assert.Equal(t, false, *updResp.Response[0].Active, "Expected Delivery Service to be Inactive.") + assert.Equal(t, tc.DSActiveStateInactive, updResp.Response.Active, "Expected Delivery Service to be Inactive.") alerts, _, err := TOSession.DeleteDeliveryServiceServer(*dss.DeliveryService, *dss.Server, client.RequestOptions{}) assert.NoError(t, err, "Unexpected error removing server-to-Delivery-Service assignments: %v - alerts: %+v", err, alerts.Alerts) diff --git a/traffic_ops/testing/api/v5/tc-fixtures.json b/traffic_ops/testing/api/v5/tc-fixtures.json index d407f411eb..41d2565d61 100644 --- a/traffic_ops/testing/api/v5/tc-fixtures.json +++ b/traffic_ops/testing/api/v5/tc-fixtures.json @@ -401,7 +401,7 @@ ], "deliveryServices": [ { - "active": true, + "active": "ACTIVE", "cdnName": "cdn1", "ccrDnsTtl": 3600, "checkPath": "", @@ -420,7 +420,7 @@ ], "fqPacingRate": 0, "geoLimit": 0, - "geoLimitCountries": "", + "geoLimitCountries": [], "geoLimitRedirectURL": null, "geoProvider": 0, "globalMaxMbps": 0, @@ -467,7 +467,7 @@ "maxRequestHeaderBytes": 131072 }, { - "active": true, + "active": "ACTIVE", "cdnName": "cdn1", "ccrDnsTtl": 3600, "checkPath": "", @@ -490,7 +490,7 @@ ], "fqPacingRate": 0, "geoLimit": 0, - "geoLimitCountries": "", + "geoLimitCountries": [], "geoLimitRedirectURL": null, "geoProvider": 0, "globalMaxMbps": 0, @@ -538,7 +538,7 @@ "maxRequestHeaderBytes": 131072 }, { - "active": true, + "active": "ACTIVE", "cdnName": "cdn1", "ccrDnsTtl": 3600, "checkPath": "", @@ -557,7 +557,7 @@ ], "fqPacingRate": 0, "geoLimit": 0, - "geoLimitCountries": "", + "geoLimitCountries": [], "geoLimitRedirectURL": null, "geoProvider": 0, "globalMaxMbps": 0, @@ -605,7 +605,7 @@ "maxRequestHeaderBytes": 131072 }, { - "active": true, + "active": "ACTIVE", "cdnName": "cdn1", "ccrDnsTtl": 3600, "checkPath": "", @@ -620,7 +620,7 @@ "exampleURLs": [], "fqPacingRate": 0, "geoLimit": 0, - "geoLimitCountries": "", + "geoLimitCountries": [], "geoLimitRedirectURL": null, "geoProvider": 0, "globalMaxMbps": 0, @@ -662,7 +662,7 @@ "maxRequestHeaderBytes": 131072 }, { - "active": true, + "active": "ACTIVE", "cdnName": "cdn1", "ccrDnsTtl": 3600, "checkPath": "", @@ -682,7 +682,7 @@ "edgeHeaderRewrite": "edgeRewrite1\nedgeHeader2", "fqPacingRate": 42, "geoLimit": 0, - "geoLimitCountries": "", + "geoLimitCountries": [], "geoLimitRedirectURL": null, "geoProvider": 0, "globalMaxMbps": 0, @@ -725,7 +725,7 @@ "maxRequestHeaderBytes": 131072 }, { - "active": true, + "active": "ACTIVE", "cdnName": "cdn1", "ccrDnsTtl": 3600, "checkPath": "", @@ -744,7 +744,7 @@ ], "fqPacingRate": 0, "geoLimit": 0, - "geoLimitCountries": "", + "geoLimitCountries": [], "geoLimitRedirectURL": null, "geoProvider": 0, "globalMaxMbps": 0, @@ -791,7 +791,7 @@ "maxRequestHeaderBytes": 131072 }, { - "active": true, + "active": "ACTIVE", "cdnName": "cdn1", "ccrDnsTtl": 3600, "checkPath": "", @@ -810,7 +810,7 @@ ], "fqPacingRate": 0, "geoLimit": 0, - "geoLimitCountries": "", + "geoLimitCountries": [], "geoLimitRedirectURL": null, "geoProvider": 0, "globalMaxMbps": 0, @@ -857,7 +857,7 @@ "maxRequestHeaderBytes": 131072 }, { - "active": true, + "active": "ACTIVE", "cdnName": "cdn1", "ccrDnsTtl": 3600, "checkPath": "", @@ -872,7 +872,7 @@ "edgeHeaderRewrite": null, "fqPacingRate": 0, "geoLimit": 0, - "geoLimitCountries": "", + "geoLimitCountries": [], "geoLimitRedirectURL": null, "geoProvider": 0, "globalMaxMbps": 0, @@ -923,7 +923,7 @@ "maxRequestHeaderBytes": 131072 }, { - "active": true, + "active": "ACTIVE", "cdnName": "cdn1", "ccrDnsTtl": 3600, "checkPath": "", @@ -938,7 +938,7 @@ "edgeHeaderRewrite": null, "fqPacingRate": 0, "geoLimit": 0, - "geoLimitCountries": "", + "geoLimitCountries": [], "geoLimitRedirectURL": null, "geoProvider": 0, "globalMaxMbps": 0, @@ -986,7 +986,7 @@ "maxRequestHeaderBytes": 131072 }, { - "active": true, + "active": "ACTIVE", "cdnName": "cdn1", "ccrDnsTtl": 3600, "checkPath": "", @@ -1001,7 +1001,7 @@ "edgeHeaderRewrite": null, "fqPacingRate": 0, "geoLimit": 0, - "geoLimitCountries": "", + "geoLimitCountries": [], "geoLimitRedirectURL": null, "geoProvider": 0, "globalMaxMbps": 0, @@ -1049,7 +1049,7 @@ "maxRequestHeaderBytes": 131072 }, { - "active": true, + "active": "ACTIVE", "cdnName": "cdn1", "ccrDnsTtl": 3600, "checkPath": "", @@ -1064,7 +1064,7 @@ "edgeHeaderRewrite": null, "fqPacingRate": 0, "geoLimit": 0, - "geoLimitCountries": "", + "geoLimitCountries": [], "geoLimitRedirectURL": null, "geoProvider": 0, "globalMaxMbps": 0, @@ -1111,7 +1111,7 @@ "maxRequestHeaderBytes": 131072 }, { - "active": true, + "active": "ACTIVE", "cdnName": "cdn2", "ccrDnsTtl": 3600, "checkPath": "", @@ -1126,7 +1126,7 @@ "edgeHeaderRewrite": null, "fqPacingRate": 0, "geoLimit": 0, - "geoLimitCountries": "", + "geoLimitCountries": [], "geoLimitRedirectURL": null, "geoProvider": 0, "globalMaxMbps": 0, @@ -1174,7 +1174,7 @@ "maxRequestHeaderBytes": 131072 }, { - "active": true, + "active": "ACTIVE", "cdnName": "cdn1", "ccrDnsTtl": 3600, "checkPath": "", @@ -1189,7 +1189,7 @@ "edgeHeaderRewrite": null, "fqPacingRate": 0, "geoLimit": 0, - "geoLimitCountries": "", + "geoLimitCountries": [], "geoLimitRedirectURL": null, "geoProvider": 0, "globalMaxMbps": 0, @@ -1237,7 +1237,7 @@ "maxRequestHeaderBytes": 131072 }, { - "active": true, + "active": "ACTIVE", "cdnName": "cdn1", "ccrDnsTtl": 3600, "checkPath": "", @@ -1252,7 +1252,7 @@ "edgeHeaderRewrite": null, "fqPacingRate": 0, "geoLimit": 0, - "geoLimitCountries": "", + "geoLimitCountries": [], "geoLimitRedirectURL": null, "geoProvider": 0, "globalMaxMbps": 0, @@ -1300,7 +1300,7 @@ "maxRequestHeaderBytes": 131072 }, { - "active": true, + "active": "ACTIVE", "cdnName": "cdn2", "ccrDnsTtl": 3600, "checkPath": "", @@ -1315,7 +1315,7 @@ "edgeHeaderRewrite": null, "fqPacingRate": 0, "geoLimit": 0, - "geoLimitCountries": "", + "geoLimitCountries": [], "geoLimitRedirectURL": null, "geoProvider": 0, "globalMaxMbps": 0, @@ -1362,7 +1362,7 @@ "maxRequestHeaderBytes": 131072 }, { - "active": true, + "active": "ACTIVE", "cdnName": "cdn2", "ccrDnsTtl": 3600, "checkPath": "", @@ -1377,7 +1377,7 @@ "edgeHeaderRewrite": null, "fqPacingRate": 0, "geoLimit": 0, - "geoLimitCountries": "", + "geoLimitCountries": [], "geoLimitRedirectURL": null, "geoProvider": 0, "globalMaxMbps": 0, @@ -1425,7 +1425,7 @@ "maxRequestHeaderBytes": 131072 }, { - "active": false, + "active": "PRIMED", "cdnName": "cdn1", "ccrDnsTtl": 3600, "checkPath": "", @@ -1444,7 +1444,7 @@ ], "fqPacingRate": 0, "geoLimit": 0, - "geoLimitCountries": "", + "geoLimitCountries": [], "geoLimitRedirectURL": null, "geoProvider": 0, "globalMaxMbps": 0, @@ -1491,7 +1491,7 @@ "maxRequestHeaderBytes": 131072 }, { - "active": true, + "active": "ACTIVE", "anonymousBlockingEnabled": false, "cdnName": "cdn1", "displayName": "test", @@ -1515,7 +1515,7 @@ "maxRequestHeaderBytes": 131072 }, { - "active": false, + "active": "PRIMED", "cdnName": "cdn1", "cacheurl": "cacheUrl3", "ccrDnsTtl": 3600, @@ -1535,7 +1535,7 @@ ], "fqPacingRate": 0, "geoLimit": 0, - "geoLimitCountries": "", + "geoLimitCountries": [], "geoLimitRedirectURL": null, "geoProvider": 0, "globalMaxMbps": 0, @@ -1583,7 +1583,7 @@ "maxRequestHeaderBytes": 131072 }, { - "active": false, + "active": "INACTIVE", "cdnName": "cdn1", "cacheurl": "cacheUrl3", "ccrDnsTtl": 3600, @@ -1603,7 +1603,7 @@ ], "fqPacingRate": 0, "geoLimit": 0, - "geoLimitCountries": "", + "geoLimitCountries": [], "geoLimitRedirectURL": null, "geoProvider": 0, "globalMaxMbps": 0, @@ -1653,7 +1653,7 @@ "maxRequestHeaderBytes": 131072 }, { - "active": true, + "active": "ACTIVE", "cdnName": "cdn1", "ccrDnsTtl": 3600, "checkPath": "", @@ -1668,7 +1668,7 @@ "exampleURLs": [], "fqPacingRate": 0, "geoLimit": 0, - "geoLimitCountries": "", + "geoLimitCountries": [], "geoLimitRedirectURL": null, "geoProvider": 0, "globalMaxMbps": 0, @@ -1710,7 +1710,7 @@ "maxRequestHeaderBytes": 131072 }, { - "active": true, + "active": "ACTIVE", "anonymousBlockingEnabled": false, "cdnName": "cdn1", "displayName": "test-rm-ssc", diff --git a/traffic_ops/testing/api/v5/traffic_control_test.go b/traffic_ops/testing/api/v5/traffic_control_test.go index a86ffcfb05..67bdbf5592 100644 --- a/traffic_ops/testing/api/v5/traffic_control_test.go +++ b/traffic_ops/testing/api/v5/traffic_control_test.go @@ -30,7 +30,7 @@ type TrafficControl struct { DeliveryServicesRegexes []tc.DeliveryServiceRegexesTest `json:"deliveryServicesRegexes"` DeliveryServiceRequests []tc.DeliveryServiceRequestV40 `json:"deliveryServiceRequests"` DeliveryServiceRequestComments []tc.DeliveryServiceRequestComment `json:"deliveryServiceRequestComments"` - DeliveryServices []tc.DeliveryServiceV4 `json:"deliveryservices"` + DeliveryServices []tc.DeliveryServiceV5 `json:"deliveryservices"` DeliveryServicesRequiredCapabilities []tc.DeliveryServicesRequiredCapability `json:"deliveryservicesRequiredCapabilities"` DeliveryServiceServerAssignments []tc.DeliveryServiceServers `json:"deliveryServiceServerAssignments"` TopologyBasedDeliveryServicesRequiredCapabilities []tc.DeliveryServicesRequiredCapability `json:"topologyBasedDeliveryServicesRequiredCapabilities"` diff --git a/traffic_ops/v5-client/deliveryservice.go b/traffic_ops/v5-client/deliveryservice.go index e464784ebf..ac238c6321 100644 --- a/traffic_ops/v5-client/deliveryservice.go +++ b/traffic_ops/v5-client/deliveryservice.go @@ -117,37 +117,37 @@ const ( // GetDeliveryServicesByServer retrieves all Delivery Services assigned to the // server with the given ID. -func (to *Session) GetDeliveryServicesByServer(id int, opts RequestOptions) (tc.DeliveryServicesResponseV4, toclientlib.ReqInf, error) { - var data tc.DeliveryServicesResponseV4 +func (to *Session) GetDeliveryServicesByServer(id int, opts RequestOptions) (tc.DeliveryServicesResponseV5, toclientlib.ReqInf, error) { + var data tc.DeliveryServicesResponseV5 reqInf, err := to.get(fmt.Sprintf(apiServerDeliveryServices, id), opts, &data) return data, reqInf, err } // GetDeliveryServices returns (tenant-visible) Delivery Services. -func (to *Session) GetDeliveryServices(opts RequestOptions) (tc.DeliveryServicesResponseV4, toclientlib.ReqInf, error) { - var data tc.DeliveryServicesResponseV4 +func (to *Session) GetDeliveryServices(opts RequestOptions) (tc.DeliveryServicesResponseV5, toclientlib.ReqInf, error) { + var data tc.DeliveryServicesResponseV5 reqInf, err := to.get(apiDeliveryServices, opts, &data) return data, reqInf, err } // CreateDeliveryService creates the Delivery Service it's passed. -func (to *Session) CreateDeliveryService(ds tc.DeliveryServiceV4, opts RequestOptions) (tc.DeliveryServicesResponseV4, toclientlib.ReqInf, error) { +func (to *Session) CreateDeliveryService(ds tc.DeliveryServiceV5, opts RequestOptions) (tc.DeliveryServiceResponseV5, toclientlib.ReqInf, error) { var reqInf toclientlib.ReqInf - var resp tc.DeliveryServicesResponseV4 - if ds.TypeID == nil && ds.Type != nil { + var resp tc.DeliveryServiceResponseV5 + if ds.TypeID <= 0 && ds.Type != nil { typeOpts := NewRequestOptions() - typeOpts.QueryParameters.Set("name", ds.Type.String()) + typeOpts.QueryParameters.Set("name", *ds.Type) ty, _, err := to.GetTypes(typeOpts) if err != nil { return resp, reqInf, err } if len(ty.Response) == 0 { - return resp, reqInf, fmt.Errorf("no Type named '%s'", ds.Type) + return resp, reqInf, fmt.Errorf("no Type named '%s'", *ds.Type) } - ds.TypeID = &ty.Response[0].ID + ds.TypeID = ty.Response[0].ID } - if ds.CDNID == nil && ds.CDNName != nil { + if ds.CDNID <= 0 && ds.CDNName != nil { cdnOpts := NewRequestOptions() cdnOpts.QueryParameters.Set("name", *ds.CDNName) cdns, _, err := to.GetCDNs(cdnOpts) @@ -158,7 +158,7 @@ func (to *Session) CreateDeliveryService(ds tc.DeliveryServiceV4, opts RequestOp if len(cdns.Response) == 0 { return resp, reqInf, fmt.Errorf("no CDN named '%s'", *ds.CDNName) } - ds.CDNID = &cdns.Response[0].ID + ds.CDNID = cdns.Response[0].ID } if ds.ProfileID == nil && ds.ProfileName != nil { @@ -174,7 +174,7 @@ func (to *Session) CreateDeliveryService(ds tc.DeliveryServiceV4, opts RequestOp ds.ProfileID = &profiles.Response[0].ID } - if ds.TenantID == nil && ds.Tenant != nil { + if ds.TenantID <= 0 && ds.Tenant != nil { tenantOpts := NewRequestOptions() tenantOpts.QueryParameters.Set("name", *ds.Tenant) ten, _, err := to.GetTenants(tenantOpts) @@ -184,7 +184,7 @@ func (to *Session) CreateDeliveryService(ds tc.DeliveryServiceV4, opts RequestOp if len(ten.Response) == 0 { return resp, reqInf, fmt.Errorf("no Tenant named '%s'", *ds.Tenant) } - ds.TenantID = &ten.Response[0].ID + ds.TenantID = ten.Response[0].ID } reqInf, err := to.post(apiDeliveryServices, RequestOptions{Header: opts.Header}, ds, &resp) @@ -197,8 +197,8 @@ func (to *Session) CreateDeliveryService(ds tc.DeliveryServiceV4, opts RequestOp // UpdateDeliveryService replaces the Delivery Service identified by the // integral, unique identifier 'id' with the one it's passed. -func (to *Session) UpdateDeliveryService(id int, ds tc.DeliveryServiceV4, opts RequestOptions) (tc.DeliveryServicesResponseV4, toclientlib.ReqInf, error) { - var data tc.DeliveryServicesResponseV4 +func (to *Session) UpdateDeliveryService(id int, ds tc.DeliveryServiceV5, opts RequestOptions) (tc.DeliveryServiceResponseV5, toclientlib.ReqInf, error) { + var data tc.DeliveryServiceResponseV5 reqInf, err := to.put(fmt.Sprintf(apiDeliveryServiceID, id), opts, ds, &data) if err != nil { return data, reqInf, err @@ -343,8 +343,8 @@ func (to *Session) SafeDeliveryServiceUpdate( id int, r tc.DeliveryServiceSafeUpdateRequest, opts RequestOptions, -) (tc.DeliveryServiceSafeUpdateResponseV4, toclientlib.ReqInf, error) { - var data tc.DeliveryServiceSafeUpdateResponseV4 +) (tc.DeliveryServiceResponseV5, toclientlib.ReqInf, error) { + var data tc.DeliveryServiceResponseV5 reqInf, err := to.put(fmt.Sprintf(apiDeliveryServicesSafeUpdate, id), opts, r, &data) return data, reqInf, err } From ef2b1e81c8218f9f4f60b5b41ab00a0d49239224 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Thu, 29 Sep 2022 13:03:16 -0600 Subject: [PATCH 31/48] Update DS/server relationship client methods (and associated tests) --- .../testing/api/v5/servers_id_deliveryservices_test.go | 2 +- traffic_ops/v5-client/server.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/traffic_ops/testing/api/v5/servers_id_deliveryservices_test.go b/traffic_ops/testing/api/v5/servers_id_deliveryservices_test.go index 468b530f97..5b5bcc8741 100644 --- a/traffic_ops/testing/api/v5/servers_id_deliveryservices_test.go +++ b/traffic_ops/testing/api/v5/servers_id_deliveryservices_test.go @@ -159,7 +159,7 @@ func validateServersDeliveryServices(expectedDSID int) utils.CkReqFunc { return func(t *testing.T, _ toclientlib.ReqInf, resp interface{}, _ tc.Alerts, _ error) { assert.RequireNotNil(t, resp, "Expected Server Delivery Service response to not be nil.") var found bool - deliveryServices := resp.([]tc.DeliveryServiceV4) + deliveryServices := resp.([]tc.DeliveryServiceV5) for _, ds := range deliveryServices { if ds.ID != nil && *ds.ID == expectedDSID { found = true diff --git a/traffic_ops/v5-client/server.go b/traffic_ops/v5-client/server.go index ab56c42c47..faad8c0cbb 100644 --- a/traffic_ops/v5-client/server.go +++ b/traffic_ops/v5-client/server.go @@ -153,9 +153,9 @@ func (to *Session) AssignDeliveryServiceIDsToServerID(server int, dsIDs []int, r // GetServerIDDeliveryServices returns all of the Delivery Services assigned to the server identified // by the integral, unique identifier 'server'. -func (to *Session) GetServerIDDeliveryServices(server int, opts RequestOptions) (tc.DeliveryServicesResponseV4, toclientlib.ReqInf, error) { +func (to *Session) GetServerIDDeliveryServices(server int, opts RequestOptions) (tc.DeliveryServicesResponseV5, toclientlib.ReqInf, error) { endpoint := fmt.Sprintf(apiServerDeliveryServices, server) - var data tc.DeliveryServicesResponseV4 + var data tc.DeliveryServicesResponseV5 reqInf, err := to.get(endpoint, opts, &data) return data, reqInf, err } From 408455a33ed6c0393cc0b21fac0035e003cdd107 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Thu, 29 Sep 2022 13:07:39 -0600 Subject: [PATCH 32/48] Update DSR client methods (and associated tests) --- .../deliveryservice_request_comments_test.go | 4 +- .../api/v5/deliveryservice_requests_test.go | 40 ++++++------------- traffic_ops/testing/api/v5/tc-fixtures.json | 4 +- .../testing/api/v5/traffic_control_test.go | 2 +- .../v5-client/deliveryservice_requests.go | 34 ++++++++-------- 5 files changed, 36 insertions(+), 48 deletions(-) diff --git a/traffic_ops/testing/api/v5/deliveryservice_request_comments_test.go b/traffic_ops/testing/api/v5/deliveryservice_request_comments_test.go index 9e09b6afca..6c2932c6db 100644 --- a/traffic_ops/testing/api/v5/deliveryservice_request_comments_test.go +++ b/traffic_ops/testing/api/v5/deliveryservice_request_comments_test.go @@ -166,7 +166,9 @@ func CreateTestDeliveryServiceRequestComments(t *testing.T) { opts.QueryParameters.Set("xmlId", comment.XMLID) resp, _, err := TOSession.GetDeliveryServiceRequests(opts) assert.NoError(t, err, "Cannot get Delivery Service Request by XMLID '%s': %v - alerts: %+v", comment.XMLID, err, resp.Alerts) - assert.Equal(t, len(resp.Response), 1, "Found %d Delivery Service request by XMLID '%s, expected exactly one", len(resp.Response), comment.XMLID) + if !assert.Equal(t, len(resp.Response), 1, "Found %d Delivery Service request by XMLID '%s, expected exactly one", len(resp.Response), comment.XMLID) { + continue + } assert.NotNil(t, resp.Response[0].ID, "Got Delivery Service Request with xml_id '%s' that had a null ID", comment.XMLID) comment.DeliveryServiceRequestID = *resp.Response[0].ID diff --git a/traffic_ops/testing/api/v5/deliveryservice_requests_test.go b/traffic_ops/testing/api/v5/deliveryservice_requests_test.go index b38ab23429..5eaedd99c2 100644 --- a/traffic_ops/testing/api/v5/deliveryservice_requests_test.go +++ b/traffic_ops/testing/api/v5/deliveryservice_requests_test.go @@ -42,15 +42,15 @@ import ( // A better solution _might_ be to reload all the test fixtures every time // to wipe any and all referential modifications made to any test data, but // for now that's overkill. -func resetDS(ds *tc.DeliveryServiceV4) { +func resetDS(ds *tc.DeliveryServiceV5) { if ds == nil { return } - ds.CDNID = nil + ds.CDNID = -1 ds.ID = nil ds.ProfileID = nil - ds.TenantID = nil - ds.TypeID = nil + ds.TenantID = -1 + ds.TypeID = -1 } func TestDeliveryServiceRequests(t *testing.T) { @@ -103,21 +103,6 @@ func TestDeliveryServiceRequests(t *testing.T) { Expectations: utils.CkRequest(utils.NoError(), utils.HasStatus(http.StatusOK), validatePutDSRequestFields(map[string]interface{}{"STATUS": tc.RequestStatusSubmitted})), }, - "BAD REQUEST when using LONG DESCRIPTION 2 and 3 fields": { - EndpointID: GetDeliveryServiceRequestId(t, "test-ds1"), - ClientSession: TOSession, - RequestBody: map[string]interface{}{ - "changeType": "create", - "requested": generateDeliveryService(t, map[string]interface{}{ - "longDesc1": "long desc 1", - "longDesc2": "long desc 2", - "tenantId": GetTenantID(t, "tenant1")(), - "xmlId": "test-ds1", - }), - "status": "draft", - }, - Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), - }, "PRECONDITION FAILED when updating with IF-UNMODIFIED-SINCE Header": { EndpointID: GetDeliveryServiceRequestId(t, "test-ds1"), ClientSession: TOSession, @@ -203,7 +188,7 @@ func TestDeliveryServiceRequests(t *testing.T) { RequestBody: map[string]interface{}{ "changeType": "create", "requested": map[string]interface{}{ - "active": false, + "active": "INACTIVE", "cdnName": "cdn1", "displayName": "Testing transitions", "dscp": 3, @@ -234,7 +219,7 @@ func TestDeliveryServiceRequests(t *testing.T) { RequestBody: map[string]interface{}{ "changeType": "create", "requested": map[string]interface{}{ - "active": true, + "active": "ACTIVE", "cdnName": "cdn1", "displayName": "Good Kabletown CDN", "dscp": 1, @@ -280,7 +265,7 @@ func TestDeliveryServiceRequests(t *testing.T) { for method, testCases := range methodTests { t.Run(method, func(t *testing.T) { for name, testCase := range testCases { - dsReq := tc.DeliveryServiceRequestV4{} + var dsReq tc.DeliveryServiceRequestV5 if testCase.RequestBody != nil { dat, err := json.Marshal(testCase.RequestBody) @@ -340,12 +325,13 @@ func GetDeliveryServiceRequestId(t *testing.T, xmlId string) func() int { func validateGetDSRequestFields(expectedResp map[string]interface{}) utils.CkReqFunc { return func(t *testing.T, _ toclientlib.ReqInf, resp interface{}, _ tc.Alerts, _ error) { - dsReqResp := resp.([]tc.DeliveryServiceRequestV40) + dsReqResp := resp.([]tc.DeliveryServiceRequestV5) for field, expected := range expectedResp { for _, ds := range dsReqResp { switch field { case "XMLID": - assert.Equal(t, expected, *ds.Requested.XMLID, "Expected XMLID to be %v, but got %v", expected, *ds.Requested.XMLID) + assert.RequireNotNil(t, ds.Requested, "expected 'requested' DS in DSR to not be null/undefined") + assert.Equal(t, expected, ds.Requested.XMLID, "Expected XMLID to be %v, but got %v", expected, ds.Requested.XMLID) default: t.Errorf("Expected field: %v, does not exist in response", field) } @@ -356,7 +342,7 @@ func validateGetDSRequestFields(expectedResp map[string]interface{}) utils.CkReq func validatePutDSRequestFields(expectedResp map[string]interface{}) utils.CkReqFunc { return func(t *testing.T, _ toclientlib.ReqInf, resp interface{}, _ tc.Alerts, _ error) { - dsReqResp := resp.(tc.DeliveryServiceRequestV40) + dsReqResp := resp.(tc.DeliveryServiceRequestV5) for field, expected := range expectedResp { switch field { case "STATUS": @@ -372,8 +358,8 @@ func CreateTestDeliveryServiceRequests(t *testing.T) { for _, dsr := range testData.DeliveryServiceRequests { resetDS(dsr.Original) resetDS(dsr.Requested) - respDSR, _, err := TOSession.CreateDeliveryServiceRequest(dsr, client.RequestOptions{}) - assert.NoError(t, err, "Could not create Delivery Service Requests: %v - alerts: %+v", err, respDSR.Alerts) + _, _, err := TOSession.CreateDeliveryServiceRequest(dsr, client.RequestOptions{}) + assert.NoError(t, err, "Could not create Delivery Service Requests: %v", err) } } diff --git a/traffic_ops/testing/api/v5/tc-fixtures.json b/traffic_ops/testing/api/v5/tc-fixtures.json index 41d2565d61..18dc10c256 100644 --- a/traffic_ops/testing/api/v5/tc-fixtures.json +++ b/traffic_ops/testing/api/v5/tc-fixtures.json @@ -341,7 +341,7 @@ { "changeType": "create", "requested": { - "active": true, + "active": "ACTIVE", "cdnName": "cdn1", "ccrDnsTtl": 30, "deepCachingType": "NEVER", @@ -371,7 +371,7 @@ { "changeType": "create", "requested": { - "active": true, + "active": "ACTIVE", "cdnName": "cdn1", "ccrDnsTtl": 30, "deepCachingType": "NEVER", diff --git a/traffic_ops/testing/api/v5/traffic_control_test.go b/traffic_ops/testing/api/v5/traffic_control_test.go index 67bdbf5592..acabaac327 100644 --- a/traffic_ops/testing/api/v5/traffic_control_test.go +++ b/traffic_ops/testing/api/v5/traffic_control_test.go @@ -28,7 +28,7 @@ type TrafficControl struct { Capabilities []tc.Capability `json:"capability"` Coordinates []tc.Coordinate `json:"coordinates"` DeliveryServicesRegexes []tc.DeliveryServiceRegexesTest `json:"deliveryServicesRegexes"` - DeliveryServiceRequests []tc.DeliveryServiceRequestV40 `json:"deliveryServiceRequests"` + DeliveryServiceRequests []tc.DeliveryServiceRequestV5 `json:"deliveryServiceRequests"` DeliveryServiceRequestComments []tc.DeliveryServiceRequestComment `json:"deliveryServiceRequestComments"` DeliveryServices []tc.DeliveryServiceV5 `json:"deliveryservices"` DeliveryServicesRequiredCapabilities []tc.DeliveryServicesRequiredCapability `json:"deliveryservicesRequiredCapabilities"` diff --git a/traffic_ops/v5-client/deliveryservice_requests.go b/traffic_ops/v5-client/deliveryservice_requests.go index 89e59575d0..0198cb98c0 100644 --- a/traffic_ops/v5-client/deliveryservice_requests.go +++ b/traffic_ops/v5-client/deliveryservice_requests.go @@ -30,8 +30,8 @@ import ( const apiDSRequests = "/deliveryservice_requests" // CreateDeliveryServiceRequest creates the given Delivery Service Request. -func (to *Session) CreateDeliveryServiceRequest(dsr tc.DeliveryServiceRequestV4, opts RequestOptions) (tc.DeliveryServiceRequestResponseV4, toclientlib.ReqInf, error) { - var resp tc.DeliveryServiceRequestResponseV4 +func (to *Session) CreateDeliveryServiceRequest(dsr tc.DeliveryServiceRequestV5, opts RequestOptions) (tc.DeliveryServiceRequestResponseV5, toclientlib.ReqInf, error) { + var resp tc.DeliveryServiceRequestResponseV5 if dsr.AssigneeID == nil && dsr.Assignee != nil { assigneeOpts := NewRequestOptions() assigneeOpts.QueryParameters.Set("username", *dsr.Assignee) @@ -58,31 +58,31 @@ func (to *Session) CreateDeliveryServiceRequest(dsr tc.DeliveryServiceRequestV4, dsr.AuthorID = res.Response[0].ID } - var ds *tc.DeliveryServiceV4 + var ds *tc.DeliveryServiceV5 if dsr.ChangeType == tc.DSRChangeTypeDelete { ds = dsr.Original } else { ds = dsr.Requested } - if ds.TypeID == nil && ds.Type.String() != "" { + if ds.TypeID <= 0 && ds.Type != nil && *ds.Type != "" { typeOpts := NewRequestOptions() - typeOpts.QueryParameters.Set("name", ds.Type.String()) + typeOpts.QueryParameters.Set("name", *ds.Type) ty, reqInf, err := to.GetTypes(typeOpts) if err != nil || len(ty.Response) == 0 { - return resp, reqInf, errors.New("no type named " + ds.Type.String()) + return resp, reqInf, errors.New("no type named " + *ds.Type) } - ds.TypeID = &ty.Response[0].ID + ds.TypeID = ty.Response[0].ID } - if ds.CDNID == nil && ds.CDNName != nil { + if ds.CDNID <= 0 && ds.CDNName != nil { cdnOpts := NewRequestOptions() cdnOpts.QueryParameters.Set("name", *ds.CDNName) cdns, reqInf, err := to.GetCDNs(cdnOpts) if err != nil || len(cdns.Response) == 0 { return resp, reqInf, fmt.Errorf("no CDN named '%s'", *ds.CDNName) } - ds.CDNID = &cdns.Response[0].ID + ds.CDNID = cdns.Response[0].ID } if ds.ProfileID == nil && ds.ProfileName != nil { @@ -95,14 +95,14 @@ func (to *Session) CreateDeliveryServiceRequest(dsr tc.DeliveryServiceRequestV4, ds.ProfileID = &profiles.Response[0].ID } - if ds.TenantID == nil && ds.Tenant != nil { + if ds.TenantID <= 0 && ds.Tenant != nil { tenantOpts := NewRequestOptions() tenantOpts.QueryParameters.Set("name", *ds.Tenant) ten, reqInf, err := to.GetTenants(tenantOpts) if err != nil || len(ten.Response) == 0 { return resp, reqInf, fmt.Errorf("no Tenant named '%s'", *ds.Tenant) } - ds.TenantID = &ten.Response[0].ID + ds.TenantID = ten.Response[0].ID } reqInf, err := to.post(apiDSRequests, opts, dsr, &resp) @@ -110,32 +110,32 @@ func (to *Session) CreateDeliveryServiceRequest(dsr tc.DeliveryServiceRequestV4, } // GetDeliveryServiceRequests retrieves Delivery Service Requests available to session user. -func (to *Session) GetDeliveryServiceRequests(opts RequestOptions) (tc.DeliveryServiceRequestsResponseV4, toclientlib.ReqInf, error) { - var data tc.DeliveryServiceRequestsResponseV4 +func (to *Session) GetDeliveryServiceRequests(opts RequestOptions) (tc.DeliveryServiceRequestsResponseV5, toclientlib.ReqInf, error) { + var data tc.DeliveryServiceRequestsResponseV5 reqInf, err := to.get(apiDSRequests, opts, &data) return data, reqInf, err } // DeleteDeliveryServiceRequest deletes the Delivery Service Request with the given ID. -func (to *Session) DeleteDeliveryServiceRequest(id int, opts RequestOptions) (tc.DeliveryServiceRequestResponseV4, toclientlib.ReqInf, error) { +func (to *Session) DeleteDeliveryServiceRequest(id int, opts RequestOptions) (tc.DeliveryServiceRequestResponseV5, toclientlib.ReqInf, error) { if opts.QueryParameters == nil { opts.QueryParameters = url.Values{} } opts.QueryParameters.Set("id", strconv.Itoa(id)) - var resp tc.DeliveryServiceRequestResponseV4 + var resp tc.DeliveryServiceRequestResponseV5 reqInf, err := to.del(apiDSRequests, opts, &resp) return resp, reqInf, err } // UpdateDeliveryServiceRequest replaces the existing DSR that has the given // ID with the DSR passed. -func (to *Session) UpdateDeliveryServiceRequest(id int, dsr tc.DeliveryServiceRequestV4, opts RequestOptions) (tc.DeliveryServiceRequestResponseV4, toclientlib.ReqInf, error) { +func (to *Session) UpdateDeliveryServiceRequest(id int, dsr tc.DeliveryServiceRequestV5, opts RequestOptions) (tc.DeliveryServiceRequestResponseV5, toclientlib.ReqInf, error) { if opts.QueryParameters == nil { opts.QueryParameters = url.Values{} } opts.QueryParameters.Set("id", strconv.Itoa(id)) - var payload tc.DeliveryServiceRequestResponseV4 + var payload tc.DeliveryServiceRequestResponseV5 reqInf, err := to.put(apiDSRequests, opts, dsr, &payload) return payload, reqInf, err From 75a3a1cf4ec7c9cef6313d9d49f5895a817fa9a3 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Thu, 29 Sep 2022 13:08:54 -0600 Subject: [PATCH 33/48] Add PUT/POST handlers for V5 DSes (because I forgot them the first time) --- .../deliveryservice/deliveryservices.go | 92 +++++++++++++++++-- .../traffic_ops_golang/routing/routes.go | 4 +- 2 files changed, 87 insertions(+), 9 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go index 6aa5f52a5a..8371a5e742 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go @@ -198,6 +198,33 @@ func CreateV31(w http.ResponseWriter, r *http.Request) { api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Delivery Service creation was successful", []tc.DeliveryServiceV31{*res}) } +// CreateV50 is used to handle POST requests to create a Delivery Service at +// version 5.0 of the Traffic Ops API. +func CreateV50(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() + + var ds tc.DeliveryServiceV5 + if err := json.NewDecoder(r.Body).Decode(&ds); err != nil { + api.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, fmt.Errorf("decoding: %w", err), nil) + return + } + res, status, userErr, sysErr := createV50(w, r, inf, ds, true, nil, nil) + 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, *res) +} + // CreateV40 is used to handle POST requests to create a Delivery Service at // version 4.0 of the Traffic Ops API (and isomorphic API versions thereof, with // respect to Delivery Service representations). @@ -772,11 +799,14 @@ func UpdateV40(w http.ResponseWriter, r *http.Request) { api.WriteAlertsObj(w, r, http.StatusOK, alerts, []tc.DeliveryServiceV40{*res}) } -// UpdateV41 is a handler for PUT requests used to update a Delivery Service. +// UpdateV41 is used to handle PUT requests to update a Delivery Service in +// version 4.1 of the Traffic Ops API (and isomorphic API versions thereof, with +// respect to Delivery Service representations). func UpdateV41(w http.ResponseWriter, r *http.Request) { inf, userErr, sysErr, errCode := api.NewInfo(r, nil, []string{"id"}) + tx := inf.Tx.Tx if userErr != nil || sysErr != nil { - api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr) + api.HandleErr(w, r, tx, errCode, userErr, sysErr) return } defer inf.Close() @@ -784,18 +814,22 @@ func UpdateV41(w http.ResponseWriter, r *http.Request) { var ds tc.DeliveryServiceV41 if err := json.NewDecoder(r.Body).Decode(&ds); err != nil { - api.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, fmt.Errorf("malformed JSON: %w", err), nil) + api.HandleErr(w, r, tx, http.StatusBadRequest, fmt.Errorf("malformed JSON: %w", err), nil) return } ds.ID = &id - _, cdn, _, err := dbhelpers.GetDSNameAndCDNFromID(inf.Tx.Tx, id) + _, cdn, exists, err := dbhelpers.GetDSNameAndCDNFromID(tx, id) if err != nil { - api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, fmt.Errorf("deliveryservice update: getting CDN from DS ID: %w", err)) + api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, fmt.Errorf("deliveryservice update: getting CDN from DS ID %w", err)) return } - userErr, sysErr, statusCode := dbhelpers.CheckIfCurrentUserCanModifyCDN(inf.Tx.Tx, string(cdn), inf.User.UserName) + if !exists { + api.HandleErr(w, r, tx, http.StatusNotFound, fmt.Errorf("no such Delivery Service: #%d", id), nil) + return + } + userErr, sysErr, statusCode := dbhelpers.CheckIfCurrentUserCanModifyCDN(tx, string(cdn), inf.User.UserName) if userErr != nil || sysErr != nil { - api.HandleErr(w, r, inf.Tx.Tx, statusCode, userErr, sysErr) + api.HandleErr(w, r, tx, statusCode, userErr, sysErr) return } res, status, userErr, sysErr := updateV41(w, r, inf, &ds, true) @@ -809,6 +843,50 @@ func UpdateV41(w http.ResponseWriter, r *http.Request) { api.WriteAlertsObj(w, r, http.StatusOK, alerts, []tc.DeliveryServiceV41{*res}) } +// UpdateV50 is used to handle PUT requests to update a Delivery Service in +// version 5.0 of the Traffic Ops API (and isomorphic API versions thereof, with +// respect to Delivery Service representations). +func UpdateV50(w http.ResponseWriter, r *http.Request) { + inf, userErr, sysErr, errCode := api.NewInfo(r, nil, []string{"id"}) + tx := inf.Tx.Tx + if userErr != nil || sysErr != nil { + api.HandleErr(w, r, tx, errCode, userErr, sysErr) + return + } + defer inf.Close() + id := inf.IntParams["id"] + + var ds tc.DeliveryServiceV5 + if err := json.NewDecoder(r.Body).Decode(&ds); err != nil { + api.HandleErr(w, r, tx, http.StatusBadRequest, fmt.Errorf("malformed JSON: %w", err), nil) + return + } + ds.ID = &id + _, cdn, exists, err := dbhelpers.GetDSNameAndCDNFromID(tx, id) + if err != nil { + api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, fmt.Errorf("deliveryservice update: getting CDN from DS ID %w", err)) + return + } + if !exists { + api.HandleErr(w, r, tx, http.StatusNotFound, fmt.Errorf("no such Delivery Service: #%d", id), nil) + return + } + userErr, sysErr, statusCode := dbhelpers.CheckIfCurrentUserCanModifyCDN(tx, string(cdn), inf.User.UserName) + if userErr != nil || sysErr != nil { + api.HandleErr(w, r, tx, statusCode, userErr, sysErr) + return + } + res, status, userErr, sysErr := updateV50(w, r, inf, &ds, true, nil, nil) + 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, *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 diff --git a/traffic_ops/traffic_ops_golang/routing/routes.go b/traffic_ops/traffic_ops_golang/routing/routes.go index 0b5796b39c..87703283d0 100644 --- a/traffic_ops/traffic_ops_golang/routing/routes.go +++ b/traffic_ops/traffic_ops_golang/routing/routes.go @@ -485,8 +485,8 @@ func Routes(d ServerData) ([]Route, http.Handler, error) { ////DeliveryServices {Version: api.Version{Major: 5, Minor: 0}, Method: http.MethodGet, Path: `deliveryservices/?$`, Handler: api.ReadHandler(&deliveryservice.TODeliveryService{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: []string{"DELIVERY-SERVICE:READ", "CDN:READ", "TYPE:READ"}, Authenticated: Authenticated, Middlewares: nil, ID: 423831729431}, - {Version: api.Version{Major: 5, Minor: 0}, Method: http.MethodPost, Path: `deliveryservices/?$`, Handler: deliveryservice.CreateV41, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: []string{"DELIVERY-SERVICE:CREATE", "DELIVERY-SERVICE:READ", "CDN:READ", "TYPE:READ"}, Authenticated: Authenticated, Middlewares: nil, ID: 40643153231}, - {Version: api.Version{Major: 5, Minor: 0}, Method: http.MethodPut, Path: `deliveryservices/{id}/?$`, Handler: deliveryservice.UpdateV41, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: []string{"DELIVERY-SERVICE:UPDATE", "DELIVERY-SERVICE:READ", "CDN:READ", "TYPE:READ"}, Authenticated: Authenticated, Middlewares: nil, ID: 476656756731}, + {Version: api.Version{Major: 5, Minor: 0}, Method: http.MethodPost, Path: `deliveryservices/?$`, Handler: deliveryservice.CreateV50, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: []string{"DELIVERY-SERVICE:CREATE", "DELIVERY-SERVICE:READ", "CDN:READ", "TYPE:READ"}, Authenticated: Authenticated, Middlewares: nil, ID: 40643153231}, + {Version: api.Version{Major: 5, Minor: 0}, Method: http.MethodPut, Path: `deliveryservices/{id}/?$`, Handler: deliveryservice.UpdateV50, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: []string{"DELIVERY-SERVICE:UPDATE", "DELIVERY-SERVICE:READ", "CDN:READ", "TYPE:READ"}, Authenticated: Authenticated, Middlewares: nil, ID: 476656756731}, {Version: api.Version{Major: 5, Minor: 0}, Method: http.MethodPut, Path: `deliveryservices/{id}/safe/?$`, Handler: deliveryservice.UpdateSafe, RequiredPrivLevel: auth.PrivLevelUnauthenticated, RequiredPermissions: []string{"DELIVERY-SERVICE-SAFE:UPDATE", "DELIVERY-SERVICE:READ", "TYPE:READ"}, Authenticated: Authenticated, Middlewares: nil, ID: 44721093131}, {Version: api.Version{Major: 5, Minor: 0}, Method: http.MethodDelete, Path: `deliveryservices/{id}/?$`, Handler: api.DeleteHandler(&deliveryservice.TODeliveryService{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: []string{"DELIVERY-SERVICE:DELETE", "DELIVERY-SERVICE:READ", "CDN:READ", "TYPE:READ"}, Authenticated: Authenticated, Middlewares: nil, ID: 42264207431}, {Version: api.Version{Major: 5, Minor: 0}, Method: http.MethodGet, Path: `deliveryservices/{id}/servers/eligible/?$`, Handler: deliveryservice.GetServersEligible, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: []string{"DELIVERY-SERVICE:READ", "SERVER:READ", "CACHE-GROUP:READ", "TYPE:READ", "CDN:READ"}, Authenticated: Authenticated, Middlewares: nil, ID: 47476158431}, From d4cfe612b36b8196c9a90d4b05ab36bb6fdd534d Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Thu, 29 Sep 2022 13:09:25 -0600 Subject: [PATCH 34/48] Fix DSRs using incorrect DS representations --- .../deliveryservice/request/requests.go | 184 +++++++++++++++++- 1 file changed, 180 insertions(+), 4 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go b/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go index f56d735f60..e19bebf0c9 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go @@ -403,6 +403,72 @@ func (d dsrManipulationResult) String() string { return builder.String() } +func createV5(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (result dsrManipulationResult) { + tx := inf.Tx.Tx + var dsr tc.DeliveryServiceRequestV5 + if err := json.NewDecoder(r.Body).Decode(&dsr); err != nil { + api.HandleErr(w, r, tx, http.StatusBadRequest, fmt.Errorf("decoding: %w", err), nil) + return + } + if userErr, sysErr := validateV5(dsr, tx); userErr != nil || sysErr != nil { + api.HandleErr(w, r, tx, http.StatusBadRequest, userErr, sysErr) + return + } + + if dsr.Status != tc.RequestStatusDraft && dsr.Status != tc.RequestStatusSubmitted { + userErr := fmt.Errorf("invalid initial request status '%s' - must be '%s' or '%s'", dsr.Status, tc.RequestStatusDraft, tc.RequestStatusSubmitted) + api.HandleErr(w, r, tx, http.StatusBadRequest, userErr, nil) + return + } + + ok, err := isTenantAuthorized(dsr, inf) + if err != nil { + api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, err) + return + } + if !ok { + api.HandleErr(w, r, tx, http.StatusForbidden, errors.New("not authorized on this tenant"), nil) + return + } + + dsr.SetXMLID() + if ok, err = dbhelpers.DSRExistsWithXMLID(dsr.XMLID, tx); err != nil { + err = fmt.Errorf("checking for existence of DSR with xmlid '%s'", dsr.XMLID) + api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, err) + return + } else if ok { + userErr := fmt.Errorf("an open Delivery Service Request for XMLID '%s' already exists", dsr.XMLID) + api.HandleErr(w, r, tx, http.StatusBadRequest, userErr, nil) + return + } + if dsr.Original != nil { + if len(dsr.Original.TLSVersions) < 1 { + dsr.Original.TLSVersions = nil + } + } + if dsr.Requested != nil { + if len(dsr.Requested.TLSVersions) < 1 { + dsr.Requested.TLSVersions = nil + } + } + errCode, userErr, sysErr := insert(&dsr, inf) + if userErr != nil || sysErr != nil { + api.HandleErr(w, r, tx, errCode, userErr, sysErr) + return + } + + w.Header().Set("Location", fmt.Sprintf("/api/%d.%d/deliveryservice_requests/%d", inf.Version.Major, inf.Version.Minor, *dsr.ID)) + w.WriteHeader(http.StatusCreated) + api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Delivery Service request created", dsr) + + result.Successful = true + result.Assignee = dsr.Assignee + result.XMLID = dsr.XMLID + result.ChangeType = dsr.ChangeType + result.Action = api.Created + return +} + func createV4(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (result dsrManipulationResult) { tx := inf.Tx.Tx var dsr tc.DeliveryServiceRequestV4 @@ -576,9 +642,14 @@ func Post(w http.ResponseWriter, r *http.Request) { } var result dsrManipulationResult - if version.Major >= 4 { + switch version.Major { + default: + fallthrough + case 5: + result = createV5(w, r, inf) + case 4: result = createV4(w, r, inf) - } else { + case 3: result = createLegacy(w, r, inf) } @@ -685,6 +756,106 @@ func Delete(w http.ResponseWriter, r *http.Request) { inf.CreateChangeLog(res.String()) } +func putV50(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (result dsrManipulationResult) { + tx := inf.Tx.Tx + var dsr tc.DeliveryServiceRequestV5 + if err := json.NewDecoder(r.Body).Decode(&dsr); err != nil { + api.HandleErr(w, r, tx, http.StatusBadRequest, fmt.Errorf("decoding: %w", err), nil) + return + } + if userErr, sysErr := validateV5(dsr, tx); userErr != nil || sysErr != nil { + api.HandleErr(w, r, tx, http.StatusBadRequest, userErr, sysErr) + return + } + + if dsr.Status != tc.RequestStatusDraft && dsr.Status != tc.RequestStatusSubmitted { + userErr := fmt.Errorf("cannot change DeliveryServiceRequest status to '%s'", dsr.Status) + api.HandleErr(w, r, tx, http.StatusBadRequest, userErr, nil) + return + } + + if dsr.ChangeType != tc.DSRChangeTypeDelete { + dsr.Original = nil + } else { + dsr.Requested = nil + } + + authorized, err := isTenantAuthorized(dsr, inf) + if err != nil { + api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, err) + return + } + if !authorized { + api.HandleErr(w, r, tx, http.StatusForbidden, errors.New("not authorized on this tenant"), nil) + return + } + + dsr.LastEditedBy = inf.User.UserName + dsr.LastEditedByID = new(int) + *dsr.LastEditedByID = inf.User.ID + + if dsr.Requested != nil && len(dsr.Requested.TLSVersions) < 1 { + dsr.Requested.TLSVersions = nil + } + if dsr.Original != nil && len(dsr.Original.TLSVersions) < 1 { + dsr.Original.TLSVersions = nil + } + + args := []interface{}{ + dsr.AssigneeID, + dsr.ChangeType, + inf.User.ID, + dsr.Requested, + dsr.Original, + dsr.Status, + inf.IntParams["id"], + } + + if err := tx.QueryRow(updateQuery, args...).Scan(&dsr.CreatedAt, &dsr.LastUpdated); err != nil { + var userErr, sysErr error + var errCode int + if errors.Is(err, sql.ErrNoRows) { + userErr = fmt.Errorf("no such Delivery Service Request: #%d", inf.IntParams["id"]) + errCode = http.StatusNotFound + sysErr = fmt.Errorf("running update query for Delivery Service Requests: %w", err) + } else { + userErr, sysErr, errCode = api.ParseDBError(err) + } + api.HandleErr(w, r, tx, errCode, userErr, sysErr) + return + } + dsr.SetXMLID() + + if dsr.ChangeType == tc.DSRChangeTypeUpdate { + query := deliveryservice.SelectDeliveryServicesQuery + `WHERE xml_id=:XMLID` + originals, userErr, sysErr, errCode := deliveryservice.GetDeliveryServices(query, map[string]interface{}{"XMLID": dsr.XMLID}, inf.Tx) + if userErr != nil || sysErr != nil { + api.HandleErr(w, r, tx, errCode, userErr, sysErr) + return + } + if len(originals) < 1 { + userErr = fmt.Errorf("cannot update non-existent Delivery Service '%s'", dsr.XMLID) + api.HandleErr(w, r, tx, http.StatusBadRequest, userErr, nil) + return + } + if len(originals) > 1 { + sysErr = fmt.Errorf("too many Delivery Services with XMLID '%s'; want: 1, got: %d", dsr.XMLID, len(originals)) + api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, sysErr) + return + } + dsr.Original = new(tc.DeliveryServiceV5) + *dsr.Original = originals[0].DS + } + + api.WriteRespAlertObj(w, r, tc.SuccessLevel, fmt.Sprintf("Delivery Service Request #%d updated", inf.IntParams["id"]), dsr) + result.Successful = true + result.Action = "Updated" + result.Assignee = dsr.Assignee + result.ChangeType = dsr.ChangeType + result.XMLID = dsr.XMLID + return +} + func putV40(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (result dsrManipulationResult) { tx := inf.Tx.Tx var dsr tc.DeliveryServiceRequestV40 @@ -930,9 +1101,14 @@ func Put(w http.ResponseWriter, r *http.Request) { } var result dsrManipulationResult - if inf.Version.Major >= 4 { + switch inf.Version.Major { + default: + fallthrough + case 5: + result = putV50(w, r, inf) + case 4: result = putV40(w, r, inf) - } else { + case 3: result = putLegacy(w, r, inf) } From 28db999e59927967bb1fd2d67a4c569604e8938d Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Thu, 29 Sep 2022 15:40:33 -0600 Subject: [PATCH 35/48] Fix hard-coded/incorrect Location headers on DS POST responses --- .../traffic_ops_golang/deliveryservice/deliveryservices.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go index 8371a5e742..4b9913e6d9 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go @@ -221,7 +221,7 @@ func CreateV50(w http.ResponseWriter, r *http.Request) { 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)) + w.Header().Set("Location", fmt.Sprintf("/api/%d.%d/deliveryservices?id=%d", inf.Version.Major, inf.Version.Minor, *res.ID)) api.WriteAlertsObj(w, r, http.StatusCreated, alerts, *res) } @@ -249,7 +249,7 @@ func CreateV40(w http.ResponseWriter, r *http.Request) { 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)) + w.Header().Set("Location", fmt.Sprintf("/api/%d.%d/deliveryservices?id=%d", inf.Version.Major, inf.Version.Minor, *res.ID)) api.WriteAlertsObj(w, r, http.StatusCreated, alerts, []tc.DeliveryServiceV40{*res}) } From d26dd15f92188daea9616cf9396d12b5fe2d183e Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Thu, 29 Sep 2022 16:34:54 -0600 Subject: [PATCH 36/48] Update docs --- .../api/v5/deliveryservice_requests.rst | 1006 +++++++++++------ .../v5/deliveryservice_requests_id_assign.rst | 133 +-- .../v5/deliveryservice_requests_id_status.rst | 144 +-- docs/source/api/v5/deliveryservices.rst | 117 +- docs/source/api/v5/deliveryservices_id.rst | 77 +- .../api/v5/deliveryservices_id_safe.rst | 46 +- .../api/v5/servers_id_deliveryservices.rst | 58 +- docs/source/overview/delivery_services.rst | 41 +- 8 files changed, 970 insertions(+), 652 deletions(-) diff --git a/docs/source/api/v5/deliveryservice_requests.rst b/docs/source/api/v5/deliveryservice_requests.rst index e9f0fc1c9b..e268ab26bf 100644 --- a/docs/source/api/v5/deliveryservice_requests.rst +++ b/docs/source/api/v5/deliveryservice_requests.rst @@ -73,11 +73,11 @@ Request Structure :caption: Request Example GET /api/5.0/deliveryservice_requests?status=draft HTTP/1.1 - User-Agent: python-requests/2.22.0 + User-Agent: python-requests/2.25.1 Accept-Encoding: gzip, deflate Accept: */* Connection: keep-alive - Cookie: mojolicious=... + Cookie: access_token=...; mojolicious=... Response Structure ------------------ @@ -93,36 +93,50 @@ The response is an array of representations of :term:`Delivery Service Requests` Access-Control-Allow-Origin: * Content-Encoding: gzip Content-Type: application/json - Set-Cookie: mojolicious=...; Path=/; Expires=Mon, 24 Feb 2020 20:14:07 GMT; Max-Age=3600; HttpOnly + Permissions-Policy: interest-cohort=() + Set-Cookie: mojolicious=...; Path=/; Expires=Thu, 29 Sep 2022 23:10:56 GMT; Max-Age=3600; HttpOnly, access_token=...; Path=/; Expires=Thu, 29 Sep 2022 23:10:56 GMT; Max-Age=3600; HttpOnly + Vary: Accept-Encoding X-Server-Name: traffic_ops_golang/ - Date: Mon, 24 Feb 2020 19:14:07 GMT - Content-Length: 872 + Date: Thu, 29 Sep 2022 22:10:56 GMT + Content-Length: 988 { "response": [{ - "authorId": 2, + "assignee": null, "author": "admin", "changeType": "update", - "createdAt": "2020-02-24 19:11:12+00", + "createdAt": "2022-09-29T22:07:15.008503Z", "id": 1, "lastEditedBy": "admin", - "lastEditedById": 2, - "lastUpdated": "2020-02-24 19:11:12+00", - "requested": { - "active": false, + "lastUpdated": "2022-09-29T22:07:15.008503Z", + "original": { + "active": "ACTIVE", "anonymousBlockingEnabled": false, - "cacheurl": null, "ccrDnsTtl": null, "cdnId": 2, "cdnName": "CDN-in-a-Box", "checkPath": null, + "consistentHashQueryParams": [ + "abc", + "pdq", + "xxx", + "zyx" + ], + "consistentHashRegex": null, + "deepCachingType": "NEVER", "displayName": "Demo 1", "dnsBypassCname": null, "dnsBypassIp": null, "dnsBypassIp6": null, "dnsBypassTtl": null, "dscp": 0, + "ecsEnabled": false, "edgeHeaderRewrite": null, + "exampleURLs": [ + "http://video.demo1.mycdn.ciab.test", + "https://video.demo1.mycdn.ciab.test" + ], "firstHeaderRewrite": null, + "fqPacingRate": null, "geoLimit": 0, "geoLimitCountries": null, "geoLimitRedirectURL": null, @@ -136,7 +150,7 @@ The response is an array of representations of :term:`Delivery Service Requests` "innerHeaderRewrite": null, "ipv6RoutingEnabled": true, "lastHeaderRewrite": null, - "lastUpdated": "0001-01-01T00:00:00Z", + "lastUpdated": "2022-09-29T20:58:53.07251Z", "logsEnabled": true, "longDesc": "Apachecon North America 2018", "matchList": [ @@ -147,10 +161,12 @@ The response is an array of representations of :term:`Delivery Service Requests` } ], "maxDnsAnswers": null, + "maxOriginConnections": 0, + "maxRequestHeaderBytes": 0, "midHeaderRewrite": null, "missLat": 42, "missLong": -88, - "multiSiteOrigin": false, + "multiSiteOrigin": true, "originShield": null, "orgServerFqdn": "http://origin.infra.ciab.test", "profileDescription": null, @@ -159,38 +175,111 @@ The response is an array of representations of :term:`Delivery Service Requests` "protocol": 2, "qstringIgnore": 0, "rangeRequestHandling": 0, + "rangeSliceBlockSize": null, "regexRemap": null, - "regional": false, "regionalGeoBlocking": false, "remapText": null, "routingName": "video", + "serviceCategory": null, "signed": false, + "signingAlgorithm": null, "sslKeyVersion": 1, + "tenant": "root", "tenantId": 1, - "topology": null, + "tlsVersions": null, + "topology": "demo1-top", + "trResponseHeaders": null, + "trRequestHeaders": null, "type": "HTTP", "typeId": 1, - "xmlId": "demo1", + "xmlId": "demo1" + }, + "requested": { + "active": "INACTIVE", + "anonymousBlockingEnabled": false, + "ccrDnsTtl": null, + "cdnId": 2, + "cdnName": "CDN-in-a-Box", + "checkPath": null, + "consistentHashQueryParams": [ + "abc", + "pdq", + "xxx", + "zyx" + ], + "consistentHashRegex": null, + "deepCachingType": "NEVER", + "displayName": "Demo 1", + "dnsBypassCname": null, + "dnsBypassIp": null, + "dnsBypassIp6": null, + "dnsBypassTtl": null, + "dscp": 0, + "ecsEnabled": false, + "edgeHeaderRewrite": null, "exampleURLs": [ "http://video.demo1.mycdn.ciab.test", "https://video.demo1.mycdn.ciab.test" ], - "deepCachingType": "NEVER", + "firstHeaderRewrite": null, "fqPacingRate": null, + "geoLimit": 0, + "geoLimitCountries": null, + "geoLimitRedirectURL": null, + "geoProvider": 0, + "globalMaxMbps": null, + "globalMaxTps": null, + "httpBypassFqdn": null, + "id": 1, + "infoUrl": null, + "initialDispersion": 1, + "innerHeaderRewrite": null, + "ipv6RoutingEnabled": true, + "lastHeaderRewrite": null, + "lastUpdated": "2020-02-13T16:43:54Z", + "logsEnabled": true, + "longDesc": "Apachecon North America 2018", + "matchList": [ + { + "type": "HOST_REGEXP", + "setNumber": 0, + "pattern": ".*\\.demo1\\..*" + } + ], + "maxDnsAnswers": null, + "maxOriginConnections": 0, + "maxRequestHeaderBytes": 0, + "midHeaderRewrite": null, + "missLat": 42, + "missLong": -88, + "multiSiteOrigin": false, + "originShield": null, + "orgServerFqdn": "http://origin.infra.ciab.test", + "profileDescription": null, + "profileId": null, + "profileName": null, + "protocol": 2, + "qstringIgnore": 0, + "rangeRequestHandling": 0, + "rangeSliceBlockSize": null, + "regexRemap": null, + "regional": false, + "regionalGeoBlocking": false, + "remapText": null, + "routingName": "video", + "serviceCategory": null, + "signed": false, "signingAlgorithm": null, + "sslKeyVersion": 1, "tenant": "root", + "tenantId": 1, + "tlsVersions": null, + "topology": null, "trResponseHeaders": null, "trRequestHeaders": null, - "consistentHashRegex": null, - "consistentHashQueryParams": [ - "abc", - "pdq", - "xxx", - "zyx" - ], - "maxOriginConnections": 0, - "ecsEnabled": false, - "tlsVersions": null + "type": "HTTP", + "typeId": 1, + "xmlId": "demo1" }, "status": "draft" }]} @@ -201,10 +290,10 @@ The response is an array of representations of :term:`Delivery Service Requests` ======== Creates a new :term:`Delivery Service Request`. "Closed" :term:`Delivery Service Requests` cannot be created, an existing :term:`Delivery Service Request` must be placed into a closed :ref:`dsr-status`. A :term:`Delivery Service Request` to create, modify or delete a :term:`Delivery Service` cannot be created if an open :term:`Delivery Service Request` exists for a :term:`Delivery Service` with the same :ref:`ds-xmlid`. Because of this, :term:`Delivery Service Requests` cannot be used to change a :term:`Delivery Service`'s :ref:`ds-xmlid`. -:Auth. Required: Yes -:Roles Required: "admin", "Federation", "operations", "Portal", or "Steering" +:Auth. Required: Yes +:Roles Required: "admin", "Federation", "operations", "Portal", or "Steering" :Permissions Required: DS-REQUEST:CREATE, DELIVERY-SERVICE:READ, USER:READ -:Response Type: Object +:Response Type: Object Request Structure ----------------- @@ -214,18 +303,19 @@ The request must be a well-formed representation of a :term:`Delivery Service Re :caption: Request Example POST /api/5.0/deliveryservice_requests HTTP/1.1 - User-Agent: python-requests/2.22.0 + User-Agent: python-requests/2.25.1 Accept-Encoding: gzip, deflate Accept: */* Connection: keep-alive - Cookie: mojolicious=... - Content-Length: 1979 + Cookie: access_token=...; mojolicious=... + Content-Length: 2011 + Content-Type: application/json { "changeType": "update", "status": "draft", "requested": { - "active": false, + "active": "INACTIVE", "anonymousBlockingEnabled": false, "cacheurl": null, "ccrDnsTtl": null, @@ -320,315 +410,62 @@ The response will be a representation of the created :term:`Delivery Service Req .. code-block:: http :caption: Response Example - HTTP/1.1 201 CREATED - Access-Control-Allow-Credentials: true - Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Set-Cookie, Cookie - Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE - Access-Control-Allow-Origin: * - Content-Encoding: gzip - Content-Type: application/json - Set-Cookie: mojolicious=...; Path=/; Expires=Mon, 24 Feb 2020 20:11:12 GMT; Max-Age=3600; HttpOnly - Location: /api/5.0/deliveryservice_requests/2 - X-Server-Name: traffic_ops_golang/ - Date: Mon, 24 Feb 2020 19:11:12 GMT - Content-Length: 901 - - { - "alerts": [ - { - "text": "deliveryservice_request was created.", - "level": "success" - } - ], - "response": { - "authorId": 2, - "author": null, - "changeType": "update", - "createdAt": null, - "id": 2, - "lastEditedBy": null, - "lastEditedById": 2, - "lastUpdated": "2020-02-24 19:11:12+00", - "requested": { - "active": false, - "anonymousBlockingEnabled": false, - "cacheurl": null, - "ccrDnsTtl": null, - "cdnId": 2, - "cdnName": "CDN-in-a-Box", - "checkPath": null, - "displayName": "Demo 1", - "dnsBypassCname": null, - "dnsBypassIp": null, - "dnsBypassIp6": null, - "dnsBypassTtl": null, - "dscp": 0, - "edgeHeaderRewrite": null, - "firstHeaderRewrite": null, - "geoLimit": 0, - "geoLimitCountries": null, - "geoLimitRedirectURL": null, - "geoProvider": 0, - "globalMaxMbps": null, - "globalMaxTps": null, - "httpBypassFqdn": null, - "id": 1, - "infoUrl": null, - "initialDispersion": 1, - "innerHeaderRewrite": null, - "ipv6RoutingEnabled": true, - "lastHeaderRewrite": null, - "lastUpdated": "0001-01-01T00:00:00Z", - "logsEnabled": true, - "longDesc": "Apachecon North America 2018", - "matchList": [ - { - "type": "HOST_REGEXP", - "setNumber": 0, - "pattern": ".*\\.demo1\\..*" - } - ], - "maxDnsAnswers": null, - "midHeaderRewrite": null, - "missLat": 42, - "missLong": -88, - "multiSiteOrigin": false, - "originShield": null, - "orgServerFqdn": "http://origin.infra.ciab.test", - "profileDescription": null, - "profileId": null, - "profileName": null, - "protocol": 2, - "qstringIgnore": 0, - "rangeRequestHandling": 0, - "regexRemap": null, - "regional": false, - "regionalGeoBlocking": false, - "remapText": null, - "routingName": "video", - "signed": false, - "sslKeyVersion": 1, - "tenantId": 1, - "topology": null, - "type": "HTTP", - "typeId": 1, - "xmlId": "demo1", - "exampleURLs": [ - "http://video.demo1.mycdn.ciab.test", - "https://video.demo1.mycdn.ciab.test" - ], - "deepCachingType": "NEVER", - "fqPacingRate": null, - "signingAlgorithm": null, - "tenant": "root", - "trResponseHeaders": null, - "trRequestHeaders": null, - "consistentHashRegex": null, - "consistentHashQueryParams": [ - "abc", - "pdq", - "xxx", - "zyx" - ], - "maxOriginConnections": 0, - "ecsEnabled": false, - "tlsVersions": null - }, - "original": { - "active": true, - "anonymousBlockingEnabled": false, - "cacheurl": null, - "ccrDnsTtl": null, - "cdnId": 2, - "cdnName": "CDN-in-a-Box", - "checkPath": null, - "displayName": "Demo 1", - "dnsBypassCname": null, - "dnsBypassIp": null, - "dnsBypassIp6": null, - "dnsBypassTtl": null, - "dscp": 0, - "edgeHeaderRewrite": null, - "firstHeaderRewrite": null, - "geoLimit": 0, - "geoLimitCountries": null, - "geoLimitRedirectURL": null, - "geoProvider": 0, - "globalMaxMbps": null, - "globalMaxTps": null, - "httpBypassFqdn": null, - "id": 1, - "infoUrl": null, - "initialDispersion": 1, - "innerHeaderRewrite": null, - "ipv6RoutingEnabled": true, - "lastHeaderRewrite": null, - "lastUpdated": "2020-02-13T16:43:54Z", - "logsEnabled": true, - "longDesc": "Apachecon North America 2018", - "matchList": [ - { - "type": "HOST_REGEXP", - "setNumber": 0, - "pattern": ".*\\.demo1\\..*" - } - ], - "maxDnsAnswers": null, - "midHeaderRewrite": null, - "missLat": 42, - "missLong": -88, - "multiSiteOrigin": false, - "originShield": null, - "orgServerFqdn": "http://origin.infra.ciab.test", - "profileDescription": null, - "profileId": null, - "profileName": null, - "protocol": 2, - "qstringIgnore": 0, - "rangeRequestHandling": 0, - "regexRemap": null, - "regional": false, - "regionalGeoBlocking": false, - "remapText": null, - "routingName": "video", - "signed": false, - "sslKeyVersion": 1, - "tenantId": 1, - "type": "HTTP", - "typeId": 1, - "xmlId": "demo1", - "exampleURLs": [ - "http://video.demo1.mycdn.ciab.test", - "https://video.demo1.mycdn.ciab.test" - ], - "deepCachingType": "NEVER", - "fqPacingRate": null, - "signingAlgorithm": null, - "tenant": "root", - "topology": null, - "trResponseHeaders": null, - "trRequestHeaders": null, - "consistentHashRegex": null, - "consistentHashQueryParams": [ - "abc", - "pdq", - "xxx", - "zyx" - ], - "maxOriginConnections": 0, - "ecsEnabled": false, - "serviceCategory": null, - "tlsVersions": null - }, - "status": "draft" - } - } - -``PUT`` -======= -Updates an existing :term:`Delivery Service Request`. Note that "closed" :term:`Delivery Service Requests` are uneditable. - -.. seealso:: The proper way to change a :term:`Delivery Service Request`'s :ref:`dsr-status` is by using the :ref:`to-api-deliveryservice_requests-id-status` endpoint's ``PUT`` handler. - -:Auth. Required: Yes -:Roles Required: "admin", "Federation", "operations", "Portal", or "Steering" -:Permissions Required: DS-REQUEST:UPDATE, DELIVERY-SERVICE:READ, USER:READ -:Response Type: Object - -Request Structure ------------------ -.. table:: Request Query Parameters - - +-----------+----------+--------------------------------------------------------------------------------------------------+ - | Name | Required | Description | - +===========+==========+==================================================================================================+ - | id | yes | The integral, unique identifier of the :term:`Delivery Service Request` that you want to update. | - +-----------+----------+--------------------------------------------------------------------------------------------------+ - -The request body must be a representation of a :term:`Delivery Service Request` without any response-only fields. - -.. code-block:: http - :caption: Request Example - - PUT /api/5.0/deliveryservice_requests?id=1 HTTP/1.1 - User-Agent: python-requests/2.22.0 - Accept-Encoding: gzip, deflate - Accept: */* - Connection: keep-alive - Cookie: mojolicious=... - Content-Length: 2256 - - { - "changeType": "update", - "requested": { - "active": true, - "cdnId": 2, - "ccrDnsTtl": 30, - "deepCachingType": "NEVER", - "displayName": "Demo 1 but I modified the DSR", - "dscp": 0, - "geoLimit": 0, - "geoProvider": 0, - "initialDispersion": 3, - "logsEnabled": false, - "longDesc": "long desc", - "regional": false, - "regionalGeoBlocking": false, - "tenantId": 1, - "typeId": 8, - "xmlId": "demo1", - "id": 1 - }, - "status": "draft" - } - -Response Structure ------------------- -The response is a full representation of the edited :term:`Delivery Service Request`. - -.. code-block:: http - :caption: Response Example - - HTTP/1.1 200 OK + HTTP/1.1 201 Created Access-Control-Allow-Credentials: true Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Set-Cookie, Cookie Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE Access-Control-Allow-Origin: * Content-Encoding: gzip Content-Type: application/json - Set-Cookie: mojolicious=...; Path=/; Expires=Mon, 24 Feb 2020 20:36:16 GMT; Max-Age=3600; HttpOnly - Whole-Content-Sha512: +W0vFm96yFkZUJqa0GAX7uzIpRKh/ohyBm0uH3egpiERTcxy5OfVVtoP3h8Ee2teLu8KFooDYXJ6rpQg6UhbNQ== + Location: /api/5.0/deliveryservice_requests/1 + Permissions-Policy: interest-cohort=() + Set-Cookie: mojolicious=...; Path=/; Expires=Thu, 29 Sep 2022 23:07:15 GMT; Max-Age=3600; HttpOnly, access_token=...; Path=/; Expires=Thu, 29 Sep 2022 23:07:15 GMT; Max-Age=3600; HttpOnly + Vary: Accept-Encoding X-Server-Name: traffic_ops_golang/ - Date: Mon, 24 Feb 2020 19:36:16 GMT - Content-Length: 913 + Date: Thu, 29 Sep 2022 22:07:15 GMT + Content-Length: 1027 { "alerts": [{ - "text": "Delivery Service Request #2 updated", + "text": "Delivery Service request created", "level": "success" }], "response": { "assignee": null, - "author": "", + "author": "admin", "changeType": "update", - "createdAt": "2020-09-25T06:23:30.683058Z", - "id": null, + "createdAt": "2022-09-29T22:07:15.008503Z", + "id": 1, "lastEditedBy": "admin", - "lastUpdated": "2020-09-25T02:38:04.180237Z", + "lastUpdated": "2022-09-29T22:07:15.008503Z", "original": { - "active": true, + "active": "ACTIVE", "anonymousBlockingEnabled": false, - "cacheurl": null, "ccrDnsTtl": null, "cdnId": 2, "cdnName": "CDN-in-a-Box", "checkPath": null, + "consistentHashQueryParams": [ + "abc", + "pdq", + "xxx", + "zyx" + ], + "consistentHashRegex": null, + "deepCachingType": "NEVER", "displayName": "Demo 1", "dnsBypassCname": null, "dnsBypassIp": null, "dnsBypassIp6": null, "dnsBypassTtl": null, "dscp": 0, + "ecsEnabled": false, "edgeHeaderRewrite": null, + "exampleURLs": [ + "http://video.demo1.mycdn.ciab.test", + "https://video.demo1.mycdn.ciab.test" + ], + "firstHeaderRewrite": null, + "fqPacingRate": null, "geoLimit": 0, "geoLimitCountries": null, "geoLimitRedirectURL": null, @@ -639,8 +476,10 @@ The response is a full representation of the edited :term:`Delivery Service Requ "id": 1, "infoUrl": null, "initialDispersion": 1, + "innerHeaderRewrite": null, "ipv6RoutingEnabled": true, - "lastUpdated": "2020-09-25T02:09:54Z", + "lastHeaderRewrite": null, + "lastUpdated": "2022-09-29T20:58:53.07251Z", "logsEnabled": true, "longDesc": "Apachecon North America 2018", "matchList": [ @@ -651,10 +490,12 @@ The response is a full representation of the edited :term:`Delivery Service Requ } ], "maxDnsAnswers": null, + "maxOriginConnections": 0, + "maxRequestHeaderBytes": 0, "midHeaderRewrite": null, "missLat": 42, "missLong": -88, - "multiSiteOrigin": false, + "multiSiteOrigin": true, "originShield": null, "orgServerFqdn": "http://origin.infra.ciab.test", "profileDescription": null, @@ -663,59 +504,315 @@ The response is a full representation of the edited :term:`Delivery Service Requ "protocol": 2, "qstringIgnore": 0, "rangeRequestHandling": 0, + "rangeSliceBlockSize": null, "regexRemap": null, "regional": false, "regionalGeoBlocking": false, "remapText": null, "routingName": "video", + "serviceCategory": null, "signed": false, - "sslKeyVersion": 1, - "tenantId": 1, - "type": "HTTP", - "typeId": 1, - "xmlId": "demo1", - "exampleURLs": [ - "http://video.demo1.mycdn.ciab.test", - "https://video.demo1.mycdn.ciab.test" - ], - "deepCachingType": "NEVER", - "fqPacingRate": null, "signingAlgorithm": null, + "sslKeyVersion": 1, "tenant": "root", + "tenantId": 1, + "tlsVersions": null, + "topology": "demo1-top", "trResponseHeaders": null, "trRequestHeaders": null, - "consistentHashRegex": null, + "type": "HTTP", + "typeId": 1, + "xmlId": "demo1" + }, + "requested": { + "active": "INACTIVE", + "anonymousBlockingEnabled": false, + "ccrDnsTtl": null, + "cdnId": 2, + "cdnName": "CDN-in-a-Box", + "checkPath": null, "consistentHashQueryParams": [ "abc", "pdq", "xxx", "zyx" ], - "maxOriginConnections": 0, + "consistentHashRegex": null, + "deepCachingType": "NEVER", + "displayName": "Demo 1", + "dnsBypassCname": null, + "dnsBypassIp": null, + "dnsBypassIp6": null, + "dnsBypassTtl": null, + "dscp": 0, "ecsEnabled": false, - "rangeSliceBlockSize": null, - "topology": "demo1-top", + "edgeHeaderRewrite": null, + "exampleURLs": [ + "http://video.demo1.mycdn.ciab.test", + "https://video.demo1.mycdn.ciab.test" + ], "firstHeaderRewrite": null, + "fqPacingRate": null, + "geoLimit": 0, + "geoLimitCountries": null, + "geoLimitRedirectURL": null, + "geoProvider": 0, + "globalMaxMbps": null, + "globalMaxTps": null, + "httpBypassFqdn": null, + "id": 1, + "infoUrl": null, + "initialDispersion": 1, "innerHeaderRewrite": null, + "ipv6RoutingEnabled": true, "lastHeaderRewrite": null, + "lastUpdated": "2020-02-13T16:43:54Z", + "logsEnabled": true, + "longDesc": "Apachecon North America 2018", + "matchList": [ + { + "type": "HOST_REGEXP", + "setNumber": 0, + "pattern": ".*\\.demo1\\..*" + } + ], + "maxDnsAnswers": null, + "maxOriginConnections": 0, + "maxRequestHeaderBytes": 0, + "midHeaderRewrite": null, + "missLat": 42, + "missLong": -88, + "multiSiteOrigin": false, + "originShield": null, + "orgServerFqdn": "http://origin.infra.ciab.test", + "profileDescription": null, + "profileId": null, + "profileName": null, + "protocol": 2, + "qstringIgnore": 0, + "rangeRequestHandling": 0, + "rangeSliceBlockSize": null, + "regexRemap": null, + "regional": false, + "regionalGeoBlocking": false, + "remapText": null, + "routingName": "video", "serviceCategory": null, - "tlsVersions": null + "signed": false, + "signingAlgorithm": null, + "sslKeyVersion": 1, + "tenant": "root", + "tenantId": 1, + "tlsVersions": null, + "topology": null, + "trResponseHeaders": null, + "trRequestHeaders": null, + "type": "HTTP", + "typeId": 1, + "xmlId": "demo1" }, + "status": "draft" + }} + +``PUT`` +======= +Updates an existing :term:`Delivery Service Request`. Note that "closed" :term:`Delivery Service Requests` are uneditable. + +.. seealso:: The proper way to change a :term:`Delivery Service Request`'s :ref:`dsr-status` is by using the :ref:`to-api-deliveryservice_requests-id-status` endpoint's ``PUT`` handler. + +:Auth. Required: Yes +:Roles Required: "admin", "Federation", "operations", "Portal", or "Steering" +:Permissions Required: DS-REQUEST:UPDATE, DELIVERY-SERVICE:READ, USER:READ +:Response Type: Object + +Request Structure +----------------- +.. table:: Request Query Parameters + + +-----------+----------+--------------------------------------------------------------------------------------------------+ + | Name | Required | Description | + +===========+==========+==================================================================================================+ + | id | yes | The integral, unique identifier of the :term:`Delivery Service Request` that you want to update. | + +-----------+----------+--------------------------------------------------------------------------------------------------+ + +The request body must be a representation of a :term:`Delivery Service Request` without any response-only fields. + +.. code-block:: http + :caption: Request Example + + PUT /api/5.0/deliveryservice_requests?id=1 HTTP/1.1 + User-Agent: python-requests/2.25.1 + Accept-Encoding: gzip, deflate + Accept: */* + Connection: keep-alive + Cookie: access_token=...; mojolicious=... + Content-Length: 426 + + { + "changeType": "update", "requested": { - "active": true, + "active": "INACTIVE", + "cdnId": 2, + "ccrDnsTtl": 30, + "deepCachingType": "NEVER", + "displayName": "Demo 1 but I modified the DSR", + "dscp": 0, + "geoLimit": 0, + "geoProvider": 0, + "initialDispersion": 3, + "logsEnabled": false, + "longDesc": "long desc", + "regional": false, + "regionalGeoBlocking": false, + "tenantId": 1, + "typeId": 8, + "xmlId": "demo1", + "id": 1 + }, + "status": "draft" + } + +Response Structure +------------------ +The response is a full representation of the edited :term:`Delivery Service Request`. + +.. code-block:: http + :caption: Response Example + + HTTP/1.1 200 OK + Access-Control-Allow-Credentials: true + Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Set-Cookie, Cookie + Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE + Access-Control-Allow-Origin: * + Content-Encoding: gzip + Content-Type: application/json + Permissions-Policy: interest-cohort=() + Set-Cookie: mojolicious=...; Path=/; Expires=Thu, 29 Sep 2022 23:16:06 GMT; Max-Age=3600; HttpOnly, access_token=...; Path=/; Expires=Thu, 29 Sep 2022 23:16:06 GMT; Max-Age=3600; HttpOnly + Vary: Accept-Encoding + X-Server-Name: traffic_ops_golang/ + Date: Thu, 29 Sep 2022 22:16:06 GMT + Content-Length: 1142 + + { "alerts": [{ + "text": "Delivery Service Request #1 updated", + "level": "success" + }], + "response": { + "assignee": null, + "author": "", + "changeType": "update", + "createdAt": "2022-09-29T22:16:06.971122Z", + "id": null, + "lastEditedBy": "admin", + "lastUpdated": "2022-09-29T22:07:15.008503Z", + "original": { + "active": "ACTIVE", + "anonymousBlockingEnabled": false, + "ccrDnsTtl": null, + "cdnId": 2, + "cdnName": "CDN-in-a-Box", + "checkPath": null, + "consistentHashQueryParams": [ + "abc", + "pdq", + "xxx", + "zyx" + ], + "consistentHashRegex": null, + "deepCachingType": "NEVER", + "displayName": "Demo 1", + "dnsBypassCname": null, + "dnsBypassIp": null, + "dnsBypassIp6": null, + "dnsBypassTtl": null, + "dscp": 0, + "ecsEnabled": false, + "edgeHeaderRewrite": null, + "exampleURLs": [ + "http://video.demo1.mycdn.ciab.test", + "https://video.demo1.mycdn.ciab.test" + ], + "firstHeaderRewrite": null, + "fqPacingRate": null, + "geoLimit": 0, + "geoLimitCountries": null, + "geoLimitRedirectURL": null, + "geoProvider": 0, + "globalMaxMbps": null, + "globalMaxTps": null, + "httpBypassFqdn": null, + "id": 1, + "infoUrl": null, + "initialDispersion": 1, + "innerHeaderRewrite": null, + "ipv6RoutingEnabled": true, + "lastHeaderRewrite": null, + "lastUpdated": "2022-09-29T20:58:53.07251Z", + "logsEnabled": true, + "longDesc": "Apachecon North America 2018", + "matchList": [ + { + "type": "HOST_REGEXP", + "setNumber": 0, + "pattern": ".*\\.demo1\\..*" + } + ], + "maxDnsAnswers": null, + "maxOriginConnections": 0, + "maxRequestHeaderBytes": 0, + "midHeaderRewrite": null, + "missLat": 42, + "missLong": -88, + "multiSiteOrigin": true, + "originShield": null, + "orgServerFqdn": "http://origin.infra.ciab.test", + "profileDescription": null, + "profileId": null, + "profileName": null, + "protocol": 2, + "qstringIgnore": 0, + "rangeRequestHandling": 0, + "rangeSliceBlockSize": null, + "regexRemap": null, + "regional": false, + "regionalGeoBlocking": false, + "remapText": null, + "routingName": "video", + "serviceCategory": null, + "signed": false, + "signingAlgorithm": null, + "sslKeyVersion": 1, + "tenant": "root", + "tenantId": 1, + "tlsVersions": null, + "topology": "demo1-top", + "trResponseHeaders": null, + "trRequestHeaders": null, + "type": "HTTP", + "typeId": 1, + "xmlId": "demo1" + }, + "requested": { + "active": "INACTIVE", "anonymousBlockingEnabled": false, - "cacheurl": null, "ccrDnsTtl": 30, "cdnId": 2, "cdnName": null, "checkPath": null, + "consistentHashQueryParams": null, + "consistentHashRegex": null, + "deepCachingType": "NEVER", "displayName": "Demo 1 but I modified the DSR", "dnsBypassCname": null, "dnsBypassIp": null, "dnsBypassIp6": null, "dnsBypassTtl": null, "dscp": 0, + "ecsEnabled": false, "edgeHeaderRewrite": null, + "exampleURLs": null, + "firstHeaderRewrite": null, + "fqPacingRate": null, "geoLimit": 0, "geoLimitCountries": null, "geoLimitRedirectURL": null, @@ -726,16 +823,20 @@ The response is a full representation of the edited :term:`Delivery Service Requ "id": 1, "infoUrl": null, "initialDispersion": 3, + "innerHeaderRewrite": null, "ipv6RoutingEnabled": null, - "lastUpdated": null, + "lastHeaderRewrite": null, + "lastUpdated": "0001-01-01T00:00:00Z", "logsEnabled": false, "longDesc": "long desc", "matchList": null, "maxDnsAnswers": null, + "maxOriginConnections": 0, + "maxRequestHeaderBytes": 0, "midHeaderRewrite": null, "missLat": null, "missLong": null, - "multiSiteOrigin": null, + "multiSiteOrigin": false, "originShield": null, "orgServerFqdn": null, "profileDescription": null, @@ -744,35 +845,25 @@ The response is a full representation of the edited :term:`Delivery Service Requ "protocol": null, "qstringIgnore": null, "rangeRequestHandling": null, + "rangeSliceBlockSize": null, "regexRemap": null, "regional": false, "regionalGeoBlocking": false, "remapText": null, "routingName": "cdn", + "serviceCategory": null, "signed": false, - "sslKeyVersion": null, - "tenantId": 1, - "type": null, - "typeId": 8, - "xmlId": "demo1", - "exampleURLs": null, - "deepCachingType": "NEVER", - "fqPacingRate": null, "signingAlgorithm": null, + "sslKeyVersion": null, "tenant": null, + "tenantId": 1, + "tlsVersions": null, + "topology": null, "trResponseHeaders": null, "trRequestHeaders": null, - "consistentHashRegex": null, - "consistentHashQueryParams": null, - "maxOriginConnections": 0, - "ecsEnabled": false, - "rangeSliceBlockSize": null, - "topology": null, - "firstHeaderRewrite": null, - "innerHeaderRewrite": null, - "lastHeaderRewrite": null, - "serviceCategory": null, - "tlsVersions": null + "type": null, + "typeId": 8, + "xmlId": "demo1" }, "status": "draft" }} @@ -782,10 +873,10 @@ The response is a full representation of the edited :term:`Delivery Service Requ ========== Deletes a :term:`Delivery Service Request`. -:Auth. Required: Yes -:Roles Required: "admin", "Federation", "operations", "Portal", or "Steering" +:Auth. Required: Yes +:Roles Required: "admin", "Federation", "operations", "Portal", or "Steering" :Permissions Required: DS-REQUEST:DELETE, DELIVERY-SERVICE:READ, USER:READ -:Response Type: Object +:Response Type: Object Request Structure ----------------- @@ -801,11 +892,11 @@ Request Structure :caption: Request Example DELETE /api/5.0/deliveryservice_requests?id=1 HTTP/1.1 - User-Agent: python-requests/2.22.0 + User-Agent: python-requests/2.25.1 Accept-Encoding: gzip, deflate Accept: */* Connection: keep-alive - Cookie: mojolicious=... + Cookie: access_token=...; mojolicious=... Content-Length: 0 Response Structure @@ -815,24 +906,189 @@ The response is a full representation of the deleted :term:`Delivery Service Req .. code-block:: http :caption: Response Example - HTTP/1.1 200 OK + HTTP/1.1 200 OK HTTP/1.1 200 OK Access-Control-Allow-Credentials: true Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Set-Cookie, Cookie Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE Access-Control-Allow-Origin: * Content-Encoding: gzip Content-Type: application/json - Set-Cookie: mojolicious=...; Path=/; Expires=Mon, 24 Feb 2020 20:48:55 GMT; Max-Age=3600; HttpOnly - Whole-Content-Sha512: jNCbNo8Tw+JMMaWpAYQgntSXPq2Xuj+n2zSEVRaDQFWMV1SYbT9djes6SPdwiBoKq6W0lNE04hOE92jBVcjtEw== + Permissions-Policy: interest-cohort=() + Set-Cookie: mojolicious=...; Path=/; Expires=Thu, 29 Sep 2022 23:26:31 GMT; Max-Age=3600; HttpOnly, access_token=...; Path=/; Expires=Thu, 29 Sep 2022 23:26:31 GMT; Max-Age=3600; HttpOnly + Vary: Accept-Encoding X-Server-Name: traffic_ops_golang/ - Date: Mon, 24 Feb 2020 19:48:55 GMT - Content-Length: 96 + Date: Thu, 29 Sep 2022 22:26:31 GMT + Content-Length: 1147 - { - "alerts": [ - { - "text": "deliveryservice_request was deleted.", - "level": "success" - } - ] - } + { "alerts": [{ + "text": "Delivery Service Request #1 deleted", + "level": "success" + }], + "response": { + "assignee": "admin", + "author": "admin", + "changeType": "update", + "createdAt": "2022-09-29T22:07:15.008503Z", + "id": 1, + "lastEditedBy": "admin", + "lastUpdated": "2022-09-29T22:23:28.034845Z", + "original": { + "active": "ACTIVE", + "anonymousBlockingEnabled": false, + "ccrDnsTtl": null, + "cdnId": 2, + "cdnName": "CDN-in-a-Box", + "checkPath": null, + "consistentHashQueryParams": [ + "abc", + "pdq", + "xxx", + "zyx" + ], + "consistentHashRegex": null, + "deepCachingType": "NEVER", + "displayName": "Demo 1", + "dnsBypassCname": null, + "dnsBypassIp": null, + "dnsBypassIp6": null, + "dnsBypassTtl": null, + "dscp": 0, + "ecsEnabled": false, + "edgeHeaderRewrite": null, + "exampleURLs": [ + "http://video.demo1.mycdn.ciab.test", + "https://video.demo1.mycdn.ciab.test" + ], + "firstHeaderRewrite": null, + "fqPacingRate": null, + "geoLimit": 0, + "geoLimitCountries": null, + "geoLimitRedirectURL": null, + "geoProvider": 0, + "globalMaxMbps": null, + "globalMaxTps": null, + "httpBypassFqdn": null, + "id": 1, + "infoUrl": null, + "initialDispersion": 1, + "innerHeaderRewrite": null, + "ipv6RoutingEnabled": true, + "lastHeaderRewrite": null, + "lastUpdated": "2022-09-29T20:58:53.07251Z", + "logsEnabled": true, + "longDesc": "Apachecon North America 2018", + "matchList": [ + { + "type": "HOST_REGEXP", + "setNumber": 0, + "pattern": ".*\\.demo1\\..*" + } + ], + "maxDnsAnswers": null, + "maxOriginConnections": 0, + "maxRequestHeaderBytes": 0, + "midHeaderRewrite": null, + "missLat": 42, + "missLong": -88, + "multiSiteOrigin": true, + "originShield": null, + "orgServerFqdn": "http://origin.infra.ciab.test", + "profileDescription": null, + "profileId": null, + "profileName": null, + "protocol": 2, + "qstringIgnore": 0, + "rangeRequestHandling": 0, + "rangeSliceBlockSize": null, + "regexRemap": null, + "regionalGeoBlocking": false, + "remapText": null, + "routingName": "video", + "serviceCategory": null, + "signed": false, + "signingAlgorithm": null, + "sslKeyVersion": 1, + "tenant": "root", + "tenantId": 1, + "tlsVersions": null, + "topology": "demo1-top", + "trResponseHeaders": null, + "trRequestHeaders": null, + "type": "HTTP", + "typeId": 1, + "xmlId": "demo1" + }, + "requested": { + "active": "INACTIVE", + "anonymousBlockingEnabled": false, + "ccrDnsTtl": 30, + "cdnId": 2, + "cdnName": null, + "checkPath": null, + "consistentHashQueryParams": null, + "consistentHashRegex": null, + "deepCachingType": "NEVER", + "displayName": "Demo 1 but I modified the DSR", + "dnsBypassCname": null, + "dnsBypassIp": null, + "dnsBypassIp6": null, + "dnsBypassTtl": null, + "dscp": 0, + "ecsEnabled": false, + "edgeHeaderRewrite": null, + "exampleURLs": null, + "firstHeaderRewrite": null, + "fqPacingRate": null, + "geoLimit": 0, + "geoLimitCountries": null, + "geoLimitRedirectURL": null, + "geoProvider": 0, + "globalMaxMbps": null, + "globalMaxTps": null, + "httpBypassFqdn": null, + "id": 1, + "infoUrl": null, + "initialDispersion": 3, + "innerHeaderRewrite": null, + "ipv6RoutingEnabled": null, + "lastHeaderRewrite": null, + "lastUpdated": "0001-01-01T00:00:00Z", + "logsEnabled": false, + "longDesc": "long desc", + "matchList": null, + "maxDnsAnswers": null, + "maxOriginConnections": 0, + "maxRequestHeaderBytes": 0, + "midHeaderRewrite": null, + "missLat": null, + "missLong": null, + "multiSiteOrigin": false, + "originShield": null, + "orgServerFqdn": null, + "profileDescription": null, + "profileId": null, + "profileName": null, + "protocol": null, + "qstringIgnore": null, + "rangeRequestHandling": null, + "rangeSliceBlockSize": null, + "regexRemap": null, + "regionalGeoBlocking": false, + "remapText": null, + "routingName": "cdn", + "serviceCategory": null, + "signed": false, + "signingAlgorithm": null, + "sslKeyVersion": null, + "tenant": null, + "tenantId": 1, + "tlsVersions": null, + "topology": null, + "trResponseHeaders": null, + "trRequestHeaders": null, + "type": null, + "typeId": 8, + "xmlId": "demo1" + }, + "status": "submitted" + }} diff --git a/docs/source/api/v5/deliveryservice_requests_id_assign.rst b/docs/source/api/v5/deliveryservice_requests_id_assign.rst index 389bcab17e..cf3637959a 100644 --- a/docs/source/api/v5/deliveryservice_requests_id_assign.rst +++ b/docs/source/api/v5/deliveryservice_requests_id_assign.rst @@ -97,12 +97,12 @@ Request Structure :caption: Request Example PUT /api/5.0/deliveryservice_requests/1/assign HTTP/1.1 - User-Agent: python-requests/2.24.0 + User-Agent: python-requests/2.25.1 Accept-Encoding: gzip, deflate Accept: */* Connection: keep-alive - Cookie: mojolicious=... - Content-Length: 20 + Cookie: access_token=...; mojolicious=... + Content-Length: 21 {"assignee": "admin"} @@ -120,11 +120,12 @@ The response contains a full representation of the newly assigned :term:`Deliver Access-Control-Allow-Origin: * Content-Encoding: gzip Content-Type: application/json - Set-Cookie: mojolicious=...; Path=/; Expires=Sun, 23 Feb 2020 14:45:51 GMT; Max-Age=3600; HttpOnly - Whole-Content-Sha512: h7uBZHLQtRYbOSOR5AtQQrZ4uMeEWivWNT74fCf6WtLbAMwGpRrMjNmBYKduv48DEnRqG6WVM/4nBu3AkCUqPw== + Permissions-Policy: interest-cohort=() + Set-Cookie: mojolicious=...; Path=/; Expires=Thu, 29 Sep 2022 23:23:28 GMT; Max-Age=3600; HttpOnly, access_token=...; Path=/; Expires=Thu, 29 Sep 2022 23:23:28 GMT; Max-Age=3600; HttpOnly + Vary: Accept-Encoding X-Server-Name: traffic_ops_golang/ - Date: Sun, 23 Feb 2020 13:45:51 GMT - Content-Length: 931 + Date: Thu, 29 Sep 2022 22:23:28 GMT + Content-Length: 1159 { "alerts": [{ "text": "Changed assignee of 'demo1' Delivery Service Request to 'admin'", @@ -134,25 +135,39 @@ The response contains a full representation of the newly assigned :term:`Deliver "assignee": "admin", "author": "admin", "changeType": "update", - "createdAt": "2020-09-25T06:52:23.758877Z", - "id": 6, + "createdAt": "2022-09-29T22:07:15.008503Z", + "id": 1, "lastEditedBy": "admin", - "lastUpdated": "2020-09-25T07:01:24.600029Z", + "lastUpdated": "2022-09-29T22:23:28.034845Z", "original": { - "active": true, + "active": "ACTIVE", "anonymousBlockingEnabled": false, - "cacheurl": null, "ccrDnsTtl": null, "cdnId": 2, "cdnName": "CDN-in-a-Box", "checkPath": null, + "consistentHashQueryParams": [ + "abc", + "pdq", + "xxx", + "zyx" + ], + "consistentHashRegex": null, + "deepCachingType": "NEVER", "displayName": "Demo 1", "dnsBypassCname": null, "dnsBypassIp": null, "dnsBypassIp6": null, "dnsBypassTtl": null, "dscp": 0, + "ecsEnabled": false, "edgeHeaderRewrite": null, + "exampleURLs": [ + "http://video.demo1.mycdn.ciab.test", + "https://video.demo1.mycdn.ciab.test" + ], + "firstHeaderRewrite": null, + "fqPacingRate": null, "geoLimit": 0, "geoLimitCountries": null, "geoLimitRedirectURL": null, @@ -163,8 +178,10 @@ The response contains a full representation of the newly assigned :term:`Deliver "id": 1, "infoUrl": null, "initialDispersion": 1, + "innerHeaderRewrite": null, "ipv6RoutingEnabled": true, - "lastUpdated": "2020-09-25T02:09:54Z", + "lastHeaderRewrite": null, + "lastUpdated": "2022-09-29T20:58:53.07251Z", "logsEnabled": true, "longDesc": "Apachecon North America 2018", "matchList": [ @@ -175,10 +192,12 @@ The response contains a full representation of the newly assigned :term:`Deliver } ], "maxDnsAnswers": null, + "maxOriginConnections": 0, + "maxRequestHeaderBytes": 0, "midHeaderRewrite": null, "missLat": 42, "missLong": -88, - "multiSiteOrigin": false, + "multiSiteOrigin": true, "originShield": null, "orgServerFqdn": "http://origin.infra.ciab.test", "profileDescription": null, @@ -187,59 +206,47 @@ The response contains a full representation of the newly assigned :term:`Deliver "protocol": 2, "qstringIgnore": 0, "rangeRequestHandling": 0, + "rangeSliceBlockSize": null, "regexRemap": null, "regional": false, "regionalGeoBlocking": false, "remapText": null, "routingName": "video", + "serviceCategory": null, "signed": false, - "sslKeyVersion": 1, - "tenantId": 1, - "type": "HTTP", - "typeId": 1, - "xmlId": "demo1", - "exampleURLs": [ - "http://video.demo1.mycdn.ciab.test", - "https://video.demo1.mycdn.ciab.test" - ], - "deepCachingType": "NEVER", - "fqPacingRate": null, "signingAlgorithm": null, + "sslKeyVersion": 1, "tenant": "root", + "tenantId": 1, + "tlsVersions": null, + "topology": "demo1-top", "trResponseHeaders": null, "trRequestHeaders": null, - "consistentHashRegex": null, - "consistentHashQueryParams": [ - "abc", - "pdq", - "xxx", - "zyx" - ], - "maxOriginConnections": 0, - "ecsEnabled": false, - "rangeSliceBlockSize": null, - "topology": "demo1-top", - "firstHeaderRewrite": null, - "innerHeaderRewrite": null, - "lastHeaderRewrite": null, - "serviceCategory": null, - "tlsVersions": null + "type": "HTTP", + "typeId": 1, + "xmlId": "demo1" }, "requested": { - "active": true, + "active": "INACTIVE", "anonymousBlockingEnabled": false, - "cacheurl": null, "ccrDnsTtl": 30, "cdnId": 2, "cdnName": null, "checkPath": null, - "displayName": "Demo 1 but modified by a DSR", + "consistentHashQueryParams": null, + "consistentHashRegex": null, + "deepCachingType": "NEVER", + "displayName": "Demo 1 but I modified the DSR", "dnsBypassCname": null, "dnsBypassIp": null, "dnsBypassIp6": null, "dnsBypassTtl": null, "dscp": 0, + "ecsEnabled": false, "edgeHeaderRewrite": null, + "exampleURLs": null, + "firstHeaderRewrite": null, + "fqPacingRate": null, "geoLimit": 0, "geoLimitCountries": null, "geoLimitRedirectURL": null, @@ -250,16 +257,20 @@ The response contains a full representation of the newly assigned :term:`Deliver "id": 1, "infoUrl": null, "initialDispersion": 3, + "innerHeaderRewrite": null, "ipv6RoutingEnabled": null, - "lastUpdated": null, + "lastHeaderRewrite": null, + "lastUpdated": "0001-01-01T00:00:00Z", "logsEnabled": false, "longDesc": "long desc", "matchList": null, "maxDnsAnswers": null, + "maxOriginConnections": 0, + "maxRequestHeaderBytes": 0, "midHeaderRewrite": null, "missLat": null, "missLong": null, - "multiSiteOrigin": null, + "multiSiteOrigin": false, "originShield": null, "orgServerFqdn": null, "profileDescription": null, @@ -268,37 +279,27 @@ The response contains a full representation of the newly assigned :term:`Deliver "protocol": null, "qstringIgnore": null, "rangeRequestHandling": null, + "rangeSliceBlockSize": null, "regexRemap": null, "regional": false, "regionalGeoBlocking": false, "remapText": null, "routingName": "cdn", + "serviceCategory": null, "signed": false, - "sslKeyVersion": null, - "tenantId": 1, - "type": null, - "typeId": 8, - "xmlId": "demo1", - "exampleURLs": null, - "deepCachingType": "NEVER", - "fqPacingRate": null, "signingAlgorithm": null, + "sslKeyVersion": null, "tenant": null, + "tenantId": 1, + "tlsVersions": null, + "topology": null, "trResponseHeaders": null, "trRequestHeaders": null, - "consistentHashRegex": null, - "consistentHashQueryParams": null, - "maxOriginConnections": 0, - "ecsEnabled": false, - "rangeSliceBlockSize": null, - "topology": null, - "firstHeaderRewrite": null, - "innerHeaderRewrite": null, - "lastHeaderRewrite": null, - "serviceCategory": null, - "tlsVersions": null + "type": null, + "typeId": 8, + "xmlId": "demo1" }, - "status": "draft" + "status": "submitted" }} .. [#implicit-null] Because of how the Traffic Ops API parses requests, there is no distinction between ``null`` and ``undefined``/missing properties. This means that sending the request payload ``{}`` in this case will result in the :term:`DSR` being unassigned. diff --git a/docs/source/api/v5/deliveryservice_requests_id_status.rst b/docs/source/api/v5/deliveryservice_requests_id_status.rst index 436fa6799b..c09fe3bb94 100644 --- a/docs/source/api/v5/deliveryservice_requests_id_status.rst +++ b/docs/source/api/v5/deliveryservice_requests_id_status.rst @@ -24,10 +24,10 @@ Get or set the status of a :term:`Delivery Service Request`. ======= Gets the status of a :term:`DSR`. -:Auth. Required: Yes -:Roles Required: "admin", "Federation", "operations", "Portal", or "Steering" +:Auth. Required: Yes +:Roles Required: "admin", "Federation", "operations", "Portal", or "Steering" :Permissions Required: DS-REQUEST:READ -:Response Type: Object (string) +:Response Type: Object (string) Request Structure ----------------- @@ -97,16 +97,15 @@ Request Structure :caption: Request Example PUT /api/5.0/deliveryservice_requests/1/status HTTP/1.1 - User-Agent: python-requests/2.22.0 + User-Agent: python-requests/2.25.1 Accept-Encoding: gzip, deflate Accept: */* Connection: keep-alive - Cookie: mojolicious=... - Content-Length: 28 + Cookie: access_token=...; mojolicious=... + Content-Length: 23 + Content-Type: application/json - { - "status": "rejected" - } + {"status": "submitted"} Response Structure ------------------ @@ -122,39 +121,54 @@ The response is a full representation of the modified :term:`DSR`. Access-Control-Allow-Origin: * Content-Encoding: gzip Content-Type: application/json - Set-Cookie: mojolicious=...; Path=/; Expires=Sun, 23 Feb 2020 15:54:53 GMT; Max-Age=3600; HttpOnly - Whole-Content-Sha512: C8Nhciy1jv5X7CGgHwAnLp1qmLIzHq+4dvlAApb3cFSz5V2dABl7+N1Z4ndzB7GertB7rNLP31pVcat8vEz6rA== + Permissions-Policy: interest-cohort=() + Set-Cookie: mojolicious=...; Path=/; Expires=Thu, 29 Sep 2022 23:21:02 GMT; Max-Age=3600; HttpOnly, access_token=...; Path=/; Expires=Thu, 29 Sep 2022 23:21:02 GMT; Max-Age=3600; HttpOnly + Vary: Accept-Encoding X-Server-Name: traffic_ops_golang/ - Date: Sun, 23 Feb 2020 14:54:53 GMT - Content-Length: 930 + Date: Thu, 29 Sep 2022 22:21:02 GMT + Content-Length: 1174 { "alerts": [{ "text": "Changed status of 'demo1' Delivery Service Request from 'draft' to 'submitted'", "level": "success" }], "response": { - "assignee": "admin", + "assignee": null, "author": "admin", "changeType": "update", - "createdAt": "2020-09-25T06:52:23.758877Z", - "id": 6, + "createdAt": "2022-09-29T22:07:15.008503Z", + "id": 1, "lastEditedBy": "admin", - "lastUpdated": "2020-09-25T07:13:28.753352Z", + "lastUpdated": "2022-09-29T22:21:02.144598Z", "original": { - "active": true, + "active": "ACTIVE", "anonymousBlockingEnabled": false, - "cacheurl": null, "ccrDnsTtl": null, "cdnId": 2, "cdnName": "CDN-in-a-Box", "checkPath": null, + "consistentHashQueryParams": [ + "abc", + "pdq", + "xxx", + "zyx" + ], + "consistentHashRegex": null, + "deepCachingType": "NEVER", "displayName": "Demo 1", "dnsBypassCname": null, "dnsBypassIp": null, "dnsBypassIp6": null, "dnsBypassTtl": null, "dscp": 0, + "ecsEnabled": false, "edgeHeaderRewrite": null, + "exampleURLs": [ + "http://video.demo1.mycdn.ciab.test", + "https://video.demo1.mycdn.ciab.test" + ], + "firstHeaderRewrite": null, + "fqPacingRate": null, "geoLimit": 0, "geoLimitCountries": null, "geoLimitRedirectURL": null, @@ -165,8 +179,10 @@ The response is a full representation of the modified :term:`DSR`. "id": 1, "infoUrl": null, "initialDispersion": 1, + "innerHeaderRewrite": null, "ipv6RoutingEnabled": true, - "lastUpdated": "2020-09-25T02:09:54Z", + "lastHeaderRewrite": null, + "lastUpdated": "2022-09-29T20:58:53.07251Z", "logsEnabled": true, "longDesc": "Apachecon North America 2018", "matchList": [ @@ -177,10 +193,12 @@ The response is a full representation of the modified :term:`DSR`. } ], "maxDnsAnswers": null, + "maxOriginConnections": 0, + "maxRequestHeaderBytes": 0, "midHeaderRewrite": null, "missLat": 42, "missLong": -88, - "multiSiteOrigin": false, + "multiSiteOrigin": true, "originShield": null, "orgServerFqdn": "http://origin.infra.ciab.test", "profileDescription": null, @@ -189,59 +207,47 @@ The response is a full representation of the modified :term:`DSR`. "protocol": 2, "qstringIgnore": 0, "rangeRequestHandling": 0, + "rangeSliceBlockSize": null, "regexRemap": null, "regional": false, "regionalGeoBlocking": false, "remapText": null, "routingName": "video", + "serviceCategory": null, "signed": false, - "sslKeyVersion": 1, - "tenantId": 1, - "type": "HTTP", - "typeId": 1, - "xmlId": "demo1", - "exampleURLs": [ - "http://video.demo1.mycdn.ciab.test", - "https://video.demo1.mycdn.ciab.test" - ], - "deepCachingType": "NEVER", - "fqPacingRate": null, "signingAlgorithm": null, + "sslKeyVersion": 1, "tenant": "root", + "tenantId": 1, + "tlsVersions": null, + "topology": "demo1-top", "trResponseHeaders": null, "trRequestHeaders": null, - "consistentHashRegex": null, - "consistentHashQueryParams": [ - "abc", - "pdq", - "xxx", - "zyx" - ], - "maxOriginConnections": 0, - "ecsEnabled": false, - "rangeSliceBlockSize": null, - "topology": "demo1-top", - "firstHeaderRewrite": null, - "innerHeaderRewrite": null, - "lastHeaderRewrite": null, - "serviceCategory": null, - "tlsVersions": null + "type": "HTTP", + "typeId": 1, + "xmlId": "demo1" }, "requested": { - "active": true, + "active": "INACTIVE", "anonymousBlockingEnabled": false, - "cacheurl": null, "ccrDnsTtl": 30, "cdnId": 2, "cdnName": null, "checkPath": null, - "displayName": "Demo 1 but modified by a DSR", + "consistentHashQueryParams": null, + "consistentHashRegex": null, + "deepCachingType": "NEVER", + "displayName": "Demo 1 but I modified the DSR", "dnsBypassCname": null, "dnsBypassIp": null, "dnsBypassIp6": null, "dnsBypassTtl": null, "dscp": 0, + "ecsEnabled": false, "edgeHeaderRewrite": null, + "exampleURLs": null, + "firstHeaderRewrite": null, + "fqPacingRate": null, "geoLimit": 0, "geoLimitCountries": null, "geoLimitRedirectURL": null, @@ -252,16 +258,20 @@ The response is a full representation of the modified :term:`DSR`. "id": 1, "infoUrl": null, "initialDispersion": 3, + "innerHeaderRewrite": null, "ipv6RoutingEnabled": null, - "lastUpdated": null, + "lastHeaderRewrite": null, + "lastUpdated": "0001-01-01T00:00:00Z", "logsEnabled": false, "longDesc": "long desc", "matchList": null, "maxDnsAnswers": null, + "maxOriginConnections": 0, + "maxRequestHeaderBytes": 0, "midHeaderRewrite": null, "missLat": null, "missLong": null, - "multiSiteOrigin": null, + "multiSiteOrigin": false, "originShield": null, "orgServerFqdn": null, "profileDescription": null, @@ -270,35 +280,25 @@ The response is a full representation of the modified :term:`DSR`. "protocol": null, "qstringIgnore": null, "rangeRequestHandling": null, + "rangeSliceBlockSize": null, "regexRemap": null, "regional": false, "regionalGeoBlocking": false, "remapText": null, "routingName": "cdn", + "serviceCategory": null, "signed": false, - "sslKeyVersion": null, - "tenantId": 1, - "type": null, - "typeId": 8, - "xmlId": "demo1", - "exampleURLs": null, - "deepCachingType": "NEVER", - "fqPacingRate": null, "signingAlgorithm": null, + "sslKeyVersion": null, "tenant": null, + "tenantId": 1, + "tlsVersions": null, + "topology": null, "trResponseHeaders": null, "trRequestHeaders": null, - "consistentHashRegex": null, - "consistentHashQueryParams": null, - "maxOriginConnections": 0, - "ecsEnabled": false, - "rangeSliceBlockSize": null, - "topology": null, - "firstHeaderRewrite": null, - "innerHeaderRewrite": null, - "lastHeaderRewrite": null, - "serviceCategory": null, - "tlsVersions": null + "type": null, + "typeId": 8, + "xmlId": "demo1" }, "status": "submitted" }} diff --git a/docs/source/api/v5/deliveryservices.rst b/docs/source/api/v5/deliveryservices.rst index 407fb3691e..bc75722c32 100644 --- a/docs/source/api/v5/deliveryservices.rst +++ b/docs/source/api/v5/deliveryservices.rst @@ -73,18 +73,18 @@ Request Structure .. code-block:: http :caption: Request Example - GET /api/5.0/deliveryservices?xmlId=demo2 HTTP/1.1 - Host: trafficops.infra.ciab.test - User-Agent: python-requests/2.24.0 + GET /api/5.0/deliveryservices?xmlId=test HTTP/1.1 + User-Agent: python-requests/2.25.1 Accept-Encoding: gzip, deflate Accept: */* Connection: keep-alive - Cookie: mojolicious=... + Cookie: access_token=; mojolicious=... + Host: trafficops.infra.ciab.test Response Structure ------------------ -:active: A boolean that defines :ref:`ds-active`. -:anonymousBlockingEnabled: A boolean that defines :ref:`ds-anonymous-blocking` +:active: The :term:`Delivery Service`'s :ref:`ds-active` state +:anonymousBlockingEnabled: A boolean that defines :ref:`ds-anonymous-blocking` :ccrDnsTtl: The :ref:`ds-dns-ttl` - named "ccrDnsTtl" for legacy reasons :cdnId: The integral, unique identifier of the :ref:`ds-cdn` to which the :term:`Delivery Service` belongs :cdnName: Name of the :ref:`ds-cdn` to which the :term:`Delivery Service` belongs @@ -169,15 +169,15 @@ Response Structure Content-Encoding: gzip Content-Type: application/json Permissions-Policy: interest-cohort=() - Set-Cookie: mojolicious=...; Path=/; Expires=Mon, 07 Jun 2021 22:52:20 GMT; Max-Age=3600; HttpOnly + Set-Cookie: mojolicious=...; Path=/; Expires=Thu, 29 Sep 2022 22:46:23 GMT; Max-Age=3600; HttpOnly, access_token=; Path=/; Expires=Thu, 29 Sep 2022 22:46:23 GMT; Max-Age=3600; HttpOnly Vary: Accept-Encoding X-Server-Name: traffic_ops_golang/ - Date: Mon, 07 Jun 2021 21:52:20 GMT - Content-Length: 847 + Date: Thu, 29 Sep 2022 21:46:23 GMT + Content-Length: 842 { "response": [ { - "active": true, + "active": "PRIMED", "anonymousBlockingEnabled": false, "ccrDnsTtl": null, "cdnId": 2, @@ -186,17 +186,16 @@ Response Structure "consistentHashQueryParams": [], "consistentHashRegex": null, "deepCachingType": "NEVER", - "displayName": "Demo 2", + "displayName": "test", "dnsBypassCname": null, "dnsBypassIp": null, "dnsBypassIp6": null, "dnsBypassTtl": null, "dscp": 0, - "ecsEnabled": false, + "ecsEnabled": true, "edgeHeaderRewrite": null, "exampleURLs": [ - "http://video.demo2.mycdn.ciab.test", - "https://video.demo2.mycdn.ciab.test" + "http://test.test.mycdn.ciab.test" ], "firstHeaderRewrite": null, "fqPacingRate": null, @@ -207,35 +206,35 @@ Response Structure "globalMaxMbps": null, "globalMaxTps": null, "httpBypassFqdn": null, - "id": 1, + "id": 3, "infoUrl": null, "initialDispersion": 1, "innerHeaderRewrite": null, - "ipv6RoutingEnabled": true, + "ipv6RoutingEnabled": false, "lastHeaderRewrite": null, - "lastUpdated": "2021-06-07T21:50:03.009954Z", + "lastUpdated": "2022-09-29T21:33:33.407404Z", "logsEnabled": true, - "longDesc": "DNS Delivery Service for use with a Federation", + "longDesc": "A Delivery Service created expressly for API documentation examples", "matchList": [ { "type": "HOST_REGEXP", "setNumber": 0, - "pattern": ".*\\.demo2\\..*" + "pattern": ".*\\.test\\..*" } ], "maxDnsAnswers": null, "maxOriginConnections": 0, - "maxRequestHeaderBytes": 0, + "maxRequestHeaderBytes": 131072, "midHeaderRewrite": null, - "missLat": 42, - "missLong": -88, - "multiSiteOrigin": true, + "missLat": 0, + "missLong": 0, + "multiSiteOrigin": false, "originShield": null, "orgServerFqdn": "http://origin.infra.ciab.test", "profileDescription": null, "profileId": null, "profileName": null, - "protocol": 2, + "protocol": 0, "qstringIgnore": 0, "rangeRequestHandling": 0, "rangeSliceBlockSize": null, @@ -243,37 +242,44 @@ Response Structure "regional": false, "regionalGeoBlocking": false, "remapText": null, - "routingName": "video", + "routingName": "test", "serviceCategory": null, "signed": false, "signingAlgorithm": null, "sslKeyVersion": null, "tenant": "root", "tenantId": 1, - "tlsVersions": null, - "topology": "demo1-top", + "tlsVersions": [ + "1.2", + "1.3" + ], + "topology": null, "trResponseHeaders": null, "trRequestHeaders": null, - "type": "DNS", - "typeId": 5, - "xmlId": "demo2" + "type": "HTTP", + "typeId": 1, + "xmlId": "test" } ]} + ``POST`` ======== Allows users to create :term:`Delivery Service`. -:Auth. Required: Yes -:Roles Required: "admin" or "operations"\ [#tenancy]_ +:Auth. Required: Yes +:Roles Required: "admin" or "operations"\ [#tenancy]_ :Permissions Required: DELIVERY-SERVICE:CREATE, DELIVERY-SERVICE:READ, CDN:READ, TYPE:READ -:Response Type: Array +:Response Type: Object + + .. versionchanged:: 5.0 + In earlier API versions, this would return an array containing the single :term:`Delivery Service` created. It is now simply the object itself. This is tracked by :issue:`6904`. Request Structure ----------------- -:active: A boolean that defines :ref:`ds-active`. -:anonymousBlockingEnabled: A boolean that defines :ref:`ds-anonymous-blocking` +:active: The :term:`Delivery Service`'s :ref:`ds-active` state +:anonymousBlockingEnabled: A boolean that defines :ref:`ds-anonymous-blocking` :ccrDnsTtl: The :ref:`ds-dns-ttl` - named "ccrDnsTtl" for legacy reasons :cdnId: The integral, unique identifier of the :ref:`ds-cdn` to which the :term:`Delivery Service` belongs :checkPath: A :ref:`ds-check-path` @@ -291,7 +297,7 @@ Request Structure :firstHeaderRewrite: A set of :ref:`ds-first-header-rw-rules` :fqPacingRate: The :ref:`ds-fqpr` :geoLimit: An integer that defines the :ref:`ds-geo-limit` -:geoLimitCountries: A string containing a comma-separated list, or an array of strings defining the :ref:`ds-geo-limit-countries`\ [#geolimit]_ +:geoLimitCountries: An array of strings defining the :ref:`ds-geo-limit-countries`\ [#geolimit]_ :geoLimitRedirectUrl: A :ref:`ds-geo-limit-redirect-url`\ [#geolimit]_ :geoProvider: The :ref:`ds-geo-provider` :globalMaxMbps: The :ref:`ds-global-max-mbps` @@ -339,17 +345,17 @@ Request Structure :caption: Request Example POST /api/5.0/deliveryservices HTTP/1.1 - User-Agent: python-requests/2.24.0 + User-Agent: python-requests/2.25.1 Accept-Encoding: gzip, deflate Accept: */* Connection: keep-alive - Cookie: mojolicious=... - Content-Length: 1602 + Cookie: access_token=...; mojolicious=... + Content-Length: 1565 Content-Type: application/json Host: trafficops.infra.ciab.test { - "active": false, + "active": "PRIMED", "anonymousBlockingEnabled": false, "ccrDnsTtl": null, "cdnId": 2, @@ -420,8 +426,8 @@ Request Structure Response Structure ------------------ -:active: A boolean that defines :ref:`ds-active`. -:anonymousBlockingEnabled: A boolean that defines :ref:`ds-anonymous-blocking` +:active: The :term:`Delivery Service`'s :ref:`ds-active` state +:anonymousBlockingEnabled: A boolean that defines :ref:`ds-anonymous-blocking` :ccrDnsTtl: The :ref:`ds-dns-ttl` - named "ccrDnsTtl" for legacy reasons :cdnId: The integral, unique identifier of the :ref:`ds-cdn` to which the :term:`Delivery Service` belongs :cdnName: Name of the :ref:`ds-cdn` to which the :term:`Delivery Service` belongs @@ -505,17 +511,21 @@ Response Structure Access-Control-Allow-Origin: * Content-Encoding: gzip Content-Type: application/json - Location: /api/5.0/deliveryservices?id=6 + Location: /api/5.0/deliveryservices?id=3 Permissions-Policy: interest-cohort=() - Set-Cookie: mojolicious=...; Path=/; Expires=Mon, 07 Jun 2021 23:37:37 GMT; Max-Age=3600; HttpOnly + Set-Cookie: mojolicious=...; Path=/; Expires=Thu, 29 Sep 2022 22:33:33 GMT; Max-Age=3600; HttpOnly, access_token=...; Path=/; Expires=Thu, 29 Sep 2022 22:33:33 GMT; Max-Age=3600; HttpOnly Vary: Accept-Encoding X-Server-Name: traffic_ops_golang/ - Date: Mon, 07 Jun 2021 22:37:37 GMT - Content-Length: 903 + Date: Thu, 29 Sep 2022 21:33:33 GMT + Content-Length: 988 { "alerts": [ { - "text": "tlsVersions has no effect on 'HTTP' Delivery Services", + "text": "setting TLS Versions that are explicitly supported may break older clients that can't use the specified versions", + "level": "warning" + }, + { + "text": "tlsVersions has no effect on Delivery Services with Protocol '0' (HTTP_ONLY)", "level": "warning" }, { @@ -523,8 +533,8 @@ Response Structure "level": "success" } ], - "response": [{ - "active": false, + "response": { + "active": "PRIMED", "anonymousBlockingEnabled": false, "ccrDnsTtl": null, "cdnId": 2, @@ -553,13 +563,13 @@ Response Structure "globalMaxMbps": null, "globalMaxTps": null, "httpBypassFqdn": null, - "id": 6, + "id": 3, "infoUrl": null, "initialDispersion": 1, "innerHeaderRewrite": null, "ipv6RoutingEnabled": false, "lastHeaderRewrite": null, - "lastUpdated": "2021-06-07T22:37:37.187822Z", + "lastUpdated": "2022-09-29T21:33:33.407404Z", "logsEnabled": true, "longDesc": "A Delivery Service created expressly for API documentation examples", "matchList": [ @@ -606,8 +616,7 @@ Response Structure "type": "HTTP", "typeId": 1, "xmlId": "test" - }]} - + }} .. [#tenancy] Only those :term:`Delivery Services` assigned to :term:`Tenants` that are the requesting user's :term:`Tenant` or children thereof will appear in the output of a ``GET`` request, and the same constraints are placed on the allowed values of the ``tenantId`` field of a ``POST`` request to create a new :term:`Delivery Service` -.. [#geoLimit] These fields must be defined if and only if ``geoLimit`` is non-zero +.. [#geoLimit] These fields only must be defined if ``geoLimit`` is non-zero diff --git a/docs/source/api/v5/deliveryservices_id.rst b/docs/source/api/v5/deliveryservices_id.rst index d2f28f5518..52e41c83ae 100644 --- a/docs/source/api/v5/deliveryservices_id.rst +++ b/docs/source/api/v5/deliveryservices_id.rst @@ -23,15 +23,19 @@ ======= Allows users to edit an existing :term:`Delivery Service`. -:Auth. Required: Yes -:Roles Required: "admin" or "operations"\ [#tenancy]_ +:Auth. Required: Yes +:Roles Required: "admin" or "operations"\ [#tenancy]_ :Permissions Required: DELIVERY-SERVICE:UPDATE, DELIVERY-SERVICE:READ, CDN:READ, TYPE:READ -:Response Type: Array (should always have a length of exactly one on success) +:Response Type: Object + + .. versionchanged:: 5.0 + In earlier API versions, this would return an array containing the single :term:`Delivery Service` modified. It is now simply the object itself. This is tracked by :issue:`6904`. + Request Structure ----------------- -:active: A boolean that defines :ref:`ds-active`. -:anonymousBlockingEnabled: A boolean that defines :ref:`ds-anonymous-blocking` +:active: The :term:`Delivery Service`'s :ref:`ds-active` state +:anonymousBlockingEnabled: A boolean that defines :ref:`ds-anonymous-blocking` :ccrDnsTtl: The :ref:`ds-dns-ttl` - named "ccrDnsTtl" for legacy reasons :cdnId: The integral, unique identifier of the :ref:`ds-cdn` to which the :term:`Delivery Service` belongs @@ -52,7 +56,7 @@ Request Structure :firstHeaderRewrite: A set of :ref:`ds-first-header-rw-rules` :fqPacingRate: The :ref:`ds-fqpr` :geoLimit: An integer that defines the :ref:`ds-geo-limit` -:geoLimitCountries: A string containing a comma-separated list, or an array of strings defining the :ref:`ds-geo-limit-countries`\ [#geolimit]_ +:geoLimitCountries: An array of strings defining the :ref:`ds-geo-limit-countries`\ [#geolimit]_ :geoLimitRedirectUrl: A :ref:`ds-geo-limit-redirect-url`\ [#geolimit]_ :geoProvider: The :ref:`ds-geo-provider` :globalMaxMbps: The :ref:`ds-global-max-mbps` @@ -97,23 +101,23 @@ Request Structure :typeId: The integral, unique identifier of the :ref:`ds-types` of this :term:`Delivery Service` :xmlId: This :term:`Delivery Service`'s :ref:`ds-xmlid` - .. note:: While this field **must** be present, it is **not** allowed to change; this must be the same as the ``xml_id`` the :term:`Delivery Service` already has. This should almost never be different from the :term:`Delivery Service`'s ``displayName``. + .. note:: While this field **must** be present, it is **not** allowed to change; this must be the same as the ``xml_id`` the :term:`Delivery Service` already has. .. code-block:: http :caption: Request Example - PUT /api/5.0/deliveryservices/6 HTTP/1.1 + PUT /api/5.0/deliveryservices/3 HTTP/1.1 Host: trafficops.infra.ciab.test - User-Agent: python-requests/2.24.0 + User-Agent: python-requests/2.25.1 Accept-Encoding: gzip, deflate Accept: */* Connection: keep-alive - Cookie: mojolicious=... - Content-Length: 1585 + Cookie: access_token=...; mojolicious=... + Content-Length: 1548 Content-Type: application/json { - "active": false, + "active": "ACTIVE", "anonymousBlockingEnabled": false, "ccrDnsTtl": null, "cdnId": 2, @@ -181,8 +185,8 @@ Request Structure Response Structure ------------------ -:active: A boolean that defines :ref:`ds-active`. -:anonymousBlockingEnabled: A boolean that defines :ref:`ds-anonymous-blocking` +:active: The :term:`Delivery Service`'s :ref:`ds-active` state +:anonymousBlockingEnabled: A boolean that defines :ref:`ds-anonymous-blocking` :ccrDnsTtl: The :ref:`ds-dns-ttl` - named "ccrDnsTtl" for legacy reasons :cdnId: The integral, unique identifier of the :ref:`ds-cdn` to which the :term:`Delivery Service` belongs :cdnName: Name of the :ref:`ds-cdn` to which the :term:`Delivery Service` belongs @@ -267,12 +271,11 @@ Response Structure Content-Encoding: gzip Content-Type: application/json Permissions-Policy: interest-cohort=() - Set-Cookie: mojolicious=...; Path=/; Expires=Tue, 08 Jun 2021 00:34:04 GMT; Max-Age=3600; HttpOnly + Set-Cookie: mojolicious=...; Path=/; Expires=Thu, 29 Sep 2022 22:55:09 GMT; Max-Age=3600; HttpOnly, access_token=...; Path=/; Expires=Thu, 29 Sep 2022 22:55:09 GMT; Max-Age=3600; HttpOnly Vary: Accept-Encoding - Whole-Content-Sha512: tTncbRoJR+pyykVbEc6nWyoFnhlJzsbge9hVZfw+WK28rzSGECZ/Q4zXTQtFjHWY5G+0Rk4w9GKrSFK3k+u5Ng== X-Server-Name: traffic_ops_golang/ - Date: Mon, 07 Jun 2021 23:34:04 GMT - Content-Length: 840 + Date: Thu, 29 Sep 2022 21:55:09 GMT + Content-Length: 838 { "alerts": [ { @@ -280,8 +283,8 @@ Response Structure "level": "success" } ], - "response": [{ - "active": false, + "response": { + "active": "ACTIVE", "anonymousBlockingEnabled": false, "ccrDnsTtl": null, "cdnId": 2, @@ -308,13 +311,13 @@ Response Structure "globalMaxMbps": null, "globalMaxTps": null, "httpBypassFqdn": null, - "id": 6, + "id": 3, "infoUrl": null, "initialDispersion": 1, "innerHeaderRewrite": null, "ipv6RoutingEnabled": false, "lastHeaderRewrite": null, - "lastUpdated": "2021-06-07T23:34:04.831215Z", + "lastUpdated": "2022-09-29T21:55:09.170596Z", "logsEnabled": true, "longDesc": "A Delivery Service created expressly for API documentation examples", "matchList": [ @@ -358,7 +361,7 @@ Response Structure "type": "HTTP", "typeId": 1, "xmlId": "test" - }]} + }} ``DELETE`` @@ -383,12 +386,13 @@ Request Structure .. code-block:: http :caption: Request Example - DELETE /api/5.0/deliveryservices/2 HTTP/1.1 - Host: trafficops.infra.ciab.test - User-Agent: curl/7.47.0 + DELETE /api/5.0/deliveryservices/3 HTTP/1.1 + User-Agent: python-requests/2.25.1 + Accept-Encoding: gzip, deflate Accept: */* - Cookie: mojolicious=... - + Connection: keep-alive + Cookie: access_token=...; mojolicious=... + Content-Length: 0 Response Structure ------------------ @@ -400,20 +404,25 @@ Response Structure Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Set-Cookie, Cookie Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE Access-Control-Allow-Origin: * + Content-Encoding: gzip Content-Type: application/json - Set-Cookie: mojolicious=...; Path=/; Expires=Mon, 18 Nov 2019 17:40:54 GMT; Max-Age=3600; HttpOnly - Whole-Content-Sha512: w9NlQpJJEl56r6iYq/fk8o5WfAXeUS5XR9yDHvKUgPO8lYEo8YyftaSF0MPFseeOk60dk6kQo+MLYTDIAhhRxw== + Permissions-Policy: interest-cohort=() + Set-Cookie: mojolicious=...; Path=/; Expires=Thu, 29 Sep 2022 22:59:08 GMT; Max-Age=3600; HttpOnly, access_token=...; Path=/; Expires=Thu, 29 Sep 2022 22:59:08 GMT; Max-Age=3600; HttpOnly + Vary: Accept-Encoding X-Server-Name: traffic_ops_golang/ - Date: Tue, 20 Nov 2018 14:56:37 GMT - Content-Length: 57 + Date: Thu, 29 Sep 2022 21:59:08 GMT + Content-Length: 161 { "alerts": [ { "text": "ds was deleted.", "level": "success" + }, + { + "text": "Perform a CDN snapshot then queue updates on all servers in the cdn for the changes to take effect.", + "level": "info" } ]} - .. [#tenancy] Only those :term:`Delivery Services` assigned to :term:`Tenants` that are the requesting user's :term:`Tenant` or children thereof will appear in the output of a ``GET`` request, and the same constraints are placed on the allowed values of the ``tenantId`` field of a ``PUT`` request to update a new :term:`Delivery Service`. Furthermore, the only :term:`Delivery Services` a user may delete are those assigned to a :term:`Tenant` that is either the same :term:`Tenant` as the user's :term:`Tenant`, or a descendant thereof. -.. [#geoLimit] These fields must be defined if and only if ``geoLimit`` is non-zero +.. [#geoLimit] These fields only must be defined if ``geoLimit`` is non-zero diff --git a/docs/source/api/v5/deliveryservices_id_safe.rst b/docs/source/api/v5/deliveryservices_id_safe.rst index 525384607d..d5b4cdfe7b 100644 --- a/docs/source/api/v5/deliveryservices_id_safe.rst +++ b/docs/source/api/v5/deliveryservices_id_safe.rst @@ -46,11 +46,11 @@ Request Structure :caption: Request Example PUT /api/5.0/deliveryservices/1/safe HTTP/1.1 - User-Agent: python-requests/2.22.0 + User-Agent: python-requests/2.25.1 Accept-Encoding: gzip, deflate Accept: */* Connection: keep-alive - Cookie: mojolicious=... + Cookie: access_token=...; mojolicious=... Content-Length: 132 Content-Type: application/json @@ -62,8 +62,8 @@ Request Structure Response Structure ------------------ -:active: A boolean that defines :ref:`ds-active`. -:anonymousBlockingEnabled: A boolean that defines :ref:`ds-anonymous-blocking` +:active: The :term:`Delivery Service`'s :ref:`ds-active` state +:anonymousBlockingEnabled: A boolean that defines :ref:`ds-anonymous-blocking` :ccrDnsTtl: The :ref:`ds-dns-ttl` - named "ccrDnsTtl" for legacy reasons :cdnId: The integral, unique identifier of the :ref:`ds-cdn` to which the :term:`Delivery Service` belongs :cdnName: Name of the :ref:`ds-cdn` to which the :term:`Delivery Service` belongs @@ -142,25 +142,29 @@ Response Structure Content-Encoding: gzip Content-Type: application/json Permissions-Policy: interest-cohort=() - Set-Cookie: mojolicious=...; Path=/; Expires=Tue, 08 Jun 2021 00:53:26 GMT; Max-Age=3600; HttpOnly + Set-Cookie: mojolicious=...; Path=/; Expires=Thu, 29 Sep 2022 23:30:08 GMT; Max-Age=3600; HttpOnly, access_token=...; Path=/; Expires=Thu, 29 Sep 2022 23:30:08 GMT; Max-Age=3600; HttpOnly Vary: Accept-Encoding - Whole-Content-Sha512: Ys/SfWWijsXCNXEqZ84oldfyXTgMe8UE/wWb53VU39OH7kWOXF1BH5Hg7Y40nCgXoWEqcaBq5+WCZg0bYuJdAA== X-Server-Name: traffic_ops_golang/ - Date: Mon, 07 Jun 2021 23:53:26 GMT - Content-Length: 903 + Date: Thu, 29 Sep 2022 22:30:08 GMT + Content-Length: 904 { "alerts": [{ "text": "Delivery Service safe update successful.", "level": "success" }], - "response": [{ - "active": true, + "response": { + "active": "ACTIVE", "anonymousBlockingEnabled": false, "ccrDnsTtl": null, "cdnId": 2, "cdnName": "CDN-in-a-Box", "checkPath": null, - "consistentHashQueryParams": [], + "consistentHashQueryParams": [ + "abc", + "pdq", + "xxx", + "zyx" + ], "consistentHashRegex": null, "deepCachingType": "NEVER", "displayName": "test", @@ -172,8 +176,8 @@ Response Structure "ecsEnabled": false, "edgeHeaderRewrite": null, "exampleURLs": [ - "http://video.demo2.mycdn.ciab.test", - "https://video.demo2.mycdn.ciab.test" + "http://video.demo1.mycdn.ciab.test", + "https://video.demo1.mycdn.ciab.test" ], "firstHeaderRewrite": null, "fqPacingRate": null, @@ -190,14 +194,14 @@ Response Structure "innerHeaderRewrite": null, "ipv6RoutingEnabled": true, "lastHeaderRewrite": null, - "lastUpdated": "2021-06-07T23:53:26.139899Z", + "lastUpdated": "2022-09-29T22:30:08.574513Z", "logsEnabled": true, "longDesc": "this is a description of the delivery service", "matchList": [ { "type": "HOST_REGEXP", "setNumber": 0, - "pattern": ".*\\.demo2\\..*" + "pattern": ".*\\.demo1\\..*" } ], "maxDnsAnswers": null, @@ -224,17 +228,17 @@ Response Structure "serviceCategory": null, "signed": false, "signingAlgorithm": null, - "sslKeyVersion": null, + "sslKeyVersion": 1, "tenant": "root", "tenantId": 1, "tlsVersions": null, "topology": "demo1-top", "trResponseHeaders": null, "trRequestHeaders": null, - "type": "DNS", - "typeId": 5, - "xmlId": "demo2" - ]} + "type": "HTTP", + "typeId": 1, + "xmlId": "demo1" + }} .. [#tenancy] Only those :term:`Delivery Services` assigned to :term:`Tenants` that are the requesting user's :term:`Tenant` or children thereof may be modified with this endpoint. -.. [#optional] If these fields are not present in the request body they are *implicitly set to* ``null``. +.. [#optional] If ``infoUrl`` is not present in the request body it is *implicitly set to* ``null``. If ``longDesc`` isn't in the request body, it is *implicitly set to* an empty string. diff --git a/docs/source/api/v5/servers_id_deliveryservices.rst b/docs/source/api/v5/servers_id_deliveryservices.rst index 3e6c01bfaa..4db5c7d845 100644 --- a/docs/source/api/v5/servers_id_deliveryservices.rst +++ b/docs/source/api/v5/servers_id_deliveryservices.rst @@ -60,18 +60,17 @@ Request Structure .. code-block:: http :caption: Request Example - GET /api/5.0/servers/10/deliveryservices HTTP/1.1 - Host: trafficops.infra.ciab.test - User-Agent: python-requests/2.24.0 + GET /api/5.0/servers/1/deliveryservices HTTP/1.1 + User-Agent: python-requests/2.25.1 Accept-Encoding: gzip, deflate Accept: */* Connection: keep-alive - Cookie: mojolicious=... + Cookie: access_token=...; mojolicious=... Response Structure ------------------ -:active: A boolean that defines :ref:`ds-active`. -:anonymousBlockingEnabled: A boolean that defines :ref:`ds-anonymous-blocking` +:active: The :term:`Delivery Service`'s :ref:`ds-active` state +:anonymousBlockingEnabled: A boolean that defines :ref:`ds-anonymous-blocking` :ccrDnsTtl: The :ref:`ds-dns-ttl` - named "ccrDnsTtl" for legacy reasons :cdnId: The integral, unique identifier of the :ref:`ds-cdn` to which the :term:`Delivery Service` belongs :cdnName: Name of the :ref:`ds-cdn` to which the :term:`Delivery Service` belongs @@ -154,24 +153,28 @@ Response Structure Content-Encoding: gzip Content-Type: application/json Permissions-Policy: interest-cohort=() - Set-Cookie: mojolicious=...; Path=/; Expires=Tue, 08 Jun 2021 01:15:07 GMT; Max-Age=3600; HttpOnly + Set-Cookie: mojolicious=...; Path=/; Expires=Thu, 29 Sep 2022 23:01:50 GMT; Max-Age=3600; HttpOnly, access_token=...; Path=/; Expires=Thu, 29 Sep 2022 23:01:50 GMT; Max-Age=3600; HttpOnly Vary: Accept-Encoding - Whole-Content-Sha512: RO4tVfDdqx0rEU9BqlRmvsYXmVgVNkivqr6LhJlMulfR+1bLGivP8z93jy3N9bejcMdQwl1RwJojM3MbwgXcqA== X-Server-Name: traffic_ops_golang/ - Date: Tue, 08 Jun 2021 00:15:07 GMT - Content-Length: 806 + Date: Thu, 29 Sep 2022 22:01:50 GMT + Content-Length: 845 { "response": [{ - "active": false, + "active": "ACTIVE", "anonymousBlockingEnabled": false, - "ccrDnsTtl": 3600, + "ccrDnsTtl": null, "cdnId": 2, "cdnName": "CDN-in-a-Box", "checkPath": null, - "consistentHashQueryParams": [], + "consistentHashQueryParams": [ + "abc", + "pdq", + "xxx", + "zyx" + ], "consistentHashRegex": null, "deepCachingType": "NEVER", - "displayName": "test", + "displayName": "Demo 1", "dnsBypassCname": null, "dnsBypassIp": null, "dnsBypassIp6": null, @@ -180,7 +183,8 @@ Response Structure "ecsEnabled": false, "edgeHeaderRewrite": null, "exampleURLs": [ - "http://cdn.test.mycdn.ciab.test" + "http://video.demo1.mycdn.ciab.test", + "https://video.demo1.mycdn.ciab.test" ], "firstHeaderRewrite": null, "fqPacingRate": null, @@ -191,35 +195,35 @@ Response Structure "globalMaxMbps": null, "globalMaxTps": null, "httpBypassFqdn": null, - "id": 7, + "id": 1, "infoUrl": null, "initialDispersion": 1, "innerHeaderRewrite": null, "ipv6RoutingEnabled": true, "lastHeaderRewrite": null, - "lastUpdated": "2021-06-08T00:14:04.959292Z", - "logsEnabled": false, + "lastUpdated": "2022-09-29T20:58:53.07251Z", + "logsEnabled": true, "longDesc": "Apachecon North America 2018", "matchList": [ { "type": "HOST_REGEXP", "setNumber": 0, - "pattern": ".*\\.test\\..*" + "pattern": ".*\\.demo1\\..*" } ], "maxDnsAnswers": null, "maxOriginConnections": 0, "maxRequestHeaderBytes": 0, "midHeaderRewrite": null, - "missLat": 41.881944, - "missLong": -87.627778, - "multiSiteOrigin": false, + "missLat": 42, + "missLong": -88, + "multiSiteOrigin": true, "originShield": null, "orgServerFqdn": "http://origin.infra.ciab.test", "profileDescription": null, "profileId": null, "profileName": null, - "protocol": 0, + "protocol": 2, "qstringIgnore": 0, "rangeRequestHandling": 0, "rangeSliceBlockSize": null, @@ -227,20 +231,20 @@ Response Structure "regional": false, "regionalGeoBlocking": false, "remapText": null, - "routingName": "cdn", + "routingName": "video", "serviceCategory": null, "signed": false, "signingAlgorithm": null, - "sslKeyVersion": null, + "sslKeyVersion": 1, "tenant": "root", "tenantId": 1, "tlsVersions": null, - "topology": null, + "topology": "demo1-top", "trResponseHeaders": null, "trRequestHeaders": null, "type": "HTTP", "typeId": 1, - "xmlId": "test" + "xmlId": "demo1" }]} diff --git a/docs/source/overview/delivery_services.rst b/docs/source/overview/delivery_services.rst index c0484e1b42..5b5ac21327 100644 --- a/docs/source/overview/delivery_services.rst +++ b/docs/source/overview/delivery_services.rst @@ -13,6 +13,9 @@ .. limitations under the License. .. +.. |checkmark| image:: ../admin/images/good.png +.. |X| image:: ../admin/images/bad.png + .. _delivery-services: ***************** @@ -20,7 +23,7 @@ Delivery Services ***************** "Delivery Services" are a very important construct in :abbr:`ATC (Apache Traffic Control)`. At their most basic, they are a source of content and a set of :term:`cache servers` and configuration options used to distribute that content. -Delivery Services are modeled several times over, in the Traffic Ops database, in Traffic Portal forms and tables, and several times for various :ref:`to-api` versions in the new Go Traffic Ops codebase. Go-specific data structures can be found in `the project's GoDoc documentation `_. Rather than application-specific definitions, what follows is an attempt at consolidating all of the different properties and names of properties of Delivery Service objects throughout the :abbr:`ATC (Apache Traffic Control)` suite. The names of these fields are typically chosen as the most human-readable and/or most commonly-used names for the fields, and when reading please note that in many cases these names will appear camelCased or snake_cased to be machine-readable. Any aliases of these fields that are not merely case transformations of the indicated, canonical names will be noted in a table of aliases. +Delivery Services are modeled several times over, in the Traffic Ops database, in Traffic Portal forms and tables, and several times for various :ref:`to-api` versions in the new Go Traffic Ops codebase. Go-specific data structures can be found in :godoc: `the project's GoDoc documentation `_. Rather than application-specific definitions, what follows is an attempt at consolidating all of the different properties and names of properties of Delivery Service objects throughout the :abbr:`ATC (Apache Traffic Control)` suite. The names of these fields are typically chosen as the most human-readable and/or most commonly-used names for the fields, and when reading please note that in many cases these names will appear camelCased or snake_cased to be machine-readable. Any aliases of these fields that are not merely case transformations of the indicated, canonical names will be noted in a table of aliases. .. seealso:: The API reference for Delivery Service-related endpoints such as :ref:`to-api-deliveryservices` contains definitions of the Delivery Service object(s) returned and/or accepted by those endpoints. .. seealso:: :ref:`delivery-service-requests` @@ -29,7 +32,39 @@ Delivery Services are modeled several times over, in the Traffic Ops database, i Active ------ -Whether or not this Delivery Service is active on the CDN and can be served. When a Delivery Service is not "active", Traffic Router will not be made aware of its existence - i.e. it will not appear in CDN :term:`Snapshots`. Setting a Delivery Service to be "active" (or "inactive") will require that a new :term:`Snapshot` be taken. +Whether or not this Delivery Service is active on the CDN and can be served. A Delivery Service's "active state" can be one of the three values listed below. + +ACTIVE + The Delivery Service's configuration is deployed to the appropriate :term:`cache servers` when updates are :term:`Queue`\ d, and Traffic Router is made aware of its existence through CDN :term:`Snapshots`. +PRIMED + The Delivery Service's configuration is deployed to the appropriate :term:`cache servers` when updates are :term:`Queue`\ d, but Traffic Router is *not* made aware of its existence through CDN :term:`Snapshots`, so clients will not be routed for it. +INACTIVE + The Delivery Service's configuration is *not* deployed to any :term:`cache servers` when updates are :term:`Queue`\ d, *nor* is Traffic Router made aware of its existence through CDN :term:`Snapshots`. + +Changing a Delivery Service's "active state" either to or from "ACTIVE" will require that a new :term:`Snapshot` be taken. Likewise, a :term:`Queue Updates` must be performed if the "active state" changes either to or from "INACTIVE". Table :numref:`tbl-active-state-transitions` expresses these relationships exhaustively. + +.. _tbl-active-state-transitions: + +.. table:: Active State Transitions + + +----------------+-----------+-------------------------------+--------------------------------+ + | Original State | New State | CDN :term:`Snapshot` Required | :term:`Queue Updates` Required | + +================+===========+===============================+================================+ + | ACTIVE | PRIMED | |checkmark| | |X| | + +----------------+-----------+-------------------------------+--------------------------------+ + | ACTIVE | INACTIVE | |checkmark| | |checkmark| | + +----------------+-----------+-------------------------------+--------------------------------+ + | PRIMED | ACTIVE | |checkmark| | |X| | + +----------------+-----------+-------------------------------+--------------------------------+ + | PRIMED | INACTIVE | |X| | |checkmark| | + +----------------+-----------+-------------------------------+--------------------------------+ + | INACTIVE | ACTIVE | |checkmark| | |checkmark| | + +----------------+-----------+-------------------------------+--------------------------------+ + | INACTIVE | PRIMED | |X| | |checkmark| | + +----------------+-----------+-------------------------------+--------------------------------+ + +.. versionchanged:: ATCv7.1 + In API version 5, introduced in :abbr:`ATC (Apache Traffic Control)` version 7.1 (tentative plan for release at the time of this writing), this was switched to the enumerated strings listed here. Prior to version 5 of :ref:`to-api`, this was a boolean having only the states "true" and "false". "True" was identical to today's "ACTIVE", while "false" was identical to "PRIMED". "INACTIVE" has no legacy analogue. Thus when requesting older API versions, an "active state" of "false" may actually be either INACTIVE or PRIMED, and there is no way to tell which. .. _ds-anonymous-blocking: @@ -277,7 +312,7 @@ Limits access to a Delivery Service by geographic location. The only practical d Geo Limit Countries ------------------- -When `Geo Limit`_ is being used with this Delivery Service (and is set to exactly ``2``), this is optionally a list of country codes to which access to content provided by the Delivery Service will be restricted. Normally, this is a comma-delimited string of said country codes, or an array of strings representing the country codes. When creating a Delivery Service with this field or modifying the Geo Limit Countries field on an existing Delivery Service, any amount of whitespace between country codes is permissible, as it will be removed on submission, but responses from the :ref:`to-api` should never include such whitespace. +When `Geo Limit`_ is being used with this Delivery Service (and is set to exactly ``2``), this is optionally a list of country codes to which access to content provided by the Delivery Service will be restricted. Normally, this is an array of strings representing country codes, but in legacy versions of the :ref:`to-api` it was a comma-delimited string of said country codes rather than a real array. When creating or modifying this field of a Delivery Service in said legacy API versions, any amount of whitespace between country codes is permissible, as it will be removed on submission, but responses from the :ref:`to-api` should never include such whitespace. .. table:: Aliases From d63cd2d1683f8eb62f531d04f57a73297924e821 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Thu, 29 Sep 2022 21:03:10 -0600 Subject: [PATCH 37/48] Update CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b06786ec1c..1f3c3ef2b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/). - [#6981](https://github.com/apache/trafficcontrol/pull/6981) *Traffic Portal* Obscures sensitive text in Delivery Service "Raw Remap" fields, private SSL keys, "Header Rewrite" rules, and ILO interface passwords by default. - [#7037](https://github.com/apache/trafficcontrol/pull/7037) *Traffic Router* Uses Traffic Ops API 4.0 by default - [#7191](https://github.com/apache/trafficcontrol/issues/7191) *tc-health-client* Uses Traffic Ops API 4.0. Also added reload option to systemd service file +- Switched Delivery Service active state to a three-value system, adding a state that will be used to prevent cache servers from deploying DS configuration. ### Fixed - [#7179](https://github.com/apache/trafficcontrol/issues/7179) *Traffic Portal* Fixed search filter for Delivery Service Table From 5ab61c1c71bd885596cefdef15c8b761a0ac9a37 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Thu, 29 Sep 2022 21:22:23 -0600 Subject: [PATCH 38/48] remove accidental directive --- docs/source/overview/delivery_services.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/source/overview/delivery_services.rst b/docs/source/overview/delivery_services.rst index 5b5ac21327..673dc4963e 100644 --- a/docs/source/overview/delivery_services.rst +++ b/docs/source/overview/delivery_services.rst @@ -23,7 +23,7 @@ Delivery Services ***************** "Delivery Services" are a very important construct in :abbr:`ATC (Apache Traffic Control)`. At their most basic, they are a source of content and a set of :term:`cache servers` and configuration options used to distribute that content. -Delivery Services are modeled several times over, in the Traffic Ops database, in Traffic Portal forms and tables, and several times for various :ref:`to-api` versions in the new Go Traffic Ops codebase. Go-specific data structures can be found in :godoc: `the project's GoDoc documentation `_. Rather than application-specific definitions, what follows is an attempt at consolidating all of the different properties and names of properties of Delivery Service objects throughout the :abbr:`ATC (Apache Traffic Control)` suite. The names of these fields are typically chosen as the most human-readable and/or most commonly-used names for the fields, and when reading please note that in many cases these names will appear camelCased or snake_cased to be machine-readable. Any aliases of these fields that are not merely case transformations of the indicated, canonical names will be noted in a table of aliases. +Delivery Services are modeled several times over, in the Traffic Ops database, in Traffic Portal forms and tables, and several times for various :ref:`to-api` versions in the new Go Traffic Ops codebase. Go-specific data structures can be found in `the project's GoDoc documentation `_. Rather than application-specific definitions, what follows is an attempt at consolidating all of the different properties and names of properties of Delivery Service objects throughout the :abbr:`ATC (Apache Traffic Control)` suite. The names of these fields are typically chosen as the most human-readable and/or most commonly-used names for the fields, and when reading please note that in many cases these names will appear camelCased or snake_cased to be machine-readable. Any aliases of these fields that are not merely case transformations of the indicated, canonical names will be noted in a table of aliases. .. seealso:: The API reference for Delivery Service-related endpoints such as :ref:`to-api-deliveryservices` contains definitions of the Delivery Service object(s) returned and/or accepted by those endpoints. .. seealso:: :ref:`delivery-service-requests` From 889ded60ea72300168b9de0df2e4fce44825bb14 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Fri, 30 Sep 2022 09:14:14 -0600 Subject: [PATCH 39/48] Fix improper use of 'IS' --- .../db/migrations/2022090708494015_ds_active_flag.down.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/traffic_ops/app/db/migrations/2022090708494015_ds_active_flag.down.sql b/traffic_ops/app/db/migrations/2022090708494015_ds_active_flag.down.sql index eb001e9b4c..d38780fc07 100644 --- a/traffic_ops/app/db/migrations/2022090708494015_ds_active_flag.down.sql +++ b/traffic_ops/app/db/migrations/2022090708494015_ds_active_flag.down.sql @@ -20,11 +20,11 @@ ADD COLUMN active_flag boolean DEFAULT FALSE NOT NULL; UPDATE public.deliveryservice SET active_flag = FALSE -WHERE active IS 'PRIMED' OR active IS 'INACTIVE'; +WHERE active = 'PRIMED' OR active = 'INACTIVE'; UPDATE public.deliveryservice SET active_flag = TRUE -WHERE active IS 'ACTIVE'; +WHERE active = 'ACTIVE'; ALTER TABLE public.deliveryservice DROP COLUMN active; ALTER TABLE public.deliveryservice RENAME COLUMN active_flag TO active; From 7eef878ecce782adfa30b93fe1eb48c7de7fe14b Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Tue, 25 Oct 2022 17:27:57 -0600 Subject: [PATCH 40/48] Remove unnecessary handling of a removed API version --- traffic_ops/traffic_ops_golang/deliveryservice/safe.go | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/safe.go b/traffic_ops/traffic_ops_golang/deliveryservice/safe.go index 74f505d91a..c26e612419 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/safe.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/safe.go @@ -156,13 +156,9 @@ func UpdateSafe(w http.ResponseWriter, r *http.Request) { ret := legacyDS.DowngradeToV31() if inf.Version.Minor >= 1 { api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, []tc.DeliveryServiceV31{tc.DeliveryServiceV31(ret)}) + } else { + api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, []tc.DeliveryServiceV30{ret.DeliveryServiceV30}) } - api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, []tc.DeliveryServiceV30{ret.DeliveryServiceV30}) - case 2: - legacyDS := ds.Downgrade() - legacyDS.LongDesc1 = dses[0].LongDesc1 - legacyDS.LongDesc2 = dses[0].LongDesc2 - api.WriteRespAlertObj(w, r, tc.SuccessLevel, alertMsg, []tc.DeliveryServiceNullableV15{legacyDS.DowngradeToV31().DeliveryServiceNullableV15}) } } From 065277a68824a5e399f85e76361b6f33afe525d0 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Thu, 27 Oct 2022 14:13:26 -0600 Subject: [PATCH 41/48] Fix illegal value in test column data --- .../deliveryservice/deliveryservices_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices_test.go b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices_test.go index 68eced8730..baec7cb466 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices_test.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices_test.go @@ -298,7 +298,7 @@ func TestReadGetDeliveryServices(t *testing.T) { {"last_header_rewrite", nil}, {"last_updated", time.Now()}, {"logs_enabled", false}, - {"long_desc", nil}, + {"long_desc", ""}, {"long_desc_1", nil}, {"long_desc_2", nil}, {"max_dns_answers", nil}, @@ -355,7 +355,7 @@ func TestReadGetDeliveryServices(t *testing.T) { mock.ExpectQuery("SELECT ds\\.xml_id as ds_name, t\\.name as type, r\\.pattern, COALESCE\\(dsr\\.set_number, 0\\) FROM regex").WillReturnRows(regexRows) mock.ExpectCommit() - _, userErr, sysErr, _, _ := readGetDeliveryServices(nil, nil, db.MustBegin(), &u, false, api.Version{Major: 4, Minor: 1}) + _, userErr, sysErr, _, _ := readGetDeliveryServices(nil, nil, db.MustBegin(), &u, false, api.Version{Major: 5, Minor: 0}) if userErr != nil { t.Errorf("Unexpected user error reading Delivery Services: %v", userErr) } From 2d74dfdbec26d3c5a74703176752d86ef96a9392 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Wed, 9 Nov 2022 11:27:46 -0700 Subject: [PATCH 42/48] Fix database migration order --- ...ive_flag.down.sql => 2022110908494015_ds_active_flag.down.sql} | 0 ..._active_flag.up.sql => 2022110908494015_ds_active_flag.up.sql} | 0 ...cit_mso.down.sql => 2022110908494016_ds_explicit_mso.down.sql} | 0 ...xplicit_mso.up.sql => 2022110908494016_ds_explicit_mso.up.sql} | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename traffic_ops/app/db/migrations/{2022090708494015_ds_active_flag.down.sql => 2022110908494015_ds_active_flag.down.sql} (100%) rename traffic_ops/app/db/migrations/{2022090708494015_ds_active_flag.up.sql => 2022110908494015_ds_active_flag.up.sql} (100%) rename traffic_ops/app/db/migrations/{2022092107561215_ds_explicit_mso.down.sql => 2022110908494016_ds_explicit_mso.down.sql} (100%) rename traffic_ops/app/db/migrations/{2022092107561215_ds_explicit_mso.up.sql => 2022110908494016_ds_explicit_mso.up.sql} (100%) diff --git a/traffic_ops/app/db/migrations/2022090708494015_ds_active_flag.down.sql b/traffic_ops/app/db/migrations/2022110908494015_ds_active_flag.down.sql similarity index 100% rename from traffic_ops/app/db/migrations/2022090708494015_ds_active_flag.down.sql rename to traffic_ops/app/db/migrations/2022110908494015_ds_active_flag.down.sql diff --git a/traffic_ops/app/db/migrations/2022090708494015_ds_active_flag.up.sql b/traffic_ops/app/db/migrations/2022110908494015_ds_active_flag.up.sql similarity index 100% rename from traffic_ops/app/db/migrations/2022090708494015_ds_active_flag.up.sql rename to traffic_ops/app/db/migrations/2022110908494015_ds_active_flag.up.sql diff --git a/traffic_ops/app/db/migrations/2022092107561215_ds_explicit_mso.down.sql b/traffic_ops/app/db/migrations/2022110908494016_ds_explicit_mso.down.sql similarity index 100% rename from traffic_ops/app/db/migrations/2022092107561215_ds_explicit_mso.down.sql rename to traffic_ops/app/db/migrations/2022110908494016_ds_explicit_mso.down.sql diff --git a/traffic_ops/app/db/migrations/2022092107561215_ds_explicit_mso.up.sql b/traffic_ops/app/db/migrations/2022110908494016_ds_explicit_mso.up.sql similarity index 100% rename from traffic_ops/app/db/migrations/2022092107561215_ds_explicit_mso.up.sql rename to traffic_ops/app/db/migrations/2022110908494016_ds_explicit_mso.up.sql From 9c4ad02d2f59762cc6a9fb1d434a92e748c6aacd Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Wed, 9 Nov 2022 15:06:37 -0700 Subject: [PATCH 43/48] Fix accidentally removed DS field in DSR endpoint docs --- docs/source/api/v5/deliveryservice_requests.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/source/api/v5/deliveryservice_requests.rst b/docs/source/api/v5/deliveryservice_requests.rst index e268ab26bf..b95920c902 100644 --- a/docs/source/api/v5/deliveryservice_requests.rst +++ b/docs/source/api/v5/deliveryservice_requests.rst @@ -177,6 +177,7 @@ The response is an array of representations of :term:`Delivery Service Requests` "rangeRequestHandling": 0, "rangeSliceBlockSize": null, "regexRemap": null, + "regional": false, "regionalGeoBlocking": false, "remapText": null, "routingName": "video", @@ -1001,6 +1002,7 @@ The response is a full representation of the deleted :term:`Delivery Service Req "rangeRequestHandling": 0, "rangeSliceBlockSize": null, "regexRemap": null, + "regional": false, "regionalGeoBlocking": false, "remapText": null, "routingName": "video", @@ -1073,6 +1075,7 @@ The response is a full representation of the deleted :term:`Delivery Service Req "rangeRequestHandling": null, "rangeSliceBlockSize": null, "regexRemap": null, + "regional": false, "regionalGeoBlocking": false, "remapText": null, "routingName": "cdn", From 20017339d6f9761ea9d1f295accd78565ad91f3c Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Wed, 9 Nov 2022 15:33:32 -0700 Subject: [PATCH 44/48] Fix v4 representations shown in apiv3 dsr post responses --- .../traffic_ops_golang/deliveryservice/request/requests.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go b/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go index e19bebf0c9..4b3ddac65c 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go @@ -610,14 +610,14 @@ func createLegacy(w http.ResponseWriter, r *http.Request, inf *api.APIInfo) (res return } - api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Delivery Service request created", upgraded.Downgrade()) + api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Delivery Service request created", upgraded.Downgrade().Downgrade()) result.Successful = true result.Assignee = dsr.Assignee result.XMLID = upgraded.XMLID result.ChangeType = upgraded.ChangeType result.Action = api.Created - return + return result } // Post is the handler for POST requests to /deliveryservice_requests. From 89f3aa777a9023341bcaaa9f80ae640672a3baf4 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Wed, 9 Nov 2022 16:12:07 -0700 Subject: [PATCH 45/48] Revert routingName changes in testing fixture data --- traffic_ops/testing/api/v3/tc-fixtures.json | 2 +- traffic_ops/testing/api/v4/tc-fixtures.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/traffic_ops/testing/api/v3/tc-fixtures.json b/traffic_ops/testing/api/v3/tc-fixtures.json index c485f5e5ea..f392b2d5f1 100644 --- a/traffic_ops/testing/api/v3/tc-fixtures.json +++ b/traffic_ops/testing/api/v3/tc-fixtures.json @@ -858,7 +858,7 @@ "regexRemap": null, "regionalGeoBlocking": false, "remapText": null, - "routingName": "ccr-ds1", + "routingName": "cdn", "signed": false, "signingAlgorithm": null, "sslKeyVersion": 0, diff --git a/traffic_ops/testing/api/v4/tc-fixtures.json b/traffic_ops/testing/api/v4/tc-fixtures.json index 6e9b6eaa6e..f0d73e79c5 100644 --- a/traffic_ops/testing/api/v4/tc-fixtures.json +++ b/traffic_ops/testing/api/v4/tc-fixtures.json @@ -907,7 +907,7 @@ "regexRemap": null, "regionalGeoBlocking": false, "remapText": null, - "routingName": "ccr-ds1", + "routingName": "cdn", "signed": false, "signingAlgorithm": null, "sslKeyVersion": 0, From 8af7cdc3177b8ce5bad3c3a99fb5e5a89bd41666 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Mon, 14 Nov 2022 11:40:18 -0700 Subject: [PATCH 46/48] Improve SQL migration readability --- .../app/db/migrations/2022110908494015_ds_active_flag.down.sql | 3 +++ .../app/db/migrations/2022110908494015_ds_active_flag.up.sql | 3 +++ .../app/db/migrations/2022110908494016_ds_explicit_mso.up.sql | 1 + 3 files changed, 7 insertions(+) diff --git a/traffic_ops/app/db/migrations/2022110908494015_ds_active_flag.down.sql b/traffic_ops/app/db/migrations/2022110908494015_ds_active_flag.down.sql index d38780fc07..f782558a18 100644 --- a/traffic_ops/app/db/migrations/2022110908494015_ds_active_flag.down.sql +++ b/traffic_ops/app/db/migrations/2022110908494015_ds_active_flag.down.sql @@ -39,6 +39,7 @@ WHERE deliveryservice ? 'active' AND deliveryservice ->> 'active' = 'ACTIVE'; + UPDATE public.deliveryservice_request SET deliveryservice = jsonb_set(deliveryservice, '{active}', 'false') @@ -51,6 +52,7 @@ WHERE OR deliveryservice ->> 'active' = 'INACTIVE' ); + UPDATE public.deliveryservice_request SET original = jsonb_set(original, '{active}', 'true') @@ -60,6 +62,7 @@ WHERE original ? 'active' AND original ->> 'active' = 'ACTIVE'; + UPDATE public.deliveryservice_request SET original = jsonb_set(original, '{active}', 'false') diff --git a/traffic_ops/app/db/migrations/2022110908494015_ds_active_flag.up.sql b/traffic_ops/app/db/migrations/2022110908494015_ds_active_flag.up.sql index 1074e7cff5..98d50d142c 100644 --- a/traffic_ops/app/db/migrations/2022110908494015_ds_active_flag.up.sql +++ b/traffic_ops/app/db/migrations/2022110908494015_ds_active_flag.up.sql @@ -39,6 +39,7 @@ WHERE deliveryservice ? 'active' AND (deliveryservice -> 'active')::boolean IS TRUE; + UPDATE public.deliveryservice_request SET deliveryservice = jsonb_set(deliveryservice, '{active}', '"PRIMED"') @@ -48,6 +49,7 @@ WHERE deliveryservice ? 'active' AND (deliveryservice -> 'active')::boolean IS FALSE; + UPDATE public.deliveryservice_request SET original = jsonb_set(original, '{active}', '"ACTIVE"') @@ -57,6 +59,7 @@ WHERE original ? 'active' AND (original -> 'active')::boolean IS TRUE; + UPDATE public.deliveryservice_request SET original = jsonb_set(original, '{active}', '"PRIMED"') diff --git a/traffic_ops/app/db/migrations/2022110908494016_ds_explicit_mso.up.sql b/traffic_ops/app/db/migrations/2022110908494016_ds_explicit_mso.up.sql index 9b452d9d12..7a4085c110 100644 --- a/traffic_ops/app/db/migrations/2022110908494016_ds_explicit_mso.up.sql +++ b/traffic_ops/app/db/migrations/2022110908494016_ds_explicit_mso.up.sql @@ -34,6 +34,7 @@ WHERE OR jsonb_typeof(deliveryservice -> 'multiSiteOrigin') = 'null' ); + UPDATE public.deliveryservice_request SET original = jsonb_set(original, '{multiSiteOrigin}', 'false') From d831648238e2404ace52c86f457aaa7c91459c57 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Thu, 17 Nov 2022 15:51:05 -0700 Subject: [PATCH 47/48] Add test coverage for invalid active states in requests --- .../testing/api/v5/deliveryservices_test.go | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/traffic_ops/testing/api/v5/deliveryservices_test.go b/traffic_ops/testing/api/v5/deliveryservices_test.go index a40f57d644..ded0f46730 100644 --- a/traffic_ops/testing/api/v5/deliveryservices_test.go +++ b/traffic_ops/testing/api/v5/deliveryservices_test.go @@ -247,8 +247,29 @@ func TestDeliveryServices(t *testing.T) { }), Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusForbidden)), }, + "BAD REQUEST when creating DS with INVALID ACTIVE STATE": { + ClientSession: TOSession, + RequestBody: generateDeliveryService( + t, + map[string]interface{}{ + "active": "this is a totally invalid active value", + }, + ), + Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), + }, }, "PUT": { + "BAD REQUEST when INVALID ACTIVE STATE": { + ClientSession: TOSession, + EndpointID: GetDeliveryServiceId(t, "ds1"), + RequestBody: generateDeliveryService( + t, + map[string]interface{}{ + "active": "this is a totally invalid active value", + }, + ), + Expectations: utils.CkRequest(utils.HasError(), utils.HasStatus(http.StatusBadRequest)), + }, "OK when VALID request": { EndpointID: GetDeliveryServiceId(t, "ds2"), ClientSession: TOSession, RequestBody: generateDeliveryService(t, map[string]interface{}{ From 8d7a14a4030669bb2a8735475da5e86750b54f37 Mon Sep 17 00:00:00 2001 From: ocket8888 Date: Thu, 17 Nov 2022 16:05:38 -0700 Subject: [PATCH 48/48] Replace literal active states with use of Go constant --- .../crconfig/deliveryservice.go | 15 +++++++-------- .../crconfig/deliveryservice_test.go | 6 +++--- .../traffic_ops_golang/crconfig/servers.go | 6 +++--- .../traffic_ops_golang/crconfig/servers_test.go | 4 ++-- .../traffic_ops_golang/dbhelpers/db_helpers.go | 12 ++++++++---- .../deliveryservice/deliveryservices.go | 4 ++-- .../deliveryservice/deliveryservices_test.go | 2 +- traffic_ops/traffic_ops_golang/server/servers.go | 4 ++-- .../server/servers_assignment.go | 10 +++++----- 9 files changed, 33 insertions(+), 30 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/crconfig/deliveryservice.go b/traffic_ops/traffic_ops_golang/crconfig/deliveryservice.go index b84d98d697..94875ac764 100644 --- a/traffic_ops/traffic_ops_golang/crconfig/deliveryservice.go +++ b/traffic_ops/traffic_ops_golang/crconfig/deliveryservice.go @@ -22,7 +22,6 @@ package crconfig import ( "database/sql" "errors" - "fmt" "math" "strconv" "strings" @@ -145,10 +144,10 @@ FROM deliveryservice AS d INNER JOIN type AS t ON t.id = d.type LEFT OUTER JOIN profile AS p ON p.id = d.profile WHERE d.cdn_id = (select id FROM cdn WHERE name = $1) -AND d.active = 'ACTIVE' +AND d.active = $2 +AND t.name != $3 ` - q += fmt.Sprintf(" and t.name != '%s'", tc.DSTypeAnyMap) - rows, err := tx.Query(q, cdn) + rows, err := tx.Query(q, cdn, tc.DSActiveStateActive, tc.DSTypeAnyMap) if err != nil { return nil, errors.New("querying deliveryservices: " + err.Error()) } @@ -465,9 +464,9 @@ from staticdnsentry as e inner join deliveryservice as d on d.id = e.deliveryservice inner join type as t on t.id = e.type where d.cdn_id = (select id from cdn where name = $1) -and d.active = 'ACTIVE' +and d.active = $2 ` - rows, err := tx.Query(q, cdn) + rows, err := tx.Query(q, cdn, tc.DSActiveStateActive) if err != nil { return nil, errors.New("querying static DNS entries: " + err.Error()) } @@ -500,10 +499,10 @@ inner join deliveryservice as d on d.id = dr.deliveryservice inner join type as t on t.id = r.type inner join type as dt on dt.id = d.type where d.cdn_id = (select id from cdn where name = $1) -and d.active = 'ACTIVE' +and d.active = $2 order by dr.set_number asc ` - rows, err := tx.Query(q, cdn) + rows, err := tx.Query(q, cdn, tc.DSActiveStateActive) if err != nil { return nil, nil, errors.New("querying deliveryservices: " + err.Error()) } diff --git a/traffic_ops/traffic_ops_golang/crconfig/deliveryservice_test.go b/traffic_ops/traffic_ops_golang/crconfig/deliveryservice_test.go index 2e5b9c9ab2..3c02242608 100644 --- a/traffic_ops/traffic_ops_golang/crconfig/deliveryservice_test.go +++ b/traffic_ops/traffic_ops_golang/crconfig/deliveryservice_test.go @@ -225,7 +225,7 @@ func MockMakeDSes(mock sqlmock.Sqlmock, expected map[string]tc.CRConfigDeliveryS "HTTP", dsName) } - mock.ExpectQuery("select").WithArgs(cdn).WillReturnRows(rows) + mock.ExpectQuery("select").WithArgs(cdn, tc.DSActiveStateActive, tc.DSTypeAnyMap).WillReturnRows(rows) } func TestMakeDSesGeoLimit(t *testing.T) { @@ -468,7 +468,7 @@ func MockGetDSRegexesDomains(mock sqlmock.Sqlmock, expectedMatchsets map[string] } } } - mock.ExpectQuery("select").WithArgs(cdn).WillReturnRows(rows) + mock.ExpectQuery("select").WithArgs(cdn, tc.DSActiveStateActive).WillReturnRows(rows) } func TestGetDSRegexesDomains(t *testing.T) { @@ -542,7 +542,7 @@ func MockGetStaticDNSEntries(mock sqlmock.Sqlmock, expected map[tc.DeliveryServi rows = rows.AddRow(dsName, entry.Name, entry.TTL, entry.Value, entry.Type+"_RECORD") } } - mock.ExpectQuery("select").WithArgs(cdn).WillReturnRows(rows) + mock.ExpectQuery("select").WithArgs(cdn, tc.DSActiveStateActive).WillReturnRows(rows) } func TestGetStaticDNSEntries(t *testing.T) { diff --git a/traffic_ops/traffic_ops_golang/crconfig/servers.go b/traffic_ops/traffic_ops_golang/crconfig/servers.go index 9127939242..ad12f2d64c 100644 --- a/traffic_ops/traffic_ops_golang/crconfig/servers.go +++ b/traffic_ops/traffic_ops_golang/crconfig/servers.go @@ -274,12 +274,12 @@ inner join deliveryservice_regex as dsr on dsr.regex = r.id inner join deliveryservice as ds on ds.id = dsr.deliveryservice inner join type as dt on dt.id = ds.type where ds.cdn_id = (select id from cdn where name = $1) -and ds.active = 'ACTIVE'` + - fmt.Sprintf(" and dt.name != '%s' ", tc.DSTypeAnyMap) + ` +and ds.active = $2 +and dt.name != $3 and rt.name = 'HOST_REGEXP' order by dsr.set_number asc ` - rows, err := tx.Query(q, cdn) + rows, err := tx.Query(q, cdn, tc.DSActiveStateActive, tc.DSTypeAnyMap) if err != nil { return nil, errors.New("Error server deliveryservices: " + err.Error()) } diff --git a/traffic_ops/traffic_ops_golang/crconfig/servers_test.go b/traffic_ops/traffic_ops_golang/crconfig/servers_test.go index 3a2577b54c..983594f498 100644 --- a/traffic_ops/traffic_ops_golang/crconfig/servers_test.go +++ b/traffic_ops/traffic_ops_golang/crconfig/servers_test.go @@ -435,7 +435,7 @@ func MockGetServerDSNames(mock sqlmock.Sqlmock, expected map[tc.CacheName][]stri rows = rows.AddRow(cache, ds) } } - mock.ExpectQuery("SELECT").WithArgs(cdn).WillReturnRows(rows) + mock.ExpectQuery("SELECT").WithArgs(cdn, tc.DSActiveStateActive, tc.DSTypeAnyMap, tc.CacheStatusOnline, tc.CacheStatusReported, tc.CacheStatusAdminDown).WillReturnRows(rows) } func TestGetServerDSNames(t *testing.T) { @@ -500,7 +500,7 @@ func MockGetServerDSes(mock sqlmock.Sqlmock, expected map[tc.CacheName]map[strin rows = rows.AddRow(ds, "DNS", "", pattern, false) } } - mock.ExpectQuery("select").WithArgs(cdn).WillReturnRows(rows) + mock.ExpectQuery("select").WithArgs(cdn, tc.DSActiveStateActive, tc.DSTypeAnyMap).WillReturnRows(rows) } func TestGetServerDSes(t *testing.T) { diff --git a/traffic_ops/traffic_ops_golang/dbhelpers/db_helpers.go b/traffic_ops/traffic_ops_golang/dbhelpers/db_helpers.go index a9531263d7..7b1dae9fd0 100644 --- a/traffic_ops/traffic_ops_golang/dbhelpers/db_helpers.go +++ b/traffic_ops/traffic_ops_golang/dbhelpers/db_helpers.go @@ -617,12 +617,16 @@ 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 = 'ACTIVE' -AND dt.name != '` + tc.DSTypeAnyMap.String() + `' +AND ds.active = $2 +AND dt.name != $3 AND p.routing_disabled = false -AND (st.name = '` + tc.CacheStatusOnline.String() + `' OR st.name = '` + tc.CacheStatusReported.String() + `' OR st.name = '` + tc.CacheStatusAdminDown.String() + `') +AND ( + st.name = $4 + OR st.name = $5 + OR st.name = $6 +) ` - rows, err := tx.Query(q, cdn) + 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()) } diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go index 4b9913e6d9..1cc3525545 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go @@ -1383,9 +1383,9 @@ func addActive(where string, params map[string]string, queryValues map[string]in return where, fmt.Errorf("active cannot parse to boolean: %w", err) } if b { - return dbhelpers.AppendWhere(where, "ds.active = 'ACTIVE'"), nil + return dbhelpers.AppendWhere(where, "ds.active = '"+string(tc.DSActiveStateActive)+"'"), nil } - return dbhelpers.AppendWhere(where, "ds.active <> 'ACTIVE'"), nil + return dbhelpers.AppendWhere(where, "ds.active <> '"+string(tc.DSActiveStateActive)+"'"), nil } switch tc.DeliveryServiceActiveState(active) { case tc.DSActiveStateActive: diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices_test.go b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices_test.go index baec7cb466..01e9fd1fe2 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices_test.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices_test.go @@ -265,7 +265,7 @@ func TestReadGetDeliveryServices(t *testing.T) { key string value driver.Value }{ - {"active", "ACTIVE"}, + {"active", tc.DSActiveStateActive}, {"anonymous_blocking_enabled", false}, {"ccr_dns_ttl", nil}, {"cdn_id", 1}, diff --git a/traffic_ops/traffic_ops_golang/server/servers.go b/traffic_ops/traffic_ops_golang/server/servers.go index 3a5615ffdf..e576aeb7e1 100644 --- a/traffic_ops/traffic_ops_golang/server/servers.go +++ b/traffic_ops/traffic_ops_golang/server/servers.go @@ -2094,7 +2094,7 @@ FROM deliveryservice_server dss JOIN server s ON dss.server = s.id JOIN type t ON s.type = t.id JOIN deliveryservice ds ON dss.deliveryservice = ds.id -WHERE t.name LIKE $1 AND ds.active = 'ACTIVE' +WHERE t.name LIKE $1 AND ds.active = $3 GROUP BY ds.id, ds.multi_site_origin, ds.topology HAVING COUNT(dss.server) = 1 AND $2 = ANY(ARRAY_AGG(dss.server)); ` @@ -2118,7 +2118,7 @@ func getActiveDeliveryServicesThatOnlyHaveThisServerAssigned(id int, serverType return ids, errors.New("nil transaction") } - rows, err := tx.Query(lastServerTypeOfDSesQuery, like, id) + rows, err := tx.Query(lastServerTypeOfDSesQuery, like, id, tc.DSActiveStateActive) if err != nil { return ids, fmt.Errorf("querying: %v", err) } diff --git a/traffic_ops/traffic_ops_golang/server/servers_assignment.go b/traffic_ops/traffic_ops_golang/server/servers_assignment.go index f7edcaddea..fe11af3f65 100644 --- a/traffic_ops/traffic_ops_golang/server/servers_assignment.go +++ b/traffic_ops/traffic_ops_golang/server/servers_assignment.go @@ -74,11 +74,11 @@ WHERE d.id IN ( FROM deliveryservice_server dss INNER JOIN deliveryservice d ON d.id = dss.deliveryservice WHERE dss.server=$1 - AND d.active = 'ACTIVE' + AND d.active = $2 ) -AND NOT (dss.deliveryservice = ANY($2::BIGINT[])) -AND (st.name = '` + string(tc.CacheStatusOnline) + `' OR st.name = '` + string(tc.CacheStatusReported) + `') -AND t.name LIKE $3 +AND NOT (dss.deliveryservice = ANY($3::BIGINT[])) +AND (st.name = $4 OR st.name = $5) +AND t.name LIKE $6 GROUP BY d.id, d.multi_site_origin, d.topology HAVING COUNT(dss.server) = 1 ` @@ -96,7 +96,7 @@ func checkForLastServerInActiveDeliveryServices(serverID int, serverType string, // by definition, only EDGE-type or ORG-type servers can be assigned return violations, nil } - rows, err := tx.Query(lastServerInActiveDeliveryServicesQuery, serverID, pq.Array(dsIDs), like) + rows, err := tx.Query(lastServerInActiveDeliveryServicesQuery, serverID, tc.DSActiveStateActive, pq.Array(dsIDs), tc.CacheStatusOnline, tc.CacheStatusReported, like) if err != nil { return violations, fmt.Errorf("querying: %v", err) }