From 1738b7667ef9e4ec92e5a47c4d0abe63448641a9 Mon Sep 17 00:00:00 2001 From: Zach Hoffman Date: Tue, 28 Jun 2022 09:29:07 -0600 Subject: [PATCH 01/14] Remove Traffic Ops API v2 tests --- .github/workflows/traffic-ops.yml | 72 - .../traffic_ops_integration_test/Dockerfile | 3 +- .../traffic_ops_integration_test/run.sh | 4 +- traffic_ops/testing/api/v2/about_test.go | 33 - .../testing/api/v2/api_capability_test.go | 77 - .../api/v2/cachegroups_parameters_test.go | 121 - .../testing/api/v2/cachegroups_test.go | 330 -- .../v2/cachegroupsdeliveryservices_test.go | 173 -- .../testing/api/v2/capabilities_test.go | 126 - .../testing/api/v2/cdn_domains_test.go | 34 - .../testing/api/v2/cdnfederations_test.go | 254 -- traffic_ops/testing/api/v2/cdns_test.go | 125 - traffic_ops/testing/api/v2/cookie_test.go | 80 - .../testing/api/v2/coordinates_test.go | 100 - traffic_ops/testing/api/v2/crconfig_test.go | 278 -- .../deliveryservice_request_comments_test.go | 113 - .../api/v2/deliveryservice_requests_test.go | 326 -- ...veryservices_required_capabilities_test.go | 320 -- .../testing/api/v2/deliveryservices_test.go | 582 ---- .../api/v2/deliveryserviceservers_test.go | 253 -- .../api/v2/deliveryservicesideligible_test.go | 44 - .../api/v2/deliveryservicesregexes_test.go | 174 -- traffic_ops/testing/api/v2/divisions_test.go | 143 - .../api/v2/federation_resolvers_test.go | 220 -- .../testing/api/v2/federation_users_test.go | 160 - .../testing/api/v2/federations_test.go | 245 -- traffic_ops/testing/api/v2/fixtures_test.go | 43 - traffic_ops/testing/api/v2/iso_test.go | 103 - traffic_ops/testing/api/v2/jobs_test.go | 192 -- traffic_ops/testing/api/v2/loginfail_test.go | 129 - traffic_ops/testing/api/v2/logs_test.go | 44 - traffic_ops/testing/api/v2/monitoring_test.go | 76 - traffic_ops/testing/api/v2/origins_test.go | 221 -- traffic_ops/testing/api/v2/parameters_test.go | 139 - .../testing/api/v2/phys_locations_test.go | 137 - traffic_ops/testing/api/v2/ping_test.go | 32 - .../testing/api/v2/profile_parameters_test.go | 121 - traffic_ops/testing/api/v2/profiles_test.go | 390 --- .../api/v2/readonlycannotmodify_test.go | 69 - traffic_ops/testing/api/v2/regions_test.go | 115 - traffic_ops/testing/api/v2/roles_test.go | 167 - .../testing/api/v2/servercapabilities_test.go | 86 - .../api/v2/servercheckextension_test.go | 132 - .../testing/api/v2/serverchecks_test.go | 145 - traffic_ops/testing/api/v2/servers_test.go | 239 -- ...vers_to_deliveryservice_assignment_test.go | 129 - .../api/v2/serverservercapability_test.go | 232 -- .../testing/api/v2/serverupdatestatus_test.go | 297 -- traffic_ops/testing/api/v2/session_test.go | 54 - .../testing/api/v2/staticdnsentries_test.go | 191 -- .../testing/api/v2/stats_summary_test.go | 178 -- traffic_ops/testing/api/v2/statuses_test.go | 129 - traffic_ops/testing/api/v2/steering_test.go | 67 - .../testing/api/v2/steeringtargets_test.go | 305 -- traffic_ops/testing/api/v2/tc-fixtures.json | 2714 ----------------- traffic_ops/testing/api/v2/tenants_test.go | 318 -- traffic_ops/testing/api/v2/todb_test.go | 319 -- .../testing/api/v2/traffic_control_test.go | 64 - .../testing/api/v2/traffic_ops_test.go | 112 - traffic_ops/testing/api/v2/types_test.go | 176 -- traffic_ops/testing/api/v2/user_test.go | 468 --- traffic_ops/testing/api/v2/withobjs_test.go | 116 - 62 files changed, 3 insertions(+), 12836 deletions(-) delete mode 100644 traffic_ops/testing/api/v2/about_test.go delete mode 100644 traffic_ops/testing/api/v2/api_capability_test.go delete mode 100644 traffic_ops/testing/api/v2/cachegroups_parameters_test.go delete mode 100644 traffic_ops/testing/api/v2/cachegroups_test.go delete mode 100644 traffic_ops/testing/api/v2/cachegroupsdeliveryservices_test.go delete mode 100644 traffic_ops/testing/api/v2/capabilities_test.go delete mode 100644 traffic_ops/testing/api/v2/cdn_domains_test.go delete mode 100644 traffic_ops/testing/api/v2/cdnfederations_test.go delete mode 100644 traffic_ops/testing/api/v2/cdns_test.go delete mode 100644 traffic_ops/testing/api/v2/cookie_test.go delete mode 100644 traffic_ops/testing/api/v2/coordinates_test.go delete mode 100644 traffic_ops/testing/api/v2/crconfig_test.go delete mode 100644 traffic_ops/testing/api/v2/deliveryservice_request_comments_test.go delete mode 100644 traffic_ops/testing/api/v2/deliveryservice_requests_test.go delete mode 100644 traffic_ops/testing/api/v2/deliveryservices_required_capabilities_test.go delete mode 100644 traffic_ops/testing/api/v2/deliveryservices_test.go delete mode 100644 traffic_ops/testing/api/v2/deliveryserviceservers_test.go delete mode 100644 traffic_ops/testing/api/v2/deliveryservicesideligible_test.go delete mode 100644 traffic_ops/testing/api/v2/deliveryservicesregexes_test.go delete mode 100644 traffic_ops/testing/api/v2/divisions_test.go delete mode 100644 traffic_ops/testing/api/v2/federation_resolvers_test.go delete mode 100644 traffic_ops/testing/api/v2/federation_users_test.go delete mode 100644 traffic_ops/testing/api/v2/federations_test.go delete mode 100644 traffic_ops/testing/api/v2/fixtures_test.go delete mode 100644 traffic_ops/testing/api/v2/iso_test.go delete mode 100644 traffic_ops/testing/api/v2/jobs_test.go delete mode 100644 traffic_ops/testing/api/v2/loginfail_test.go delete mode 100644 traffic_ops/testing/api/v2/logs_test.go delete mode 100644 traffic_ops/testing/api/v2/monitoring_test.go delete mode 100644 traffic_ops/testing/api/v2/origins_test.go delete mode 100644 traffic_ops/testing/api/v2/parameters_test.go delete mode 100644 traffic_ops/testing/api/v2/phys_locations_test.go delete mode 100644 traffic_ops/testing/api/v2/ping_test.go delete mode 100644 traffic_ops/testing/api/v2/profile_parameters_test.go delete mode 100644 traffic_ops/testing/api/v2/profiles_test.go delete mode 100644 traffic_ops/testing/api/v2/readonlycannotmodify_test.go delete mode 100644 traffic_ops/testing/api/v2/regions_test.go delete mode 100644 traffic_ops/testing/api/v2/roles_test.go delete mode 100644 traffic_ops/testing/api/v2/servercapabilities_test.go delete mode 100644 traffic_ops/testing/api/v2/servercheckextension_test.go delete mode 100644 traffic_ops/testing/api/v2/serverchecks_test.go delete mode 100644 traffic_ops/testing/api/v2/servers_test.go delete mode 100644 traffic_ops/testing/api/v2/servers_to_deliveryservice_assignment_test.go delete mode 100644 traffic_ops/testing/api/v2/serverservercapability_test.go delete mode 100644 traffic_ops/testing/api/v2/serverupdatestatus_test.go delete mode 100644 traffic_ops/testing/api/v2/session_test.go delete mode 100644 traffic_ops/testing/api/v2/staticdnsentries_test.go delete mode 100644 traffic_ops/testing/api/v2/stats_summary_test.go delete mode 100644 traffic_ops/testing/api/v2/statuses_test.go delete mode 100644 traffic_ops/testing/api/v2/steering_test.go delete mode 100644 traffic_ops/testing/api/v2/steeringtargets_test.go delete mode 100644 traffic_ops/testing/api/v2/tc-fixtures.json delete mode 100644 traffic_ops/testing/api/v2/tenants_test.go delete mode 100644 traffic_ops/testing/api/v2/todb_test.go delete mode 100644 traffic_ops/testing/api/v2/traffic_control_test.go delete mode 100644 traffic_ops/testing/api/v2/traffic_ops_test.go delete mode 100644 traffic_ops/testing/api/v2/types_test.go delete mode 100644 traffic_ops/testing/api/v2/user_test.go delete mode 100644 traffic_ops/testing/api/v2/withobjs_test.go diff --git a/.github/workflows/traffic-ops.yml b/.github/workflows/traffic-ops.yml index a4eb5c8bbf..c9e638d9d0 100644 --- a/.github/workflows/traffic-ops.yml +++ b/.github/workflows/traffic-ops.yml @@ -57,78 +57,6 @@ on: jobs: - APIv2Tests: - if: github.event.pull_request.draft == false - runs-on: ubuntu-latest - - services: - postgres: - image: postgres:13 - env: - POSTGRES_USER: traffic_ops - POSTGRES_PASSWORD: twelve - POSTGRES_DB: traffic_ops - ports: - - 5432:5432 - options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 - - smtp: - image: maildev/maildev:2.0.0-beta3 - ports: - - 25:25 - options: >- - --entrypoint=bin/maildev - --user=root - --health-cmd="sh -c \"[[ \$(wget -qO- http://smtp/healthz) == true ]]\"" - -- - maildev/maildev:2.0.0-beta3 - --smtp=25 - --hide-extensions=STARTTLS - --web=80 - - steps: - - name: Checkout - uses: actions/checkout@master - - name: Cache Alpine Docker image - uses: actions/cache@v2 - with: - path: ${{ github.workspace }}/docker-images - key: docker-images/alpine@${{ env.ALPINE_VERSION }}.tar.gz - - name: Import cached Alpine Docker image - run: .github/actions/save-alpine-tar/entrypoint.sh load ${{ env.ALPINE_VERSION }} - - name: Initialize Traffic Ops Database - id: todb - uses: ./.github/actions/todb-init - - name: Initialize Traffic Vault Database - id: tvdb - uses: ./.github/actions/tvdb-init - - name: Check Go Version - run: echo "::set-output name=value::$(cat GO_VERSION)" - id: go-version - - name: Install Go - uses: actions/setup-go@v2 - with: - go-version: ${{ steps.go-version.outputs.value }} - - name: Run API v2 tests - id: v2Tests - if: ${{ steps.todb.outcome == 'success' && always() }} - uses: ./.github/actions/to-integration-tests - with: - version: 2 - smtp_address: 172.17.0.1 - - name: Upload v2 Vault logs - if: ${{ steps.v2Tests.outcome != 'success' && always() }} - uses: actions/upload-artifact@v2 - with: - name: v2 Traffic Vault logs - path: ${{ github.workspace }}/infrastructure/cdn-in-a-box/traffic.vault.logs - - name: Upload v2 Ops logs - if: ${{ steps.v2Tests.outcome != 'success' && always() }} - uses: actions/upload-artifact@v2 - with: - name: v2 Traffic Ops logs - path: ${{ github.workspace }}/traffic_ops/traffic_ops_golang/traffic.ops.log - APIv3Tests: if: github.event.pull_request.draft == false runs-on: ubuntu-latest diff --git a/infrastructure/cdn-in-a-box/traffic_ops_integration_test/Dockerfile b/infrastructure/cdn-in-a-box/traffic_ops_integration_test/Dockerfile index cceed3181e..37c6e1edc4 100644 --- a/infrastructure/cdn-in-a-box/traffic_ops_integration_test/Dockerfile +++ b/infrastructure/cdn-in-a-box/traffic_ops_integration_test/Dockerfile @@ -43,7 +43,6 @@ COPY ./vendor/ /go/src/github.com/apache/trafficcontrol/vendor/ # integration source and dependencies COPY ./lib/ /go/src/github.com/apache/trafficcontrol/lib/ COPY ./traffic_ops/toclientlib/ /go/src/github.com/apache/trafficcontrol/traffic_ops/toclientlib/ -COPY ./traffic_ops/v2-client/ /go/src/github.com/apache/trafficcontrol/traffic_ops/v2-client/ COPY ./traffic_ops/v3-client/ /go/src/github.com/apache/trafficcontrol/traffic_ops/v3-client/ COPY ./traffic_ops/v4-client/ /go/src/github.com/apache/trafficcontrol/traffic_ops/v4-client/ COPY ./traffic_ops/testing/api /go/src/github.com/apache/trafficcontrol/traffic_ops/testing/api @@ -56,7 +55,7 @@ RUN go mod vendor -v ENV CGO_ENABLED=0 RUN set -o errexit -o xtrace;\ - for api_version in v2 v3 v4; do\ + for api_version in v3 v4; do\ go test -c ./$api_version -ldflags="-w -s" -o traffic_ops_${api_version}_integration_test;\ done diff --git a/infrastructure/cdn-in-a-box/traffic_ops_integration_test/run.sh b/infrastructure/cdn-in-a-box/traffic_ops_integration_test/run.sh index 26cd115a2c..99e74fc25d 100755 --- a/infrastructure/cdn-in-a-box/traffic_ops_integration_test/run.sh +++ b/infrastructure/cdn-in-a-box/traffic_ops_integration_test/run.sh @@ -41,7 +41,7 @@ done source config.sh exit_code=0 -for api_version in v{2..4}; do +for api_version in v{3..4}; do ./traffic_ops_${api_version}_integration_test -test.v -cfg=traffic-ops-test.conf -fixtures=tc-fixtures-${api_version}.json 2>&1 | ./go-junit-report --package-name=golang.test.toapi.${api_version} --set-exit-code > /junit/golang.test.toapi.${api_version}.xml && find /junit -type 'f' | xargs chmod 664 declare ${api_version}_exit_code=$? done @@ -49,7 +49,7 @@ done cat /junit/golang.test.toapi.v{2..4}.xml -if [[ $v2_exit_code -eq 0 && $v3_exit_code -eq 0 && $v4_exit_code -eq 0 ]]; then +if [[ $v3_exit_code -eq 0 && $v4_exit_code -eq 0 ]]; then echo "TO API tests success" else echo "TO API tests failed" diff --git a/traffic_ops/testing/api/v2/about_test.go b/traffic_ops/testing/api/v2/about_test.go deleted file mode 100644 index f549d44b8d..0000000000 --- a/traffic_ops/testing/api/v2/about_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package v2 - -/* - - Licensed 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 TestAbout(t *testing.T) { - m, _, err := TOSession.GetAbout() - if err != nil { - t.Errorf("error from GetAbout(): %v", err) - } - t.Logf("about: %v", m) - - m, _, err = NoAuthTOSession.GetAbout() - if err == nil { - t.Error("expected error from GetAbout() when unauthenticated") - } -} diff --git a/traffic_ops/testing/api/v2/api_capability_test.go b/traffic_ops/testing/api/v2/api_capability_test.go deleted file mode 100644 index e02b93b25a..0000000000 --- a/traffic_ops/testing/api/v2/api_capability_test.go +++ /dev/null @@ -1,77 +0,0 @@ -package v2 - -/* - - Licensed 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 TestAPICapabilities(t *testing.T) { - testCases := []struct { - description string - capability string - order string - first string - hasRecords bool - }{ - { - description: "Successfully get all asns-write API Capabilities", - capability: "asns-write", - hasRecords: true, - }, - { - description: "Successfully get all asns-read API Capabilities", - capability: "asns-read", - hasRecords: true, - }, - { - description: "Successfully get all cache-groups-read API Capabilities", - capability: "cache-groups-read", - hasRecords: true, - }, - { - description: "Fail to get any API Capabilities with a bogus capability", - capability: "foo", - hasRecords: false, - }, - { - description: "Successfully get all API Capabilities in order of HTTP Method", - order: "httpMethod", - first: "GET", - }, - } - - for _, c := range testCases { - t.Run(c.description, func(t *testing.T) { - caps, _, err := TOSession.GetAPICapabilities(c.capability, c.order) - - if err != nil { - t.Fatalf("error retrieving API capabilities: %s", err.Error()) - } - - if len(caps.Response) == 0 && c.hasRecords { - t.Fatalf("error: expected capability %s to have records, but found 0", c.capability) - } - - if c.order != "" { - if c.first != caps.Response[0].HTTPMethod { - t.Fatalf("error: expected first element to be %s, got %s", c.first, caps.Response[0].HTTPMethod) - } - } - }) - } - -} diff --git a/traffic_ops/testing/api/v2/cachegroups_parameters_test.go b/traffic_ops/testing/api/v2/cachegroups_parameters_test.go deleted file mode 100644 index e5d256a111..0000000000 --- a/traffic_ops/testing/api/v2/cachegroups_parameters_test.go +++ /dev/null @@ -1,121 +0,0 @@ -/* - - Licensed 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. -*/ - -package v2 - -import ( - "fmt" - "testing" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -func TestCacheGroupParameters(t *testing.T) { - WithObjs(t, []TCObj{Types, Parameters, CacheGroups, CacheGroupParameters}, func() { - GetTestCacheGroupParameters(t) - }) -} - -func CreateTestCacheGroupParameters(t *testing.T) { - // Get Cache Group to assign parameter to - firstCacheGroup := testData.CacheGroups[0] - cacheGroupResp, _, err := TOSession.GetCacheGroupNullableByName(*firstCacheGroup.Name) - if err != nil { - t.Errorf("cannot GET Cache Group by name: %v - %v", firstCacheGroup.Name, err) - } - if cacheGroupResp == nil { - t.Fatal("Cache Groups response should not be nil") - } - - // Get Parameter to assign to Cache Group - firstParameter := testData.Parameters[0] - paramResp, _, err := TOSession.GetParameterByName(firstParameter.Name) - if err != nil { - t.Errorf("cannot GET Parameter by name: %v - %v", firstParameter.Name, err) - } - if paramResp == nil { - t.Fatal("Parameter response should not be nil") - } - - // Assign Parameter to Cache Group - cacheGroupID := cacheGroupResp[0].ID - parameterID := paramResp[0].ID - resp, _, err := TOSession.CreateCacheGroupParameter(*cacheGroupID, parameterID) - if err != nil { - t.Errorf("could not CREATE cache group parameter: %v", err) - } - if resp == nil { - t.Fatal("Cache Group Parameter response should not be nil") - } - testData.CacheGroupParameterRequests = append(testData.CacheGroupParameterRequests, resp.Response...) -} - -func GetTestCacheGroupParameters(t *testing.T) { - for _, cgp := range testData.CacheGroupParameterRequests { - resp, _, err := TOSession.GetCacheGroupParameters(cgp.CacheGroupID) - if err != nil { - t.Errorf("cannot GET Parameter by cache group: %v - %v", err, resp) - } - if resp == nil { - t.Fatal("Cache Group Parameters response should not be nil") - } - } -} - -func DeleteTestCacheGroupParameters(t *testing.T) { - for _, cgp := range testData.CacheGroupParameterRequests { - DeleteTestCacheGroupParameter(t, cgp) - } -} - -func DeleteTestCacheGroupParameter(t *testing.T, cgp tc.CacheGroupParameterRequest) { - - delResp, _, err := TOSession.DeleteCacheGroupParameter(cgp.CacheGroupID, cgp.ParameterID) - if err != nil { - t.Fatalf("cannot DELETE Parameter by cache group: %v - %v", err, delResp) - } - - // Retrieve the Cache Group Parameter to see if it got deleted - queryParams := fmt.Sprintf("?parameterId=%d", cgp.ParameterID) - - parameters, _, err := TOSession.GetCacheGroupParametersByQueryParams(cgp.CacheGroupID, queryParams) - if err != nil { - t.Errorf("error deleting Parameter name: %s", err.Error()) - } - if parameters == nil { - t.Fatal("Cache Group Parameters response should not be nil") - } - if len(parameters) > 0 { - t.Errorf("expected Parameter: %d to be to be disassociated from Cache Group: %d", cgp.ParameterID, cgp.CacheGroupID) - } - - // Attempt to delete it again and it should return an error now - _, _, err = TOSession.DeleteCacheGroupParameter(cgp.CacheGroupID, cgp.ParameterID) - if err == nil { - t.Error("expected error when deleting unassociated cache group parameter") - } - - // Attempt to delete using a non existing cache group - _, _, err = TOSession.DeleteCacheGroupParameter(-1, cgp.ParameterID) - if err == nil { - t.Error("expected error when deleting cache group parameter with non existing cache group") - } - - // Attempt to delete using a non existing parameter - _, _, err = TOSession.DeleteCacheGroupParameter(cgp.CacheGroupID, -1) - if err == nil { - t.Error("expected error when deleting cache group parameter with non existing parameter") - } -} diff --git a/traffic_ops/testing/api/v2/cachegroups_test.go b/traffic_ops/testing/api/v2/cachegroups_test.go deleted file mode 100644 index bff2fbe61f..0000000000 --- a/traffic_ops/testing/api/v2/cachegroups_test.go +++ /dev/null @@ -1,330 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "fmt" - "reflect" - "testing" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -func TestCacheGroups(t *testing.T) { - WithObjs(t, []TCObj{Types, Parameters, CacheGroups}, func() { - GetTestCacheGroupsByName(t) - GetTestCacheGroupsByShortName(t) - CheckCacheGroupsAuthentication(t) - UpdateTestCacheGroups(t) - }) -} - -func CreateTestCacheGroups(t *testing.T) { - - var err error - var resp *tc.CacheGroupDetailResponse - - for _, cg := range testData.CacheGroups { - - resp, _, err = TOSession.CreateCacheGroupNullable(cg) - if err != nil { - t.Errorf("could not CREATE cachegroups: %v, request: %v", err, cg) - continue - } - if resp == nil { - t.Error("Traffic Ops returned a null or undefined Cache Group in creation response") - continue - } - - // Testing 'join' fields during create - if cg.ParentName != nil && resp.Response.ParentName == nil { - t.Error("Parent cachegroup is null in response when it should have a value") - } - if cg.SecondaryParentName != nil && resp.Response.SecondaryParentName == nil { - t.Error("Secondary parent cachegroup is null in response when it should have a value\n") - } - if cg.Type != nil && resp.Response.Type == nil { - t.Error("Type is null in response when it should have a value\n") - } - if resp.Response.LocalizationMethods == nil { - t.Error("Localization methods are null") - } - if resp.Response.Fallbacks == nil { - t.Error("Fallbacks are null") - } - - } -} - -func GetTestCacheGroupsByName(t *testing.T) { - for _, cg := range testData.CacheGroups { - resp, _, err := TOSession.GetCacheGroupNullableByName(*cg.Name) - if err != nil { - t.Errorf("cannot GET CacheGroup by name: %v - %v", err, resp) - } - } -} - -func GetTestCacheGroupsByShortName(t *testing.T) { - for _, cg := range testData.CacheGroups { - resp, _, err := TOSession.GetCacheGroupNullableByName(*cg.ShortName) - if err != nil { - t.Errorf("cannot GET CacheGroup by shortName: %v - %v", err, resp) - } - } -} - -func UpdateTestCacheGroups(t *testing.T) { - firstCG := testData.CacheGroups[0] - resp, _, err := TOSession.GetCacheGroupNullableByName(*firstCG.Name) - if err != nil { - t.Errorf("cannot GET CACHEGROUP by name: %v - %v", *firstCG.Name, err) - } - cg := resp[0] - expectedShortName := "blah" - cg.ShortName = &expectedShortName - - // fix the type id for test - typeResp, _, err := TOSession.GetTypeByID(*cg.TypeID) - if err != nil { - t.Error("could not lookup a typeID for this cachegroup") - } - cg.TypeID = &typeResp[0].ID - - updResp, _, err := TOSession.UpdateCacheGroupNullableByID(*cg.ID, cg) - if err != nil { - t.Errorf("cannot UPDATE CacheGroup by id: %v - %v", err, updResp) - } - - // Check response to make sure fields aren't null - if cg.ParentName != nil && updResp.Response.ParentName == nil { - t.Error("Parent cachegroup is null in response when it should have a value") - } - if cg.SecondaryParentName != nil && updResp.Response.SecondaryParentName == nil { - t.Error("Secondary parent cachegroup is null in response when it should have a value\n") - } - if cg.Type != nil && updResp.Response.Type == nil { - t.Error("Type is null in response when it should have a value\n") - } - if updResp.Response.LocalizationMethods == nil { - t.Error("Localization methods are null") - } - if updResp.Response.Fallbacks == nil { - t.Error("Fallbacks are null") - } - - // Retrieve the CacheGroup to check CacheGroup name got updated - resp, _, err = TOSession.GetCacheGroupNullableByID(*cg.ID) - if err != nil { - t.Errorf("cannot GET CacheGroup by name: '%s', %v", *firstCG.Name, err) - } - cg = resp[0] - if *cg.ShortName != expectedShortName { - t.Errorf("results do not match actual: %s, expected: %s", *cg.ShortName, expectedShortName) - } - - // test coordinate updates - expectedLat := 7.0 - expectedLong := 8.0 - cg.Latitude = &expectedLat - cg.Longitude = &expectedLong - updResp, _, err = TOSession.UpdateCacheGroupNullableByID(*cg.ID, cg) - if err != nil { - t.Errorf("cannot UPDATE CacheGroup by id: %v - %v", err, updResp) - } - - resp, _, err = TOSession.GetCacheGroupNullableByID(*cg.ID) - if err != nil { - t.Errorf("cannot GET CacheGroup by id: '%d', %v", *cg.ID, err) - } - cg = resp[0] - if *cg.Latitude != expectedLat { - t.Errorf("failed to update latitude (expected = %f, actual = %f)", expectedLat, *cg.Latitude) - } - if *cg.Longitude != expectedLong { - t.Errorf("failed to update longitude (expected = %f, actual = %f)", expectedLong, *cg.Longitude) - } - - // test localizationMethods - expectedMethods := []tc.LocalizationMethod{tc.LocalizationMethodGeo} - cg.LocalizationMethods = &expectedMethods - updResp, _, err = TOSession.UpdateCacheGroupNullableByID(*cg.ID, cg) - if err != nil { - t.Errorf("cannot UPDATE CacheGroup by id: %v - %v", err, updResp) - } - - resp, _, err = TOSession.GetCacheGroupNullableByID(*cg.ID) - if err != nil { - t.Errorf("cannot GET CacheGroup by id: '%d', %v", *cg.ID, err) - } - cg = resp[0] - if !reflect.DeepEqual(expectedMethods, *cg.LocalizationMethods) { - t.Errorf("failed to update localizationMethods (expected = %v, actual = %v)", expectedMethods, *cg.LocalizationMethods) - } - - // test cachegroup fallbacks - - // Retrieve the CacheGroup to check CacheGroup name got updated - firstEdgeCGName := "cachegroup1" - resp, _, err = TOSession.GetCacheGroupNullableByName(firstEdgeCGName) - if err != nil { - t.Errorf("cannot GET CacheGroup by name: '$%s', %v", firstEdgeCGName, err) - } - cg = resp[0] - if *cg.Name != firstEdgeCGName { - t.Errorf("results do not match actual: %s, expected: %s", *cg.ShortName, firstEdgeCGName) - } - - // Test adding fallbacks when previously nil - expectedFallbacks := []string{"fallback1", "fallback2"} - cg.Fallbacks = &expectedFallbacks - updResp, _, err = TOSession.UpdateCacheGroupNullableByID(*cg.ID, cg) - if err != nil { - t.Errorf("cannot UPDATE CacheGroup by id: %v - %v", err, updResp) - } - - resp, _, err = TOSession.GetCacheGroupNullableByID(*cg.ID) - if err != nil { - t.Errorf("cannot GET CacheGroup by id: '%d', %v", *cg.ID, err) - } - cg = resp[0] - if !reflect.DeepEqual(expectedFallbacks, *cg.Fallbacks) { - t.Errorf("failed to update fallbacks (expected = %v, actual = %v)", expectedFallbacks, *cg.Fallbacks) - } - - // Test adding fallback to existing list - expectedFallbacks = []string{"fallback1", "fallback2", "fallback3"} - cg.Fallbacks = &expectedFallbacks - updResp, _, err = TOSession.UpdateCacheGroupNullableByID(*cg.ID, cg) - if err != nil { - t.Errorf("cannot UPDATE CacheGroup by id: %v - %v)", err, updResp) - } - - resp, _, err = TOSession.GetCacheGroupNullableByID(*cg.ID) - if err != nil { - t.Errorf("cannot GET CacheGroup by id: '%d', %v", *cg.ID, err) - } - cg = resp[0] - if !reflect.DeepEqual(expectedFallbacks, *cg.Fallbacks) { - t.Errorf("failed to update fallbacks (expected = %v, actual = %v)", expectedFallbacks, *cg.Fallbacks) - } - - // Test removing fallbacks - expectedFallbacks = []string{} - cg.Fallbacks = &expectedFallbacks - updResp, _, err = TOSession.UpdateCacheGroupNullableByID(*cg.ID, cg) - if err != nil { - t.Errorf("cannot UPDATE CacheGroup by id: %v - %v", err, updResp) - } - - resp, _, err = TOSession.GetCacheGroupNullableByID(*cg.ID) - if err != nil { - t.Errorf("cannot GET CacheGroup by id: '%d', %v", *cg.ID, err) - } - cg = resp[0] - if !reflect.DeepEqual(expectedFallbacks, *cg.Fallbacks) { - t.Errorf("failed to update fallbacks (expected = %v, actual = %v)", expectedFallbacks, *cg.Fallbacks) - } -} - -func DeleteTestCacheGroups(t *testing.T) { - var mids []tc.CacheGroupNullable - - // delete the edge caches. - for _, cg := range testData.CacheGroups { - // Retrieve the CacheGroup by name so we can get the id for the Update - resp, _, err := TOSession.GetCacheGroupNullableByName(*cg.Name) - if err != nil { - t.Errorf("cannot GET CacheGroup by name: %v - %v", *cg.Name, err) - } - // Mids are parents and need to be deleted only after the children - // cachegroups are deleted. - if *cg.Type == "MID_LOC" { - mids = append(mids, cg) - continue - } - if len(resp) > 0 { - respCG := resp[0] - _, _, err := TOSession.DeleteCacheGroupByID(*respCG.ID) - if err != nil { - t.Errorf("cannot DELETE CacheGroup by name: '%s' %v", *respCG.Name, err) - } - // Retrieve the CacheGroup to see if it got deleted - cgs, _, err := TOSession.GetCacheGroupNullableByName(*cg.Name) - if err != nil { - t.Errorf("error deleting CacheGroup by name: %s", err.Error()) - } - if len(cgs) > 0 { - t.Errorf("expected CacheGroup name: %s to be deleted", *cg.Name) - } - } - } - // now delete the mid tier caches - for _, cg := range mids { - // Retrieve the CacheGroup by name so we can get the id for the Update - resp, _, err := TOSession.GetCacheGroupNullableByName(*cg.Name) - if err != nil { - t.Errorf("cannot GET CacheGroup by name: %v - %v", *cg.Name, err) - } - if len(resp) > 0 { - respCG := resp[0] - _, _, err := TOSession.DeleteCacheGroupByID(*respCG.ID) - if err != nil { - t.Errorf("cannot DELETE CacheGroup by name: '%s' %v", *respCG.Name, err) - } - - // Retrieve the CacheGroup to see if it got deleted - cgs, _, err := TOSession.GetCacheGroupNullableByName(*cg.Name) - if err != nil { - t.Errorf("error deleting CacheGroup name: %s", err.Error()) - } - if len(cgs) > 0 { - t.Errorf("expected CacheGroup name: %s to be deleted", *cg.Name) - } - } - } -} - -func CheckCacheGroupsAuthentication(t *testing.T) { - errFormat := "expected error from %s when unauthenticated" - - cg := testData.CacheGroups[0] - - resp, _, err := TOSession.GetCacheGroupNullableByName(*cg.Name) - if err != nil { - t.Errorf("cannot GET CacheGroup by name: %v - %v", *cg.Name, err) - } - cg = resp[0] - - if _, _, err = NoAuthTOSession.CreateCacheGroupNullable(cg); err == nil { - t.Error(fmt.Errorf(errFormat, "CreateCacheGroup")) - } - if _, _, err = NoAuthTOSession.GetCacheGroupsNullable(); err == nil { - t.Error(fmt.Errorf(errFormat, "GetCacheGroups")) - } - if _, _, err = NoAuthTOSession.GetCacheGroupNullableByName(*cg.Name); err == nil { - t.Error(fmt.Errorf(errFormat, "GetCacheGroupByName")) - } - if _, _, err = NoAuthTOSession.GetCacheGroupNullableByID(*cg.ID); err == nil { - t.Error(fmt.Errorf(errFormat, "GetCacheGroupByID")) - } - if _, _, err = NoAuthTOSession.UpdateCacheGroupNullableByID(*cg.ID, cg); err == nil { - t.Error(fmt.Errorf(errFormat, "UpdateCacheGroupByID")) - } - if _, _, err = NoAuthTOSession.DeleteCacheGroupByID(*cg.ID); err == nil { - t.Error(fmt.Errorf(errFormat, "DeleteCacheGroupByID")) - } -} diff --git a/traffic_ops/testing/api/v2/cachegroupsdeliveryservices_test.go b/traffic_ops/testing/api/v2/cachegroupsdeliveryservices_test.go deleted file mode 100644 index beb6b05741..0000000000 --- a/traffic_ops/testing/api/v2/cachegroupsdeliveryservices_test.go +++ /dev/null @@ -1,173 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "strconv" - "testing" -) - -func TestCacheGroupsDeliveryServices(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Tenants, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, Servers, DeliveryServices, CacheGroupsDeliveryServices}, func() {}) -} - -// TODO this is the name hard-coded in the create servers test; change to be dynamic -// TODO this test assumes that a CDN named "cdn1" exists, has at least one Delivery Service, and also -// assumes that ALL SERVERS IN "cachegroup3" ARE EDGE-TIER CACHE SERVERS IN "cdn1". If that EVER changes, -// this WILL break. -const TestEdgeServerCacheGroupName = "cachegroup3" - -func CreateTestCachegroupsDeliveryServices(t *testing.T) { - dss, _, err := TOSession.GetDeliveryServiceServers() - if err != nil { - t.Fatalf("cannot GET DeliveryServiceServers: %v", err) - } - if len(dss.Response) > 0 { - t.Fatalf("cannot test cachegroups delivery services: expected no initial delivery service servers, actual %v", len(dss.Response)) - } - - dses, _, err := TOSession.GetDeliveryServicesNullable() - if err != nil { - t.Fatalf("cannot GET DeliveryServices: %v - %v", err, dses) - } - - clientCGs, _, err := TOSession.GetCacheGroupNullableByName(TestEdgeServerCacheGroupName) - if err != nil { - t.Fatalf("getting cachegroup: %v", err) - } - if len(clientCGs) != 1 { - t.Fatalf("getting cachegroup expected 1, got %v", len(clientCGs)) - } - - clientCG := clientCGs[0] - - if clientCG.ID == nil { - t.Fatalf("Cachegroup has a nil ID") - } - cgID := *clientCG.ID - - dsIDs := []int{} - for _, ds := range dses { - if *ds.CDNName == "cdn1" { - dsIDs = append(dsIDs, *ds.ID) - } - } - if len(dsIDs) < 1 { - t.Fatal("No Delivery Services found in CDN 'cdn1', cannot continue.") - } - - resp, _, err := TOSession.SetCachegroupDeliveryServices(cgID, dsIDs) - if err != nil { - t.Fatalf("setting cachegroup delivery services returned error: %v", err) - } - if len(resp.Response.ServerNames) == 0 { - t.Fatal("setting cachegroup delivery services returned success, but no servers set") - } - - // Note this second post of the same cg-dses specifically tests a previous bug, where the query - // failed if any servers with location parameters were already assigned, due to a foreign key - // violation. See https://github.com/apache/trafficcontrol/pull/3199 - resp, _, err = TOSession.SetCachegroupDeliveryServices(cgID, dsIDs) - if err != nil { - t.Fatalf("setting cachegroup delivery services returned error: %v", err) - } - if len(resp.Response.ServerNames) == 0 { - t.Fatal("setting cachegroup delivery services returned success, but no servers set") - } - - for _, serverName := range resp.Response.ServerNames { - servers, _, err := TOSession.GetServerByHostName(string(serverName)) - if err != nil { - t.Fatalf("getting server: %v", err) - } - if len(servers) != 1 { - t.Fatalf("getting servers: expected 1 got %v", len(servers)) - } - server := servers[0] - serverID := server.ID - - serverDSes, _, err := TOSession.GetDeliveryServicesByServer(serverID) - if err != nil { - t.Fatalf("getting delivery services by server: %v", err) - } - for _, dsID := range dsIDs { - found := false - for _, serverDS := range serverDSes { - if *serverDS.ID == int(dsID) { - found = true - break - } - } - if !found { - t.Errorf("post succeeded, but didn't assign delivery service %v to server", dsID) - } - } - } -} - -func setInactive(t *testing.T, dsID int) { - strID := strconv.Itoa(dsID) - ds, _, err := TOSession.GetDeliveryServiceNullable(strID) - if err != nil { - t.Errorf("Failed to fetch details for Delivery Service #%d", dsID) - return - } - if ds == nil { - t.Errorf("Got null or undefined Delivery Service for #%d", dsID) - return - } - 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 - _, err = TOSession.UpdateDeliveryServiceNullable(strID, ds) - if err != nil { - t.Errorf("Failed to set Delivery Service #%d to inactive: %v", dsID, err) - } - } -} - -func DeleteTestCachegroupsDeliveryServices(t *testing.T) { - dss, _, err := TOSession.GetDeliveryServiceServersN(1000000) - if err != nil { - t.Errorf("cannot GET DeliveryServiceServers: %v", err) - } - for _, ds := range dss.Response { - if ds.DeliveryService == nil { - t.Errorf("nil DeliveryService field") - continue - } - if ds.Server == nil { - t.Errorf("nil Server field") - continue - } - setInactive(t, *ds.DeliveryService) - _, _, err := TOSession.DeleteDeliveryServiceServer(*ds.DeliveryService, *ds.Server) - if err != nil { - t.Errorf("deleting delivery service servers: " + err.Error() + "\n") - } - } - - dss, _, err = TOSession.GetDeliveryServiceServers() - if err != nil { - t.Errorf("cannot GET DeliveryServiceServers: %v", err) - } - if len(dss.Response) > 0 { - t.Errorf("deleting delivery service servers: delete succeeded, expected empty subsequent get, actual %v", len(dss.Response)) - } -} diff --git a/traffic_ops/testing/api/v2/capabilities_test.go b/traffic_ops/testing/api/v2/capabilities_test.go deleted file mode 100644 index b053b04d38..0000000000 --- a/traffic_ops/testing/api/v2/capabilities_test.go +++ /dev/null @@ -1,126 +0,0 @@ -package v2 - -/* - * 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 ( - "fmt" - "testing" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -// These capabilities are defined during the setup process in todb.go. -// ANY TIME THOSE ARE CHANGED THIS MUST BE UPDATED. -var staticCapabilities = []tc.Capability{ - tc.Capability{ - Name: "all-read", - Description: "Full read access", - }, - tc.Capability{ - Name: "all-write", - Description: "Full write access", - }, - tc.Capability{ - Name: "cdn-read", - Description: "View CDN configuration", - }, - tc.Capability{ - Name: "asns-read", - Description: "Read ASNs", - }, - tc.Capability{ - Name: "asns-write", - Description: "Write ASNs", - }, - tc.Capability{ - Name: "cache-groups-read", - Description: "Read CGs", - }, -} - -func TestCapabilities(t *testing.T) { - CreateTestCapabilities(t) - GetTestCapabilities(t) -} - -func CreateTestCapabilities(t *testing.T) { - db, err := OpenConnection() - if err != nil { - t.Fatal("cannot open db") - } - defer db.Close() - dbInsertTemplate := `INSERT INTO capability (name, description) VALUES ('%v', '%v');` - - for _, c := range testData.Capabilities { - err = execSQL(db, fmt.Sprintf(dbInsertTemplate, c.Name, c.Description)) - if err != nil { - t.Errorf("could not create capability: %v", err) - } - } -} - -func GetTestCapabilities(t *testing.T) { - testDataLen := len(testData.Capabilities) + len(staticCapabilities) - capMap := make(map[string]string, testDataLen) - - for _, c := range testData.Capabilities { - capMap[c.Name] = c.Description - cap, _, err := TOSession.GetCapability(c.Name) - if err != nil { - t.Errorf("could not get capability '%s': %v", c.Name, err) - continue - } - - if cap.Name != c.Name { - t.Errorf("requested capacity '%s' but got a capacity with the name '%s'", c.Name, cap.Name) - } - if cap.Description != c.Description { - t.Errorf("capacity '%s' has the wrong description, want '%s' but got '%s'", c.Name, c.Description, cap.Description) - } - } - - // Hopefully this won't need to be done for much longer - for _, c := range staticCapabilities { - capMap[c.Name] = c.Description - } - - caps, _, err := TOSession.GetCapabilities() - if err != nil { - t.Fatalf("could not get all capabilities: %v", err) - } - if len(caps) != testDataLen { - t.Fatalf("response returned different number of capabilities than those that exist; got %d, want %d", len(caps), testDataLen) - } - - for _, c := range caps { - if desc, ok := capMap[c.Name]; !ok { - t.Errorf("capability '%s' found in response, but not in test data!", c.Name) - } else { - if desc != c.Description { - t.Errorf("capability '%s' has description '%s' in response, but had '%s' in the test data", c.Name, c.Description, desc) - } - delete(capMap, c.Name) - } - } - - for c, _ := range capMap { - t.Errorf("Capability '%s' existed in the test data but didn't appear in the response!", c) - } -} diff --git a/traffic_ops/testing/api/v2/cdn_domains_test.go b/traffic_ops/testing/api/v2/cdn_domains_test.go deleted file mode 100644 index 94b5b8a7b7..0000000000 --- a/traffic_ops/testing/api/v2/cdn_domains_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package v2 - -/* - - Licensed 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 GetTestDomains(t *testing.T) { - resp, _, err := TOSession.GetDomains() - t.Log("Response: ", resp) - if err != nil { - t.Errorf("could not GET domains: %v", err) - } -} - -func TestDomains(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Parameters, Profiles, Statuses}, func() { - GetTestDomains(t) - }) -} diff --git a/traffic_ops/testing/api/v2/cdnfederations_test.go b/traffic_ops/testing/api/v2/cdnfederations_test.go deleted file mode 100644 index 7e811edff9..0000000000 --- a/traffic_ops/testing/api/v2/cdnfederations_test.go +++ /dev/null @@ -1,254 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "encoding/json" - "strings" - "testing" - - "github.com/apache/trafficcontrol/lib/go-log" -) - -var fedIDs []int - -func TestCDNFederations(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Parameters, Tenants, DeliveryServices, CDNFederations}, func() { - UpdateTestCDNFederations(t) - GetTestCDNFederations(t) - }) -} - -func TestFederationFederationResolvers(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Parameters, Tenants, DeliveryServices, CDNFederations, FederationResolvers}, func() { - AssignTestFederationFederationResolvers(t) - GetTestFederationFederationResolvers(t) - }) -} - -func CreateTestCDNFederations(t *testing.T) { - - // Every federation is associated with a cdn - for i, f := range testData.Federations { - - // CDNs test data and Federations test data are not naturally parallel - if i >= len(testData.CDNs) { - break - } - - data, _, err := TOSession.CreateCDNFederationByName(f, "cdn1") - if err != nil { - t.Errorf("could not POST federations: " + err.Error()) - } - bytes, _ := json.Marshal(data) - t.Logf("POST Response: %s\n", bytes) - - // need to save the ids, otherwise the other tests won't be able to reference the federations - if data.Response.ID == nil { - t.Error("Federation id is nil after posting") - } else { - fedIDs = append(fedIDs, *data.Response.ID) - resp, _, err := TOSession.GetDeliveryServiceByXMLIDNullable("ds1") - if err != nil { - t.Errorf("could not get delivery service by xml ID: %v", err) - } - if len(resp) != 1 { - t.Fatalf("expected one response for delivery service, but got %d", len(resp)) - } - _, err = TOSession.CreateFederationDeliveryServices(*data.Response.ID, []int{*resp[0].ID}, false) - if err != nil { - t.Errorf("could not create federation delivery service: %v", err) - } - } - } -} - -func UpdateTestCDNFederations(t *testing.T) { - - for _, id := range fedIDs { - fed, _, err := TOSession.GetCDNFederationsByID("cdn1", id) - if err != nil { - t.Errorf("cannot GET federation by id: %v", err) - } - - expectedCName := "new.cname." - fed.Response[0].CName = &expectedCName - resp, _, err := TOSession.UpdateCDNFederationsByID(fed.Response[0], "cdn1", id) - if err != nil { - t.Errorf("cannot PUT federation by id: %v", err) - } - bytes, _ := json.Marshal(resp) - t.Logf("PUT Response: %s\n", bytes) - - resp2, _, err := TOSession.GetCDNFederationsByID("cdn1", id) - if err != nil { - t.Errorf("cannot GET federation by id after PUT: %v", err) - } - bytes, _ = json.Marshal(resp2) - t.Logf("GET Response: %s\n", bytes) - - if resp2.Response[0].CName == nil { - log.Errorln("CName is nil after updating") - } else if *resp2.Response[0].CName != expectedCName { - t.Errorf("results do not match actual: %s, expected: %s", *resp2.Response[0].CName, expectedCName) - } - - } -} - -func GetTestCDNFederations(t *testing.T) { - - // TOSession.GetCDNFederationsByName can't be tested until - // POST /federations/{{id}}/deliveryservices has been - // created. (DELETE cdns/:name/federations/:id may need to - // clean up fedIDs connection?) - - for _, id := range fedIDs { - data, _, err := TOSession.GetCDNFederationsByID("cdn1", id) - if err != nil { - t.Errorf("could not GET federations: " + err.Error()) - } - bytes, _ := json.Marshal(data) - t.Logf("GET Response: %s\n", bytes) - } -} - -func AssignTestFederationFederationResolvers(t *testing.T) { - // Setup - if len(fedIDs) < 2 { - t.Fatal("not enough federations to test") - } - - frCnt := len(testData.FederationResolvers) - if frCnt < 2 { - t.Fatal("not enough federation resolvers to test") - } - - frs, _, err := TOSession.GetFederationResolvers() - if err != nil { - t.Fatalf("Unexpected error getting Federation Resolvers: %v", err) - } - if len(frs) != frCnt { - t.Fatalf("Wrong number of Federation Resolvers from GET, want %d got %d", frCnt, len(frs)) - } - - frIDs := make([]int, 0, len(frs)) - for _, fr := range frs { - frIDs = append(frIDs, int(*fr.ID)) - } - - // Test Cases - testCases := []struct { - description string - fedID int - resolverIDs []int - replace bool - err string - }{ - { - description: "Successfully assign one federation_resolver to a federation", - fedID: fedIDs[0], - resolverIDs: frIDs[0:0], - replace: false, - err: "", - }, - { - description: "Successfully assign multiple federation_resolver to a federation", - fedID: fedIDs[0], - resolverIDs: frIDs[1:frCnt], - replace: false, - err: "", - }, - { - description: "Successfully replace all federation_resolver for a federation", - fedID: fedIDs[0], - resolverIDs: frIDs[0:frCnt], - replace: true, - err: "", - }, - { - description: "Fail to assign federation_resolver to a federation when federation does not exist", - fedID: -1, - resolverIDs: frIDs[0:0], - replace: false, - err: "no such Federation", - }, - } - - for _, c := range testCases { - t.Run(c.description, func(t *testing.T) { - _, _, err := TOSession.AssignFederationFederationResolver(c.fedID, c.resolverIDs, c.replace) - - if err != nil && !strings.Contains(err.Error(), c.err) { - t.Fatalf("error: expected error result %v, want: %v", err, c.err) - } - }) - } - -} - -func GetTestFederationFederationResolvers(t *testing.T) { - if len(fedIDs) < 2 { - t.Fatal("not enough federations to test") - } - - testCases := []struct { - description string - fedID int - hasRecords bool - }{ - { - description: "successfully get federation_federation_resolvers for a federation with some", - fedID: fedIDs[0], - hasRecords: true, - }, - { - description: "successfully get federation_federation_resolvers for a federation without any", - fedID: fedIDs[1], - hasRecords: false, - }, - } - - for _, c := range testCases { - t.Run(c.description, func(t *testing.T) { - resp, _, err := TOSession.GetFederationFederationResolversByID(c.fedID) - if err != nil { - t.Fatalf("Error getting federation federation resolvers by federation id: %d, err: %s", c.fedID, err.Error()) - } - if len(resp.Response) == 0 && c.hasRecords { - t.Fatalf("expected federation of ID %d to have associated federation resolvers, but had 0", c.fedID) - } - }) - } -} - -func DeleteTestCDNFederations(t *testing.T) { - - for _, id := range fedIDs { - resp, _, err := TOSession.DeleteCDNFederationByID("cdn1", id) - if err != nil { - t.Errorf("cannot DELETE federation by id: '%d' %v", id, err) - } - bytes, err := json.Marshal(resp) - t.Logf("DELETE Response: %s\n", bytes) - - data, _, err := TOSession.GetCDNFederationsByID("cdn1", id) - if len(data.Response) != 0 { - t.Error("expected federation to be deleted") - } - } - fedIDs = nil // reset the global variable for the next test -} diff --git a/traffic_ops/testing/api/v2/cdns_test.go b/traffic_ops/testing/api/v2/cdns_test.go deleted file mode 100644 index 7a5e82cc58..0000000000 --- a/traffic_ops/testing/api/v2/cdns_test.go +++ /dev/null @@ -1,125 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "sort" - "testing" - - tc "github.com/apache/trafficcontrol/lib/go-tc" -) - -func TestCDNs(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Parameters}, func() { - SortTestCDNs(t) - UpdateTestCDNs(t) - GetTestCDNs(t) - }) -} - -func CreateTestCDNs(t *testing.T) { - - for _, cdn := range testData.CDNs { - resp, _, err := TOSession.CreateCDN(cdn) - t.Log("Response: ", resp) - if err != nil { - t.Errorf("could not CREATE cdns: %v", err) - } - } - -} - -func SortTestCDNs(t *testing.T) { - var sortedList []string - resp, _, _ := TOSession.GetCDNs() - for i, _ := range resp { - sortedList = append(sortedList, resp[i].Name) - } - - res := sort.SliceIsSorted(sortedList, func(p, q int) bool { - return sortedList[p] < sortedList[q] - }) - if res != true { - t.Errorf("list is not sorted by their names: %v", sortedList) - } -} - -func UpdateTestCDNs(t *testing.T) { - - firstCDN := testData.CDNs[0] - // Retrieve the CDN by name so we can get the id for the Update - resp, _, err := TOSession.GetCDNByName(firstCDN.Name) - if err != nil { - t.Errorf("cannot GET CDN by name: '%s', %v", firstCDN.Name, err) - } - remoteCDN := resp[0] - expectedCDNDomain := "domain2" - remoteCDN.DomainName = expectedCDNDomain - var alert tc.Alerts - alert, _, err = TOSession.UpdateCDNByID(remoteCDN.ID, remoteCDN) - if err != nil { - t.Errorf("cannot UPDATE CDN by id: %v - %v", err, alert) - } - - // Retrieve the CDN to check CDN name got updated - resp, _, err = TOSession.GetCDNByID(remoteCDN.ID) - if err != nil { - t.Errorf("cannot GET CDN by name: '$%s', %v", firstCDN.Name, err) - } - respCDN := resp[0] - if respCDN.DomainName != expectedCDNDomain { - t.Errorf("results do not match actual: %s, expected: %s", respCDN.DomainName, expectedCDNDomain) - } - -} - -func GetTestCDNs(t *testing.T) { - - for _, cdn := range testData.CDNs { - resp, _, err := TOSession.GetCDNByName(cdn.Name) - if err != nil { - t.Errorf("cannot GET CDN by name: %v - %v", err, resp) - } - } -} - -func DeleteTestCDNs(t *testing.T) { - - for _, cdn := range testData.CDNs { - // Retrieve the CDN by name so we can get the id for the Update - resp, _, err := TOSession.GetCDNByName(cdn.Name) - if err != nil { - t.Errorf("cannot GET CDN by name: %v - %v", cdn.Name, err) - } - if len(resp) > 0 { - respCDN := resp[0] - - _, _, err := TOSession.DeleteCDNByID(respCDN.ID) - if err != nil { - t.Errorf("cannot DELETE CDN by name: '%s' %v", respCDN.Name, err) - } - - // Retrieve the CDN to see if it got deleted - cdns, _, err := TOSession.GetCDNByName(cdn.Name) - if err != nil { - t.Errorf("error deleting CDN name: %s", err.Error()) - } - if len(cdns) > 0 { - t.Errorf("expected CDN name: %s to be deleted", cdn.Name) - } - } - } -} diff --git a/traffic_ops/testing/api/v2/cookie_test.go b/traffic_ops/testing/api/v2/cookie_test.go deleted file mode 100644 index 883431f221..0000000000 --- a/traffic_ops/testing/api/v2/cookie_test.go +++ /dev/null @@ -1,80 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "encoding/json" - "io/ioutil" - "net/http" - "testing" - - "github.com/apache/trafficcontrol/lib/go-tc" - toclient "github.com/apache/trafficcontrol/traffic_ops/v2-client" -) - -func TestCookies(t *testing.T) { - WithObjs(t, []TCObj{CDNs}, func() { - CookiesTest(t) - }) -} - -func CookiesTest(t *testing.T) { - s, _, err := toclient.LoginWithAgent(Config.TrafficOps.URL, Config.TrafficOps.Users.Admin, Config.TrafficOps.UserPassword, true, "to-api-v2-client-tests", false, toReqTimeout) - credentials := tc.UserCredentials{ - Username: Config.TrafficOps.Users.Admin, - Password: Config.TrafficOps.UserPassword, - } - - js, err := json.Marshal(credentials) - if err != nil { - t.Fatal("unable to json marshal login credentials") - } - path := "/api/2.0/user/login" - loginResp, _, err := s.RawRequest(http.MethodPost, path, js) - if err != nil { - t.Fatal("unable to request POST /user/login") - } - defer loginResp.Body.Close() - _, readErr := ioutil.ReadAll(loginResp.Body) - if readErr != nil { - t.Fatal("unable to read response body from POST /user/login") - } - ensureCookie(loginResp, t) - - cdnResp, _, err := s.RawRequest(http.MethodGet, "/api/2.0/cdns", nil) - if err != nil { - t.Fatal("unable to request GET /cdns") - } - defer cdnResp.Body.Close() - _, readErr = ioutil.ReadAll(cdnResp.Body) - if readErr != nil { - t.Fatal("unable to read response body from GET /cdns") - } - ensureCookie(cdnResp, t) -} - -func ensureCookie(r *http.Response, t *testing.T) { - cookies := r.Cookies() - if len(cookies) < 1 { - t.Fatal("expected at least one cookie in response, actual: zero") - } - if cookies[0].MaxAge < 1 { - t.Errorf("expected auth cookie Max-Age > 0, actual: %v", *cookies[0]) - } - if cookies[0].Expires.IsZero() { - t.Errorf("expected auth cookie with non-zero Expires, actual: %v", *cookies[0]) - } -} diff --git a/traffic_ops/testing/api/v2/coordinates_test.go b/traffic_ops/testing/api/v2/coordinates_test.go deleted file mode 100644 index 29f8ad03b7..0000000000 --- a/traffic_ops/testing/api/v2/coordinates_test.go +++ /dev/null @@ -1,100 +0,0 @@ -package v2 - -/* - - Licensed 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" - - tc "github.com/apache/trafficcontrol/lib/go-tc" -) - -func TestCoordinates(t *testing.T) { - WithObjs(t, []TCObj{Parameters, Coordinates}, func() { - GetTestCoordinates(t) - UpdateTestCoordinates(t) - }) -} - -func CreateTestCoordinates(t *testing.T) { - for _, coord := range testData.Coordinates { - - _, _, err := TOSession.CreateCoordinate(coord) - if err != nil { - t.Errorf("could not CREATE coordinates: %v", err) - } - } -} - -func GetTestCoordinates(t *testing.T) { - for _, coord := range testData.Coordinates { - resp, _, err := TOSession.GetCoordinateByName(coord.Name) - if err != nil { - t.Errorf("cannot GET Coordinate: %v - %v", err, resp) - } - } -} - -func UpdateTestCoordinates(t *testing.T) { - firstCoord := testData.Coordinates[0] - resp, _, err := TOSession.GetCoordinateByName(firstCoord.Name) - if err != nil { - t.Errorf("cannot GET Coordinate by name: %v - %v", firstCoord.Name, err) - } - coord := resp[0] - expectedLat := 12.34 - coord.Latitude = expectedLat - - var alert tc.Alerts - alert, _, err = TOSession.UpdateCoordinateByID(coord.ID, coord) - if err != nil { - t.Errorf("cannot UPDATE Coordinate by id: %v - %v", err, alert) - } - - // Retrieve the Coordinate to check Coordinate name got updated - resp, _, err = TOSession.GetCoordinateByID(coord.ID) - if err != nil { - t.Errorf("cannot GET Coordinate by name: '$%s', %v", firstCoord.Name, err) - } - coord = resp[0] - if coord.Latitude != expectedLat { - t.Errorf("results do not match actual: %s, expected: %f", coord.Name, expectedLat) - } -} - -func DeleteTestCoordinates(t *testing.T) { - for _, coord := range testData.Coordinates { - // Retrieve the Coordinate by name so we can get the id for the Update - resp, _, err := TOSession.GetCoordinateByName(coord.Name) - if err != nil { - t.Errorf("cannot GET Coordinate by name: %v - %v", coord.Name, err) - } - if len(resp) > 0 { - respCoord := resp[0] - _, _, err := TOSession.DeleteCoordinateByID(respCoord.ID) - if err != nil { - t.Errorf("cannot DELETE Coordinate by name: '%s' %v", respCoord.Name, err) - } - // Retrieve the Coordinate to see if it got deleted - coords, _, err := TOSession.GetCoordinateByName(coord.Name) - if err != nil { - t.Errorf("error deleting Coordinate name: %s", err.Error()) - } - if len(coords) > 0 { - t.Errorf("expected Coordinate name: %s to be deleted", coord.Name) - } - } - } -} diff --git a/traffic_ops/testing/api/v2/crconfig_test.go b/traffic_ops/testing/api/v2/crconfig_test.go deleted file mode 100644 index 657f927cb1..0000000000 --- a/traffic_ops/testing/api/v2/crconfig_test.go +++ /dev/null @@ -1,278 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "encoding/json" - "strings" - "testing" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -func TestCRConfig(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Tenants, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, Servers, DeliveryServices}, func() { - UpdateTestCRConfigSnapshot(t) - MonitoringConfig(t) - SnapshotTestCDNbyName(t) - SnapshotTestCDNbyInvalidName(t) - SnapshotTestCDNbyID(t) - SnapshotTestCDNbyInvalidID(t) - }) -} - -func UpdateTestCRConfigSnapshot(t *testing.T) { - if len(testData.CDNs) < 1 { - t.Fatalf("no cdn test data") - } - cdn := testData.CDNs[0].Name - - tmURLParamName := "tm.url" - tmURLExpected := "crconfig.tm.url.test.invalid" - _, _, err := TOSession.CreateParameter(tc.Parameter{ - ConfigFile: "global", - Name: tmURLParamName, - Value: "https://crconfig.tm.url.test.invalid", - }) - if err != nil { - t.Fatalf("GetCRConfig CreateParameter error expected: nil, actual: " + err.Error()) - } - - // create an ANY_MAP DS assignment to verify that it doesn't show up in the CRConfig - servers, _, err := TOSession.GetServers() - if err != nil { - t.Errorf("GetServers err expected nil, actual %+v", err) - } - serverID := 0 - for _, server := range servers { - if server.Type == "EDGE" && server.CDNName == "cdn1" { - serverID = server.ID - break - } - } - if serverID == 0 { - t.Errorf("GetServers expected EDGE server in cdn1, actual: %+v", servers) - } - res, _, err := TOSession.GetDeliveryServiceByXMLIDNullable("anymap-ds") - if err != nil { - t.Errorf("GetDeliveryServiceByXMLIDNullable err expected nil, actual %+v", err) - } - if len(res) != 1 { - t.Error("GetDeliveryServiceByXMLIDNullable expected 1 DS, actual 0") - } - if res[0].ID == nil { - t.Error("GetDeliveryServiceByXMLIDNullable got unknown delivery service id") - } - anymapDSID := *res[0].ID - _, err = TOSession.CreateDeliveryServiceServers(anymapDSID, []int{serverID}, true) - if err != nil { - t.Errorf("POST delivery service servers: %v", err) - } - - _, err = TOSession.SnapshotCRConfig(cdn) - if err != nil { - t.Errorf("SnapshotCRConfig err expected nil, actual %+v", err) - } - crcBts, _, err := TOSession.GetCRConfig(cdn) - if err != nil { - t.Errorf("GetCRConfig err expected nil, actual %+v", err) - } - crc := tc.CRConfig{} - if err := json.Unmarshal(crcBts, &crc); err != nil { - t.Errorf("GetCRConfig bytes expected: valid tc.CRConfig, actual JSON unmarshal err: %+v", err) - } - - if len(crc.DeliveryServices) == 0 { - t.Error("GetCRConfig len(crc.DeliveryServices) expected: >0, actual: 0") - } - - // verify no ANY_MAP delivery services are in the CRConfig - for ds := range crc.DeliveryServices { - if ds == "anymap-ds" { - t.Error("found ANY_MAP delivery service in CRConfig deliveryServices") - } - } - for server := range crc.ContentServers { - for ds := range crc.ContentServers[server].DeliveryServices { - if ds == "anymap-ds" { - t.Error("found ANY_MAP delivery service in contentServers deliveryServices mapping") - } - } - } - - if crc.Stats.TMPath == nil { - t.Error("GetCRConfig crc.Stats.Path expected: some non-null string (but we don't check contents because it's deprecated), actual: null") - } - - if crc.Stats.TMHost == nil { - t.Errorf("GetCRConfig crc.Stats.Path expected: '"+tmURLExpected+"', actual: %+v", crc.Stats.TMHost) - } else if *crc.Stats.TMHost != tmURLExpected { - t.Errorf("GetCRConfig crc.Stats.Path expected: '"+tmURLExpected+"', actual: %+v", *crc.Stats.TMHost) - } - - paramResp, _, err := TOSession.GetParameterByName(tmURLParamName) - if err != nil { - t.Fatalf("cannot GET Parameter by name: %v - %v", tmURLParamName, err) - } - if len(paramResp) == 0 { - t.Fatal("CRConfig create tm.url parameter was successful, but GET returned no parameters") - } - tmURLParam := paramResp[0] - - delResp, _, err := TOSession.DeleteParameterByID(tmURLParam.ID) - if err != nil { - t.Fatalf("cannot DELETE Parameter by name: %v - %v", err, delResp) - } - - crcBtsNew, _, err := TOSession.GetCRConfigNew(cdn) - if err != nil { - t.Errorf("GetCRConfig err expected nil, actual %+v", err) - } - crcNew := tc.CRConfig{} - if err := json.Unmarshal(crcBtsNew, &crcNew); err != nil { - t.Errorf("GetCRConfig bytes expected: valid tc.CRConfig, actual JSON unmarshal err: %+v", err) - } - - if len(crcNew.DeliveryServices) != len(crc.DeliveryServices) { - t.Errorf("/new endpoint returned a different snapshot. DeliveryServices length expected %v, was %v", len(crc.DeliveryServices), len(crcNew.DeliveryServices)) - } - - if *crcNew.Stats.TMHost != "" { - t.Errorf("update to snapshot not captured in /new endpoint") - } -} - -func MonitoringConfig(t *testing.T) { - if len(testData.CDNs) < 1 { - t.Fatalf("no cdn test data") - } - const cdnName = "cdn1" - const profileName = "EDGE1" - cdns, _, err := TOSession.GetCDNByName(cdnName) - if err != nil { - t.Fatalf("getting CDNs with name '%s': %s", cdnName, err.Error()) - } - if len(cdns) < 1 { - t.Fatalf("expected to find a CDN named %s", cdnName) - } - if len(cdns) > 1 { - t.Fatalf("expected exactly 1 CDN named %s but found %d CDNs", cdnName, len(cdns)) - } - profiles, _, err := TOSession.GetProfileByName(profileName) - if err != nil { - t.Fatalf("getting Profiles with name '%s': %s", profileName, err.Error()) - } - if len(profiles) != 1 { - t.Fatalf("expected exactly 1 Profiles named %s but found %d Profiles", profileName, len(profiles)) - } - parameters, _, err := TOSession.GetParametersByProfileName(profileName) - if err != nil { - t.Fatalf("getting Parameters by Profile name '%s': %s", profileName, err.Error()) - } - parameterMap := map[string]tc.HealthThreshold{} - parameterFound := map[string]bool{} - const thresholdPrefixLength = len(tc.ThresholdPrefix) - for _, parameter := range parameters { - if !strings.HasPrefix(parameter.Name, tc.ThresholdPrefix) { - continue - } - parameterName := parameter.Name[thresholdPrefixLength:] - parameterMap[parameterName], err = tc.StrToThreshold(parameter.Value) - if err != nil { - t.Fatalf("converting string '%s' to HealthThreshold: %s", parameter.Value, err.Error()) - } - parameterFound[parameterName] = false - } - const expectedThresholdParameters = 3 - if len(parameterMap) != expectedThresholdParameters { - t.Fatalf("expected Profile '%s' to contain %d Parameters with names starting with '%s' but %d such Parameters were found", profileName, expectedThresholdParameters, tc.ThresholdPrefix, len(parameterMap)) - } - tmConfig, _, err := TOSession.GetTrafficMonitorConfig(cdnName) - if err != nil { - t.Fatalf("getting Traffic Monitor Config: %s", err.Error()) - } - profileFound := false - var profile tc.TMProfile - for _, profile = range tmConfig.Profiles { - if profile.Name == profileName { - profileFound = true - break - } - } - if !profileFound { - t.Fatalf("Traffic Monitor Config contained no Profile named '%s", profileName) - } - for parameterName, value := range profile.Parameters.Thresholds { - if _, ok := parameterFound[parameterName]; !ok { - t.Fatalf("unexpected Threshold Parameter name '%s' found in Profile '%s' in Traffic Monitor Config", parameterName, profileName) - } - parameterFound[parameterName] = true - if parameterMap[parameterName].String() != value.String() { - t.Fatalf("expected '%s' but received '%s' for Threshold Parameter '%s' in Profile '%s' in Traffic Monitor Config", parameterMap[parameterName].String(), value.String(), parameterName, profileName) - } - } - missingParameters := []string{} - for parameterName, found := range parameterFound { - if !found { - missingParameters = append(missingParameters, parameterName) - } - } - if len(missingParameters) != 0 { - t.Fatalf("Threshold parameters defined for Profile '%s' but missing for Profile '%s' in Traffic Monitor Config: %s", profileName, profileName, strings.Join(missingParameters, ", ")) - } -} - -func SnapshotTestCDNbyName(t *testing.T) { - - firstCDN := testData.CDNs[0] - _, err := TOSession.SnapshotCRConfig(firstCDN.Name) - if err != nil { - t.Errorf("failed to snapshot CDN by name: %v", err) - } -} - -func SnapshotTestCDNbyInvalidName(t *testing.T) { - - invalidCDNName := "cdn-invalid" - _, err := TOSession.SnapshotCRConfig(invalidCDNName) - if err == nil { - t.Errorf("snapshot occurred on invalid cdn name: %v - %v", invalidCDNName, err) - } -} - -func SnapshotTestCDNbyID(t *testing.T) { - - firstCDN := testData.CDNs[0] - // Retrieve the CDN by name so we can get the id for the snapshot - resp, _, err := TOSession.GetCDNByName(firstCDN.Name) - if err != nil { - t.Errorf("cannot GET CDN by name: '%s', %v", firstCDN.Name, err) - } - remoteCDN := resp[0] - alert, _, err := TOSession.SnapshotCRConfigByID(remoteCDN.ID) - if err != nil { - t.Errorf("failed to snapshot CDN by id: %v - %v", err, alert) - } -} - -func SnapshotTestCDNbyInvalidID(t *testing.T) { - - invalidCDNID := 999999 - alert, _, err := TOSession.SnapshotCRConfigByID(invalidCDNID) - if err == nil { - t.Errorf("snapshot occurred on invalid cdn id: %v - %v - %v", invalidCDNID, err, alert) - } -} diff --git a/traffic_ops/testing/api/v2/deliveryservice_request_comments_test.go b/traffic_ops/testing/api/v2/deliveryservice_request_comments_test.go deleted file mode 100644 index ec34520a24..0000000000 --- a/traffic_ops/testing/api/v2/deliveryservice_request_comments_test.go +++ /dev/null @@ -1,113 +0,0 @@ -package v2 - -/* - - Licensed 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" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -func TestDeliveryServiceRequestComments(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Parameters, Tenants, DeliveryServiceRequests, DeliveryServiceRequestComments}, func() { - UpdateTestDeliveryServiceRequestComments(t) - GetTestDeliveryServiceRequestComments(t) - }) -} - -func CreateTestDeliveryServiceRequestComments(t *testing.T) { - - // Retrieve a delivery service request by xmlId so we can get the ID needed to create a dsr comment - dsr := testData.DeliveryServiceRequests[0].DeliveryService - - resp, _, err := TOSession.GetDeliveryServiceRequestByXMLID(dsr.XMLID) - if err != nil { - t.Errorf("cannot GET delivery service request by xml id: %v - %v", dsr.XMLID, err) - } - if len(resp) != 1 { - t.Errorf("found %d delivery service request by xml id, expected %d: %s", len(resp), 1, dsr.XMLID) - } - - respDSR := resp[0] - - for _, comment := range testData.DeliveryServiceRequestComments { - comment.DeliveryServiceRequestID = respDSR.ID - resp, _, err := TOSession.CreateDeliveryServiceRequestComment(comment) - if err != nil { - t.Errorf("could not CREATE delivery service request comment: %v - %v", err, resp) - } - } - -} - -func UpdateTestDeliveryServiceRequestComments(t *testing.T) { - - comments, _, err := TOSession.GetDeliveryServiceRequestComments() - - firstComment := comments[0] - newFirstCommentValue := "new comment value" - firstComment.Value = newFirstCommentValue - - var alert tc.Alerts - alert, _, err = TOSession.UpdateDeliveryServiceRequestCommentByID(firstComment.ID, firstComment) - if err != nil { - t.Errorf("cannot UPDATE delivery service request comment by id: %v - %v", err, alert) - } - - // Retrieve the delivery service request comment to check that the value got updated - resp, _, err := TOSession.GetDeliveryServiceRequestCommentByID(firstComment.ID) - if err != nil { - t.Errorf("cannot GET delivery service request comment by id: '$%d', %v", firstComment.ID, err) - } - respDSRC := resp[0] - if respDSRC.Value != newFirstCommentValue { - t.Errorf("results do not match actual: %s, expected: %s", respDSRC.Value, newFirstCommentValue) - } - -} - -func GetTestDeliveryServiceRequestComments(t *testing.T) { - - comments, _, _ := TOSession.GetDeliveryServiceRequestComments() - - for _, comment := range comments { - resp, _, err := TOSession.GetDeliveryServiceRequestCommentByID(comment.ID) - if err != nil { - t.Errorf("cannot GET delivery service request comment by id: %v - %v", err, resp) - } - } -} - -func DeleteTestDeliveryServiceRequestComments(t *testing.T) { - - comments, _, _ := TOSession.GetDeliveryServiceRequestComments() - - for _, comment := range comments { - _, _, err := TOSession.DeleteDeliveryServiceRequestCommentByID(comment.ID) - if err != nil { - t.Errorf("cannot DELETE delivery service request comment by id: '%d' %v", comment.ID, err) - } - - // Retrieve the delivery service request comment to see if it got deleted - comments, _, err := TOSession.GetDeliveryServiceRequestCommentByID(comment.ID) - if err != nil { - t.Errorf("error deleting delivery service request comment: %s", err.Error()) - } - if len(comments) > 0 { - t.Errorf("expected delivery service request comment: %d to be deleted", comment.ID) - } - } -} diff --git a/traffic_ops/testing/api/v2/deliveryservice_requests_test.go b/traffic_ops/testing/api/v2/deliveryservice_requests_test.go deleted file mode 100644 index d5e7670b8a..0000000000 --- a/traffic_ops/testing/api/v2/deliveryservice_requests_test.go +++ /dev/null @@ -1,326 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "strings" - "testing" - - tc "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - dsrGood = 0 - dsrBadTenant = 1 - dsrRequired = 2 - dsrDraft = 3 -) - -func TestDeliveryServiceRequests(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Parameters, Tenants, DeliveryServiceRequests}, func() { - GetTestDeliveryServiceRequests(t) - UpdateTestDeliveryServiceRequests(t) - }) -} - -func CreateTestDeliveryServiceRequests(t *testing.T) { - t.Log("CreateTestDeliveryServiceRequests") - - dsr := testData.DeliveryServiceRequests[dsrGood] - respDSR, _, err := TOSession.CreateDeliveryServiceRequest(dsr) - t.Log("Response: ", respDSR) - if err != nil { - t.Errorf("could not CREATE DeliveryServiceRequests: %v", err) - } - -} - -func TestDeliveryServiceRequestRequired(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Parameters, Tenants}, func() { - dsr := testData.DeliveryServiceRequests[dsrRequired] - alerts, _, err := TOSession.CreateDeliveryServiceRequest(dsr) - if err != nil { - t.Errorf("Error occurred %v", err) - } - - if len(alerts.Alerts) == 0 { - t.Errorf("Expected: validation error alerts, actual: %+v", alerts) - } - }) -} - -func TestDeliveryServiceRequestRules(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Parameters, Tenants}, func() { - routingName := strings.Repeat("X", 1) + "." + strings.Repeat("X", 48) - // Test the xmlId length and form - XMLID := "X " + strings.Repeat("X", 46) - displayName := strings.Repeat("X", 49) - - dsr := testData.DeliveryServiceRequests[dsrGood] - dsr.DeliveryService.DisplayName = displayName - dsr.DeliveryService.RoutingName = routingName - dsr.DeliveryService.XMLID = XMLID - - alerts, _, err := TOSession.CreateDeliveryServiceRequest(dsr) - if err != nil { - t.Errorf("Error occurred %v", err) - } - if len(alerts.Alerts) == 0 { - t.Errorf("Expected: validation error alerts, actual: %+v", alerts) - } - }) -} - -func TestDeliveryServiceRequestTypeFields(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Tenants, Parameters}, func() { - dsr := testData.DeliveryServiceRequests[dsrBadTenant] - - alerts, _, err := TOSession.CreateDeliveryServiceRequest(dsr) - if err != nil { - t.Errorf("Error occurred %v", err) - } - - found := false - for _, alert := range alerts.Alerts { - if alert.Level == tc.ErrorLevel.String() { - t.Errorf("Expected only succuss-level alerts creating a DSR, got error-level alert: %s", alert.Text) - } else if alert.Level == tc.SuccessLevel.String() { - t.Logf("Got expected alert creating a DSR: %s", alert.Text) - found = true - } - } - if !found { - t.Errorf("Expected a success-level alert creating a DSR, got none") - } - - dsrs, _, err := TOSession.GetDeliveryServiceRequestByXMLID(dsr.DeliveryService.XMLID) - if len(dsrs) != 1 { - t.Errorf("expected 1 deliveryservice_request with XMLID %s; got %d", dsr.DeliveryService.XMLID, len(dsrs)) - } - alert, _, err := TOSession.DeleteDeliveryServiceRequestByID(dsrs[0].ID) - if err != nil { - t.Errorf("cannot DELETE DeliveryServiceRequest by id: %d - %v - %v", dsrs[0].ID, err, alert) - } - }) -} - -func TestDeliveryServiceRequestBad(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Parameters, Tenants}, func() { - // try to create non-draft/submitted - src := testData.DeliveryServiceRequests[dsrDraft] - s, err := tc.RequestStatusFromString("pending") - if err != nil { - t.Errorf(`unable to create Status from string "pending"`) - } - src.Status = s - - alerts, _, err := TOSession.CreateDeliveryServiceRequest(src) - if err != nil { - t.Errorf("Error creating DeliveryServiceRequest %v", err) - } - - found := false - for _, alert := range alerts.Alerts { - if alert.Level == tc.SuccessLevel.String() { - t.Errorf("Expected only error-level alerts creating a DSR with a bad status, got success-level alert: %s", alert.Text) - } else if alert.Level == tc.ErrorLevel.String() { - t.Logf("Got expected alert creating a DSR with a bad status: %s", alert.Text) - found = true - } - } - - if !found { - t.Errorf("Expected an error-level alert creating a DSR with a bad status, got none") - } - }) -} - -// TestDeliveryServiceRequestWorkflow tests that transitions of Status are -func TestDeliveryServiceRequestWorkflow(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Parameters, Tenants}, func() { - // test empty request table - dsrs, _, err := TOSession.GetDeliveryServiceRequests() - if err != nil { - t.Errorf("Error getting empty list of DeliveryServiceRequests %v++", err) - } - if dsrs == nil { - t.Error("Expected empty DeliveryServiceRequest slice -- got nil") - } - if len(dsrs) != 0 { - t.Errorf("Expected no entries in DeliveryServiceRequest slice -- got %d", len(dsrs)) - } - - // Create a draft request - src := testData.DeliveryServiceRequests[dsrDraft] - - alerts, _, err := TOSession.CreateDeliveryServiceRequest(src) - if err != nil { - t.Errorf("Error creating DeliveryServiceRequest %v", err) - } - - found := false - for _, alert := range alerts.Alerts { - if alert.Level == tc.ErrorLevel.String() { - t.Errorf("Expected only succuss-level alerts creating a DSR, got error-level alert: %s", alert.Text) - } else if alert.Level == tc.SuccessLevel.String() { - t.Logf("Got expected alert creating a DSR: %s", alert.Text) - found = true - } - } - if !found { - t.Errorf("Expected a success-level alert creating a DSR, got none") - } - - // Create a duplicate request -- should fail because xmlId is the same - alerts, _, err = TOSession.CreateDeliveryServiceRequest(src) - if err != nil { - t.Errorf("Error creating DeliveryServiceRequest %v", err) - } - - found = false - for _, alert := range alerts.Alerts { - if alert.Level == tc.SuccessLevel.String() { - t.Errorf("Expected only error-level alerts creating a duplicate DSR, got success-level alert: %s", alert.Text) - } else if alert.Level == tc.ErrorLevel.String() { - t.Logf("Got expected alert creating a duplicate DSR: %s", alert.Text) - found = true - } - } - if !found { - t.Errorf("Expected an error-level alert creating a DSR, got none") - } - - dsrs, _, err = TOSession.GetDeliveryServiceRequestByXMLID(`test-transitions`) - if len(dsrs) != 1 { - t.Errorf("Expected 1 deliveryServiceRequest -- got %d", len(dsrs)) - if len(dsrs) == 0 { - t.Fatal("Cannot proceed") - } - } - - alerts, dsr := updateDeliveryServiceRequestStatus(t, dsrs[0], "submitted") - - found = false - for _, alert := range alerts.Alerts { - if alert.Level == tc.ErrorLevel.String() { - t.Errorf("Expected only succuss-level alerts updating a DSR, got error-level alert: %s", alert.Text) - } else if alert.Level == tc.SuccessLevel.String() { - t.Logf("Got expected alert updating a DSR: %s", alert.Text) - found = true - } - } - if !found { - t.Errorf("Expected a success-level alert updating a DSR, got none") - } - - if dsr.Status != tc.RequestStatus("submitted") { - t.Errorf("expected status=submitted, got %s", string(dsr.Status)) - } - }) -} - -func updateDeliveryServiceRequestStatus(t *testing.T, dsr tc.DeliveryServiceRequest, newstate string) (tc.Alerts, tc.DeliveryServiceRequest) { - ID := dsr.ID - dsr.Status = tc.RequestStatus("submitted") - - alerts, _, err := TOSession.UpdateDeliveryServiceRequestByID(ID, dsr) - if err != nil { - t.Errorf("Error updating deliveryservice_request: %v", err) - return alerts, dsr - } - - d, _, err := TOSession.GetDeliveryServiceRequestByID(ID) - if err != nil { - t.Errorf("Error updating deliveryservice_request %d: %v", ID, err) - return alerts, dsr - } - - if len(d) != 1 { - t.Errorf("Expected 1 deliveryservice_request, got %d", len(d)) - } - return alerts, d[0] -} - -func GetTestDeliveryServiceRequests(t *testing.T) { - dsr := testData.DeliveryServiceRequests[dsrGood] - resp, _, err := TOSession.GetDeliveryServiceRequestByXMLID(dsr.DeliveryService.XMLID) - if err != nil { - t.Errorf("cannot GET DeliveryServiceRequest by XMLID: %v - %v", err, resp) - } -} - -func UpdateTestDeliveryServiceRequests(t *testing.T) { - - // Retrieve the DeliveryServiceRequest by name so we can get the id for the Update - dsr := testData.DeliveryServiceRequests[dsrGood] - resp, _, err := TOSession.GetDeliveryServiceRequestByXMLID(dsr.DeliveryService.XMLID) - if err != nil { - t.Errorf("cannot GET DeliveryServiceRequest by name: %v - %v", dsr.DeliveryService.XMLID, err) - } - if len(resp) == 0 { - t.Fatal("Length of GET DeliveryServiceRequest is 0") - } - respDSR := resp[0] - expDisplayName := "new display name" - respDSR.DeliveryService.DisplayName = expDisplayName - var alert tc.Alerts - alert, _, err = TOSession.UpdateDeliveryServiceRequestByID(respDSR.ID, respDSR) - t.Log("Response: ", alert) - if err != nil { - t.Errorf("cannot UPDATE DeliveryServiceRequest by id: %v - %v", err, alert) - return - } - - // Retrieve the DeliveryServiceRequest to check DeliveryServiceRequest name got updated - resp, _, err = TOSession.GetDeliveryServiceRequestByID(respDSR.ID) - if err != nil { - t.Errorf("cannot GET DeliveryServiceRequest by name: %v - %v", respDSR.ID, err) - } else { - respDSR = resp[0] - if respDSR.DeliveryService.DisplayName != expDisplayName { - t.Errorf("results do not match actual: %s, expected: %s", respDSR.DeliveryService.DisplayName, expDisplayName) - } - } - -} - -func DeleteTestDeliveryServiceRequests(t *testing.T) { - - // Retrieve the DeliveryServiceRequest by name so we can get the id for the Update - dsr := testData.DeliveryServiceRequests[dsrGood] - resp, _, err := TOSession.GetDeliveryServiceRequestByXMLID(dsr.DeliveryService.XMLID) - if err != nil { - t.Errorf("cannot GET DeliveryServiceRequest by id: %v - %v", dsr.DeliveryService.XMLID, err) - } - if len(resp) < 1 { - t.Fatalf("Expected at least one Delivery Service Request to exist for a Delivery Service with XMLID '%s', found: 0", dsr.DeliveryService.XMLID) - } - respDSR := resp[0] - alert, _, err := TOSession.DeleteDeliveryServiceRequestByID(respDSR.ID) - t.Log("Response: ", alert) - if err != nil { - t.Errorf("cannot DELETE DeliveryServiceRequest by id: %d - %v - %v", respDSR.ID, err, alert) - } - - // Retrieve the DeliveryServiceRequest to see if it got deleted - dsrs, _, err := TOSession.GetDeliveryServiceRequestByXMLID(dsr.DeliveryService.XMLID) - if err != nil { - t.Errorf("error deleting DeliveryServiceRequest name: %s", err.Error()) - } - if len(dsrs) > 0 { - t.Errorf("expected DeliveryServiceRequest XMLID: %s to be deleted", dsr.DeliveryService.XMLID) - } -} diff --git a/traffic_ops/testing/api/v2/deliveryservices_required_capabilities_test.go b/traffic_ops/testing/api/v2/deliveryservices_required_capabilities_test.go deleted file mode 100644 index e98571f607..0000000000 --- a/traffic_ops/testing/api/v2/deliveryservices_required_capabilities_test.go +++ /dev/null @@ -1,320 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "fmt" - "strings" - "testing" - - "github.com/apache/trafficcontrol/lib/go-tc" - "github.com/apache/trafficcontrol/lib/go-util" -) - -func TestDeliveryServicesRequiredCapabilities(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Tenants, Users, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, Servers, ServerCapabilities, DeliveryServices, DeliveryServicesRequiredCapabilities}, func() { - InvalidDeliveryServicesRequiredCapabilityAddition(t) - GetTestDeliveryServicesRequiredCapabilities(t) - }) -} - -func GetTestDeliveryServicesRequiredCapabilities(t *testing.T) { - data := testData.DeliveryServicesRequiredCapabilities - ds1 := helperGetDeliveryServiceID(t, data[0].XMLID) - - testCases := []struct { - description string - capability tc.DeliveryServicesRequiredCapability - expected int - }{ - { - description: "get all deliveryservices required capabilities", - expected: len(testData.DeliveryServicesRequiredCapabilities), - }, - { - description: fmt.Sprintf("get all deliveryservices required capabilities by deliveryServiceID: %d", *ds1), - capability: tc.DeliveryServicesRequiredCapability{ - DeliveryServiceID: ds1, - }, - expected: 1, - }, - { - description: fmt.Sprintf("get all deliveryservices required capabilities by xmlID: %s", *data[0].XMLID), - capability: tc.DeliveryServicesRequiredCapability{ - XMLID: data[0].XMLID, - }, - expected: 1, - }, - { - description: fmt.Sprintf("get all deliveryservices required capabilities by requiredCapability: %s", *data[0].RequiredCapability), - capability: tc.DeliveryServicesRequiredCapability{ - RequiredCapability: data[0].RequiredCapability, - }, - expected: 1, - }, - } - - for _, tc := range testCases { - t.Run(tc.description, func(t *testing.T) { - capabilities, _, err := TOSession.GetDeliveryServicesRequiredCapabilities(tc.capability.DeliveryServiceID, tc.capability.XMLID, tc.capability.RequiredCapability) - if err != nil { - t.Fatalf("%s; got err= %v; expected err= nil", tc.description, err) - } - if len(capabilities) != tc.expected { - t.Errorf("got %d; expected %d required capabilities assigned to deliveryservices", len(capabilities), tc.expected) - } - }) - } -} - -func CreateTestDeliveryServicesRequiredCapabilities(t *testing.T) { - data := testData.DeliveryServicesRequiredCapabilities - if len(data) == 0 { - t.Fatal("there must be at least one test ds required capability defined") - } - ds1 := helperGetDeliveryServiceID(t, data[0].XMLID) - amDS := helperGetDeliveryServiceID(t, util.StrPtr("anymap-ds")) - testCases := []struct { - description string - capability tc.DeliveryServicesRequiredCapability - }{ - { - description: fmt.Sprintf("re-assign a deliveryservice to a required capability; deliveryServiceID: %d, requiredCapability: %s", *ds1, *data[0].RequiredCapability), - capability: tc.DeliveryServicesRequiredCapability{ - DeliveryServiceID: ds1, - RequiredCapability: data[0].RequiredCapability, - }, - }, - { - description: fmt.Sprintf("assign a deliveryservice to a required capability with no delivery service id; deliveryServiceID: 0, requiredCapability: %s", *data[0].RequiredCapability), - capability: tc.DeliveryServicesRequiredCapability{ - RequiredCapability: data[0].RequiredCapability, - }, - }, - { - description: fmt.Sprintf("assign a deliveryservice to a required capability with no requiredCapability; deliveryServiceID: %d, requiredCapability: 0", *ds1), - capability: tc.DeliveryServicesRequiredCapability{ - DeliveryServiceID: ds1, - }, - }, - { - description: fmt.Sprintf("assign a deliveryservice to a required capability with an invalid required capability; deliveryServiceID: %d, requiredCapability: bogus", *ds1), - capability: tc.DeliveryServicesRequiredCapability{ - DeliveryServiceID: ds1, - RequiredCapability: util.StrPtr("bogus"), - }, - }, - { - description: fmt.Sprintf("assign a deliveryservice to a required capability with an invalid delivery service id; deliveryServiceID: -1, requiredCapability: %s", *data[0].RequiredCapability), - capability: tc.DeliveryServicesRequiredCapability{ - DeliveryServiceID: util.IntPtr(-1), - RequiredCapability: data[0].RequiredCapability, - }, - }, - { - description: "assign a deliveryservice to a required capability with an invalid deliveryservice type", - capability: tc.DeliveryServicesRequiredCapability{ - DeliveryServiceID: amDS, - RequiredCapability: data[0].RequiredCapability, - }, - }, - } - - // Assign all required capability to delivery services listed in `tc-fixtures.json`. - for _, td := range testData.DeliveryServicesRequiredCapabilities { - var dsID int - if td.DeliveryServiceID != nil { - dsID = *td.DeliveryServiceID - } - - var capability string - if td.RequiredCapability != nil { - capability = *td.RequiredCapability - } - - t.Run(fmt.Sprintf("assign a deliveryservice to a required capability; deliveryServiceID: %d, requiredCapability: %s", dsID, capability), func(t *testing.T) { - cap := tc.DeliveryServicesRequiredCapability{ - DeliveryServiceID: helperGetDeliveryServiceID(t, td.XMLID), - RequiredCapability: td.RequiredCapability, - } - - _, _, err := TOSession.CreateDeliveryServicesRequiredCapability(cap) - if err != nil { - t.Fatalf(err.Error()) - } - }) - } - - for _, tc := range testCases { - t.Run(tc.description, func(t *testing.T) { - _, _, err := TOSession.CreateDeliveryServicesRequiredCapability(tc.capability) - if err == nil { - t.Fatalf("%s; expected err", tc.description) - } - }) - } -} - -func InvalidDeliveryServicesRequiredCapabilityAddition(t *testing.T) { - // Tests that a capability cannot be made required if the DS's services do not have it assigned - - // Get Delivery Capability for a DS - capabilities, _, err := TOSession.GetDeliveryServicesRequiredCapabilities(nil, util.StrPtr("ds1"), nil) - if err != nil { - t.Fatalf("cannot GET delivery service required capabilities: %v", err) - } - if len(capabilities) == 0 { - t.Fatal("delivery service ds1 needs at least one capability required") - } - - // First assign current capabilities to edge server so we can assign it to the DS - servers, _, err := TOSession.GetServerByHostName("atlanta-edge-01") - if err != nil { - t.Fatalf("cannot GET Server by hostname: %v", err) - } - if len(servers) < 1 { - t.Fatal("need at least one server to test invalid ds required capability assignment") - } - - dsID := capabilities[0].DeliveryServiceID - sID := servers[0].ID - serverCaps := []tc.ServerServerCapability{} - - for _, cap := range capabilities { - sCap := tc.ServerServerCapability{ - ServerID: &sID, - ServerCapability: cap.RequiredCapability, - } - _, _, err := TOSession.CreateServerServerCapability(sCap) - if err != nil { - t.Errorf("could not POST the server capability %v to server %v: %v", *cap.RequiredCapability, sID, err) - } - serverCaps = append(serverCaps, sCap) - } - - // Assign server to ds - _, err = TOSession.CreateDeliveryServiceServers(*dsID, []int{sID}, false) - if err != nil { - t.Fatalf("cannot CREATE server delivery service assignement: %v", err) - } - - // Create new bogus server capability - _, _, err = TOSession.CreateServerCapability(tc.ServerCapability{ - Name: "newcap", - }) - if err != nil { - t.Fatalf("cannot CREATE newcap server capability: %v", err) - } - - // Attempt to assign to DS should fail - _, _, err = TOSession.CreateDeliveryServicesRequiredCapability(tc.DeliveryServicesRequiredCapability{ - DeliveryServiceID: dsID, - RequiredCapability: util.StrPtr("newcap"), - }) - if err == nil { - t.Fatal("expected error requiring a capability that is not associated on the delivery service's servers") - } - - // Disassociate server from DS - setInactive(t, *dsID) - _, _, err = TOSession.DeleteDeliveryServiceServer(*dsID, sID) - if err != nil { - t.Fatalf("could not DELETE the server %v from ds %v: %v", sID, *dsID, err) - } - - // Remove server capabilities from server - for _, ssc := range serverCaps { - _, _, err := TOSession.DeleteServerServerCapability(*ssc.ServerID, *ssc.ServerCapability) - if err != nil { - t.Errorf("could not DELETE the server capability %v from server %v: %v", *ssc.ServerCapability, *ssc.Server, err) - } - } - - // Delete server capability - _, _, err = TOSession.DeleteServerCapability("newcap") - if err != nil { - t.Fatalf("cannot DELETE newcap server capability: %v", err) - } - -} - -func DeleteTestDeliveryServicesRequiredCapabilities(t *testing.T) { - // Get Required Capabilities to delete them - capabilities, _, err := TOSession.GetDeliveryServicesRequiredCapabilities(nil, nil, nil) - if err != nil { - t.Fatalf(err.Error()) - } - if len(capabilities) < 1 { - t.Fatal("no delivery services returned") - } - - type testCase struct { - description string - capability tc.DeliveryServicesRequiredCapability - err string - } - - testCases := []testCase{ - testCase{ - description: fmt.Sprintf("delete a deliveryservices required capability with an invalid delivery service id; deliveryServiceID: -1, requiredCapability: %s", *capabilities[0].RequiredCapability), - capability: tc.DeliveryServicesRequiredCapability{ - DeliveryServiceID: util.IntPtr(-1), - RequiredCapability: capabilities[0].RequiredCapability, - }, - err: "no deliveryservice.RequiredCapability with that key found", - }, - testCase{ - description: fmt.Sprintf("delete a deliveryservices required capability with an invalid required capability; deliveryServiceID: %d, requiredCapability: bogus", *capabilities[0].DeliveryServiceID), - capability: tc.DeliveryServicesRequiredCapability{ - DeliveryServiceID: capabilities[0].DeliveryServiceID, - RequiredCapability: util.StrPtr("bogus"), - }, - err: "no deliveryservice.RequiredCapability with that key found", - }, - } - - for _, c := range capabilities { - t := testCase{ - description: fmt.Sprintf("delete a deliveryservices required capability; deliveryServiceID: %d, requiredCapability: %s", *c.DeliveryServiceID, *c.RequiredCapability), - capability: c, - } - testCases = append(testCases, t) - } - - for _, c := range testCases { - t.Run(c.description, func(t *testing.T) { - _, _, err := TOSession.DeleteDeliveryServicesRequiredCapability(*c.capability.DeliveryServiceID, *c.capability.RequiredCapability) - if err != nil && !strings.Contains(err.Error(), c.err) { - t.Fatalf("%s; got err= %s; expected err= %s", c.description, err, c.err) - } - }) - } -} - -func helperGetDeliveryServiceID(t *testing.T, xmlID *string) *int { - t.Helper() - if xmlID == nil { - t.Fatal("xml id must not be nil") - } - ds, _, err := TOSession.GetDeliveryServiceByXMLIDNullable(*xmlID) - if err != nil { - t.Fatal(err) - } - if len(ds) < 1 { - t.Fatalf("cannot GET deliveyservice by xml id: %v. Response did not include record.", *xmlID) - } - return ds[0].ID -} diff --git a/traffic_ops/testing/api/v2/deliveryservices_test.go b/traffic_ops/testing/api/v2/deliveryservices_test.go deleted file mode 100644 index c089ee278b..0000000000 --- a/traffic_ops/testing/api/v2/deliveryservices_test.go +++ /dev/null @@ -1,582 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "encoding/json" - "errors" - "fmt" - "reflect" - "strconv" - "strings" - "testing" - "time" - - "github.com/apache/trafficcontrol/lib/go-tc" - "github.com/apache/trafficcontrol/lib/go-util" - toclient "github.com/apache/trafficcontrol/traffic_ops/v2-client" -) - -func TestDeliveryServices(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Tenants, Users, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, Servers, DeliveryServices}, func() { - GetAccessibleToTest(t) - if includeSystemTests { - GetTestDeliveryServicesURLSigKeys(t) - } - UpdateTestDeliveryServices(t) - UpdateNullableTestDeliveryServices(t) - UpdateDeliveryServiceWithInvalidRemapText(t) - UpdateDeliveryServiceWithInvalidSliceRangeRequest(t) - GetTestDeliveryServices(t) - GetTestDeliveryServicesCapacity(t) - DeliveryServiceMinorVersionsTest(t) - DeliveryServiceTenancyTest(t) - PostDeliveryServiceTest(t) - }) -} - -func PostDeliveryServiceTest(t *testing.T) { - ds := testData.DeliveryServices[0] - ds.XMLID = util.StrPtr("") - _, err := TOSession.CreateDeliveryServiceNullable(&ds) - if err == nil { - t.Fatal("Expected error with empty xmlid") - } - ds.XMLID = nil - _, err = TOSession.CreateDeliveryServiceNullable(&ds) - if err == nil { - t.Fatal("Expected error with nil xmlid") - } -} - -func CreateTestDeliveryServices(t *testing.T) { - pl := tc.Parameter{ - ConfigFile: "remap.config", - Name: "location", - Value: "/remap/config/location/parameter/", - } - _, _, err := TOSession.CreateParameter(pl) - if err != nil { - t.Errorf("cannot create parameter: %v", err) - } - for _, ds := range testData.DeliveryServices { - _, err = TOSession.CreateDeliveryServiceNullable(&ds) - if err != nil { - t.Errorf("could not CREATE delivery service '%s': %v", *ds.XMLID, err) - } - } -} - -func GetTestDeliveryServices(t *testing.T) { - actualDSes, _, err := TOSession.GetDeliveryServicesNullable() - if err != nil { - t.Errorf("cannot GET DeliveryServices: %v - %v", err, actualDSes) - } - actualDSMap := map[string]tc.DeliveryServiceNullable{} - for _, ds := range actualDSes { - actualDSMap[*ds.XMLID] = ds - } - cnt := 0 - for _, ds := range testData.DeliveryServices { - if _, ok := actualDSMap[*ds.XMLID]; !ok { - t.Errorf("GET DeliveryService missing: %v", ds.XMLID) - } - // exactly one ds should have exactly 3 query params. the rest should have none - if c := len(ds.ConsistentHashQueryParams); c > 0 { - if c != 3 { - t.Errorf("deliveryservice %s has %d query params; expected %d or %d", *ds.XMLID, c, 3, 0) - } - cnt++ - } - } - if cnt > 2 { - t.Errorf("exactly 2 deliveryservices should have more than one query param; found %d", cnt) - } -} - -func GetTestDeliveryServicesCapacity(t *testing.T) { - actualDSes, _, err := TOSession.GetDeliveryServicesNullable() - if err != nil { - t.Errorf("cannot GET DeliveryServices: %v - %v", err, actualDSes) - } - actualDSMap := map[string]tc.DeliveryServiceNullable{} - for _, ds := range actualDSes { - actualDSMap[*ds.XMLID] = ds - capDS, _, err := TOSession.GetDeliveryServiceCapacity(strconv.Itoa(*ds.ID)) - if err != nil { - t.Errorf("cannot GET DeliveryServices: %v's Capacity: %v - %v", ds, err, capDS) - } - } - -} - -func UpdateTestDeliveryServices(t *testing.T) { - firstDS := testData.DeliveryServices[0] - - dses, _, err := TOSession.GetDeliveryServicesNullable() - if err != nil { - t.Errorf("cannot GET Delivery Services: %v", err) - } - - remoteDS := tc.DeliveryServiceNullable{} - found := false - for _, ds := range dses { - if *ds.XMLID == *firstDS.XMLID { - found = true - remoteDS = ds - break - } - } - if !found { - t.Errorf("GET Delivery Services missing: %v", firstDS.XMLID) - } - - updatedLongDesc := "something different" - updatedMaxDNSAnswers := 164598 - updatedMaxOriginConnections := 100 - remoteDS.LongDesc = &updatedLongDesc - remoteDS.MaxDNSAnswers = &updatedMaxDNSAnswers - remoteDS.MaxOriginConnections = &updatedMaxOriginConnections - remoteDS.MatchList = nil // verify that this field is optional in a PUT request, doesn't cause nil dereference panic - - if updateResp, err := TOSession.UpdateDeliveryServiceNullable(strconv.Itoa(*remoteDS.ID), &remoteDS); err != nil { - t.Errorf("cannot UPDATE DeliveryService by ID: %v - %v", err, updateResp) - } - - // Retrieve the server to check rack and interfaceName values were updated - resp, _, err := TOSession.GetDeliveryServiceNullable(strconv.Itoa(*remoteDS.ID)) - if err != nil { - t.Errorf("cannot GET Delivery Service by ID: %v - %v", remoteDS.XMLID, err) - } - if resp == nil { - t.Errorf("cannot GET Delivery Service by ID: %v - nil", remoteDS.XMLID) - } - - if *resp.LongDesc != updatedLongDesc || *resp.MaxDNSAnswers != updatedMaxDNSAnswers || *resp.MaxOriginConnections != updatedMaxOriginConnections { - t.Errorf("results do not match actual: %s, expected: %s", *resp.LongDesc, updatedLongDesc) - t.Errorf("results do not match actual: %v, expected: %v", resp.MaxDNSAnswers, updatedMaxDNSAnswers) - t.Errorf("results do not match actual: %v, expected: %v", resp.MaxOriginConnections, updatedMaxOriginConnections) - } -} - -func UpdateNullableTestDeliveryServices(t *testing.T) { - firstDS := testData.DeliveryServices[0] - - dses, _, err := TOSession.GetDeliveryServicesNullable() - if err != nil { - t.Fatalf("cannot GET Delivery Services: %v", err) - } - - remoteDS := tc.DeliveryServiceNullable{} - found := false - for _, ds := range dses { - if ds.XMLID == nil || ds.ID == nil { - continue - } - if *ds.XMLID == *firstDS.XMLID { - found = true - remoteDS = ds - break - } - } - if !found { - t.Fatalf("GET Delivery Services missing: %v", firstDS.XMLID) - } - - updatedLongDesc := "something else different" - updatedMaxDNSAnswers := 164599 - remoteDS.LongDesc = &updatedLongDesc - remoteDS.MaxDNSAnswers = &updatedMaxDNSAnswers - - if updateResp, err := TOSession.UpdateDeliveryServiceNullable(strconv.Itoa(*remoteDS.ID), &remoteDS); err != nil { - t.Fatalf("cannot UPDATE DeliveryService by ID: %v - %v", err, updateResp) - } - - // Retrieve the server to check rack and interfaceName values were updated - resp, _, err := TOSession.GetDeliveryServiceNullable(strconv.Itoa(*remoteDS.ID)) - if err != nil { - t.Fatalf("cannot GET Delivery Service by ID: %v - %v", remoteDS.XMLID, err) - } - if resp == nil { - t.Fatalf("cannot GET Delivery Service by ID: %v - nil", remoteDS.XMLID) - } - - if resp.LongDesc == nil || resp.MaxDNSAnswers == nil { - t.Errorf("results do not match actual: %v, expected: %s", resp.LongDesc, updatedLongDesc) - t.Fatalf("results do not match actual: %v, expected: %d", resp.MaxDNSAnswers, updatedMaxDNSAnswers) - } - - if *resp.LongDesc != updatedLongDesc || *resp.MaxDNSAnswers != updatedMaxDNSAnswers { - t.Errorf("results do not match actual: %s, expected: %s", *resp.LongDesc, updatedLongDesc) - t.Fatalf("results do not match actual: %d, expected: %d", *resp.MaxDNSAnswers, updatedMaxDNSAnswers) - } -} - -// UpdateDeliveryServiceWithInvalidRemapText ensures that a delivery service can't be updated with a remap text value with a line break in it. -func UpdateDeliveryServiceWithInvalidRemapText(t *testing.T) { - firstDS := testData.DeliveryServices[0] - - dses, _, err := TOSession.GetDeliveryServicesNullable() - if err != nil { - t.Fatalf("cannot GET Delivery Services: %v", err) - } - - remoteDS := tc.DeliveryServiceNullable{} - found := false - for _, ds := range dses { - if ds.XMLID == nil || ds.ID == nil { - continue - } - if *ds.XMLID == *firstDS.XMLID { - found = true - remoteDS = ds - break - } - } - if !found { - t.Fatalf("GET Delivery Services missing: %v", firstDS.XMLID) - } - - updatedRemapText := "@plugin=tslua.so @pparam=/opt/trafficserver/etc/trafficserver/remapPlugin1.lua\nline2" - remoteDS.RemapText = &updatedRemapText - - if _, err := TOSession.UpdateDeliveryServiceNullable(strconv.Itoa(*remoteDS.ID), &remoteDS); err == nil { - t.Errorf("Delivery service updated with invalid remap text: %v", updatedRemapText) - } -} - -// UpdateDeliveryServiceWithInvalidSliceRangeRequest ensures that a delivery service can't be updated with a invalid slice range request handler setting. -func UpdateDeliveryServiceWithInvalidSliceRangeRequest(t *testing.T) { - // GET a HTTP / DNS type DS - var dsXML *string - for _, ds := range testData.DeliveryServices { - if ds.Type.IsDNS() || ds.Type.IsHTTP() { - dsXML = ds.XMLID - break - } - } - if dsXML == nil { - t.Fatal("no HTTP or DNS Delivery Services to test with") - } - - dses, _, err := TOSession.GetDeliveryServicesNullable() - if err != nil { - t.Fatalf("cannot GET Delivery Services: %v", err) - } - - remoteDS := tc.DeliveryServiceNullable{} - found := false - for _, ds := range dses { - if ds.XMLID == nil || ds.ID == nil { - continue - } - if *ds.XMLID == *dsXML { - found = true - remoteDS = ds - break - } - } - if !found { - t.Fatalf("GET Delivery Services missing: %v", *dsXML) - } - testCases := []struct { - description string - rangeRequestSetting *int - slicePluginSize *int - }{ - { - description: "Missing slice plugin size", - rangeRequestSetting: util.IntPtr(tc.RangeRequestHandlingSlice), - slicePluginSize: nil, - }, - { - description: "Slice plugin size set with incorrect range request setting", - rangeRequestSetting: util.IntPtr(tc.RangeRequestHandlingBackgroundFetch), - slicePluginSize: util.IntPtr(262144), - }, - { - description: "Slice plugin size set to small", - rangeRequestSetting: util.IntPtr(tc.RangeRequestHandlingSlice), - slicePluginSize: util.IntPtr(0), - }, - { - description: "Slice plugin size set to large", - rangeRequestSetting: util.IntPtr(tc.RangeRequestHandlingSlice), - slicePluginSize: util.IntPtr(40000000), - }, - } - - for _, tc := range testCases { - t.Run(tc.description, func(t *testing.T) { - remoteDS.RangeSliceBlockSize = tc.slicePluginSize - remoteDS.RangeRequestHandling = tc.rangeRequestSetting - if _, err := TOSession.UpdateDeliveryServiceNullable(strconv.Itoa(*remoteDS.ID), &remoteDS); err == nil { - t.Error("Delivery service updated with invalid slice plugin configuration") - } - }) - } - -} - -func GetAccessibleToTest(t *testing.T) { - //Every delivery service is associated with the root tenant - err := getByTenants(1, len(testData.DeliveryServices)) - if err != nil { - t.Fatal(err.Error()) - } - - tenant := &tc.Tenant{ - Active: true, - Name: "the strongest", - ParentID: 1, - ParentName: "root", - } - - resp, err := TOSession.CreateTenant(tenant) - if err != nil { - t.Fatal(err.Error()) - } - if resp == nil { - t.Fatal("unexpected null response when creating tenant") - } - tenant = &resp.Response - - //No delivery services are associated with this new tenant - err = getByTenants(tenant.ID, 0) - if err != nil { - t.Fatal(err.Error()) - } - - //First and only child tenant, no access to root - childTenant, _, err := TOSession.TenantByName("tenant1") - if err != nil { - t.Fatal("unable to get tenant " + err.Error()) - } - err = getByTenants(childTenant.ID, len(testData.DeliveryServices)-1) - if err != nil { - t.Fatal(err.Error()) - } - - _, err = TOSession.DeleteTenant(strconv.Itoa(tenant.ID)) - if err != nil { - t.Fatalf("unable to clean up tenant %v", err.Error()) - } -} - -func getByTenants(tenantID int, expectedCount int) error { - deliveryServices, _, err := TOSession.GetAccessibleDeliveryServicesByTenant(tenantID) - if err != nil { - return err - } - if len(deliveryServices) != expectedCount { - return errors.New(fmt.Sprintf("expected %v delivery service, got %v", expectedCount, len(deliveryServices))) - } - return nil -} - -func DeleteTestDeliveryServices(t *testing.T) { - dses, _, err := TOSession.GetDeliveryServicesNullable() - if err != nil { - t.Errorf("cannot GET deliveryservices: %v", err) - } - for _, testDS := range testData.DeliveryServices { - ds := tc.DeliveryServiceNullable{} - if testDS.XMLID == nil { - t.Error("Testing Delivery Service found with null or undefined XMLID") - continue - } - found := false - for _, realDS := range dses { - if realDS.XMLID == nil || realDS.ID == nil { - t.Error("Traffic Ops returned a representation for a Delivery Service with null or undefined XMLID and/or ID") - continue - } - if *realDS.XMLID == *testDS.XMLID { - ds = realDS - found = true - break - } - } - if !found { - t.Errorf("DeliveryService not found in Traffic Ops: %s", *testDS.XMLID) - continue - } - - delResp, err := TOSession.DeleteDeliveryService(strconv.Itoa(*ds.ID)) - if err != nil { - t.Errorf("cannot DELETE DeliveryService by ID: %v - %v", err, delResp) - } - - // Retrieve the Server to see if it got deleted - foundDS, _, err := TOSession.GetDeliveryServiceNullable(strconv.Itoa(*ds.ID)) - if err == nil && foundDS != nil { - t.Errorf("expected Delivery Service: %s to be deleted", *ds.XMLID) - } - } - - // clean up parameter created in CreateTestDeliveryServices() - params, _, err := TOSession.GetParameterByNameAndConfigFile("location", "remap.config") - for _, param := range params { - deleted, _, err := TOSession.DeleteParameterByID(param.ID) - if err != nil { - t.Errorf("cannot DELETE parameter by ID (%d): %v - %v", param.ID, err, deleted) - } - } -} - -func DeliveryServiceMinorVersionsTest(t *testing.T) { - testDS := testData.DeliveryServices[4] - if *testDS.XMLID != "ds-test-minor-versions" { - t.Errorf("expected XMLID: ds-test-minor-versions, actual: %s", *testDS.XMLID) - } - - dses, _, err := TOSession.GetDeliveryServicesNullable() - if err != nil { - t.Errorf("cannot GET DeliveryServices: %v - %v", err, dses) - } - ds := tc.DeliveryServiceNullable{} - for _, d := range dses { - if *d.XMLID == *testDS.XMLID { - ds = d - break - } - } - // GET latest, verify expected values for 1.3 and 1.4 fields - if ds.DeepCachingType == nil { - t.Errorf("expected DeepCachingType: %s, actual: nil", testDS.DeepCachingType.String()) - } else if *ds.DeepCachingType != *testDS.DeepCachingType { - t.Errorf("expected DeepCachingType: %s, actual: %s", testDS.DeepCachingType.String(), ds.DeepCachingType.String()) - } - if ds.FQPacingRate == nil { - t.Errorf("expected FQPacingRate: %d, actual: nil", testDS.FQPacingRate) - } else if *ds.FQPacingRate != *testDS.FQPacingRate { - t.Errorf("expected FQPacingRate: %d, actual: %d", testDS.FQPacingRate, *ds.FQPacingRate) - } - if ds.SigningAlgorithm == nil { - t.Errorf("expected SigningAlgorithm: %s, actual: nil", *testDS.SigningAlgorithm) - } else if *ds.SigningAlgorithm != *testDS.SigningAlgorithm { - t.Errorf("expected SigningAlgorithm: %s, actual: %s", *testDS.SigningAlgorithm, *ds.SigningAlgorithm) - } - if ds.Tenant == nil { - t.Errorf("expected Tenant: %s, actual: nil", *testDS.Tenant) - } else if *ds.Tenant != *testDS.Tenant { - t.Errorf("expected Tenant: %s, actual: %s", *testDS.Tenant, *ds.Tenant) - } - if ds.TRRequestHeaders == nil { - t.Errorf("expected TRRequestHeaders: %s, actual: nil", *testDS.TRRequestHeaders) - } else if *ds.TRRequestHeaders != *testDS.TRRequestHeaders { - t.Errorf("expected TRRequestHeaders: %s, actual: %s", *testDS.TRRequestHeaders, *ds.TRRequestHeaders) - } - if ds.TRResponseHeaders == nil { - t.Errorf("expected TRResponseHeaders: %s, actual: nil", *testDS.TRResponseHeaders) - } else if *ds.TRResponseHeaders != *testDS.TRResponseHeaders { - t.Errorf("expected TRResponseHeaders: %s, actual: %s", *testDS.TRResponseHeaders, *ds.TRResponseHeaders) - } - if ds.ConsistentHashRegex == nil { - t.Errorf("expected ConsistentHashRegex: %s, actual: nil", *testDS.ConsistentHashRegex) - } else if *ds.ConsistentHashRegex != *testDS.ConsistentHashRegex { - t.Errorf("expected ConsistentHashRegex: %s, actual: %s", *testDS.ConsistentHashRegex, *ds.ConsistentHashRegex) - } - if ds.ConsistentHashQueryParams == nil { - t.Errorf("expected ConsistentHashQueryParams: %v, actual: nil", testDS.ConsistentHashQueryParams) - } else if !reflect.DeepEqual(ds.ConsistentHashQueryParams, testDS.ConsistentHashQueryParams) { - t.Errorf("expected ConsistentHashQueryParams: %v, actual: %v", testDS.ConsistentHashQueryParams, ds.ConsistentHashQueryParams) - } - if ds.MaxOriginConnections == nil { - t.Errorf("expected MaxOriginConnections: %d, actual: nil", testDS.MaxOriginConnections) - } else if *ds.MaxOriginConnections != *testDS.MaxOriginConnections { - t.Errorf("expected MaxOriginConnections: %d, actual: %d", testDS.MaxOriginConnections, *ds.MaxOriginConnections) - } - - ds.ID = nil - _, err = json.Marshal(ds) - if err != nil { - t.Errorf("cannot POST deliveryservice, failed to marshal JSON: %s", err.Error()) - } - -} - -func DeliveryServiceTenancyTest(t *testing.T) { - dses, _, err := TOSession.GetDeliveryServicesNullable() - if err != nil { - t.Errorf("cannot GET deliveryservices: %v", err) - } - tenant3DS := tc.DeliveryServiceNullable{} - foundTenant3DS := false - for _, d := range dses { - if *d.XMLID == "ds3" { - tenant3DS = d - foundTenant3DS = true - } - } - if !foundTenant3DS || *tenant3DS.Tenant != "tenant3" { - t.Error("expected to find deliveryservice 'ds3' with tenant 'tenant3'") - } - - toReqTimeout := time.Second * time.Duration(Config.Default.Session.TimeoutInSecs) - tenant4TOClient, _, err := toclient.LoginWithAgent(TOSession.URL, "tenant4user", "pa$$word", true, "to-api-v2-client-tests/tenant4user", true, toReqTimeout) - if err != nil { - t.Fatalf("failed to log in with tenant4user: %v", err.Error()) - } - - dsesReadableByTenant4, _, err := tenant4TOClient.GetDeliveryServicesNullable() - if err != nil { - t.Error("tenant4user cannot GET deliveryservices") - } - - // assert that tenant4user cannot read deliveryservices outside of its tenant - for _, ds := range dsesReadableByTenant4 { - if *ds.XMLID == "ds3" { - t.Error("expected tenant4 to be unable to read delivery services from tenant 3") - } - } - - // assert that tenant4user cannot update tenant3user's deliveryservice - if _, err = tenant4TOClient.UpdateDeliveryServiceNullable(strconv.Itoa(*tenant3DS.ID), &tenant3DS); err == nil { - t.Errorf("expected tenant4user to be unable to update tenant3's deliveryservice (%s)", *tenant3DS.XMLID) - } - - // assert that tenant4user cannot delete tenant3user's deliveryservice - if _, err = tenant4TOClient.DeleteDeliveryService(strconv.Itoa(*tenant3DS.ID)); err == nil { - t.Errorf("expected tenant4user to be unable to delete tenant3's deliveryservice (%s)", *tenant3DS.XMLID) - } - - // assert that tenant4user cannot create a deliveryservice outside of its tenant - tenant3DS.XMLID = util.StrPtr("deliveryservicetenancytest") - tenant3DS.DisplayName = util.StrPtr("deliveryservicetenancytest") - if _, err = tenant4TOClient.CreateDeliveryServiceNullable(&tenant3DS); err == nil { - t.Error("expected tenant4user to be unable to create a deliveryservice outside of its tenant") - } - -} - -func GetTestDeliveryServicesURLSigKeys(t *testing.T) { - if len(testData.DeliveryServices) == 0 { - t.Fatal("couldn't get the xml ID of test DS") - } - firstDS := testData.DeliveryServices[0] - if firstDS.XMLID == nil { - t.Fatal("couldn't get the xml ID of test DS") - } - - _, _, err := TOSession.GetDeliveryServiceURLSigKeys(*firstDS.XMLID) - if err != nil { - // The v2 tests don't support Riak, so the only thing we can test is that the endpoint exists. - if errStr := strings.ToLower(err.Error()); strings.Contains(errStr, "not found") || strings.Contains(errStr, "404") { - t.Error("Expected URL Sig path to exist, actual: " + err.Error()) - } - } -} diff --git a/traffic_ops/testing/api/v2/deliveryserviceservers_test.go b/traffic_ops/testing/api/v2/deliveryserviceservers_test.go deleted file mode 100644 index 7c8eb369e2..0000000000 --- a/traffic_ops/testing/api/v2/deliveryserviceservers_test.go +++ /dev/null @@ -1,253 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "errors" - "strings" - "testing" - - "github.com/apache/trafficcontrol/lib/go-tc" - "github.com/apache/trafficcontrol/lib/go-util" -) - -func TestDeliveryServiceServers(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Tenants, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, Servers, DeliveryServices}, func() { - DeleteTestDeliveryServiceServers(t) - }) -} - -func TestDeliveryServiceServersWithRequiredCapabilities(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Tenants, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, Servers, ServerCapabilities, DeliveryServices, DeliveryServicesRequiredCapabilities, ServerServerCapabilities}, func() { - CreateTestDeliveryServiceServersWithRequiredCapabilities(t) - CreateTestMSODSServerWithReqCap(t) - }) -} - -func CreateTestDeliveryServiceServersWithRequiredCapabilities(t *testing.T) { - sscs := testData.ServerServerCapabilities - - testCases := []struct { - ds string - serverName string - ssc tc.ServerServerCapability - description string - err error - capability tc.DeliveryServicesRequiredCapability - }{ - { - serverName: "atlanta-edge-01", - description: "missing requirements for server -> DS assignment", - err: errors.New("cannot be assigned to this delivery service"), - ssc: sscs[0], - capability: tc.DeliveryServicesRequiredCapability{ - DeliveryServiceID: helperGetDeliveryServiceID(t, util.StrPtr("ds-test-minor-versions")), - RequiredCapability: sscs[1].ServerCapability, - }, - }, - { - serverName: "atlanta-mid-01", - description: "successful server -> DS assignment", - err: nil, - ssc: sscs[1], - capability: tc.DeliveryServicesRequiredCapability{ - DeliveryServiceID: helperGetDeliveryServiceID(t, util.StrPtr("ds3")), - RequiredCapability: sscs[1].ServerCapability, - }, - }, - } - - for _, ctc := range testCases { - t.Run(ctc.description, func(t *testing.T) { - servers, _, err := TOSession.GetServerByHostName(ctc.serverName) - if err != nil { - t.Fatalf("cannot GET Server by hostname: %v", err) - } - server := servers[0] - - _, _, err = TOSession.CreateDeliveryServicesRequiredCapability(ctc.capability) - if err != nil { - t.Fatalf("*POST delivery service required capability: %v", err) - } - - ctc.ssc.ServerID = &server.ID - _, _, err = TOSession.CreateServerServerCapability(ctc.ssc) - if err != nil { - t.Fatalf("could not POST the server capability %v to server %v: %v", *ctc.ssc.ServerCapability, *ctc.ssc.Server, err) - } - - _, got := TOSession.CreateDeliveryServiceServers(*ctc.capability.DeliveryServiceID, []int{server.ID}, true) - if (ctc.err == nil && got != nil) || (ctc.err != nil && !strings.Contains(got.Error(), ctc.err.Error())) { - t.Fatalf("expected ctc.err to contain %v, got %v", ctc.err, got) - } - - _, _, err = TOSession.DeleteDeliveryServicesRequiredCapability(*ctc.capability.DeliveryServiceID, *ctc.capability.RequiredCapability) - if err != nil { - t.Fatalf("*DELETE delivery service required capability: %v", err) - } - }) - } -} - -func CreateTestMSODSServerWithReqCap(t *testing.T) { - dsReqCap, _, err := TOSession.GetDeliveryServicesRequiredCapabilities(nil, util.StrPtr("msods1"), nil) - if err != nil { - t.Fatalf("GET delivery service required capabilites: %v", err) - } - - if len(dsReqCap) == 0 { - t.Fatal("no delivery service required capabilites found for ds msods1") - } - - // Associate origin server to msods1 even though it does not have req cap - - servers, _, err := TOSession.GetServerByHostName("denver-mso-org-01") - if err != nil { - t.Fatalf("GET server denver-mso-org-01: %v", err) - } - if len(servers) != 1 { - t.Fatal("expected 1 server with hostname denver-mso-org-01") - } - - s := servers[0] - - // Make sure server has no caps to ensure test correctness - sccs, _, err := TOSession.GetServerServerCapabilities(&s.ID, nil, nil) - if err != nil { - t.Fatalf("GET server server capabilities for denver-mso-org-01: %v", err) - } - if len(sccs) != 0 { - t.Fatal("expected 0 server server capabilities for server denver-mso-org-01") - } - - // Is origin included in eligible servers even though it doesnt have required capability - eServers, _, err := TOSession.GetDeliveryServicesEligible(*dsReqCap[0].DeliveryServiceID) - if err != nil { - t.Fatalf("GET delivery service msods1 eligible servers: %v", err) - } - found := false - for _, es := range eServers { - if es.HostName != nil && *es.HostName == "denver-mso-org-01" { - found = true - break - } - } - if !found { - t.Fatal("expected to find origin server denver-mso-org-01 to be in eligible server return even though it is missing a required capability") - } - - if _, err = TOSession.CreateDeliveryServiceServers(*dsReqCap[0].DeliveryServiceID, []int{s.ID}, true); err != nil { - t.Fatalf("POST delivery service origin servers without capabilities: %v", err) - } - - // Create new bogus server capability - if _, _, err = TOSession.CreateServerCapability(tc.ServerCapability{Name: "newfun"}); err != nil { - t.Fatalf("cannot CREATE newfun server capability: %v", err) - } - - // Attempt to assign to DS should not fail - if _, _, err = TOSession.CreateDeliveryServicesRequiredCapability(tc.DeliveryServicesRequiredCapability{ - DeliveryServiceID: dsReqCap[0].DeliveryServiceID, - RequiredCapability: util.StrPtr("newfun"), - }); err != nil { - t.Fatalf("POST required capability newfun to ds msods1: %v", err) - } - - // Remove required capablity - if _, _, err = TOSession.DeleteDeliveryServicesRequiredCapability(*dsReqCap[0].DeliveryServiceID, "newfun"); err != nil { - t.Fatalf("DELETE delivery service required capability: %v", err) - } - - // Delete server capability - if _, _, err = TOSession.DeleteServerCapability("newfun"); err != nil { - t.Fatalf("DELETE newfun server capability: %v", err) - } -} - -func DeleteTestDeliveryServiceServers(t *testing.T) { - ds, server := getServerAndDSofSameCDN(t) - - _, err := TOSession.CreateDeliveryServiceServers(*ds.ID, []int{server.ID}, true) - if err != nil { - t.Errorf("POST delivery service servers: %v", err) - } - - dsServers, _, err := TOSession.GetDeliveryServiceServers() - if err != nil { - t.Errorf("GET delivery service servers: %v", err) - } - - found := false - for _, dss := range dsServers.Response { - if *dss.DeliveryService == *ds.ID && *dss.Server == server.ID { - found = true - break - } - } - if !found { - t.Error("POST delivery service servers returned success, but ds-server not in GET") - } - - setInactive(t, *ds.ID) - if _, _, err := TOSession.DeleteDeliveryServiceServer(*ds.ID, server.ID); err != nil { - t.Errorf("DELETE delivery service server: %v", err) - } - - dsServers, _, err = TOSession.GetDeliveryServiceServers() - if err != nil { - t.Errorf("GET delivery service servers: %v", err) - } - - found = false - for _, dss := range dsServers.Response { - if *dss.DeliveryService == *ds.ID && *dss.Server == server.ID { - found = true - break - } - } - if found { - t.Error("DELETE delivery service servers returned success, but still in GET") - } -} - -func getServerAndDSofSameCDN(t *testing.T) (tc.DeliveryServiceNullable, tc.Server) { - dses, _, err := TOSession.GetDeliveryServicesNullable() - if err != nil { - t.Fatalf("cannot GET DeliveryServices: %v", err) - } - if len(dses) < 1 { - t.Fatal("GET DeliveryServices returned no dses, must have at least 1 to test ds-servers") - } - - servers, _, err := TOSession.GetServers() - if err != nil { - t.Fatalf("cannot GET Servers: %v", err) - } - if len(servers) < 1 { - t.Fatal("GET Servers returned no dses, must have at least 1 to test ds-servers") - } - - for _, ds := range dses { - for _, s := range servers { - if ds.CDNName != nil && *ds.CDNName == s.CDNName { - return ds, s - } - } - } - t.Fatal("expected at least one delivery service and server in the same CDN") - - return tc.DeliveryServiceNullable{}, tc.Server{} -} diff --git a/traffic_ops/testing/api/v2/deliveryservicesideligible_test.go b/traffic_ops/testing/api/v2/deliveryservicesideligible_test.go deleted file mode 100644 index 7a04d39951..0000000000 --- a/traffic_ops/testing/api/v2/deliveryservicesideligible_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package v2 - -/* - - Licensed 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 TestDeliveryServicesEligible(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Tenants, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, Servers, DeliveryServices}, func() { - GetTestDeliveryServicesEligible(t) - }) -} - -func GetTestDeliveryServicesEligible(t *testing.T) { - dses, _, err := TOSession.GetDeliveryServicesNullable() - if err != nil { - t.Errorf("cannot GET DeliveryServices: %v", err) - } - if len(dses) == 0 { - t.Error("GET DeliveryServices returned no delivery services, need at least 1 to test") - } - dsID := dses[0].ID - servers, _, err := TOSession.GetDeliveryServicesEligible(*dsID) - if err != nil { - t.Errorf("getting delivery services eligible: %v", err) - } - if len(servers) == 0 { - t.Error("getting delivery services eligible returned no servers") - } -} diff --git a/traffic_ops/testing/api/v2/deliveryservicesregexes_test.go b/traffic_ops/testing/api/v2/deliveryservicesregexes_test.go deleted file mode 100644 index c123bbff60..0000000000 --- a/traffic_ops/testing/api/v2/deliveryservicesregexes_test.go +++ /dev/null @@ -1,174 +0,0 @@ -/* - - Licensed 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. -*/ - -package v2 - -import ( - "fmt" - "strconv" - "testing" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -func TestDeliveryServicesRegexes(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Tenants, Users, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, Servers, DeliveryServices, DeliveryServicesRegexes}, func() { - QueryDSRegexTest(t) - CreateTestDSRegexWithMissingPattern(t) - }) -} - -func CreateTestDeliveryServicesRegexes(t *testing.T) { - db, err := OpenConnection() - if err != nil { - t.Fatal("cannot open db") - } - defer func() { - err := db.Close() - if err != nil { - t.Errorf("unable to close connection to db, error: %v", err) - } - }() - - dbRegexInsertTemplate := "INSERT INTO regex (pattern, type) VALUES ('%v', '%v');" - dbRegexQueryTemplate := "SELECT id FROM regex order by id desc limit 1;" - dbDSRegexInsertTemplate := "INSERT INTO deliveryservice_regex (deliveryservice, regex, set_number) VALUES ('%v', '%v', '%v');" - - for i, regex := range testData.DeliveryServicesRegexes { - loadDSRegexIDs(t, ®ex) - - err = execSQL(db, fmt.Sprintf(dbRegexInsertTemplate, regex.Pattern, regex.Type)) - if err != nil { - t.Fatalf("unable to create regex: %v", err) - } - - row := db.QueryRow(dbRegexQueryTemplate) - err = row.Scan(®ex.ID) - if err != nil { - t.Fatalf("unable to query regex: %v", err) - } - - err = execSQL(db, fmt.Sprintf(dbDSRegexInsertTemplate, regex.DSID, regex.ID, regex.SetNumber)) - if err != nil { - t.Fatalf("unable to create ds regex %v", err) - } - - testData.DeliveryServicesRegexes[i] = regex - } -} - -func DeleteTestDeliveryServicesRegexes(t *testing.T) { - db, err := OpenConnection() - if err != nil { - t.Fatal("cannot open db") - } - defer func() { - err := db.Close() - if err != nil { - t.Errorf("unable to close connection to db, error: %v", err) - } - }() - - for _, regex := range testData.DeliveryServicesRegexes { - err = execSQL(db, fmt.Sprintf("DELETE FROM deliveryservice_regex WHERE deliveryservice = '%v' and regex ='%v';", regex.DSID, regex.ID)) - if err != nil { - t.Fatalf("unable to delete deliveryservice_regex by regex %v and ds %v: %v", regex.ID, regex.DSID, err) - } - - err := execSQL(db, fmt.Sprintf("DELETE FROM regex WHERE Id = '%v';", regex.ID)) - if err != nil { - t.Fatalf("unable to delete regex %v: %v", regex.ID, err) - } - } -} - -func CreateTestDSRegexWithMissingPattern(t *testing.T) { - var regex = testData.DeliveryServicesRegexes[3] - ds, _, err := TOSession.GetDeliveryServiceByXMLIDNullable(regex.DSName) - if err != nil { - t.Fatalf("unable to get ds %v: %v", regex.DSName, err) - } - if len(ds) == 0 { - t.Fatalf("unable to get ds %v", regex.DSName) - } - - var dsID int - if ds[0].ID == nil { - t.Fatal("ds has a nil id") - } else { - dsID = *ds[0].ID - } - - regexPost := tc.DeliveryServiceRegexPost{Type: regex.Type, SetNumber: regex.SetNumber, Pattern: regex.Pattern} - - _, _, err = TOSession.PostDeliveryServiceRegexesByDSID(dsID, regexPost) - if err == nil { - t.Fatalf("Expected: 400 Bad Request but got: %v", err) - } -} - -func loadDSRegexIDs(t *testing.T, test *tc.DeliveryServiceRegexesTest) { - dsTypes, _, err := TOSession.GetTypeByName(test.TypeName) - if err != nil { - t.Fatalf("unable to get type by name %v: %v", test.TypeName, err) - } - if len(dsTypes) < 1 { - t.Fatalf("could not find any types by name %v", test.TypeName) - } - test.Type = dsTypes[0].ID - - dses, _, err := TOSession.GetDeliveryServiceByXMLIDNullable(test.DSName) - if err != nil { - t.Fatalf("unable to ds by xmlid %v: %v", test.DSName, err) - } - if len(dses) != 1 { - t.Fatalf("unable to find ds by xmlid %v", test.DSName) - } - test.DSID = *dses[0].ID -} - -func QueryDSRegexTest(t *testing.T) { - ds, _, err := TOSession.GetDeliveryServiceByXMLIDNullable("ds1") - if err != nil { - t.Fatalf("unable to get ds ds1: %v", err) - } - if len(ds) == 0 { - t.Fatal("unable to get ds ds1") - } - var dsID int - if ds[0].ID == nil { - t.Fatal("ds has a nil id") - } else { - dsID = *ds[0].ID - } - - dsRegexes, _, err := TOSession.GetDeliveryServiceRegexesByDSID(dsID, nil) - if err != nil { - t.Fatal("unable to get ds_regex by id " + strconv.Itoa(dsID)) - } - if len(dsRegexes) != 4 { - t.Fatal("expected to get 4 ds_regex, got " + strconv.Itoa(len(dsRegexes))) - } - - params := make(map[string]string) - params["id"] = strconv.Itoa(dsRegexes[0].ID) - dsRegexes, _, err = TOSession.GetDeliveryServiceRegexesByDSID(dsID, params) - if err != nil { - t.Fatalf("unable to get ds_regex by id %v with query param %v", dsID, params["id"]) - } - if len(dsRegexes) != 1 { - t.Fatal("expected to get 1 ds_regex, got " + strconv.Itoa(len(dsRegexes))) - } -} diff --git a/traffic_ops/testing/api/v2/divisions_test.go b/traffic_ops/testing/api/v2/divisions_test.go deleted file mode 100644 index 4e8b1e7365..0000000000 --- a/traffic_ops/testing/api/v2/divisions_test.go +++ /dev/null @@ -1,143 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "strings" - "testing" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -func TestDivisions(t *testing.T) { - WithObjs(t, []TCObj{Parameters, Divisions, Regions}, func() { - TryToDeleteDivision(t) - UpdateTestDivisions(t) - GetTestDivisions(t) - }) -} - -func TryToDeleteDivision(t *testing.T) { - division := testData.Divisions[0] - - resp, _, err := TOSession.GetDivisionByName(division.Name) - if err != nil { - t.Errorf("cannot GET Division by name: %v - %v", division.Name, err) - } - division = resp[0] - _, _, err = TOSession.DeleteDivisionByID(division.ID) - - if err == nil { - t.Error("should not be able to delete a division prematurely") - return - } - - if strings.Contains(err.Error(), "Resource not found.") { - t.Errorf("division with name %v does not exist", division.Name) - return - } - - if strings.Contains(err.Error(), "cannot delete division because it is being used by a region") { - return - } - - t.Errorf("unexpected error occured: %v", err) -} - -func CreateTestDivisions(t *testing.T) { - for _, division := range testData.Divisions { - resp, _, err := TOSession.CreateDivision(division) - t.Log("Response: ", resp) - if err != nil { - t.Errorf("could not CREATE division: %v", err) - } - } -} - -func UpdateTestDivisions(t *testing.T) { - - firstDivision := testData.Divisions[0] - // Retrieve the Division by division so we can get the id for the Update - resp, _, err := TOSession.GetDivisionByName(firstDivision.Name) - if err != nil { - t.Errorf("cannot GET Division by division: %v - %v", firstDivision.Name, err) - } - remoteDivision := resp[0] - expectedDivision := "division-test" - remoteDivision.Name = expectedDivision - var alert tc.Alerts - alert, _, err = TOSession.UpdateDivisionByID(remoteDivision.ID, remoteDivision) - if err != nil { - t.Errorf("cannot UPDATE Division by id: %v - %v", err, alert) - } - - // Retrieve the Division to check division got updated - resp, _, err = TOSession.GetDivisionByID(remoteDivision.ID) - if err != nil { - t.Errorf("cannot GET Division by division: %v - %v", firstDivision.Name, err) - } - respDivision := resp[0] - if respDivision.Name != expectedDivision { - t.Errorf("results do not match actual: %s, expected: %s", respDivision.Name, expectedDivision) - } - - // Set the name back to the fixture value so we can delete it after - remoteDivision.Name = firstDivision.Name - alert, _, err = TOSession.UpdateDivisionByID(remoteDivision.ID, remoteDivision) - if err != nil { - t.Errorf("cannot UPDATE Division by id: %v - %v", err, alert) - } - -} - -func GetTestDivisions(t *testing.T) { - for _, division := range testData.Divisions { - resp, _, err := TOSession.GetDivisionByName(division.Name) - if err != nil { - t.Errorf("cannot GET Division by division: %v - %v", err, resp) - } - } -} - -func DeleteTestDivisions(t *testing.T) { - - for _, division := range testData.Divisions { - // Retrieve the Division by name so we can get the id - resp, _, err := TOSession.GetDivisionByName(division.Name) - if err != nil { - t.Errorf("cannot GET Division by name: %v - %v", division.Name, err) - } - if len(resp) != 1 { - t.Errorf("Expected exactly one Division to exist with name '%s', found: %d", division.Name, len(resp)) - continue - } - respDivision := resp[0] - - delResp, _, err := TOSession.DeleteDivisionByID(respDivision.ID) - if err != nil { - t.Errorf("cannot DELETE Division by division: %v - %v", err, delResp) - } - - // Retrieve the Division to see if it got deleted - divisionResp, _, err := TOSession.GetDivisionByName(division.Name) - if err != nil { - t.Errorf("error deleting Division division: %s", err.Error()) - } - if len(divisionResp) > 0 { - t.Errorf("expected Division : %s to be deleted", division.Name) - } - } -} diff --git a/traffic_ops/testing/api/v2/federation_resolvers_test.go b/traffic_ops/testing/api/v2/federation_resolvers_test.go deleted file mode 100644 index aa229f73c0..0000000000 --- a/traffic_ops/testing/api/v2/federation_resolvers_test.go +++ /dev/null @@ -1,220 +0,0 @@ -package v2 - -/* - - Licensed 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" - - "github.com/apache/trafficcontrol/lib/go-tc" - "github.com/apache/trafficcontrol/lib/go-util" -) - -func TestFederationResolvers(t *testing.T) { - WithObjs(t, []TCObj{Types, FederationResolvers}, func() { - GetTestFederationResolvers(t) - }) -} - -func GetTestFederationResolvers(t *testing.T) { - var tdlen = len(testData.FederationResolvers) - if tdlen < 1 { - t.Fatal("no federation resolvers test data") - } - - frs, _, err := TOSession.GetFederationResolvers() - if err != nil { - t.Errorf("Unexpected error getting Federation Resolvers: %v", err) - } - if len(frs) != tdlen { - t.Fatalf("Wrong number of Federation Resolvers from GET, want %d got %d", tdlen, len(frs)) - } - - var testFr = frs[0] - if testFr.ID == nil || testFr.Type == nil || testFr.IPAddress == nil { - t.Fatalf("Malformed federation resolver: %+v", testFr) - } - - _ = t.Run("Get Federation Resolvers by ID", getFRByIDTest(testFr)) - _ = t.Run("Get Federation Resolvers by IPAddress", getFRByIPTest(testFr)) - _ = t.Run("Get Federation Resolvers by Type", getFRByTypeTest(testFr)) -} - -func getFRByIDTest(testFr tc.FederationResolver) func(*testing.T) { - return func(t *testing.T) { - fr, _, err := TOSession.GetFederationResolverByID(*testFr.ID) - if err != nil { - t.Fatalf("Unexpected error getting Federation Resolver by ID %d: %v", *testFr.ID, err) - } - - cmpr(testFr, fr, t) - - } -} - -func getFRByIPTest(testFr tc.FederationResolver) func(*testing.T) { - return func(t *testing.T) { - fr, _, err := TOSession.GetFederationResolverByIPAddress(*testFr.IPAddress) - if err != nil { - t.Fatalf("Unexpected error getting Federation Resolver by IP %s: %v", *testFr.IPAddress, err) - } - - cmpr(testFr, fr, t) - - } -} - -func getFRByTypeTest(testFr tc.FederationResolver) func(*testing.T) { - return func(t *testing.T) { - frs, _, err := TOSession.GetFederationResolversByType(*testFr.Type) - if err != nil { - t.Fatalf("Unexpected error getting Federation Resolvers by Type %s: %v", *testFr.Type, err) - } - - if len(frs) < 1 { - t.Errorf("Expected at least one Federation Resolver by Type %s to exist, but none did", *testFr.Type) - } - - for _, fr := range frs { - if fr.ID == nil { - t.Error("Retrieved Federation Resolver has nil ID") - } - if fr.IPAddress == nil { - t.Error("Retrieved Federation Resolver has nil IPAddress") - } - if fr.Type == nil { - t.Error("Retrieved Federation Resolver has nil Type") - } else if *fr.Type != *testFr.Type { - t.Errorf("Retrieved Federation Resolver has incorrect Type; want %s, got %s", *testFr.Type, *fr.Type) - } - } - } -} - -func cmpr(testFr, apiFr tc.FederationResolver, t *testing.T) { - if apiFr.ID == nil { - t.Error("Retrieved Federation Resolver has nil ID") - } else if *apiFr.ID != *testFr.ID { - t.Errorf("Retrieved Federation Resolver has incorrect ID; want %d, got %d", *testFr.ID, *apiFr.ID) - } - - if apiFr.IPAddress == nil { - t.Error("Retrieved Federation Resolver has nil IP address") - } else if *apiFr.IPAddress != *testFr.IPAddress { - t.Errorf("Retrieved Federation Resolver has incorrect IPAddress; want %s, got %s", *testFr.IPAddress, *apiFr.IPAddress) - } - - if apiFr.Type == nil { - t.Error("Retrieved Federation Resolver has nil Type") - } else if *apiFr.Type != *testFr.Type { - t.Errorf("Retrieved Federation Resolver has incorrect Type; want %s, got %s", *testFr.Type, *apiFr.Type) - } -} - -func CreateTestFederationResolvers(t *testing.T) { - for _, fr := range testData.FederationResolvers { - if fr.Type == nil { - t.Fatal("testData Federation Resolver has nil Type") - } - - tid, _, err := TOSession.GetTypeByName(*fr.Type) - if err != nil { - t.Fatalf("Couldn't get an ID for type %s", *fr.Type) - } - if len(tid) != 1 { - t.Fatalf("Expected exactly one Type by name %s, got %d", *fr.Type, len(tid)) - } - - fr.TypeID = util.UIntPtr(uint(tid[0].ID)) - - alerts, _, err := TOSession.CreateFederationResolver(fr) - if err != nil { - t.Fatalf("failed to create Federation resolver %+v: %v\n\talerts: %+v", fr, err, alerts) - } - for _, a := range alerts.Alerts { - if a.Level != tc.SuccessLevel.String() { - t.Errorf("Unexpected %s creating a federation resolver: %s", a.Level, a.Text) - } else { - t.Logf("Received expected success creating federation resolver: %s", a.Text) - } - } - } - - var invalidFR tc.FederationResolver - alerts, _, err := TOSession.CreateFederationResolver(invalidFR) - if err == nil { - t.Error("Expected an error creating a bad Federation Resolver, but didn't get one") - } - for _, a := range alerts.Alerts { - if a.Level == tc.SuccessLevel.String() { - t.Errorf("Unexpected success creating a bad Federation Resolver: %s", a.Text) - } else { - t.Logf("Received expected %s creating federation resolver: %s", a.Level, a.Text) - } - } - - invalidFR.TypeID = util.UIntPtr(1) - invalidFR.IPAddress = util.StrPtr("not a valid IP address") - alerts, _, err = TOSession.CreateFederationResolver(invalidFR) - if err == nil { - t.Error("Expected an error creating a bad Federation Resolver, but didn't get one") - } - for _, a := range alerts.Alerts { - if a.Level == tc.SuccessLevel.String() { - t.Errorf("Unexpected success creating a bad Federation Resolver: %s", a.Text) - } else { - t.Logf("Received expected %s creating a bad federation resolver: %s", a.Level, a.Text) - } - } -} - -func DeleteTestFederationResolvers(t *testing.T) { - frs, _, err := TOSession.GetFederationResolvers() - if err != nil { - t.Errorf("Unexpected error getting Federation Resolvers: %v", err) - } - if len(frs) < 1 { - t.Fatal("Found no Federation Resolvers to delete") - } - for _, fr := range frs { - if fr.ID == nil { - t.Fatalf("Malformed Federation Resolver: %+v", fr) - } - alerts, _, err := TOSession.DeleteFederationResolver(*fr.ID) - if err != nil { - t.Fatalf("failed to delete Federation Resolver %+v: %v\n\talerts: %+v", fr, err, alerts) - } - for _, a := range alerts.Alerts { - if a.Level != tc.SuccessLevel.String() { - t.Errorf("Unexpected %s deleting a federation resolver: %s", a.Level, a.Text) - } else { - t.Logf("Received expected success deleting federation resolver: %s", a.Text) - } - } - } - - alerts, _, err := TOSession.DeleteFederationResolver(0) - if err == nil { - t.Error("Expected an error deleting a non-existent Federation Resolver, but didn't get one") - } - for _, a := range alerts.Alerts { - if a.Level == tc.SuccessLevel.String() { - t.Errorf("Unexpected success deleting a non-existent Federation Resolver: %s", a.Text) - } else { - t.Logf("Received expected %s deleting a non-existent federation resolver: %s", a.Level, a.Text) - } - } - -} diff --git a/traffic_ops/testing/api/v2/federation_users_test.go b/traffic_ops/testing/api/v2/federation_users_test.go deleted file mode 100644 index 9f1db6958d..0000000000 --- a/traffic_ops/testing/api/v2/federation_users_test.go +++ /dev/null @@ -1,160 +0,0 @@ -package v2 - -/* - - Licensed 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 TestFederationUsers(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Tenants, Users, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, DeliveryServices, CDNFederations, FederationUsers}, func() { - CreateTestInvalidFederationUsers(t) - GetTestInvalidFederationIDUsers(t) - }) -} - -func CreateTestFederationUsers(t *testing.T) { - if len(testData.Federations) == 0 { - t.Error("no federations test data") - } - - fedID := fedIDs[0] - - // Get Users - users, _, err := TOSession.GetUsers() - if err != nil { - t.Fatalf("getting users: " + err.Error()) - } - if len(users) < 3 { - t.Fatal("need > 3 users to create federation users") - } - - u1 := users[0].ID - u2 := users[1].ID - u3 := users[2].ID - - // Associate one user to federation - _, _, err = TOSession.CreateFederationUsers(fedID, []int{*u1}, false) - if err != nil { - t.Fatalf("assigning users %v to federation %v: %v", []int{*u1}, fedID, err.Error()) - } - - fedUsers, _, err := TOSession.GetFederationUsers(fedID) - if err != nil { - t.Fatalf("gettings users for federation %v: %v", fedID, err.Error()) - } - if len(fedUsers) != 1 { - t.Errorf("federation users expected 1, actual: %+v", len(fedUsers)) - } - - // Associate two users to federation and replace first one - _, _, err = TOSession.CreateFederationUsers(fedID, []int{*u2, *u3}, true) - if err != nil { - t.Fatalf("assigning users %v to federation %v: %v", []int{*u2, *u3}, fedID, err.Error()) - } - - fedUsers, _, err = TOSession.GetFederationUsers(fedID) - if err != nil { - t.Fatalf("gettings users for federation %v: %v", fedID, err.Error()) - } - if len(fedUsers) != 2 { - t.Errorf("federation users expected 2, actual: %+v", len(fedUsers)) - } - - // Associate one more user to federation - _, _, err = TOSession.CreateFederationUsers(fedID, []int{*u1}, false) - if err != nil { - t.Fatalf("assigning users %v to federation %v: %v", []int{*u1}, fedID, err.Error()) - } - - fedUsers, _, err = TOSession.GetFederationUsers(fedID) - if err != nil { - t.Fatalf("gettings users for federation %v: %v", fedID, err.Error()) - } - if len(fedUsers) != 3 { - t.Errorf("federation users expected 2, actual: %+v", len(fedUsers)) - } -} - -func GetTestInvalidFederationIDUsers(t *testing.T) { - _, _, err := TOSession.GetFederationUsers(-1) - if err == nil { - t.Fatalf("expected to get an error when requesting federation users for a non-existent federation") - } -} - -func CreateTestInvalidFederationUsers(t *testing.T) { - if len(testData.Federations) == 0 { - t.Error("no federations test data") - } - - fedID := fedIDs[0] - - // Get Users - users, _, err := TOSession.GetUsers() - if err != nil { - t.Fatalf("getting users: " + err.Error()) - } - if len(users) == 0 { - t.Fatal("need at least 1 user to test invalid federation user create") - } - - // Associate with invalid federdation id - _, _, err = TOSession.CreateFederationUsers(-1, []int{*users[0].ID}, false) - if err == nil { - t.Error("expected to get error back from associating non existent federation id") - } - - // Associate with invalid user id - _, _, err = TOSession.CreateFederationUsers(fedID, []int{-1}, false) - if err == nil { - t.Error("expected to get error back from associating non existent user id") - } -} - -func DeleteTestFederationUsers(t *testing.T) { - if len(testData.Federations) == 0 { - t.Fatal("no federations test data") - } - if len(fedIDs) < 1 { - t.Fatal("No cached federation IDs") - } - - fedID := fedIDs[0] - - fedUsers, _, err := TOSession.GetFederationUsers(fedID) - if err != nil { - t.Fatalf("gettings users for federation %v: %v", fedID, err.Error()) - } - if len(fedUsers) != 3 { - t.Errorf("federation users expected 3, actual: %+v", len(fedUsers)) - } - - for _, fedUser := range fedUsers { - _, _, err = TOSession.DeleteFederationUser(fedID, *fedUser.ID) - if err != nil { - t.Fatalf("deleting user %v from federation %v: %v", *fedUser.ID, fedID, err.Error()) - } - } - - fedUsers, _, err = TOSession.GetFederationUsers(fedID) - if err != nil { - t.Fatalf("gettings users for federation %v: %v", fedID, err.Error()) - } - if len(fedUsers) != 0 { - t.Errorf("federation users expected 0, actual: %+v", len(fedUsers)) - } -} diff --git a/traffic_ops/testing/api/v2/federations_test.go b/traffic_ops/testing/api/v2/federations_test.go deleted file mode 100644 index 8787805624..0000000000 --- a/traffic_ops/testing/api/v2/federations_test.go +++ /dev/null @@ -1,245 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "errors" - "fmt" - "testing" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -func TestFederations(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Tenants, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, DeliveryServices, CDNFederations}, func() { - PostDeleteTestFederationsDeliveryServices(t) - GetTestFederations(t) - AddFederationResolversForCurrentUserTest(t) - RemoveFederationResolversForCurrentUserTest(t) - }) -} - -func GetTestFederations(t *testing.T) { - if len(testData.Federations) == 0 { - t.Error("no federations test data") - } - - feds, _, err := TOSession.AllFederations() - if err != nil { - t.Errorf("getting federations: " + err.Error()) - } - - if len(feds) < 1 { - t.Errorf("expected atleast 1 federation, but got none") - } - fed := feds[0] - - if len(fed.Mappings) < 1 { - t.Error("federation mappings expected <0, actual: 0") - } - - mapping := fed.Mappings[0] - if mapping.CName == nil { - t.Error("federation mapping expected cname, actual: nil") - } - if mapping.TTL == nil { - t.Error("federation mapping expected ttl, actual: nil") - } - - matched := false - for _, testFed := range testData.Federations { - if testFed.CName == nil { - t.Error("test federation missing cname!") - } - if testFed.TTL == nil { - t.Error("test federation missing ttl!") - } - - if *mapping.CName != *testFed.CName { - continue - } - matched = true - - if *mapping.TTL != *testFed.TTL { - t.Errorf("federation mapping ttl expected: %v, actual: %v", *testFed.TTL, *mapping.TTL) - } - } - if !matched { - t.Errorf("federation mapping expected to match test data, actual: cname %v not in test data", *mapping.CName) - } -} - -func createFederationToDeliveryServiceAssociation() (int, tc.DeliveryServiceNullable, tc.DeliveryServiceNullable, error) { - dses, _, err := TOSession.GetDeliveryServicesNullable() - if err != nil { - return -1, tc.DeliveryServiceNullable{}, tc.DeliveryServiceNullable{}, fmt.Errorf("cannot GET DeliveryServices: %v - %v", err, dses) - } - if len(dses) == 0 { - return -1, tc.DeliveryServiceNullable{}, tc.DeliveryServiceNullable{}, errors.New("no delivery services, must have at least 1 ds to test federations deliveryservices") - } - ds := dses[0] - ds1 := dses[1] - - if len(fedIDs) == 0 { - return -1, ds, ds1, errors.New("no federations, must have at least 1 federation to test federations deliveryservices") - } - fedID := fedIDs[0] - - _, err = TOSession.CreateFederationDeliveryServices(fedID, []int{*ds.ID, *ds1.ID}, true) - if err != nil { - err = fmt.Errorf("creating federations delivery services: %v", err) - } - - return fedID, ds, ds1, err - -} - -func PostDeleteTestFederationsDeliveryServices(t *testing.T) { - fedID, ds, ds1, err := createFederationToDeliveryServiceAssociation() - if err != nil { - t.Fatalf("%v", err) - } - - // Test get created Federation Delivery Services - fedDSes, _, err := TOSession.GetFederationDeliveryServices(fedID) - if err != nil { - t.Fatalf("cannot GET Federation DeliveryServices: %v", err) - } - if len(fedDSes) != 2 { - t.Fatalf("two Federation DeliveryService expected for Federation %v, %v was returned", fedID, len(fedDSes)) - } - - // Delete one of the Delivery Services from the Federation - _, _, err = TOSession.DeleteFederationDeliveryService(fedID, *ds.ID) - if err != nil { - t.Fatalf("cannot Delete Federation %v DeliveryService %v: %v", fedID, ds.ID, err) - } - - // Make sure it is deleted - - // Test get created Federation Delivery Services - fedDSes, _, err = TOSession.GetFederationDeliveryServices(fedID) - if err != nil { - t.Fatalf("cannot GET Federation DeliveryServices: %v", err) - } - if len(fedDSes) != 1 { - t.Fatalf("one Federation DeliveryService expected for Federation %v, %v was returned", fedID, len(fedDSes)) - } - - // Attempt to delete the last one which should fail as you cannot remove the last - _, _, err = TOSession.DeleteFederationDeliveryService(fedID, *ds1.ID) - if err == nil { - t.Fatal("expected to receive error from attempting to delete last Delivery Service from a Federation") - } -} - -func RemoveFederationResolversForCurrentUserTest(t *testing.T) { - if len(testData.Federations) < 1 { - t.Fatal("No test Federations, deleting resolvers cannot be tested!") - } - - alerts, _, err := TOSession.DeleteFederationResolverMappingsForCurrentUser() - if err != nil { - t.Fatalf("Unexpected error deleting Federation Resolvers for current user: %v", err) - } - for _, a := range alerts.Alerts { - if a.Level == tc.SuccessLevel.String() { - t.Logf("Success message from current user Federation Resolver deletion: %s", a.Text) - } else { - t.Errorf("Unexpected %s from deleting Federation Resolvers for current user: %s", a.Level, a.Text) - } - } - - // Now try deleting Federation Resolvers when there are none. - _, _, err = TOSession.DeleteFederationResolverMappingsForCurrentUser() - if err != nil { - t.Logf("Received expected error deleting Federation Resolvers for current user: %v", err) - } else { - t.Error("Expected an error deleting zero Federation Resolvers, but didn't get one.") - } -} - -func AddFederationResolversForCurrentUserTest(t *testing.T) { - fedID, ds, ds1, err := createFederationToDeliveryServiceAssociation() - if err != nil { - t.Fatalf("%v", err) - } - - // need to assign myself the federation to set its mappings - me, _, err := TOSession.GetUserCurrent() - if err != nil { - t.Fatalf("Couldn't figure out who I am: %v", err) - } - if me.ID == nil { - t.Fatal("Current user has no ID, cannot continue.") - } - - _, _, err = TOSession.CreateFederationUsers(fedID, []int{*me.ID}, false) - if err != nil { - t.Fatalf("Failed to assign federation to current user: %v", err) - } - - mappings := tc.DeliveryServiceFederationResolverMappingRequest{ - tc.DeliveryServiceFederationResolverMapping{ - DeliveryService: *ds.XMLID, - Mappings: tc.ResolverMapping{ - Resolve4: []string{"0.0.0.0"}, - Resolve6: []string{"::1"}, - }, - }, - tc.DeliveryServiceFederationResolverMapping{ - DeliveryService: *ds1.XMLID, - Mappings: tc.ResolverMapping{ - Resolve4: []string{"1.2.3.4/28"}, - Resolve6: []string{"1234::/110"}, - }, - }, - } - - alerts, _, err := TOSession.AddFederationResolverMappingsForCurrentUser(mappings) - if err != nil { - t.Fatalf("Unexpected error adding Federation Resolver mappings for the current user: %v", err) - } - for _, a := range alerts.Alerts { - if a.Level == tc.SuccessLevel.String() { - t.Logf("Received expected success alert from adding Federation Resolver mappings for the current user: %s", a.Text) - } else { - t.Errorf("Unexpected %s from adding Federation Resolver mappings for the current user: %s", a.Level, a.Text) - } - } - - mappings = tc.DeliveryServiceFederationResolverMappingRequest{ - tc.DeliveryServiceFederationResolverMapping{ - DeliveryService: "aoeuhtns", - Mappings: tc.ResolverMapping{ - Resolve4: []string{}, - Resolve6: []string{"dead::beef", "f1d0::f00d/82"}, - }, - }, - } - - alerts, _, err = TOSession.AddFederationResolverMappingsForCurrentUser(mappings) - if err == nil { - t.Fatal("Expected error adding Federation Resolver mappings for the current user, but didn't get one") - } - for _, a := range alerts.Alerts { - if a.Level != tc.SuccessLevel.String() { - t.Logf("Received expected %s from adding Federation Resolver mappings for the current user: %s", a.Level, a.Text) - } else { - t.Errorf("Unexpected success from adding Federation Resolver mappings for the current user: %s", a.Text) - } - } -} diff --git a/traffic_ops/testing/api/v2/fixtures_test.go b/traffic_ops/testing/api/v2/fixtures_test.go deleted file mode 100644 index 9a3886a4f4..0000000000 --- a/traffic_ops/testing/api/v2/fixtures_test.go +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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. - */ - -package v2 - -import ( - "encoding/json" - "io/ioutil" - "os" - - "github.com/apache/trafficcontrol/lib/go-log" -) - -// LoadFixtures ... -func LoadFixtures(fixturesPath string) { - - f, err := ioutil.ReadFile(fixturesPath) - if err != nil { - log.Errorf("Cannot unmarshal fixtures json %s", err) - os.Exit(1) - } - err = json.Unmarshal(f, &testData) - if err != nil { - log.Errorf("Cannot unmarshal fixtures json %v", err) - os.Exit(1) - } -} diff --git a/traffic_ops/testing/api/v2/iso_test.go b/traffic_ops/testing/api/v2/iso_test.go deleted file mode 100644 index 805eb19ca9..0000000000 --- a/traffic_ops/testing/api/v2/iso_test.go +++ /dev/null @@ -1,103 +0,0 @@ -package v2 - -/* - * 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" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -func TestGetOSVersions(t *testing.T) { - if Config.NoISO { - t.Skip("No ISO generation available") - } - // Default value per ./traffic_ops/install/data/json/osversions.json file. - // This should be the data returned in the CiaB environment. - expected := map[string]string{ - "CentOS 7.2": "centos72", - } - - // Ensure request with an authenticated client returns expected data. - t.Run("authenticated", func(t *testing.T) { - got, _, err := TOSession.GetOSVersions() - if err != nil { - t.Fatalf("unexpected error from authenticated GetOSVersions(): %v", err) - } - - t.Logf("GetOSVersions() response: %#v", got) - - if lenGot, lenExp := len(got), len(expected); lenGot != lenExp { - t.Fatalf("incorrect map length: got %d map entries, expected %d", lenGot, lenExp) - } - for k, expectedVal := range expected { - if gotVal := got[k]; gotVal != expectedVal { - t.Fatalf("incorrect map entry for key %q: got %q, expected %q", k, gotVal, expectedVal) - } - } - }) - - // Ensure request with an un-authenticated client returns an error. - t.Run("un-authenticated", func(t *testing.T) { - _, _, err := NoAuthTOSession.GetOSVersions() - if err == nil { - t.Fatalf("expected error from unauthenticated GetOSVersions(), got: %v", err) - } - t.Logf("unauthenticated GetOSVersions() error (expected): %v", err) - }) - - // Update database with a Parameter entry. This should cause the endpoint - // to use the Parameter's value as the configuration file's directory. In this - // case, an intentionally missing/invalid directory is provided. - // Ensure authenticated request client returns an error. - // NOTE: This does not assume this test and TO are using the same filesystem, but - // does make the reasonable assumption that `/DOES/NOT/EXIST/osversions.json` will not exist - // on the TO host. - t.Run("parameter-invalid", func(t *testing.T) { - p := tc.Parameter{ - ConfigFile: "mkisofs", - Name: "kickstart.files.location", - Value: "/DOES/NOT/EXIST", - } - if _, _, err := TOSession.CreateParameter(p); err != nil { - t.Fatalf("could not CREATE parameter: %v\n", err) - } - // Cleanup DB entry - defer func() { - resp, _, err := TOSession.GetParameterByNameAndConfigFileAndValue(p.Name, p.ConfigFile, p.Value) - if err != nil { - t.Fatalf("cannot GET Parameter by name: %v - %v\n", p.Name, err) - } - if len(resp) != 1 { - t.Fatalf("unexpected response length %d", len(resp)) - } - - if delResp, _, err := TOSession.DeleteParameterByID(resp[0].ID); err != nil { - t.Fatalf("cannot DELETE Parameter by name: %v - %v\n", err, delResp) - } - }() - - _, _, err := TOSession.GetOSVersions() - if err == nil { - t.Fatalf("expected error from GetOSVersions() after adding invalid Parameter DB entry, got: %v", err) - } - t.Logf("got expected error from GetOSVersions() after adding Parameter DB entry with config directory %q: %v", p.Value, err) - }) -} diff --git a/traffic_ops/testing/api/v2/jobs_test.go b/traffic_ops/testing/api/v2/jobs_test.go deleted file mode 100644 index 04e8670147..0000000000 --- a/traffic_ops/testing/api/v2/jobs_test.go +++ /dev/null @@ -1,192 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "strings" - "testing" - "time" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -func TestJobs(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Tenants, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, Servers, DeliveryServices}, func() { - CreateTestJobs(t) - CreateTestInvalidationJobs(t) - GetTestJobsQueryParams(t) - GetTestJobs(t) - GetTestInvalidationJobs(t) - }) -} - -func CreateTestJobs(t *testing.T) { - toDSes, _, err := TOSession.GetDeliveryServicesNullable() - if err != nil { - t.Fatalf("cannot GET DeliveryServices: %v - %v", err, toDSes) - } - - for i, job := range testData.InvalidationJobs { - job.StartTime = &tc.Time{ - Time: time.Now().Add(time.Minute).UTC(), - Valid: true, - } - testData.InvalidationJobs[i] = job - } - - for _, job := range testData.InvalidationJobs { - request := tc.InvalidationJobInput{ - DeliveryService: job.DeliveryService, - Regex: job.Regex, - StartTime: job.StartTime, - TTL: job.TTL, - } - _, _, err := TOSession.CreateInvalidationJob(request) - if err != nil { - t.Errorf("could not CREATE job: %v", err) - } - } -} - -func CreateTestInvalidationJobs(t *testing.T) { - toDSes, _, err := TOSession.GetDeliveryServicesNullable() - if err != nil { - t.Fatalf("cannot GET Delivery Services: %v - %v", err, toDSes) - } - dsNameIDs := map[string]int64{} - for _, ds := range toDSes { - dsNameIDs[*ds.XMLID] = int64(*ds.ID) - } - - for _, job := range testData.InvalidationJobs { - _, ok := dsNameIDs[(*job.DeliveryService).(string)] - if !ok { - t.Fatalf("can't create test data job: delivery service '%v' not found in Traffic Ops", job.DeliveryService) - } - if _, _, err := TOSession.CreateInvalidationJob(job); err != nil { - t.Errorf("could not CREATE job: %v", err) - } - } -} - -func GetTestJobsQueryParams(t *testing.T) { - var xmlId interface{} = "ds2" - toJobs, _, err := TOSession.GetInvalidationJobs(&xmlId, nil) - if err != nil { - t.Fatalf("error getting jobs: %v", err) - } - foundOne := false - for _, j := range toJobs { - if j.DeliveryService == nil { - t.Error("expected: non-nil DeliveryService pointer, actual: nil") - } else if *j.DeliveryService != "ds2" { - t.Errorf("expected: DeliveryService == ds2, actual: DeliveryService == %s", *j.DeliveryService) - } else { - foundOne = true - } - } - if !foundOne { - t.Error("expected: to find at least one job with deliveryService == ds2, actual: found none") - } -} - -func GetTestJobs(t *testing.T) { - toJobs, _, err := TOSession.GetInvalidationJobs(nil, nil) - if err != nil { - t.Fatalf("error getting jobs: %v", err) - } - - toDSes, _, err := TOSession.GetDeliveryServicesNullable() - if err != nil { - t.Fatalf("cannot GET DeliveryServices: %v - %v", err, toDSes) - } - - for i, testJob := range testData.InvalidationJobs { - found := false - if testJob.DeliveryService == nil { - t.Errorf("test job (index %v) has nil delivery service", i) - continue - } else if testJob.Regex == nil { - t.Errorf("test job (index %v) has nil regex", i) - continue - } - for j, toJob := range toJobs { - if toJob.DeliveryService == nil { - t.Errorf("to job (index %v) has nil delivery service", j) - continue - } else if toJob.AssetURL == nil { - t.Errorf("to job (index %v) has nil asset url", j) - continue - } - if *toJob.DeliveryService != *testJob.DeliveryService { - continue - } - if !strings.HasSuffix(*toJob.AssetURL, *testJob.Regex) { - continue - } - toJobTime := toJob.StartTime.Round(time.Minute) - testJobTime := testJob.StartTime.Round(time.Minute) - if !toJobTime.Equal(testJobTime) { - t.Errorf("test job ds %v regex %v start time expected '%+v' actual '%+v'", *testJob.DeliveryService, *testJob.Regex, testJobTime, toJobTime) - continue - } - found = true - break - } - if !found { - t.Errorf("test job ds %v regex %v expected: exists, actual: not found", *testJob.DeliveryService, *testJob.Regex) - } - } -} - -func GetTestInvalidationJobs(t *testing.T) { - jobs, _, err := TOSession.GetInvalidationJobs(nil, nil) - if err != nil { - t.Fatalf("error getting invalidation jobs: %v", err) - } - - toDSes, _, err := TOSession.GetDeliveryServicesNullable() - if err != nil { - t.Fatalf("cannot GET DeliveryServices: %v - %v", err, toDSes) - } - - for _, ds := range toDSes { - if *ds.ID <= 0 { - t.Fatalf("Erroneous Delivery Service - has invalid ID: %+v", ds) - } - } - - for _, testJob := range testData.InvalidationJobs { - found := false - for _, toJob := range jobs { - if *toJob.DeliveryService != (*testJob.DeliveryService).(string) { - continue - } - if !strings.HasSuffix(*toJob.AssetURL, *testJob.Regex) { - continue - } - if !toJob.StartTime.Round(time.Minute).Equal(testJob.StartTime.Round(time.Minute)) { - t.Errorf("test invalidation job start time expected '%+v' actual '%+v'", testJob.StartTime, toJob.StartTime) - continue - } - found = true - break - } - if !found { - t.Errorf("expected a test job %+v to exist, but it didn't", testJob) - } - } -} diff --git a/traffic_ops/testing/api/v2/loginfail_test.go b/traffic_ops/testing/api/v2/loginfail_test.go deleted file mode 100644 index f78cec3e12..0000000000 --- a/traffic_ops/testing/api/v2/loginfail_test.go +++ /dev/null @@ -1,129 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "crypto/tls" - "net/http" - "net/http/cookiejar" - "testing" - "time" - - "golang.org/x/net/publicsuffix" - - toclient "github.com/apache/trafficcontrol/traffic_ops/v2-client" -) - -func TestLoginFail(t *testing.T) { - WithObjs(t, []TCObj{CDNs}, func() { - PostTestLoginFail(t) - LoginWithEmptyCredentialsTest(t) - }) - WithObjs(t, []TCObj{Roles, Tenants, Users}, func() { - LoginWithTokenTest(t) - }) -} - -func PostTestLoginFail(t *testing.T) { - // This specifically tests a previous bug: auth failure returning a 200, causing the client to think the request succeeded, and deserialize no matching fields successfully, and return an empty object. - - userAgent := "to-api-v2-client-tests-loginfailtest" - uninitializedTOClient, err := getUninitializedTOClient(Config.TrafficOps.Users.Admin, Config.TrafficOps.UserPassword, Config.TrafficOps.URL, userAgent, time.Second*time.Duration(Config.Default.Session.TimeoutInSecs)) - if err != nil { - t.Fatalf("getting uninitialized client: %+v", err) - } - - if len(testData.CDNs) < 1 { - t.Fatal("cannot test login: must have at least 1 test data cdn") - } - expectedCDN := testData.CDNs[0] - actualCDNs, _, err := uninitializedTOClient.GetCDNByName(expectedCDN.Name) - if err != nil { - t.Fatalf("GetCDNByName err expected nil, actual '%+v'", err) - } - if len(actualCDNs) < 1 { - t.Fatal("uninitialized client should have retried login (possibly login failed with a 200, so it didn't try again, and the CDN request returned an auth failure with a 200, which the client reasonably thought was success, and deserialized with no matching keys, resulting in an empty object); len(actualCDNs) expected >1, actual 0") - } - actualCDN := actualCDNs[0] - if expectedCDN.Name != actualCDN.Name { - t.Fatalf("cdn.Name expected '%+v' actual '%+v'", expectedCDN.Name, actualCDN.Name) - } -} - -func LoginWithEmptyCredentialsTest(t *testing.T) { - userAgent := "to-api-v2-client-tests-loginfailtest" - _, _, err := toclient.LoginWithAgent(Config.TrafficOps.URL, Config.TrafficOps.Users.Admin, "", true, userAgent, false, time.Second*time.Duration(Config.Default.Session.TimeoutInSecs)) - if err == nil { - t.Fatal("expected error when logging in with empty credentials, actual nil") - } -} - -func LoginWithTokenTest(t *testing.T) { - db, err := OpenConnection() - if err != nil { - t.Fatalf("Failed to get database connection: %v", err) - } - - allowedToken := "test" - disallowedToken := "quest" - - if _, err = db.Exec(`UPDATE tm_user SET token=$1 WHERE id = (SELECT id FROM tm_user WHERE role != (SELECT id FROM role WHERE name='disallowed') LIMIT 1)`, allowedToken); err != nil { - t.Fatalf("Failed to set allowed token: %v", err) - } - - if _, err = db.Exec(`UPDATE tm_user SET token=$1 WHERE id = (SELECT id FROM tm_user WHERE role = (SELECT id FROM role WHERE name='disallowed') LIMIT 1)`, disallowedToken); err != nil { - t.Fatalf("Failed to set disallowed token: %v", err) - } - - userAgent := "to-api-v2-client-tests-loginfailtest" - s, _, err := toclient.LoginWithToken(Config.TrafficOps.URL, allowedToken, true, userAgent, false, time.Second*time.Duration(Config.Default.Session.TimeoutInSecs)) - if err != nil { - t.Errorf("unexpected error when logging in with a token: %v", err) - } - if s == nil { - t.Error("returned client was nil") - } - - // disallowed token - _, _, err = toclient.LoginWithToken(Config.TrafficOps.URL, disallowedToken, true, userAgent, false, time.Second*time.Duration(Config.Default.Session.TimeoutInSecs)) - if err == nil { - t.Error("expected an error when logging in with a disallowed token, actual nil") - } - - // nonexistent token - _, _, err = toclient.LoginWithToken(Config.TrafficOps.URL, "notarealtoken", true, userAgent, false, time.Second*time.Duration(Config.Default.Session.TimeoutInSecs)) - if err == nil { - t.Error("expected an error when logging in with a nonexistent token, actual nil") - } -} - -func getUninitializedTOClient(user, pass, uri, agent string, reqTimeout time.Duration) (*toclient.Session, error) { - insecure := true - useCache := false - jar, err := cookiejar.New(&cookiejar.Options{ - PublicSuffixList: publicsuffix.List, - }) - if err != nil { - return nil, err - } - return toclient.NewSession(user, pass, uri, agent, &http.Client{ - Timeout: reqTimeout, - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}, - }, - Jar: jar, - }, useCache), nil -} diff --git a/traffic_ops/testing/api/v2/logs_test.go b/traffic_ops/testing/api/v2/logs_test.go deleted file mode 100644 index 05a79ceba9..0000000000 --- a/traffic_ops/testing/api/v2/logs_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package v2 - -/* - - Licensed 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 TestLogs(t *testing.T) { - WithObjs(t, []TCObj{Roles, Tenants, Users}, func() { // Objs added to create logs when this test is run alone - GetTestLogs(t) - GetTestLogsByLimit(t) - }) -} - -func GetTestLogs(t *testing.T) { - _, _, err := TOSession.GetLogs() - if err != nil { - t.Fatalf("error getting logs: " + err.Error()) - } -} - -func GetTestLogsByLimit(t *testing.T) { - toLogs, _, err := TOSession.GetLogsByLimit(10) - if err != nil { - t.Fatalf("error getting logs: " + err.Error()) - } - if len(toLogs) != 10 { - t.Fatalf("GET logs by limit: incorrect number of logs returned (%v)", len(toLogs)) - } -} diff --git a/traffic_ops/testing/api/v2/monitoring_test.go b/traffic_ops/testing/api/v2/monitoring_test.go deleted file mode 100644 index 60ae8d7641..0000000000 --- a/traffic_ops/testing/api/v2/monitoring_test.go +++ /dev/null @@ -1,76 +0,0 @@ -/* - - Licensed 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. -*/ - -package v2 - -import ( - "testing" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -func TestMonitoring(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Tenants, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, Servers, DeliveryServices}, func() { - GetTestMonitoringConfigNoSnapshotOnTheFly(t) // MUST run first - AllCDNsCanSnapshot(t) - }) -} - -// GetTestMonitoringConfigNoSnapshotOnTheFly verifies that Traffic Ops generates a monitoring.json on-the-fly rather than returning "" or "{}" if no snapshot exists. -// This MUST NOT be run after a different function in the same Test creates a Snapshot, or the test will be invalid. -// This prevents a critical bug of upgrading to 4.x bringing a CDN down until a Snapshot is performed. -func GetTestMonitoringConfigNoSnapshotOnTheFly(t *testing.T) { - server := tc.Server{} - for _, sv := range testData.Servers { - if sv.Type != "EDGE" { - continue - } - server = sv - break - } - if server.CDNName == "" { - t.Fatal("No edge server found in test data, cannot test") - } - - tmConfig, _, err := TOSession.GetTrafficMonitorConfigMap(server.CDNName) - if err != nil { - t.Error("getting monitoring: " + err.Error()) - } else if len(tmConfig.TrafficServer) == 0 { - t.Error("Expected Monitoring without a snapshot to generate on-the-fly, actual: empty monitoring object for cdn '" + server.CDNName + "'") - } -} - -func AllCDNsCanSnapshot(t *testing.T) { - - serversByHost := make(map[string]tc.Server) - - for _, server := range testData.Servers { - serversByHost[server.HostName] = server - } - - for _, cdn := range testData.CDNs { - _, err := TOSession.SnapshotCRConfig(cdn.Name) - if err != nil { - t.Error(err) - continue - } - - tmConfig, _, err := TOSession.GetTrafficMonitorConfigMap(cdn.Name) - if err != nil && tmConfig == nil { - t.Error(err) - continue - } - } -} diff --git a/traffic_ops/testing/api/v2/origins_test.go b/traffic_ops/testing/api/v2/origins_test.go deleted file mode 100644 index 47b3c79d60..0000000000 --- a/traffic_ops/testing/api/v2/origins_test.go +++ /dev/null @@ -1,221 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "reflect" - "strings" - "testing" - "time" - - "github.com/apache/trafficcontrol/lib/go-tc" - "github.com/apache/trafficcontrol/lib/go-util" - toclient "github.com/apache/trafficcontrol/traffic_ops/v2-client" -) - -func TestOrigins(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Tenants, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, Servers, Users, DeliveryServices, Coordinates, Origins}, func() { - UpdateTestOrigins(t) - GetTestOrigins(t) - NotFoundDeleteTest(t) - OriginTenancyTest(t) - VerifyPaginationSupport(t) - }) -} - -func CreateTestOrigins(t *testing.T) { - // loop through origins, assign FKs and create - for _, origin := range testData.Origins { - _, _, err := TOSession.CreateOrigin(origin) - if err != nil { - t.Errorf("could not CREATE origins: %v", err) - } - } -} - -func NotFoundDeleteTest(t *testing.T) { - _, _, err := TOSession.DeleteOriginByID(2020) - if !strings.Contains(err.Error(), "not found") { - t.Error("deleted origin with what should be a non-existent id") - } -} - -func GetTestOrigins(t *testing.T) { - _, _, err := TOSession.GetOrigins() - if err != nil { - t.Errorf("cannot GET origins: %v", err) - } - - for _, origin := range testData.Origins { - resp, _, err := TOSession.GetOriginByName(*origin.Name) - if err != nil { - t.Errorf("cannot GET Origin by name: %v - %v", err, resp) - } - } -} - -func UpdateTestOrigins(t *testing.T) { - firstOrigin := testData.Origins[0] - // Retrieve the origin by name so we can get the id for the Update - resp, _, err := TOSession.GetOriginByName(*firstOrigin.Name) - if err != nil { - t.Errorf("cannot GET origin by name: %v - %v", *firstOrigin.Name, err) - } - remoteOrigin := resp[0] - updatedPort := 4321 - updatedFQDN := "updated.example.com" - - // update port and FQDN values on origin - remoteOrigin.Port = &updatedPort - remoteOrigin.FQDN = &updatedFQDN - updResp, _, err := TOSession.UpdateOriginByID(*remoteOrigin.ID, remoteOrigin) - if err != nil { - t.Errorf("cannot UPDATE Origin by name: %v - %v", err, updResp.Alerts) - } - - // Retrieve the origin to check port and FQDN values were updated - resp, _, err = TOSession.GetOriginByID(*remoteOrigin.ID) - if err != nil { - t.Errorf("cannot GET Origin by ID: %v - %v", *remoteOrigin.Name, err) - } - - respOrigin := resp[0] - if *respOrigin.Port != updatedPort { - t.Errorf("results do not match actual: %d, expected: %d", *respOrigin.Port, updatedPort) - } - if *respOrigin.FQDN != updatedFQDN { - t.Errorf("results do not match actual: %s, expected: %s", *respOrigin.FQDN, updatedFQDN) - } -} - -func OriginTenancyTest(t *testing.T) { - origins, _, err := TOSession.GetOrigins() - if err != nil { - t.Errorf("cannot GET origins: %v", err) - } - tenant3Origin := tc.Origin{} - foundTenant3Origin := false - for _, o := range origins { - if *o.FQDN == "origin.ds3.example.net" { - tenant3Origin = o - foundTenant3Origin = true - } - } - if !foundTenant3Origin { - t.Error("expected to find origin with tenant 'tenant3' and fqdn 'origin.ds3.example.net'") - } - - toReqTimeout := time.Second * time.Duration(Config.Default.Session.TimeoutInSecs) - tenant4TOClient, _, err := toclient.LoginWithAgent(TOSession.URL, "tenant4user", "pa$$word", true, "to-api-v2-client-tests/tenant4user", true, toReqTimeout) - if err != nil { - t.Fatalf("failed to log in with tenant4user: %v", err.Error()) - } - - originsReadableByTenant4, _, err := tenant4TOClient.GetOrigins() - if err != nil { - t.Error("tenant4user cannot GET origins") - } - - // assert that tenant4user cannot read origins outside of its tenant - for _, origin := range originsReadableByTenant4 { - if *origin.FQDN == "origin.ds3.example.net" { - t.Error("expected tenant4 to be unable to read origins from tenant 3") - } - } - - // assert that tenant4user cannot update tenant3user's origin - if _, _, err = tenant4TOClient.UpdateOriginByID(*tenant3Origin.ID, tenant3Origin); err == nil { - t.Error("expected tenant4user to be unable to update tenant3's origin") - } - - // assert that tenant4user cannot delete an origin outside of its tenant - if _, _, err = tenant4TOClient.DeleteOriginByID(*origins[0].ID); err == nil { - t.Errorf("expected tenant4user to be unable to delete an origin outside of its tenant (origin %s)", *origins[0].Name) - } - - // assert that tenant4user cannot create origins outside of its tenant - tenant3Origin.FQDN = util.StrPtr("origin.tenancy.test.example.com") - if _, _, err = tenant4TOClient.CreateOrigin(tenant3Origin); err == nil { - t.Error("expected tenant4user to be unable to create an origin outside of its tenant") - } -} - -func VerifyPaginationSupport(t *testing.T) { - origins, _, err := TOSession.GetOriginsByQueryParams("?orderby=id") - if err != nil { - t.Fatalf("cannot GET origins: %v", err) - } - - originsWithLimit, _, err := TOSession.GetOriginsByQueryParams("?orderby=id&limit=1") - if !reflect.DeepEqual(origins[:1], originsWithLimit) { - t.Error("expected GET origins with limit = 1 to return first result") - } - - originsWithOffset, _, err := TOSession.GetOriginsByQueryParams("?orderby=id&limit=1&offset=1") - if !reflect.DeepEqual(origins[1:2], originsWithOffset) { - t.Error("expected GET origins with limit = 1, offset = 1 to return second result") - } - - originsWithPage, _, err := TOSession.GetOriginsByQueryParams("?orderby=id&limit=1&page=2") - if !reflect.DeepEqual(origins[1:2], originsWithPage) { - t.Error("expected GET origins with limit = 1, page = 2 to return second result") - } - - _, _, err = TOSession.GetOriginsByQueryParams("?limit=-2") - if err == nil { - t.Error("expected GET origins to return an error when limit is not bigger than -1") - } else if !strings.Contains(err.Error(), "must be bigger than -1") { - t.Errorf("expected GET origins to return an error for limit is not bigger than -1, actual error: " + err.Error()) - } - _, _, err = TOSession.GetOriginsByQueryParams("?limit=1&offset=0") - if err == nil { - t.Error("expected GET origins to return an error when offset is not a positive integer") - } else if !strings.Contains(err.Error(), "must be a positive integer") { - t.Errorf("expected GET origins to return an error for offset is not a positive integer, actual error: " + err.Error()) - } - _, _, err = TOSession.GetOriginsByQueryParams("?limit=1&page=0") - if err == nil { - t.Error("expected GET origins to return an error when page is not a positive integer") - } else if !strings.Contains(err.Error(), "must be a positive integer") { - t.Errorf("expected GET origins to return an error for page is not a positive integer, actual error: " + err.Error()) - } -} - -func DeleteTestOrigins(t *testing.T) { - for _, origin := range testData.Origins { - resp, _, err := TOSession.GetOriginByName(*origin.Name) - if err != nil { - t.Errorf("cannot GET Origin by name: %v - %v", *origin.Name, err) - } - if len(resp) > 0 { - respOrigin := resp[0] - - delResp, _, err := TOSession.DeleteOriginByID(*respOrigin.ID) - if err != nil { - t.Errorf("cannot DELETE Origin by ID: %v - %v", err, delResp) - } - - // Retrieve the Origin to see if it got deleted - org, _, err := TOSession.GetOriginByName(*origin.Name) - if err != nil { - t.Errorf("error deleting Origin name: %s", err.Error()) - } - if len(org) > 0 { - t.Errorf("expected Origin name: %s to be deleted", *origin.Name) - } - } - } -} diff --git a/traffic_ops/testing/api/v2/parameters_test.go b/traffic_ops/testing/api/v2/parameters_test.go deleted file mode 100644 index ed1fbc8d68..0000000000 --- a/traffic_ops/testing/api/v2/parameters_test.go +++ /dev/null @@ -1,139 +0,0 @@ -/* - - Licensed 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. -*/ - -package v2 - -import ( - "sync" - "testing" - - tc "github.com/apache/trafficcontrol/lib/go-tc" -) - -func TestParameters(t *testing.T) { - - //toReqTimeout := time.Second * time.Duration(Config.Default.Session.TimeoutInSecs) - //SwitchSession(toReqTimeout, Config.TrafficOps.URL, Config.TrafficOps.Users.Admin, Config.TrafficOps.UserPassword, Config.TrafficOps.Users.Portal, Config.TrafficOps.UserPassword) - - WithObjs(t, []TCObj{Parameters}, func() { - UpdateTestParameters(t) - GetTestParameters(t) - }) -} - -func CreateTestParameters(t *testing.T) { - - for _, pl := range testData.Parameters { - resp, _, err := TOSession.CreateParameter(pl) - t.Log("Response: ", resp) - if err != nil { - t.Errorf("could not CREATE parameters: %v", err) - } - } - -} - -func UpdateTestParameters(t *testing.T) { - - firstParameter := testData.Parameters[0] - // Retrieve the Parameter by name so we can get the id for the Update - resp, _, err := TOSession.GetParameterByName(firstParameter.Name) - if err != nil { - t.Errorf("cannot GET Parameter by name: %v - %v", firstParameter.Name, err) - } - remoteParameter := resp[0] - expectedParameterValue := "UPDATED" - remoteParameter.Value = expectedParameterValue - var alert tc.Alerts - alert, _, err = TOSession.UpdateParameterByID(remoteParameter.ID, remoteParameter) - if err != nil { - t.Errorf("cannot UPDATE Parameter by id: %v - %v", err, alert) - } - - // Retrieve the Parameter to check Parameter name got updated - resp, _, err = TOSession.GetParameterByID(remoteParameter.ID) - if err != nil { - t.Errorf("cannot GET Parameter by name: %v - %v", firstParameter.Name, err) - } - respParameter := resp[0] - if respParameter.Value != expectedParameterValue { - t.Errorf("results do not match actual: %s, expected: %s", respParameter.Value, expectedParameterValue) - } - -} - -func GetTestParameters(t *testing.T) { - - for _, pl := range testData.Parameters { - resp, _, err := TOSession.GetParameterByName(pl.Name) - if err != nil { - t.Errorf("cannot GET Parameter by name: %v - %v", err, resp) - } - } -} - -func DeleteTestParametersParallel(t *testing.T) { - - var wg sync.WaitGroup - for _, pl := range testData.Parameters { - - wg.Add(1) - go func(p tc.Parameter) { - defer wg.Done() - DeleteTestParameter(t, p) - }(pl) - - } - wg.Wait() -} - -func DeleteTestParameters(t *testing.T) { - - for _, pl := range testData.Parameters { - DeleteTestParameter(t, pl) - } -} - -func DeleteTestParameter(t *testing.T, pl tc.Parameter) { - - // Retrieve the Parameter by name so we can get the id for the Update - resp, _, err := TOSession.GetParameterByNameAndConfigFile(pl.Name, pl.ConfigFile) - if err != nil { - t.Errorf("cannot GET Parameter by name: %v - %v", pl.Name, err) - } - - if len(resp) == 0 { - // TODO This fails for the ProfileParameters test; determine a way to check this, even for ProfileParameters - // t.Errorf("DeleteTestParameter got no params for %+v %+v", pl.Name, pl.ConfigFile) - } else if len(resp) > 1 { - // TODO figure out why this happens, and be more precise about deleting things where created. - // t.Errorf("DeleteTestParameter params for %+v %+v expected 1, actual %+v", pl.Name, pl.ConfigFile, len(resp)) - } - for _, respParameter := range resp { - delResp, _, err := TOSession.DeleteParameterByID(respParameter.ID) - if err != nil { - t.Errorf("cannot DELETE Parameter by name: %v - %v", err, delResp) - } - - // Retrieve the Parameter to see if it got deleted - pls, _, err := TOSession.GetParameterByID(pl.ID) - if err != nil { - t.Errorf("error deleting Parameter name: %s", err.Error()) - } - if len(pls) > 0 { - t.Errorf("expected Parameter Name: %s and ConfigFile: %s to be deleted", pl.Name, pl.ConfigFile) - } - } -} diff --git a/traffic_ops/testing/api/v2/phys_locations_test.go b/traffic_ops/testing/api/v2/phys_locations_test.go deleted file mode 100644 index ca34954ffc..0000000000 --- a/traffic_ops/testing/api/v2/phys_locations_test.go +++ /dev/null @@ -1,137 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "sort" - "testing" - - tc "github.com/apache/trafficcontrol/lib/go-tc" -) - -func TestPhysLocations(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Parameters, Divisions, Regions, PhysLocations}, func() { - GetDefaultSortPhysLocationsTest(t) - GetSortPhysLocationsTest(t) - UpdateTestPhysLocations(t) - GetTestPhysLocations(t) - }) -} - -func CreateTestPhysLocations(t *testing.T) { - for _, pl := range testData.PhysLocations { - resp, _, err := TOSession.CreatePhysLocation(pl) - t.Log("Response: ", resp) - if err != nil { - t.Errorf("could not CREATE physlocations: %v", err) - } - } - -} - -func UpdateTestPhysLocations(t *testing.T) { - - firstPhysLocation := testData.PhysLocations[0] - // Retrieve the PhysLocation by name so we can get the id for the Update - resp, _, err := TOSession.GetPhysLocationByName(firstPhysLocation.Name) - if err != nil { - t.Errorf("cannot GET PhysLocation by name: '%s', %v", firstPhysLocation.Name, err) - } - remotePhysLocation := resp[0] - expectedPhysLocationCity := "city1" - remotePhysLocation.City = expectedPhysLocationCity - var alert tc.Alerts - alert, _, err = TOSession.UpdatePhysLocationByID(remotePhysLocation.ID, remotePhysLocation) - if err != nil { - t.Errorf("cannot UPDATE PhysLocation by id: %v - %v", err, alert) - } - - // Retrieve the PhysLocation to check PhysLocation name got updated - resp, _, err = TOSession.GetPhysLocationByID(remotePhysLocation.ID) - if err != nil { - t.Errorf("cannot GET PhysLocation by name: '$%s', %v", firstPhysLocation.Name, err) - } - respPhysLocation := resp[0] - if respPhysLocation.City != expectedPhysLocationCity { - t.Errorf("results do not match actual: %s, expected: %s", respPhysLocation.City, expectedPhysLocationCity) - } - -} - -func GetTestPhysLocations(t *testing.T) { - - for _, cdn := range testData.PhysLocations { - resp, _, err := TOSession.GetPhysLocationByName(cdn.Name) - if err != nil { - t.Errorf("cannot GET PhysLocation by name: %v - %v", err, resp) - } - } - -} - -func GetSortPhysLocationsTest(t *testing.T) { - resp, _, err := TOSession.GetPhysLocations(map[string]string{"orderby": "id"}) - if err != nil { - t.Error(err.Error()) - } - sorted := sort.SliceIsSorted(resp, func(i, j int) bool { - return resp[i].ID < resp[j].ID - }) - if !sorted { - t.Error("expected response to be sorted by id") - } -} - -func GetDefaultSortPhysLocationsTest(t *testing.T) { - resp, _, err := TOSession.GetPhysLocations(nil) - if err != nil { - t.Error(err.Error()) - } - sorted := sort.SliceIsSorted(resp, func(i, j int) bool { - return resp[i].Name < resp[j].Name - }) - if !sorted { - t.Error("expected response to be sorted by name") - } -} - -func DeleteTestPhysLocations(t *testing.T) { - - for _, cdn := range testData.PhysLocations { - // Retrieve the PhysLocation by name so we can get the id for the Update - resp, _, err := TOSession.GetPhysLocationByName(cdn.Name) - if err != nil { - t.Errorf("cannot GET PhysLocation by name: %v - %v", cdn.Name, err) - } - if len(resp) > 0 { - respPhysLocation := resp[0] - - _, _, err := TOSession.DeletePhysLocationByID(respPhysLocation.ID) - if err != nil { - t.Errorf("cannot DELETE PhysLocation by name: '%s' %v", respPhysLocation.Name, err) - } - - // Retrieve the PhysLocation to see if it got deleted - cdns, _, err := TOSession.GetPhysLocationByName(cdn.Name) - if err != nil { - t.Errorf("error deleting PhysLocation name: %s", err.Error()) - } - if len(cdns) > 0 { - t.Errorf("expected PhysLocation name: %s to be deleted", cdn.Name) - } - } - } -} diff --git a/traffic_ops/testing/api/v2/ping_test.go b/traffic_ops/testing/api/v2/ping_test.go deleted file mode 100644 index b127c13815..0000000000 --- a/traffic_ops/testing/api/v2/ping_test.go +++ /dev/null @@ -1,32 +0,0 @@ -package v2 - -/* - - Licensed 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 TestPing(t *testing.T) { - _, _, err := TOSession.Ping() - if err != nil { - t.Errorf("could not Ping authenticated: %v", err) - } - - _, _, err = NoAuthTOSession.Ping() - if err != nil { - t.Errorf("could not Ping unauthenticated: %v", err) - } -} diff --git a/traffic_ops/testing/api/v2/profile_parameters_test.go b/traffic_ops/testing/api/v2/profile_parameters_test.go deleted file mode 100644 index 64de588c9d..0000000000 --- a/traffic_ops/testing/api/v2/profile_parameters_test.go +++ /dev/null @@ -1,121 +0,0 @@ -/* - - Licensed 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. -*/ - -package v2 - -import ( - "fmt" - "sync" - "testing" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const queryParamFormat = "?profileId=%d¶meterId=%d" - -func TestProfileParameters(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Parameters, Profiles, ProfileParameters}, func() { - GetTestProfileParameters(t) - }) -} - -func CreateTestProfileParameters(t *testing.T) { - - firstProfile := testData.Profiles[0] - profileResp, _, err := TOSession.GetProfileByName(firstProfile.Name) - if err != nil { - t.Errorf("cannot GET Profile by name: %v - %v", firstProfile.Name, err) - } - - firstParameter := testData.Parameters[0] - paramResp, _, err := TOSession.GetParameterByName(firstParameter.Name) - if err != nil { - t.Errorf("cannot GET Parameter by name: %v - %v", firstParameter.Name, err) - } - - profileID := profileResp[0].ID - parameterID := paramResp[0].ID - - pp := tc.ProfileParameter{ - ProfileID: profileID, - ParameterID: parameterID, - } - resp, _, err := TOSession.CreateProfileParameter(pp) - t.Log("Response: ", resp) - if err != nil { - t.Errorf("could not CREATE profile parameters: %v", err) - } - -} - -func GetTestProfileParameters(t *testing.T) { - - for _, pp := range testData.ProfileParameters { - queryParams := fmt.Sprintf(queryParamFormat, pp.ProfileID, pp.ParameterID) - resp, _, err := TOSession.GetProfileParameterByQueryParams(queryParams) - if err != nil { - t.Errorf("cannot GET Parameter by name: %v - %v", err, resp) - } - } -} - -func DeleteTestProfileParametersParallel(t *testing.T) { - - var wg sync.WaitGroup - for _, pp := range testData.ProfileParameters { - - wg.Add(1) - go func(p tc.ProfileParameter) { - defer wg.Done() - DeleteTestProfileParameter(t, p) - }(pp) - - } - wg.Wait() -} - -func DeleteTestProfileParameters(t *testing.T) { - - for _, pp := range testData.ProfileParameters { - DeleteTestProfileParameter(t, pp) - } -} - -func DeleteTestProfileParameter(t *testing.T, pp tc.ProfileParameter) { - - queryParams := fmt.Sprintf(queryParamFormat, pp.ProfileID, pp.ParameterID) - // Retrieve the PtofileParameter by profile so we can get the id for the Update - resp, _, err := TOSession.GetProfileParameterByQueryParams(queryParams) - if err != nil { - t.Errorf("cannot GET Parameter by profile: %v - %v", pp.Profile, err) - } - if len(resp) > 0 { - respPP := resp[0] - - delResp, _, err := TOSession.DeleteParameterByProfileParameter(respPP.ProfileID, respPP.ParameterID) - if err != nil { - t.Errorf("cannot DELETE Parameter by profile: %v - %v", err, delResp) - } - - // Retrieve the Parameter to see if it got deleted - pps, _, err := TOSession.GetProfileParameterByQueryParams(queryParams) - if err != nil { - t.Errorf("error deleting Parameter name: %s", err.Error()) - } - if len(pps) > 0 { - t.Errorf("expected Parameter Name: %s and ConfigFile: %s to be deleted", pp.Profile, pp.Parameter) - } - } -} diff --git a/traffic_ops/testing/api/v2/profiles_test.go b/traffic_ops/testing/api/v2/profiles_test.go deleted file mode 100644 index 5305c018ff..0000000000 --- a/traffic_ops/testing/api/v2/profiles_test.go +++ /dev/null @@ -1,390 +0,0 @@ -/* - - Licensed 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. -*/ - -package v2 - -import ( - "strings" - "testing" - - tc "github.com/apache/trafficcontrol/lib/go-tc" - "github.com/apache/trafficcontrol/lib/go-util" -) - -func TestProfiles(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Profiles, Parameters}, func() { - CreateBadProfiles(t) - UpdateTestProfiles(t) - GetTestProfiles(t) - GetTestProfilesWithParameters(t) - ImportProfile(t) - CopyProfile(t) - }) -} - -// CreateBadProfiles ensures that profiles can't be created with bad values -func CreateBadProfiles(t *testing.T) { - - // blank profile - prs := []tc.Profile{ - {Type: "", Name: "", Description: "", CDNID: 0}, - {Type: tc.CacheServerProfileType, Name: "badprofile", Description: "description", CDNID: 0}, - {Type: tc.CacheServerProfileType, Name: "badprofile", Description: "", CDNID: 1}, - {Type: tc.CacheServerProfileType, Name: "", Description: "description", CDNID: 1}, - {Type: "", Name: "badprofile", Description: "description", CDNID: 1}, - } - - for _, pr := range prs { - resp, _, err := TOSession.CreateProfile(pr) - - if err == nil { - t.Errorf("Creating bad profile succeeded: %+v\nResponse is %+v", pr, resp) - } - } -} - -func CopyProfile(t *testing.T) { - testCases := []struct { - description string - profile tc.ProfileCopy - expectedResp string - err string - }{ - { - description: "copy profile", - profile: tc.ProfileCopy{ - Name: "profile-2", - ExistingName: "EDGE1", - }, - expectedResp: "created new profile [profile-2] from existing profile [EDGE1]", - }, - { - description: "existing profile does not exist", - profile: tc.ProfileCopy{ - Name: "profile-3", - ExistingName: "bogus", - }, - err: "profile with name bogus does not exist", - }, - { - description: "new profile already exists", - profile: tc.ProfileCopy{ - Name: "EDGE2", - ExistingName: "EDGE1", - }, - err: "profile with name EDGE2 already exists", - }, - } - - var newProfileNames []string - for _, c := range testCases { - t.Run(c.description, func(t *testing.T) { - resp, _, err := TOSession.CopyProfile(c.profile) - if c.err != "" { - if err != nil && !strings.Contains(err.Error(), c.err) { - t.Fatalf("got err= %s; expected err= %s", err, c.err) - } - } else if err != nil { - t.Fatalf("got err= %s; expected err= nil", err) - } - - if err == nil { - if got, want := resp.Alerts.ToStrings()[0], c.expectedResp; got != want { - t.Fatalf("got= %s; expected= %s", got, want) - } - - newProfileNames = append(newProfileNames, c.profile.Name) - } - }) - } - - // Cleanup profiles - for _, name := range newProfileNames { - profiles, _, err := TOSession.GetProfileByName(name) - if err != nil { - t.Fatalf("got err= %s; expected err= nil", err) - } - if len(profiles) == 0 { - t.Errorf("could not GET profile %+v: not found", name) - } - _, _, err = TOSession.DeleteProfileByID(profiles[0].ID) - if err != nil { - t.Fatalf("got err= %s; expected err= nil", err) - } - } -} - -func CreateTestProfiles(t *testing.T) { - - for _, pr := range testData.Profiles { - resp, _, err := TOSession.CreateProfile(pr) - - t.Log("Response: ", resp) - if err != nil { - t.Errorf("could not CREATE profiles with name: %s %v", pr.Name, err) - } - profiles, _, err := TOSession.GetProfileByName(pr.Name) - if err != nil { - t.Errorf("could not GET profile with name: %s %v", pr.Name, err) - } - if len(profiles) == 0 { - t.Errorf("could not GET profile %+v: not found", pr) - } - profileID := profiles[0].ID - - for _, param := range pr.Parameters { - if param.Name == nil || param.Value == nil || param.ConfigFile == nil { - t.Errorf("invalid parameter specification: %+v", param) - continue - } - _, _, err := TOSession.CreateParameter(tc.Parameter{Name: *param.Name, Value: *param.Value, ConfigFile: *param.ConfigFile}) - if err != nil { - // ok if already exists - if !strings.Contains(err.Error(), "already exists") { - t.Errorf("could not CREATE parameter %+v: %s", param, err.Error()) - continue - } - } - p, _, err := TOSession.GetParameterByNameAndConfigFileAndValue(*param.Name, *param.ConfigFile, *param.Value) - if err != nil { - t.Errorf("could not GET parameter %+v: %s", param, err.Error()) - } - if len(p) == 0 { - t.Errorf("could not GET parameter %+v: not found", param) - } - _, _, err = TOSession.CreateProfileParameter(tc.ProfileParameter{ProfileID: profileID, ParameterID: p[0].ID}) - if err != nil { - t.Errorf("could not CREATE profile_parameter %+v: %s", param, err.Error()) - } - } - - } -} - -func UpdateTestProfiles(t *testing.T) { - - firstProfile := testData.Profiles[0] - // Retrieve the Profile by name so we can get the id for the Update - resp, _, err := TOSession.GetProfileByName(firstProfile.Name) - if err != nil { - t.Errorf("cannot GET Profile by name: %v - %v", firstProfile.Name, err) - } - remoteProfile := resp[0] - expectedProfileDesc := "UPDATED" - remoteProfile.Description = expectedProfileDesc - var alert tc.Alerts - alert, _, err = TOSession.UpdateProfileByID(remoteProfile.ID, remoteProfile) - if err != nil { - t.Errorf("cannot UPDATE Profile by id: %v - %v", err, alert) - } - - // Retrieve the Profile to check Profile name got updated - resp, _, err = TOSession.GetProfileByID(remoteProfile.ID) - if err != nil { - t.Errorf("cannot GET Profile by name: %v - %v", firstProfile.Name, err) - } - respProfile := resp[0] - if respProfile.Description != expectedProfileDesc { - t.Errorf("results do not match actual: %s, expected: %s", respProfile.Description, expectedProfileDesc) - } - -} - -func GetTestProfiles(t *testing.T) { - - for _, pr := range testData.Profiles { - resp, _, err := TOSession.GetProfileByName(pr.Name) - if err != nil { - t.Errorf("cannot GET Profile by name: %v - %v", err, resp) - } - profileID := resp[0].ID - if len(pr.Parameters) > 0 { - parameter := pr.Parameters[0] - respParameter, _, err := TOSession.GetParameterByName(*parameter.Name) - if err != nil { - t.Errorf("Cannot GET Parameter by name: %v", err) - } - if len(respParameter) > 0 { - parameterID := respParameter[0].ID - if parameterID > 0 { - resp, _, err = TOSession.GetProfileByParameterId(parameterID) - if err != nil { - t.Errorf("cannot GET Profile by param: %v", err) - } - if len(resp) < 1 { - t.Errorf("Expected atleast one response for Get Profile by Parameters, but found %d", len(resp)) - } - } else { - t.Errorf("Invalid parameter ID %d", parameterID) - } - } else { - t.Errorf("No response found for GET Parameters by name") - } - } - resp, _, err = TOSession.GetProfileByCDNID(pr.CDNID) - if err != nil { - t.Errorf("cannot GET Profile by cdn: %v - %v", err, resp) - } - - // Export Profile - exportResp, _, err := TOSession.ExportProfile(profileID) - if err != nil { - t.Errorf("error exporting Profile: %v - %v", profileID, err) - } - if exportResp == nil { - t.Error("error exporting Profile: response nil") - } - } -} - -func ImportProfile(t *testing.T) { - // Get ID of Profile to export - resp, _, err := TOSession.GetProfileByName(testData.Profiles[0].Name) - if err != nil { - t.Fatalf("cannot GET Profile by name: %v - %v", err, resp) - } - if resp == nil { - t.Fatal("error getting Profile: response nil") - } - if len(resp) != 1 { - t.Fatalf("Profiles expected 1, actual %v", len(resp)) - } - profileID := resp[0].ID - - // Export Profile to import - exportResp, _, err := TOSession.ExportProfile(profileID) - if err != nil { - t.Fatalf("error exporting Profile: %v - %v", profileID, err) - } - if exportResp == nil { - t.Fatal("error exporting Profile: response nil") - } - - // Modify Profile and import - - // Add parameter and change name - profile := exportResp.Profile - profile.Name = util.StrPtr("TestProfileImport") - - newParam := tc.ProfileExportImportParameterNullable{ - ConfigFile: util.StrPtr("config_file_import_test"), - Name: util.StrPtr("param_import_test"), - Value: util.StrPtr("import_test"), - } - parameters := append(exportResp.Parameters, newParam) - // Import Profile - importReq := tc.ProfileImportRequest{ - Profile: profile, - Parameters: parameters, - } - importResp, _, err := TOSession.ImportProfile(&importReq) - if err != nil { - t.Fatalf("error importing Profile: %v - %v", profileID, err) - } - if importResp == nil { - t.Error("error importing Profile: response nil") - } - - // Add newly create profile and parameter to testData so it gets deleted - testData.Profiles = append(testData.Profiles, tc.Profile{ - Name: *profile.Name, - CDNName: *profile.CDNName, - Description: *profile.Description, - Type: *profile.Type, - }) - - testData.Parameters = append(testData.Parameters, tc.Parameter{ - ConfigFile: *newParam.ConfigFile, - Name: *newParam.Name, - Value: *newParam.Value, - }) -} - -func GetTestProfilesWithParameters(t *testing.T) { - firstProfile := testData.Profiles[0] - resp, _, err := TOSession.GetProfileByName(firstProfile.Name) - if err != nil { - t.Errorf("cannot GET Profile by name: %v - %v", err, resp) - return - } - if len(resp) == 0 { - t.Errorf("cannot GET Profile by name: not found - %v", resp) - return - } - respProfile := resp[0] - // query by name does not retrieve associated parameters. But query by id does. - resp, _, err = TOSession.GetProfileByID(respProfile.ID) - if err != nil { - t.Errorf("cannot GET Profile by name: %v - %v", err, resp) - } - if len(resp) > 0 { - respProfile = resp[0] - respParameters := respProfile.Parameters - if len(respParameters) == 0 { - t.Errorf("expected a profile with parameters to be retrieved: %v - %v", err, respParameters) - } - } -} - -func DeleteTestProfiles(t *testing.T) { - - for _, pr := range testData.Profiles { - // Retrieve the Profile by name so we can get the id for the Update - resp, _, err := TOSession.GetProfileByName(pr.Name) - if err != nil { - t.Errorf("cannot GET Profile by name: %s - %v", pr.Name, err) - continue - } - if len(resp) == 0 { - t.Errorf("cannot GET Profile by name: not found - %s", pr.Name) - continue - } - - profileID := resp[0].ID - // query by name does not retrieve associated parameters. But query by id does. - resp, _, err = TOSession.GetProfileByID(profileID) - if err != nil { - t.Errorf("cannot GET Profile by id: %v - %v", err, resp) - } - // delete any profile_parameter associations first - // the parameter is what's being deleted, but the delete is cascaded to profile_parameter - for _, param := range resp[0].Parameters { - _, _, err := TOSession.DeleteParameterByID(*param.ID) - if err != nil { - t.Errorf("cannot DELETE parameter with parameterID %d: %s", *param.ID, err.Error()) - } - } - delResp, _, err := TOSession.DeleteProfileByID(profileID) - if err != nil { - t.Errorf("cannot DELETE Profile by name: %v - %v", err, delResp) - } - //time.Sleep(1 * time.Second) - - // Retrieve the Profile to see if it got deleted - prs, _, err := TOSession.GetProfileByName(pr.Name) - if err != nil { - t.Errorf("error deleting Profile name: %s", err.Error()) - } - if len(prs) > 0 { - t.Errorf("expected Profile Name: %s to be deleted", pr.Name) - } - - // Attempt to export Profile - profile, _, err := TOSession.ExportProfile(profileID) - if profile != nil { - t.Errorf("expected Profile: %s to be nil on export", pr.Name) - } - } -} diff --git a/traffic_ops/testing/api/v2/readonlycannotmodify_test.go b/traffic_ops/testing/api/v2/readonlycannotmodify_test.go deleted file mode 100644 index 4be277fcb8..0000000000 --- a/traffic_ops/testing/api/v2/readonlycannotmodify_test.go +++ /dev/null @@ -1,69 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "strings" - "testing" - "time" - - "github.com/apache/trafficcontrol/lib/go-tc" - toclient "github.com/apache/trafficcontrol/traffic_ops/v2-client" -) - -func TestReadOnlyCannotModify(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Tenants, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, DeliveryServices, Users}, func() { - CreateTestCDNWithReadOnlyUser(t) - }) -} - -func CreateTestCDNWithReadOnlyUser(t *testing.T) { - if len(testData.CDNs) == 0 { - t.Fatal("Can't test readonly user creating a cdns: test data has no cdns") - } - - toReqTimeout := time.Second * time.Duration(Config.Default.Session.TimeoutInSecs) - readonlyTOClient, _, err := toclient.LoginWithAgent(TOSession.URL, "readonlyuser", "pa$$word", true, "to-api-v2-client-tests/readonlyuser", true, toReqTimeout) - if err != nil { - t.Fatalf("failed to get log in with readonlyuser: " + err.Error()) - } - - cdn := tc.CDN{ - Name: "cdn-test-readonly-create-failure", - DomainName: "createfailure.invalid", - } - - alerts, _, err := readonlyTOClient.CreateCDN(cdn) - - if err == nil { - t.Error("readonlyuser creating cdn error expected: not nil, actual: nil error") - } - - if !strings.Contains(strings.ToLower(err.Error()), "forbidden") { - t.Errorf("readonlyuser creating cdn error expected: contains 'forbidden', actual: '" + err.Error() + "'") - } - - for _, alert := range alerts.Alerts { - if alert.Level == tc.SuccessLevel.String() { - t.Errorf("readonlyuser creating cdn, alerts expected: no success alert, actual: got success alert '" + alert.Text + "'") - } - } - - cdns, _, _ := TOSession.GetCDNByName(cdn.Name) - if len(cdns) > 0 { - t.Errorf("readonlyuser getting created cdn, len(cdns) expected: 0, actual: %+v %+v", len(cdns), cdns) - } -} diff --git a/traffic_ops/testing/api/v2/regions_test.go b/traffic_ops/testing/api/v2/regions_test.go deleted file mode 100644 index 23aa66d53d..0000000000 --- a/traffic_ops/testing/api/v2/regions_test.go +++ /dev/null @@ -1,115 +0,0 @@ -package v2 - -/* - - Licensed 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" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -func TestRegions(t *testing.T) { - WithObjs(t, []TCObj{Parameters, Divisions, Regions}, func() { - UpdateTestRegions(t) - GetTestRegions(t) - }) -} - -func CreateTestRegions(t *testing.T) { - - for _, region := range testData.Regions { - resp, _, err := TOSession.CreateRegion(region) - t.Log("Response: ", resp) - if err != nil { - t.Errorf("could not CREATE region: %v", err) - } - } -} - -func UpdateTestRegions(t *testing.T) { - - firstRegion := testData.Regions[0] - // Retrieve the Region by region so we can get the id for the Update - resp, _, err := TOSession.GetRegionByName(firstRegion.Name) - if err != nil { - t.Errorf("cannot GET Region by region: %v - %v", firstRegion.Name, err) - } - remoteRegion := resp[0] - expectedRegion := "OFFLINE-TEST" - remoteRegion.Name = expectedRegion - var alert tc.Alerts - alert, _, err = TOSession.UpdateRegionByID(remoteRegion.ID, remoteRegion) - if err != nil { - t.Errorf("cannot UPDATE Region by id: %v - %v", err, alert) - } - - // Retrieve the Region to check region got updated - resp, _, err = TOSession.GetRegionByID(remoteRegion.ID) - if err != nil { - t.Errorf("cannot GET Region by region: %v - %v", firstRegion.Name, err) - } - respRegion := resp[0] - if respRegion.Name != expectedRegion { - t.Errorf("results do not match actual: %s, expected: %s", respRegion.Name, expectedRegion) - } - - // Set the name back to the fixture value so we can delete it after - remoteRegion.Name = firstRegion.Name - alert, _, err = TOSession.UpdateRegionByID(remoteRegion.ID, remoteRegion) - if err != nil { - t.Errorf("cannot UPDATE Region by id: %v - %v", err, alert) - } - -} - -func GetTestRegions(t *testing.T) { - for _, region := range testData.Regions { - resp, _, err := TOSession.GetRegionByName(region.Name) - if err != nil { - t.Errorf("cannot GET Region by region: %v - %v", err, resp) - } - } -} - -func DeleteTestRegions(t *testing.T) { - - for _, region := range testData.Regions { - // Retrieve the Region by name so we can get the id - resp, _, err := TOSession.GetRegionByName(region.Name) - if err != nil { - t.Errorf("cannot GET Region by name: %v - %v", region.Name, err) - } - if len(resp) != 1 { - t.Errorf("Expected exactly one Region to exist with name '%s', found: %d", region.Name, len(resp)) - continue - } - respRegion := resp[0] - - delResp, _, err := TOSession.DeleteRegionByID(respRegion.ID) - if err != nil { - t.Errorf("cannot DELETE Region by region: %v - %v", err, delResp) - } - - // Retrieve the Region to see if it got deleted - regionResp, _, err := TOSession.GetRegionByName(region.Name) - if err != nil { - t.Errorf("error deleting Region region: %s", err.Error()) - } - if len(regionResp) > 0 { - t.Errorf("expected Region : %s to be deleted", region.Name) - } - } -} diff --git a/traffic_ops/testing/api/v2/roles_test.go b/traffic_ops/testing/api/v2/roles_test.go deleted file mode 100644 index 4576f7e99a..0000000000 --- a/traffic_ops/testing/api/v2/roles_test.go +++ /dev/null @@ -1,167 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "reflect" - "testing" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - roleGood = 0 - roleInvalidCap = 1 - roleNeedCap = 2 - roleBadPrivLevel = 3 -) - -func TestRoles(t *testing.T) { - WithObjs(t, []TCObj{Roles}, func() { - UpdateTestRoles(t) - GetTestRoles(t) - VerifyGetRolesOrder(t) - }) -} - -func CreateTestRoles(t *testing.T) { - expectedAlerts := []tc.Alerts{tc.Alerts{Alerts: []tc.Alert{tc.Alert{Text: "role was created.", Level: "success"}}}, tc.Alerts{Alerts: []tc.Alert{tc.Alert{Text: "can not add non-existent capabilities: [invalid-capability]", Level: "error"}}}, tc.Alerts{Alerts: []tc.Alert{tc.Alert{Text: "role was created.", Level: "success"}}}} - for i, role := range testData.Roles { - var alerts tc.Alerts - alerts, _, status, err := TOSession.CreateRole(role) - t.Log("Status Code: ", status) - t.Log("Response: ", alerts) - if err != nil { - t.Logf("error: %v", err) - //t.Errorf("could not CREATE role: %v", err) - } - if !reflect.DeepEqual(alerts, expectedAlerts[i]) { - t.Errorf("got alerts: %v but expected alerts: %v", alerts, expectedAlerts[i]) - } - } -} - -func UpdateTestRoles(t *testing.T) { - t.Logf("testData.Roles contains: %+v\n", testData.Roles) - firstRole := testData.Roles[0] - // Retrieve the Role by role so we can get the id for the Update - resp, _, status, err := TOSession.GetRoleByName(*firstRole.Name) - t.Log("Status Code: ", status) - if err != nil { - t.Errorf("cannot GET Role by role: %v - %v", firstRole.Name, err) - } - t.Logf("got response: %+v\n", resp) - remoteRole := resp[0] - expectedRole := "new admin2" - remoteRole.Name = &expectedRole - var alert tc.Alerts - alert, _, status, err = TOSession.UpdateRoleByID(*remoteRole.ID, remoteRole) - t.Log("Status Code: ", status) - if err != nil { - t.Errorf("cannot UPDATE Role by id: %v - %v", err, alert) - } - - // Retrieve the Role to check role got updated - resp, _, status, err = TOSession.GetRoleByID(*remoteRole.ID) - t.Log("Status Code: ", status) - if err != nil { - t.Errorf("cannot GET Role by role: %v - %v", firstRole.Name, err) - } - respRole := resp[0] - if *respRole.Name != expectedRole { - t.Errorf("results do not match actual: %s, expected: %s", *respRole.Name, expectedRole) - } - - // Set the name back to the fixture value so we can delete it after - remoteRole.Name = firstRole.Name - alert, _, status, err = TOSession.UpdateRoleByID(*remoteRole.ID, remoteRole) - t.Log("Status Code: ", status) - if err != nil { - t.Errorf("cannot UPDATE Role by id: %v - %v", err, alert) - } - -} - -func GetTestRoles(t *testing.T) { - role := testData.Roles[roleGood] - resp, _, status, err := TOSession.GetRoleByName(*role.Name) - t.Log("Status Code: ", status) - if err != nil { - t.Errorf("cannot GET Role by role: %v - %v", err, resp) - } - -} - -func VerifyGetRolesOrder(t *testing.T) { - params := map[string]string{ - "orderby": "name", - "sortOrder": "desc", - } - descResp, _, status, err := TOSession.GetRoleByQueryParams(params) - t.Log("Status Code: ", status) - if err != nil { - t.Errorf("cannot GET Role by role: %v - %v", err, descResp) - } - params["sortOrder"] = "asc" - ascResp, _, status, err := TOSession.GetRoleByQueryParams(params) - t.Log("Status Code: ", status) - if err != nil { - t.Errorf("cannot GET Role by role: %v - %v", err, ascResp) - } - - if reflect.DeepEqual(descResp, ascResp) { - t.Errorf("Role responses for descending and ascending are the same: %v - %v", descResp, ascResp) - } - - // reverse the descending-sorted response and compare it to the ascending-sorted one - for start, end := 0, len(descResp)-1; start < end; start, end = start+1, end-1 { - descResp[start], descResp[end] = descResp[end], descResp[start] - } - if !reflect.DeepEqual(descResp, ascResp) { - t.Errorf("Role responses are not equal after reversal: %v - %v", descResp, ascResp) - } -} - -func DeleteTestRoles(t *testing.T) { - - role := testData.Roles[roleGood] - // Retrieve the Role by name so we can get the id - resp, _, status, err := TOSession.GetRoleByName(*role.Name) - t.Log("Status Code: ", status) - if err != nil { - t.Errorf("cannot GET Role by name: %v - %v", role.Name, err) - } - respRole := resp[0] - - delResp, _, status, err := TOSession.DeleteRoleByID(*respRole.ID) - t.Log("Status Code: ", status) - - if err != nil { - t.Errorf("cannot DELETE Role by role: %v - %v", err, delResp) - } - - // Retrieve the Role to see if it got deleted - roleResp, _, status, err := TOSession.GetRoleByName(*role.Name) - t.Log("Status Code: ", status) - - if err != nil { - t.Errorf("error deleting Role role: %s", err.Error()) - } - if len(roleResp) > 0 { - t.Errorf("expected Role : %s to be deleted", *role.Name) - } - -} diff --git a/traffic_ops/testing/api/v2/servercapabilities_test.go b/traffic_ops/testing/api/v2/servercapabilities_test.go deleted file mode 100644 index d3853575ef..0000000000 --- a/traffic_ops/testing/api/v2/servercapabilities_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package v2 - -/* - - Licensed 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" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -func TestServerCapabilities(t *testing.T) { - WithObjs(t, []TCObj{ServerCapabilities}, func() { - GetTestServerCapabilities(t) - ValidationTestServerCapabilities(t) - }) -} - -func CreateTestServerCapabilities(t *testing.T) { - - for _, sc := range testData.ServerCapabilities { - resp, _, err := TOSession.CreateServerCapability(sc) - if err != nil { - t.Errorf("could not CREATE server capability: %v", err) - } - t.Log("Response: ", resp) - } - -} - -func GetTestServerCapabilities(t *testing.T) { - - for _, sc := range testData.ServerCapabilities { - resp, _, err := TOSession.GetServerCapability(sc.Name) - if err != nil { - t.Errorf("cannot GET server capability: %v - %v", err, resp) - } else if resp == nil { - t.Error("GET server capability expected non-nil response") - } - } - - resp, _, err := TOSession.GetServerCapabilities() - if err != nil { - t.Errorf("cannot GET server capabilities: %v", err) - } - if len(resp) != len(testData.ServerCapabilities) { - t.Errorf("expected to GET %d server capabilities, actual: %d", len(testData.ServerCapabilities), len(resp)) - } -} - -func ValidationTestServerCapabilities(t *testing.T) { - _, _, err := TOSession.CreateServerCapability(tc.ServerCapability{Name: "b@dname"}) - if err == nil { - t.Error("expected POST with invalid name to return an error, actual: nil") - } -} - -func DeleteTestServerCapabilities(t *testing.T) { - - for _, sc := range testData.ServerCapabilities { - delResp, _, err := TOSession.DeleteServerCapability(sc.Name) - if err != nil { - t.Errorf("cannot DELETE server capability: %v - %v", err, delResp) - } - - serverCapability, _, err := TOSession.GetServerCapability(sc.Name) - if err == nil { - t.Errorf("expected error trying to GET deleted server capability: %s, actual: nil", sc.Name) - } - if serverCapability != nil { - t.Errorf("expected nil trying to GET deleted server capability: %s, actual: non-nil", sc.Name) - } - } -} diff --git a/traffic_ops/testing/api/v2/servercheckextension_test.go b/traffic_ops/testing/api/v2/servercheckextension_test.go deleted file mode 100644 index 7b1e4ffd3f..0000000000 --- a/traffic_ops/testing/api/v2/servercheckextension_test.go +++ /dev/null @@ -1,132 +0,0 @@ -package v2 - -/* - - Licensed 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" - "time" - - "github.com/apache/trafficcontrol/lib/go-tc" - "github.com/apache/trafficcontrol/lib/go-util" -) - -var ( - toReqTimeout = time.Second * time.Duration(Config.Default.Session.TimeoutInSecs) -) - -func TestServerCheckExtensions(t *testing.T) { - WithObjs(t, []TCObj{ServerCheckExtensions}, func() { - CreateTestInvalidServerCheckExtensions(t) - }) -} - -func CreateTestServerCheckExtensions(t *testing.T) { - SwitchSession(toReqTimeout, Config.TrafficOps.URL, Config.TrafficOps.Users.Admin, Config.TrafficOps.UserPassword, Config.TrafficOps.Users.Extension, Config.TrafficOps.UserPassword) - - for _, ext := range testData.ServerCheckExtensions { - resp, _, err := TOSession.CreateServerCheckExtension(ext) - t.Logf("Response: %v %v", *ext.Name, resp) - if err != nil { - t.Errorf("could not create to_extension %v: %v", ext.Name, err) - } - } - - SwitchSession(toReqTimeout, Config.TrafficOps.URL, Config.TrafficOps.Users.Extension, Config.TrafficOps.UserPassword, Config.TrafficOps.Users.Admin, Config.TrafficOps.UserPassword) -} - -func CreateTestInvalidServerCheckExtensions(t *testing.T) { - // Fail Attempt to Create ServerCheckExtension as non extension user - _, _, err := TOSession.CreateServerCheckExtension(testData.ServerCheckExtensions[0]) - if err == nil { - t.Error("expected to receive error with non extension user") - } - - SwitchSession(toReqTimeout, Config.TrafficOps.URL, Config.TrafficOps.Users.Admin, Config.TrafficOps.UserPassword, Config.TrafficOps.Users.Extension, Config.TrafficOps.UserPassword) - - // Attempt to create another valid ServerCheckExtension and it should fail as there is no open slots - toExt := tc.ServerCheckExtensionNullable{ - Name: util.StrPtr("MEM_CHECKER"), - Version: util.StrPtr("3.0.3"), - InfoURL: util.StrPtr("-"), - ScriptFile: util.StrPtr("mem.py"), - ServercheckShortName: util.StrPtr("MC"), - Type: util.StrPtr("CHECK_EXTENSION_MEM"), - } - _, _, err = TOSession.CreateServerCheckExtension(toExt) - if err == nil { - t.Error("expected to receive error with no open slots left") - } - - // Attempt to create a TO Extension with an invalid type - toExt.Type = util.StrPtr("INVALID_TYPE") - _, _, err = TOSession.CreateServerCheckExtension(toExt) - if err == nil { - t.Error("expected to receive error with invalid TO extension type") - } - SwitchSession(toReqTimeout, Config.TrafficOps.URL, Config.TrafficOps.Users.Extension, Config.TrafficOps.UserPassword, Config.TrafficOps.Users.Admin, Config.TrafficOps.UserPassword) - -} - -func DeleteTestServerCheckExtensions(t *testing.T) { - SwitchSession(toReqTimeout, Config.TrafficOps.URL, Config.TrafficOps.Users.Admin, Config.TrafficOps.UserPassword, Config.TrafficOps.Users.Extension, Config.TrafficOps.UserPassword) - - extensions, _, err := TOSession.GetServerCheckExtensions() - if err != nil { - t.Fatalf("could not get to_extensions: %v", err) - } - - ids := []int{} - for _, ext := range testData.ServerCheckExtensions { - found := false - for _, respTOExt := range extensions.Response { - if *ext.Name == *respTOExt.Name { - ids = append(ids, *respTOExt.ID) - found = true - continue - } - } - if !found { - t.Errorf("expected to find to_extension %v", *ext.Name) - } - } - - for _, id := range ids { - resp, _, err := TOSession.DeleteServerCheckExtension(id) - t.Logf("Response: %v %v", id, resp) - if err != nil { - t.Errorf("cannot delete to_extension: %v - %v", id, err) - } - } - extensions, _, err = TOSession.GetServerCheckExtensions() - if err != nil { - t.Fatalf("could not get to_extensions: %v", err) - } - - for _, ext := range testData.ServerCheckExtensions { - found := false - for _, respTOExt := range extensions.Response { - if *ext.Name == *respTOExt.Name { - found = true - continue - } - } - if found { - t.Errorf("to_extension %v should have been deleted", *ext.Name) - } - } - - SwitchSession(toReqTimeout, Config.TrafficOps.URL, Config.TrafficOps.Users.Extension, Config.TrafficOps.UserPassword, Config.TrafficOps.Users.Admin, Config.TrafficOps.UserPassword) -} diff --git a/traffic_ops/testing/api/v2/serverchecks_test.go b/traffic_ops/testing/api/v2/serverchecks_test.go deleted file mode 100644 index c376860211..0000000000 --- a/traffic_ops/testing/api/v2/serverchecks_test.go +++ /dev/null @@ -1,145 +0,0 @@ -package v2 - -/* - - Licensed 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" - "time" - - "github.com/apache/trafficcontrol/lib/go-tc" - "github.com/apache/trafficcontrol/lib/go-util" -) - -func TestServerChecks(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, Servers, ServerCheckExtensions, ServerChecks}, func() { - CreateTestInvalidServerChecks(t) - UpdateTestServerChecks(t) - GetTestServerChecks(t) - }) -} - -func CreateTestServerChecks(t *testing.T) { - SwitchSession(toReqTimeout, Config.TrafficOps.URL, Config.TrafficOps.Users.Admin, Config.TrafficOps.UserPassword, Config.TrafficOps.Users.Extension, Config.TrafficOps.UserPassword) - - for _, servercheck := range testData.Serverchecks { - resp, _, err := TOSession.InsertServerCheckStatus(servercheck) - t.Logf("Response: %v host_name %v check %v", *servercheck.HostName, *servercheck.Name, resp) - if err != nil { - t.Errorf("could not CREATE servercheck: %v", err) - } - } - SwitchSession(toReqTimeout, Config.TrafficOps.URL, Config.TrafficOps.Users.Extension, Config.TrafficOps.UserPassword, Config.TrafficOps.Users.Admin, Config.TrafficOps.UserPassword) -} - -func CreateTestInvalidServerChecks(t *testing.T) { - toReqTimeout := time.Second * time.Duration(Config.Default.Session.TimeoutInSecs) - - _, _, err := TOSession.InsertServerCheckStatus(testData.Serverchecks[0]) - if err == nil { - t.Error("expected to receive error with non extension user") - } - - SwitchSession(toReqTimeout, Config.TrafficOps.URL, Config.TrafficOps.Users.Admin, Config.TrafficOps.UserPassword, Config.TrafficOps.Users.Extension, Config.TrafficOps.UserPassword) - - invalidServerCheck := tc.ServercheckRequestNullable{ - Name: util.StrPtr("BOGUS"), - Value: util.IntPtr(1), - ID: util.IntPtr(-1), - HostName: util.StrPtr("bogus_hostname"), - } - - // Attempt to create a ServerCheck with invalid server ID - _, _, err = TOSession.InsertServerCheckStatus(invalidServerCheck) - if err == nil { - t.Error("expected to receive error with invalid id") - } - - invalidServerCheck.ID = nil - // Attempt to create a ServerCheck with invalid host name - _, _, err = TOSession.InsertServerCheckStatus(invalidServerCheck) - if err == nil { - t.Error("expected to receive error with invalid host name") - } - - // get valid name to get past host check - invalidServerCheck.Name = testData.Serverchecks[0].Name - - // Attempt to create a ServerCheck with invalid servercheck name - _, _, err = TOSession.InsertServerCheckStatus(invalidServerCheck) - if err == nil { - t.Error("expected to receive error with invalid servercheck name") - } - SwitchSession(toReqTimeout, Config.TrafficOps.URL, Config.TrafficOps.Users.Extension, Config.TrafficOps.UserPassword, Config.TrafficOps.Users.Admin, Config.TrafficOps.UserPassword) -} - -func UpdateTestServerChecks(t *testing.T) { - SwitchSession(toReqTimeout, Config.TrafficOps.URL, Config.TrafficOps.Users.Admin, Config.TrafficOps.UserPassword, Config.TrafficOps.Users.Extension, Config.TrafficOps.UserPassword) - for _, servercheck := range testData.Serverchecks { - *servercheck.Value-- - resp, _, err := TOSession.InsertServerCheckStatus(servercheck) - t.Logf("Response: %v host_name %v check %v", *servercheck.HostName, *servercheck.Name, resp) - if err != nil { - t.Errorf("could not update servercheck: %v", err) - } - } - SwitchSession(toReqTimeout, Config.TrafficOps.URL, Config.TrafficOps.Users.Extension, Config.TrafficOps.UserPassword, Config.TrafficOps.Users.Admin, Config.TrafficOps.UserPassword) -} - -func GetTestServerChecks(t *testing.T) { - hostname := testData.Serverchecks[0].HostName - // Get server checks - serverChecksResp, alerts, _, err := TOSession.GetServersChecks() - if err != nil { - t.Fatalf("could not GET serverchecks: %v (alerts: %+v)", err, alerts) - } - found := false - for _, sc := range serverChecksResp { - if sc.HostName == *hostname { - found = true - - if sc.Checks == nil { - t.Errorf("server %s had no checks - expected it to have at least two", *hostname) - break - } - - if ort, ok := sc.Checks["ORT"]; !ok { - t.Error("no 'ORT' servercheck exists - expected it to exist") - } else if ort == nil { - t.Error("'null' returned for ORT value servercheck - expected pointer to 12") - } else if *ort != 12 { - t.Errorf("%v returned for ORT value servercheck - expected 12", *ort) - } - - if ilo, ok := sc.Checks["ILO"]; !ok { - t.Error("no 'ILO' servercheck exists - expected it to exist") - } else if ilo == nil { - t.Error("'null' returned for ILO value servercheck - expected pointer to 0") - } else if *ilo != 0 { - t.Errorf("%v returned for ILO value servercheck - expected 0", *ilo) - } - break - } - } - if !found { - t.Errorf("expected to find servercheck for host %v", hostname) - } -} - -// Need to define no-op function as TCObj interface expects a delete function -// There is no delete path for serverchecks -func DeleteTestServerChecks(t *testing.T) { - return -} diff --git a/traffic_ops/testing/api/v2/servers_test.go b/traffic_ops/testing/api/v2/servers_test.go deleted file mode 100644 index 4c23b17773..0000000000 --- a/traffic_ops/testing/api/v2/servers_test.go +++ /dev/null @@ -1,239 +0,0 @@ -package v2 - -/* - - Licensed 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" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -func TestServers(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Tenants, Users, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, DeliveryServices, Servers}, func() { - UpdateTestServers(t) - GetTestServers(t) - GetTestServersDetails(t) - }) -} - -func CreateTestServers(t *testing.T) { - - var name string - - // loop through servers, assign FKs and create - for _, server := range testData.Servers { - resp, _, err := TOSession.CreateServer(server) - t.Log("Response: ", server.HostName, " ", resp) - if err != nil { - t.Errorf("could not CREATE servers: %v", err) - } else { - name = server.HostName - } - } - - if name == "" { - t.Fatal("Failed to create at least one valid server to use as a template") - } - - servers, _, err := TOSession.GetServerByHostName(name) - if err != nil { - t.Fatalf("Failed to get server by hostname '%s': %v", name, err) - } - if len(servers) < 1 { - t.Fatalf("Failed to get at least one server by hostname '%s'", name) - } - - testServer := servers[0] - - testServer.DomainName = "test" - testServer.HostName = "test" - testServer.ID = 0 - testServer.IPIsService = true - testServer.IPAddress = "" - testServer.IP6IsService = false - testServer.IP6Address = "::1/64" - - if alerts, _, err := TOSession.CreateServer(testServer); err == nil { - t.Error("Didn't get expected error trying to create a server with a blank service address") - } else { - t.Logf("Received expected error creating a server with a blank service address: %v", err) - t.Logf("Alerts: %v", alerts) - } - -} - -func GetTestServers(t *testing.T) { - - for _, server := range testData.Servers { - resp, _, err := TOSession.GetServerByHostName(server.HostName) - if err != nil { - t.Errorf("cannot GET Server by name: %v - %v", err, resp) - } - } -} - -func GetTestServersDetails(t *testing.T) { - - for _, server := range testData.Servers { - resp, _, err := TOSession.GetServerDetailsByHostName(server.HostName) - if err != nil { - t.Errorf("cannot GET Server Details by name: %v - %v", err, resp) - } - } -} - -func UpdateTestServers(t *testing.T) { - - firstServer := testData.Servers[0] - hostName := firstServer.HostName - // Retrieve the server by hostname so we can get the id for the Update - resp, _, err := TOSession.GetServerByHostName(hostName) - - if err != nil { - t.Errorf("cannot GET Server by hostname: %v - %v", firstServer.HostName, err) - } - remoteServer := resp[0] - originalHostname := resp[0].HostName - originalXMPIDD := resp[0].XMPPID - updatedServerInterface := "bond1" - updatedServerRack := "RR 119.03" - updatedHostName := "atl-edge-01" - updatedXMPPID := "change-it" - - // update rack, interfaceName and hostName values on server - remoteServer.InterfaceName = updatedServerInterface - remoteServer.Rack = updatedServerRack - remoteServer.HostName = updatedHostName - - var alert tc.Alerts - alert, _, err = TOSession.UpdateServerByID(remoteServer.ID, remoteServer) - if err != nil { - t.Errorf("cannot UPDATE Server by hostname: %v - %v", err, alert) - } - - // Retrieve the server to check rack and interfaceName values were updated - resp, _, err = TOSession.GetServerByID(remoteServer.ID) - if err != nil { - t.Errorf("cannot GET Server by ID: %v - %v", remoteServer.HostName, err) - } - - respServer := resp[0] - if respServer.InterfaceName != updatedServerInterface || respServer.Rack != updatedServerRack { - t.Errorf("results do not match actual: %s, expected: %s", respServer.InterfaceName, updatedServerInterface) - t.Errorf("results do not match actual: %s, expected: %s", respServer.Rack, updatedServerRack) - } - - //Check change in hostname with no change to xmppid - if originalHostname == respServer.HostName && originalXMPIDD == respServer.XMPPID { - t.Errorf("HostName didn't change. Expected: #{updatedHostName}, actual: #{originalHostname}") - } - - //Check to verify XMPPID never gets updated - remoteServer.XMPPID = updatedXMPPID - al, _, err := TOSession.UpdateServerByID(remoteServer.ID, remoteServer) - t.Logf("Alerts from changing server XMPPID: %v", al) - if err == nil { - t.Error("Didn't get expected error changing server XMPPID") - } else { - t.Logf("Got expected error trying to change server XMPPID: %v", err) - } - - //Change back hostname and xmppid to its original name for other tests to pass - remoteServer.HostName = originalHostname - remoteServer.XMPPID = originalXMPIDD - alerts, _, err := TOSession.UpdateServerByID(remoteServer.ID, remoteServer) - if err != nil { - t.Fatalf("cannot UPDATE Server by ID %d (hostname '%s'): %v - %v", remoteServer.ID, hostName, err, alerts) - } - resp, _, err = TOSession.GetServerByID(remoteServer.ID) - if err != nil { - t.Errorf("cannot GET Server by hostName: %v - %v", originalHostname, err) - } - - // Assign server to DS and then attempt to update to a different type - dses, _, err := TOSession.GetDeliveryServicesNullable() - if err != nil { - t.Fatalf("cannot GET DeliveryServices: %v", err) - } - if len(dses) < 1 { - t.Fatal("GET DeliveryServices returned no dses, must have at least 1 to test invalid type server update") - } - - serverTypes, _, err := TOSession.GetTypes("server") - if err != nil { - t.Fatalf("cannot GET Server Types: %v", err) - } - if len(serverTypes) < 2 { - t.Fatal("GET Server Types returned less then 2 types, must have at least 2 to test invalid type server update") - } - for _, t := range serverTypes { - if t.ID != remoteServer.TypeID { - remoteServer.TypeID = t.ID - break - } - } - - // Assign server to DS - _, err = TOSession.CreateDeliveryServiceServers(*dses[0].ID, []int{remoteServer.ID}, true) - if err != nil { - t.Fatalf("POST delivery service servers: %v", err) - } - - // Attempt Update - should fail - _, _, err = TOSession.UpdateServerByID(remoteServer.ID, remoteServer) - if err == nil { - t.Errorf("expected error when updating Server Type of a server assigned to DSes") - } - -} - -func DeleteTestServers(t *testing.T) { - - for _, server := range testData.Servers { - resp, _, err := TOSession.GetServerByHostName(server.HostName) - if err != nil { - t.Errorf("cannot GET Server by hostname: %v - %v", server.HostName, err) - } - if len(resp) > 0 { - respServer := resp[0] - - dses, _, err := TOSession.GetServerIDDeliveryServices(respServer.ID) - for _, ds := range dses { - if ds.ID == nil { - t.Logf("got DS assigned to server #%d that has no ID - deletion may fail!", respServer.ID) - continue - } - if ds.Active == nil || *ds.Active { - setInactive(t, *ds.ID) - } - } - - delResp, _, err := TOSession.DeleteServerByID(respServer.ID) - if err != nil { - t.Errorf("cannot DELETE Server by ID: %v - %v", err, delResp) - } - - // Retrieve the Server to see if it got deleted - serv, _, err := TOSession.GetServerByHostName(server.HostName) - if err != nil { - t.Errorf("error deleting Server hostname: %s", err.Error()) - } - if len(serv) > 0 { - t.Errorf("expected Server hostname: %s to be deleted", server.HostName) - } - } - } -} diff --git a/traffic_ops/testing/api/v2/servers_to_deliveryservice_assignment_test.go b/traffic_ops/testing/api/v2/servers_to_deliveryservice_assignment_test.go deleted file mode 100644 index 19c564441d..0000000000 --- a/traffic_ops/testing/api/v2/servers_to_deliveryservice_assignment_test.go +++ /dev/null @@ -1,129 +0,0 @@ -package v2 - -/* - Licensed 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" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -func TestAssignments(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, Servers, Tenants, DeliveryServices}, func() { - AssignTestDeliveryService(t) - AssignIncorrectTestDeliveryService(t) - }) -} - -func AssignTestDeliveryService(t *testing.T) { - rs, _, err := TOSession.GetServerByHostName(testData.Servers[0].HostName) - if err != nil { - t.Fatalf("Failed to fetch server information: %v", err) - } else if len(rs) == 0 { - t.Fatalf("Failed to fetch server information: No results returned!") - } - firstServer := rs[0] - - rd, _, err := TOSession.GetDeliveryServiceByXMLIDNullable(*testData.DeliveryServices[0].XMLID) - if err != nil { - t.Fatalf("Failed to fetch DS information: %v", err) - } else if len(rd) == 0 { - t.Fatalf("Failed to fetch DS information: No results returned!") - } - firstDS := rd[0] - - if firstDS.ID == nil { - t.Fatal("Fetch DS information returned unknown ID") - } - alerts, _, err := TOSession.AssignDeliveryServiceIDsToServerID(firstServer.ID, []int{*firstDS.ID}, true) - if err != nil { - t.Errorf("Couldn't assign DS '%+v' to server '%+v': %v (alerts: %v)", firstDS, firstServer, err, alerts) - } - t.Logf("alerts: %+v", alerts) - - response, _, err := TOSession.GetServerIDDeliveryServices(firstServer.ID) - t.Logf("response: %+v", response) - if err != nil { - t.Fatalf("Couldn't get Delivery Services assigned to Server '%+v': %v", firstServer, err) - } - - var found bool - for _, ds := range response { - if ds.ID != nil && *ds.ID == *firstDS.ID { - found = true - break - } - } - - if !found { - t.Errorf(`Server/DS assignment not found after "successful" assignment!`) - } -} - -func AssignIncorrectTestDeliveryService(t *testing.T) { - var server *tc.Server - for _, s := range testData.Servers { - if s.CDNName == "cdn2" { - server = &s - break - } - } - if server == nil { - t.Fatalf("Couldn't find a server in CDN 'cdn2'!") - } - - rs, _, err := TOSession.GetServerByHostName(server.HostName) - if err != nil { - t.Fatalf("Failed to fetch server information: %v", err) - } else if len(rs) == 0 { - t.Fatalf("Failed to fetch server information: No results returned!") - } - server = &rs[0] - - rd, _, err := TOSession.GetDeliveryServiceByXMLIDNullable(*testData.DeliveryServices[0].XMLID) - if err != nil { - t.Fatalf("Failed to fetch DS information: %v", err) - } else if len(rd) == 0 { - t.Fatalf("Failed to fetch DS information: No results returned!") - } - firstDS := rd[0] - - if firstDS.ID == nil { - t.Fatal("Fetch DS information returned unknown ID") - } - alerts, _, err := TOSession.AssignDeliveryServiceIDsToServerID(server.ID, []int{*firstDS.ID}, false) - if err == nil { - t.Errorf("Expected bad assignment to fail, but it didn't! (alerts: %v)", alerts) - } - - response, _, err := TOSession.GetServerIDDeliveryServices(server.ID) - t.Logf("response: %+v", response) - if err != nil { - t.Fatalf("Couldn't get Delivery Services assigned to Server '%+v': %v", *server, err) - } - - var found bool - for _, ds := range response { - - if ds.ID != nil && *ds.ID == *firstDS.ID { - found = true - break - } - } - - if found { - t.Errorf(`Invalid Server/DS assignment was created!`) - } -} diff --git a/traffic_ops/testing/api/v2/serverservercapability_test.go b/traffic_ops/testing/api/v2/serverservercapability_test.go deleted file mode 100644 index 26ff04a2c2..0000000000 --- a/traffic_ops/testing/api/v2/serverservercapability_test.go +++ /dev/null @@ -1,232 +0,0 @@ -package v2 - -/* - - Licensed 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" - - "github.com/apache/trafficcontrol/lib/go-tc" - "github.com/apache/trafficcontrol/lib/go-util" -) - -func TestServerServerCapabilities(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Tenants, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, Servers, DeliveryServices, ServerCapabilities, DeliveryServicesRequiredCapabilities, ServerServerCapabilities}, func() { - GetTestServerServerCapabilities(t) - }) -} - -func CreateTestServerServerCapabilities(t *testing.T) { - // Valid POSTs - - // loop through server ServerCapabilities, assign FKs and create - for _, ssc := range testData.ServerServerCapabilities { - servResp, _, err := TOSession.GetServerByHostName(*ssc.Server) - if err != nil { - t.Fatalf("cannot GET Server by hostname: %v - %v", *ssc.Server, err) - } - if len(servResp) != 1 { - t.Fatalf("cannot GET Server by hostname: %v. Response did not include record.", *ssc.Server) - } - server := servResp[0] - ssc.ServerID = &server.ID - resp, _, err := TOSession.CreateServerServerCapability(ssc) - if err != nil { - t.Errorf("could not POST the server capability %v to server %v: %v", *ssc.ServerCapability, *ssc.Server, err) - } - t.Log("Response: ", server.HostName, " ", resp) - } - - // Invalid POSTs - - ssc := testData.ServerServerCapabilities[0] - - // Attempt to assign already assigned server capability - _, _, err := TOSession.CreateServerServerCapability(ssc) - if err == nil { - t.Error("expected to receive error when assigning a already assigned server capability\n") - } - - // Attempt to assign a server capability with no ID - sscNilID := tc.ServerServerCapability{ - ServerCapability: ssc.ServerCapability, - } - _, _, err = TOSession.CreateServerServerCapability(sscNilID) - if err == nil { - t.Error("expected to receive error when assigning a server capability without a server ID\n") - } - - // Attempt to assign a server capability with no server capability - sscNilCapability := tc.ServerServerCapability{ - ServerID: ssc.ServerID, - } - _, _, err = TOSession.CreateServerServerCapability(sscNilCapability) - if err == nil { - t.Error("expected to receive error when assigning a server capability to a server without a server capability\n") - } - - // Attempt to assign a server capability with invalid server capability - sscInvalidCapability := tc.ServerServerCapability{ - ServerID: ssc.ServerID, - ServerCapability: util.StrPtr("bogus"), - } - _, _, err = TOSession.CreateServerServerCapability(sscInvalidCapability) - if err == nil { - t.Error("expected to receive error when assigning a non existent server capability to a server\n") - } - - // Attempt to assign a server capability with invalid server capability - sscInvalidID := tc.ServerServerCapability{ - ServerID: util.IntPtr(-1), - ServerCapability: ssc.ServerCapability, - } - _, _, err = TOSession.CreateServerServerCapability(sscInvalidID) - if err == nil { - t.Error("expected to receive error when assigning a server capability to a non existent server ID\n") - } - - // Attempt to assign a server capability to a non MID/EDGE server - servers, _, err := TOSession.GetServerByHostName("riak") - if err != nil { - t.Fatalf("cannot GET Server by hostname: %v - %v", *ssc.Server, err) - } - if len(servers) < 1 { - t.Fatal("need at least one server to test invalid server type assignment") - } - - sscInvalidType := tc.ServerServerCapability{ - ServerID: &servers[0].ID, - ServerCapability: ssc.ServerCapability, - } - _, _, err = TOSession.CreateServerServerCapability(sscInvalidType) - if err == nil { - t.Error("expected to receive error when assigning a server capability to a server with incorrect type\n") - } -} - -func GetTestServerServerCapabilities(t *testing.T) { - // Get All Server Capabilities - sscs, _, err := TOSession.GetServerServerCapabilities(nil, nil, nil) - if err != nil { - t.Fatalf("cannot GET server capabilities assigned to servers: %v", err) - } - if sscs == nil { - t.Fatal("returned server capabilities assigned to servers was nil\n") - } - if len(sscs) != len(testData.ServerServerCapabilities) { - t.Errorf("expect %v server capabilities assigned to servers received %v ", len(testData.ServerServerCapabilities), len(sscs)) - } - - checkResp := func(t *testing.T, sscs []tc.ServerServerCapability) { - if sscs == nil { - t.Fatal("returned server capabilities assigned to servers was nil\n") - } - if len(sscs) != 1 { - t.Errorf("expect 1 server capabilities assigned to server received %v ", len(sscs)) - } - } - - for _, ssc := range sscs { - // Get assigned Server Capabilities by server id - sscs, _, err := TOSession.GetServerServerCapabilities(ssc.ServerID, nil, nil) - if err != nil { - t.Fatalf("cannot GET server capabilities assigned to servers by server ID %v: %v", *ssc.ServerID, err) - } - checkResp(t, sscs) - // Get assigned Server Capabilities by host name - sscs, _, err = TOSession.GetServerServerCapabilities(nil, ssc.Server, nil) - if err != nil { - t.Fatalf("cannot GET server capabilities assigned to servers by server host name %v: %v", *ssc.Server, err) - } - checkResp(t, sscs) - - // Get assigned Server Capabilities by server capability - sscs, _, err = TOSession.GetServerServerCapabilities(nil, nil, ssc.ServerCapability) - if err != nil { - t.Fatalf("cannot GET server capabilities assigned to servers by server capability %v: %v", *ssc.ServerCapability, err) - } - checkResp(t, sscs) - } -} - -func DeleteTestServerServerCapabilities(t *testing.T) { - // Get Server Capabilities to delete them - sscs, _, err := TOSession.GetServerServerCapabilities(nil, nil, nil) - if err != nil { - t.Fatalf("cannot GET server capabilities assigned to servers: %v", err) - } - if sscs == nil { - t.Fatal("returned server capabilities assigned to servers was nil\n") - } - - // Assign servers to DSes that have the capability required - // Used to make sure we block server server_capability DELETE in that case - dsServers := []tc.DeliveryServiceServer{} - for _, ssc := range sscs { - - dsReqCapResp, _, err := TOSession.GetDeliveryServicesRequiredCapabilities(nil, nil, ssc.ServerCapability) - if err != nil { - t.Fatalf("cannot GET delivery service required capabilities: %v", err) - } - if len(dsReqCapResp) == 0 { - t.Fatalf("at least one delivery service needs the capability %v required", *ssc.ServerCapability) - } - dsReqCap := dsReqCapResp[0] - - // Assign server to ds - _, err = TOSession.CreateDeliveryServiceServers(*dsReqCap.DeliveryServiceID, []int{*ssc.ServerID}, false) - if err != nil { - t.Fatalf("cannot CREATE server delivery service assignment: %v", err) - } - dsServers = append(dsServers, tc.DeliveryServiceServer{ - Server: ssc.ServerID, - DeliveryService: dsReqCap.DeliveryServiceID, - }) - } - - // Delete should fail as their delivery services now require the capabilities - for _, ssc := range sscs { - _, _, err := TOSession.DeleteServerServerCapability(*ssc.ServerID, *ssc.ServerCapability) - if err == nil { - t.Fatalf("should have gotten error when using DELETE on the server capability %v from server %v as it is required by associated dses", *ssc.ServerCapability, *ssc.Server) - } - } - - for _, dsServer := range dsServers { - if dsServer.DeliveryService == nil { - t.Error("nil DeliveryService property") - continue - } - if dsServer.Server == nil { - t.Error("nil Server property") - continue - } - setInactive(t, *dsServer.DeliveryService) - _, _, err := TOSession.DeleteDeliveryServiceServer(*dsServer.DeliveryService, *dsServer.Server) - if err != nil { - t.Fatalf("could not DELETE the server %v from ds %v: %v", *dsServer.Server, *dsServer.DeliveryService, err) - } - } - - // Remove the requirement so we can actually delete them - - for _, ssc := range sscs { - _, _, err := TOSession.DeleteServerServerCapability(*ssc.ServerID, *ssc.ServerCapability) - if err != nil { - t.Errorf("could not DELETE the server capability %v from server %v: %v", *ssc.ServerCapability, *ssc.Server, err) - } - } - -} diff --git a/traffic_ops/testing/api/v2/serverupdatestatus_test.go b/traffic_ops/testing/api/v2/serverupdatestatus_test.go deleted file mode 100644 index 0191cd5c15..0000000000 --- a/traffic_ops/testing/api/v2/serverupdatestatus_test.go +++ /dev/null @@ -1,297 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "encoding/json" - "fmt" - "net/http" - "testing" - - "github.com/apache/trafficcontrol/lib/go-tc" - "github.com/apache/trafficcontrol/lib/go-util" -) - -func TestServerUpdateStatus(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, Servers}, func() { - edge1cdn1 := tc.Server{} - edge2cdn1 := tc.Server{} - mid1cdn1 := tc.Server{} - edge1cdn2 := tc.Server{} - - getServers := func() { - for _, s := range []struct { - name string - server *tc.Server - }{ - { - "atlanta-edge-01", - &edge1cdn1, - }, - { - "atlanta-edge-03", - &edge2cdn1, - }, - { - "atlanta-mid-16", - &mid1cdn1, - }, - { - "edge1-cdn2", - &edge1cdn2, - }, - } { - resp, _, err := TOSession.GetServerByHostName(s.name) - if err != nil { - t.Errorf("cannot GET Server by hostname: %v - %v", s.name, err) - } - *s.server = resp[0] - } - } - getServers() - - // assert that servers don't have updates pending - for _, s := range []tc.Server{ - edge1cdn1, - edge2cdn1, - mid1cdn1, - edge1cdn2, - } { - if s.UpdPending { - t.Error("expected UpdPending: false, actual: true") - } - } - - // update status of MID server to OFFLINE - _, _, err := TOSession.UpdateServerStatus(mid1cdn1.ID, tc.ServerPutStatus{ - Status: util.JSONNameOrIDStr{Name: util.StrPtr("OFFLINE")}, - OfflineReason: util.StrPtr("testing")}) - if err != nil { - t.Errorf("cannot update server status: %v", err) - } - - // assert that updates were queued for the proper EDGE servers - getServers() - if !edge1cdn1.UpdPending { - t.Errorf("expected: child %s to have updates pending, actual: no updates pending", edge1cdn1.HostName) - } - if !edge2cdn1.UpdPending { - t.Errorf("expected: child %s to have updates pending, actual: no updates pending", edge2cdn1.HostName) - } - if mid1cdn1.UpdPending { - t.Errorf("expected: server %s with updated status to have no updates pending, actual: updates pending", mid1cdn1.HostName) - } - if edge1cdn2.UpdPending { - t.Errorf("expected: server %s in different CDN than server with updated status to have no updates pending, actual: updates pending", edge2cdn1.HostName) - } - - // update status of MID server to OFFLINE via status ID - status, _, err := TOSession.GetStatusByName("OFFLINE") - if err != nil { - t.Fatalf("cannot GET status by name: %v", err) - } - _, _, err = TOSession.UpdateServerStatus( - mid1cdn1.ID, - tc.ServerPutStatus{ - Status: util.JSONNameOrIDStr{ID: util.IntPtr(status[0].ID)}, - OfflineReason: util.StrPtr("testing"), - }, - ) - if err != nil { - t.Errorf("cannot update server status: %v", err) - } - - // negative cases: - // server doesn't exist - _, _, err = TOSession.UpdateServerStatus( - -1, - tc.ServerPutStatus{ - Status: util.JSONNameOrIDStr{Name: util.StrPtr("OFFLINE")}, - OfflineReason: util.StrPtr("testing"), - }, - ) - if err == nil { - t.Error("update server status exected: err, actual: nil") - } - - // status does not exist - _, _, err = TOSession.UpdateServerStatus( - mid1cdn1.ID, - tc.ServerPutStatus{ - Status: util.JSONNameOrIDStr{Name: util.StrPtr("NOT_A_REAL_STATUS")}, - OfflineReason: util.StrPtr("testing"), - }, - ) - if err == nil { - t.Error("update server status exected: err, actual: nil") - } - - // offlineReason required for OFFLINE status - _, _, err = TOSession.UpdateServerStatus( - mid1cdn1.ID, - tc.ServerPutStatus{ - Status: util.JSONNameOrIDStr{Name: util.StrPtr("OFFLINE")}, - OfflineReason: nil, - }, - ) - if err == nil { - t.Error("update server status exected: err, actual: nil") - } - - // offlineReason required for ADMIN_DOWN status - _, _, err = TOSession.UpdateServerStatus( - mid1cdn1.ID, - tc.ServerPutStatus{ - Status: util.JSONNameOrIDStr{Name: util.StrPtr("ADMIN_DOWN")}, - OfflineReason: nil, - }, - ) - if err == nil { - t.Error("update server status exected: err, actual: nil") - } - }) -} - -func TestServerQueueUpdate(t *testing.T) { - WithObjs(t, []TCObj{Divisions, Regions, PhysLocations, Statuses, Types, CacheGroups, CDNs, Profiles, Servers}, func() { - const serverName = "atlanta-edge-01" - - queueUpdateActions := map[bool]string{ - false: "dequeue", - true: "queue", - } - - var s tc.Server - resp, _, err := TOSession.GetServerByHostName(serverName) - if err != nil { - t.Fatalf("failed to GET Server by hostname: %v - %v", serverName, err) - } - s = resp[0] - - // assert that servers don't have updates pending - if got, want := s.UpdPending, false; got != want { - t.Fatalf("unexpected UpdPending, got: %v, want: %v", got, want) - } - - for _, setVal := range [...]bool{true, false} { - t.Run(fmt.Sprint(setVal), func(t *testing.T) { - // queue update and check response - quResp, _, err := TOSession.SetServerQueueUpdate(s.ID, setVal) - if err != nil { - t.Fatalf("failed to set queue update for server with ID %v to %v: %v", s.ID, setVal, err) - } - if got, want := int(quResp.Response.ServerID), s.ID; got != want { - t.Errorf("wrong serverId in response, got: %v, want: %v", got, want) - } - if got, want := quResp.Response.Action, queueUpdateActions[setVal]; got != want { - t.Errorf("wrong action in response, got: %v, want: %v", got, want) - } - - // assert that the server has updates queued - resp, _, err = TOSession.GetServerByID(s.ID) - if err != nil { - t.Fatalf("failed to GET Server by ID: %v - %v", s.ID, err) - } - s = resp[0] - if got, want := s.UpdPending, setVal; got != want { - t.Errorf("unexpected UpdPending, got: %v, want: %v", got, want) - } - }) - } - - t.Run("validations", func(t *testing.T) { - // server doesn't exist - _, _, err = TOSession.SetServerQueueUpdate(-1, true) - if err == nil { - t.Error("update server status expected: error, actual: nil") - } - - // invalid action - req, err := json.Marshal(tc.ServerQueueUpdateRequest{Action: "foobar"}) - if err != nil { - t.Fatalf("failed to encode request body: %v", err) - } - path := fmt.Sprintf("/api/2.0/servers/%d/queue_update", s.ID) - httpResp, _, err := TOSession.RawRequest(http.MethodPost, path, req) - if err != nil { - t.Fatalf("POST request failed: %v", err) - } - if httpResp.StatusCode >= 200 && httpResp.StatusCode <= 299 { - t.Errorf("unexpected status code: got %v, want something outside the range [200, 299]", httpResp.StatusCode) - } - }) - }) -} - -func TestSetServerUpdateStatuses(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, Servers}, func() { - if len(testData.Servers) < 1 { - t.Fatal("cannot GET Server: no test data") - } - testServer := testData.Servers[0] - - testVals := func(queue *bool, reval *bool) { - existingServer, _, err := TOSession.GetServerByHostName(testServer.HostName) - if err != nil { - t.Errorf("cannot GET Server by name: %v - %v", err, existingServer) - } else if len(existingServer) != 1 { - t.Fatalf("GET Server expected 1, actual %v", len(existingServer)) - } - - if _, err := TOSession.SetUpdateServerStatuses(testServer.HostName, queue, reval); err != nil { - t.Fatalf("UpdateServerStatuses error expected: nil, actual: %v", err) - } - - newServer, _, err := TOSession.GetServerByHostName(testServer.HostName) - if err != nil { - t.Errorf("cannot GET Server by name: %v - %v", err, existingServer) - } else if len(newServer) != 1 { - t.Fatalf("GET Server expected 1, actual %v", len(newServer)) - } - - if queue != nil { - if newServer[0].UpdPending != *queue { - t.Errorf("set queue update pending to %v, but then got server %v", *queue, newServer[0].UpdPending) - } - } else { - if newServer[0].UpdPending != existingServer[0].UpdPending { - t.Errorf("set queue update pending with nil (don't update), but then got server %v which didn't match pre-update value %v", newServer[0].UpdPending, existingServer[0].UpdPending) - } - } - if reval != nil { - if newServer[0].RevalPending != *reval { - t.Errorf("set reval update pending to %v, but then got server %v", *reval, newServer[0].RevalPending) - } - } else { - if newServer[0].RevalPending != existingServer[0].RevalPending { - t.Errorf("set reval update pending with nil (don't update), but then got server %v which didn't match pre-update value %v", newServer[0].RevalPending, existingServer[0].RevalPending) - } - } - } - - testVals(util.BoolPtr(true), util.BoolPtr(true)) - testVals(util.BoolPtr(true), util.BoolPtr(false)) - testVals(util.BoolPtr(false), util.BoolPtr(false)) - testVals(nil, util.BoolPtr(true)) - testVals(nil, util.BoolPtr(false)) - testVals(util.BoolPtr(true), nil) - testVals(util.BoolPtr(false), nil) - - if _, err := TOSession.SetUpdateServerStatuses(testServer.HostName, nil, nil); err == nil { - t.Errorf("UpdateServerStatuses with (nil,nil) expected error, actual nil") - } - }) -} diff --git a/traffic_ops/testing/api/v2/session_test.go b/traffic_ops/testing/api/v2/session_test.go deleted file mode 100644 index 3b3f24a473..0000000000 --- a/traffic_ops/testing/api/v2/session_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "time" - - "github.com/apache/trafficcontrol/traffic_ops/v2-client" - _ "github.com/lib/pq" -) - -var ( - TOSession *client.Session - NoAuthTOSession *client.Session -) - -func SetupSession(toReqTimeout time.Duration, toURL string, toUser string, toPass string) error { - var err error - - toReqTimeout = time.Second * time.Duration(Config.Default.Session.TimeoutInSecs) - NoAuthTOSession = client.NewNoAuthSession(toURL, true, "to-api-v2-client-tests", true, toReqTimeout) - TOSession, _, err = client.LoginWithAgent(toURL, toUser, toPass, true, "to-api-v2-client-tests", true, toReqTimeout) - return err -} - -func TeardownSession(toReqTimeout time.Duration, toURL string, toUser string, toPass string) error { - var err error - toReqTimeout = time.Second * time.Duration(Config.Default.Session.TimeoutInSecs) - TOSession, _, err = client.LogoutWithAgent(toURL, toUser, toPass, true, "to-api-v2-client-tests", true, toReqTimeout) - - return err -} - -func SwitchSession(toReqTimeout time.Duration, toURL string, toOldUser string, toOldPass string, toNewUser string, toNewPass string) error { - err := TeardownSession(toReqTimeout, toURL, toOldUser, toOldPass) - - // intentially skip errors so that we can continue with setup in the event of a 403 - - err = SetupSession(toReqTimeout, toURL, toNewUser, toNewPass) - return err -} diff --git a/traffic_ops/testing/api/v2/staticdnsentries_test.go b/traffic_ops/testing/api/v2/staticdnsentries_test.go deleted file mode 100644 index ed409d3be1..0000000000 --- a/traffic_ops/testing/api/v2/staticdnsentries_test.go +++ /dev/null @@ -1,191 +0,0 @@ -package v2 - -/* - - Licensed 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" - - tc "github.com/apache/trafficcontrol/lib/go-tc" - "reflect" -) - -func TestStaticDNSEntries(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Tenants, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, Servers, DeliveryServices, StaticDNSEntries}, func() { - GetTestStaticDNSEntries(t) - UpdateTestStaticDNSEntries(t) - UpdateTestStaticDNSEntriesInvalidAddress(t) - }) -} - -func CreateTestStaticDNSEntries(t *testing.T) { - for _, staticDNSEntry := range testData.StaticDNSEntries { - resp, _, err := TOSession.CreateStaticDNSEntry(staticDNSEntry) - t.Log("Response: ", resp) - if err != nil { - t.Errorf("could not CREATE staticDNSEntry: %v", err) - } - } - -} - -func UpdateTestStaticDNSEntries(t *testing.T) { - - firstStaticDNSEntry := testData.StaticDNSEntries[0] - // Retrieve the StaticDNSEntries by name so we can get the id for the Update - resp, _, err := TOSession.GetStaticDNSEntriesByHost(firstStaticDNSEntry.Host) - if err != nil { - t.Errorf("cannot GET StaticDNSEntries by name: '%s', %v", firstStaticDNSEntry.Host, err) - } - remoteStaticDNSEntry := resp[0] - expectedAddress := "192.168.0.2" - remoteStaticDNSEntry.Address = expectedAddress - var alert tc.Alerts - var status int - alert, _, status, err = TOSession.UpdateStaticDNSEntryByID(remoteStaticDNSEntry.ID, remoteStaticDNSEntry) - t.Log("Status Code: ", status) - if err != nil { - t.Errorf("cannot UPDATE StaticDNSEntries using url: %v - %v", err, alert) - } - - // Retrieve the StaticDNSEntries to check StaticDNSEntries name got updated - resp, _, err = TOSession.GetStaticDNSEntryByID(remoteStaticDNSEntry.ID) - if err != nil { - t.Errorf("cannot GET StaticDNSEntries by name: '$%s', %v", firstStaticDNSEntry.Host, err) - } - respStaticDNSEntry := resp[0] - if respStaticDNSEntry.Address != expectedAddress { - t.Errorf("results do not match actual: %s, expected: %s", respStaticDNSEntry.Address, expectedAddress) - } - -} - -func UpdateTestStaticDNSEntriesInvalidAddress(t *testing.T) { - - expectedAlerts := []tc.Alerts{ - tc.Alerts{Alerts: []tc.Alert{tc.Alert{Text: "'address' must be a valid IPv4 address", Level: "error"}}}, - tc.Alerts{Alerts: []tc.Alert{tc.Alert{Text: "'address' must be a valid DNS name", Level: "error"}}}, - tc.Alerts{Alerts: []tc.Alert{tc.Alert{Text: "'address' for type: CNAME_RECORD must have a trailing period", Level: "error"}}}, - tc.Alerts{Alerts: []tc.Alert{tc.Alert{Text: "'address' must be a valid IPv6 address", Level: "error"}}}} - - // A_RECORD - firstStaticDNSEntry := testData.StaticDNSEntries[0] - // Retrieve the StaticDNSEntries by name so we can get the id for the Update - resp, _, err := TOSession.GetStaticDNSEntriesByHost(firstStaticDNSEntry.Host) - if err != nil { - t.Errorf("cannot GET StaticDNSEntries by name: '%s', %v", firstStaticDNSEntry.Host, err) - } - remoteStaticDNSEntry := resp[0] - expectedAddress := "test.testdomain.net." - remoteStaticDNSEntry.Address = expectedAddress - var alert tc.Alerts - var status int - alert, _, status, err = TOSession.UpdateStaticDNSEntryByID(remoteStaticDNSEntry.ID, remoteStaticDNSEntry) - t.Log("Status Code [expect 400]: ", status) - if err != nil { - t.Logf("cannot UPDATE StaticDNSEntries using url: %v - %v\n", err, alert) - } - if !reflect.DeepEqual(alert, expectedAlerts[0]) { - t.Errorf("got alerts: %v but expected alerts: %v", alert, expectedAlerts[0]) - } - - // CNAME_RECORD - secondStaticDNSEntry := testData.StaticDNSEntries[1] - // Retrieve the StaticDNSEntries by name so we can get the id for the Update - resp, _, err = TOSession.GetStaticDNSEntriesByHost(secondStaticDNSEntry.Host) - if err != nil { - t.Errorf("cannot GET StaticDNSEntries by name: '%s', %v", secondStaticDNSEntry.Host, err) - } - remoteStaticDNSEntry = resp[0] - expectedAddress = "2001:0db8:85a3:0000:0000:8a2e:0370:7334" - remoteStaticDNSEntry.Address = expectedAddress - alert, _, status, err = TOSession.UpdateStaticDNSEntryByID(remoteStaticDNSEntry.ID, remoteStaticDNSEntry) - t.Log("Status Code [expect 400]: ", status) - if err != nil { - t.Logf("cannot UPDATE StaticDNSEntries using url: %v - %v\n", err, alert) - } - if !reflect.DeepEqual(alert, expectedAlerts[1]) { - t.Errorf("got alerts: %v but expected alerts: %v", alert, expectedAlerts[1]) - } - - //CNAME_RECORD: missing a trailing period - expectedAddressMissingPeriod := "cdn.test.com" - remoteStaticDNSEntry.Address = expectedAddressMissingPeriod - alert, _, status, err = TOSession.UpdateStaticDNSEntryByID(remoteStaticDNSEntry.ID, remoteStaticDNSEntry) - t.Log("Status Code [expect 400]: ", status) - if err != nil { - t.Logf("cannot UPDATE StaticDNSEntries using url: %v - %v\n", err, alert) - } - if !reflect.DeepEqual(alert, expectedAlerts[2]) { - t.Errorf("got alerts: %v but expected alerts: %v", alert, expectedAlerts[2]) - } - - // AAAA_RECORD - thirdStaticDNSEntry := testData.StaticDNSEntries[2] - // Retrieve the StaticDNSEntries by name so we can get the id for the Update - resp, _, err = TOSession.GetStaticDNSEntriesByHost(thirdStaticDNSEntry.Host) - if err != nil { - t.Errorf("cannot GET StaticDNSEntries by name: '%s', %v", thirdStaticDNSEntry.Host, err) - } - remoteStaticDNSEntry = resp[0] - expectedAddress = "192.168.0.1" - remoteStaticDNSEntry.Address = expectedAddress - alert, _, status, err = TOSession.UpdateStaticDNSEntryByID(remoteStaticDNSEntry.ID, remoteStaticDNSEntry) - t.Log("Status Code [expect 400]: ", status) - if err != nil { - t.Logf("cannot UPDATE StaticDNSEntries using url: %v - %v\n", err, alert) - } - if !reflect.DeepEqual(alert, expectedAlerts[3]) { - t.Errorf("got alerts: %v but expected alerts: %v", alert, expectedAlerts[3]) - } -} - -func GetTestStaticDNSEntries(t *testing.T) { - - for _, staticDNSEntry := range testData.StaticDNSEntries { - resp, _, err := TOSession.GetStaticDNSEntriesByHost(staticDNSEntry.Host) - if err != nil { - t.Errorf("cannot GET StaticDNSEntries by name: %v - %v", err, resp) - } - } -} - -func DeleteTestStaticDNSEntries(t *testing.T) { - - for _, staticDNSEntry := range testData.StaticDNSEntries { - // Retrieve the StaticDNSEntries by name so we can get the id for the Update - resp, _, err := TOSession.GetStaticDNSEntriesByHost(staticDNSEntry.Host) - if err != nil { - t.Errorf("cannot GET StaticDNSEntries by name: %v - %v", staticDNSEntry.Host, err) - } - if len(resp) > 0 { - respStaticDNSEntry := resp[0] - - _, _, err := TOSession.DeleteStaticDNSEntryByID(respStaticDNSEntry.ID) - if err != nil { - t.Errorf("cannot DELETE StaticDNSEntry by name: '%s' %v", respStaticDNSEntry.Host, err) - } - - // Retrieve the StaticDNSEntry to see if it got deleted - staticDNSEntries, _, err := TOSession.GetStaticDNSEntriesByHost(staticDNSEntry.Host) - if err != nil { - t.Errorf("error deleting StaticDNSEntrie name: %s", err.Error()) - } - if len(staticDNSEntries) > 0 { - t.Errorf("expected StaticDNSEntry name: %s to be deleted", staticDNSEntry.Host) - } - } - } -} diff --git a/traffic_ops/testing/api/v2/stats_summary_test.go b/traffic_ops/testing/api/v2/stats_summary_test.go deleted file mode 100644 index 8183c83c0c..0000000000 --- a/traffic_ops/testing/api/v2/stats_summary_test.go +++ /dev/null @@ -1,178 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "fmt" - "testing" - "time" - - "github.com/apache/trafficcontrol/lib/go-tc" - "github.com/apache/trafficcontrol/lib/go-util" -) - -var ( - testStatsSummaries []tc.StatsSummary - latestTime time.Time -) - -func TestStatsSummary(t *testing.T) { - testStatsSummaries = []tc.StatsSummary{} - latestTime = time.Now().Truncate(time.Second).UTC() - CreateTestStatsSummaries(t) - GetTestStatsSummaries(t) - GetTestStatsSummariesLastUpdated(t) -} - -func CreateTestStatsSummaries(t *testing.T) { - tmpTime := latestTime - for _, ss := range testData.StatsSummaries { - ss.SummaryTime = tmpTime - _, _, err := TOSession.CreateSummaryStats(ss) - if err != nil { - t.Errorf("creating stats_summary %v: %v", ss.StatName, err) - } - - tmpTime = tmpTime.AddDate(0, 0, -1) - - testStatsSummaries = append(testStatsSummaries, ss) - } -} - -func GetTestStatsSummaries(t *testing.T) { - var testCases = []struct { - description string - stat *string - cdn *string - ds *string - expectedStatsSummaries []tc.StatsSummary - }{ - { - description: "get all summary stats", - expectedStatsSummaries: testStatsSummaries, - }, - { - description: "non-existant stat name", - stat: util.StrPtr("bogus"), - }, - { - description: "non-existant ds name", - ds: util.StrPtr("bogus"), - }, - { - description: "non-existant cdn name", - cdn: util.StrPtr("bogus"), - }, - { - description: "get stats summary by stat name", - stat: util.StrPtr("daily_bytesserved"), - expectedStatsSummaries: func() []tc.StatsSummary { - statsSummaries := []tc.StatsSummary{} - for _, ss := range testStatsSummaries { - if *ss.StatName == "daily_bytesserved" { - statsSummaries = append(statsSummaries, ss) - } - } - return statsSummaries - }(), - }, - { - description: "get stats summary by cdn name", - cdn: util.StrPtr("cdn1"), - expectedStatsSummaries: testStatsSummaries, - }, - { - description: "get stats summary by ds name", - ds: util.StrPtr("all"), - expectedStatsSummaries: testStatsSummaries, - }, - } - - for _, tc := range testCases { - t.Run(tc.description, func(t *testing.T) { - tsr, _, err := TOSession.GetSummaryStats(tc.cdn, tc.ds, tc.stat) - if err != nil { - t.Fatalf("received unexpected error %v on GET to stats_summary", err) - } - if len(tc.expectedStatsSummaries) == 0 && len(tsr.Response) != 0 { - t.Fatalf("expected to recieve no stats summaries but received %v", len(tsr.Response)) - } - for _, ess := range tc.expectedStatsSummaries { - found := false - for _, ss := range tsr.Response { - if *ess.StatName == *ss.StatName && ess.SummaryTime.Equal(ss.SummaryTime) { - found = true - break - } - } - if !found { - t.Errorf("expected to find stat %v in stats summary response", *ess.StatName) - } - } - }) - } -} - -func GetTestStatsSummariesLastUpdated(t *testing.T) { - type testCase struct { - description string - stat *string - errExpected bool - expectedTimestamp time.Time - nullTimeStamp bool - } - testCases := []testCase{ - testCase{ - description: "latest updated timestamp", - stat: nil, - errExpected: false, - expectedTimestamp: latestTime, - }, - testCase{ - description: "non-existant stat name", - stat: util.StrPtr("bogus"), - errExpected: false, - nullTimeStamp: true, - }, - } - for _, ss := range testStatsSummaries { - testCases = append(testCases, testCase{ - description: fmt.Sprintf("latest updated timestamp for - %v", *ss.StatName), - stat: ss.StatName, - errExpected: false, - expectedTimestamp: ss.SummaryTime, - }) - } - - for _, tc := range testCases { - t.Run(tc.description, func(t *testing.T) { - tsr, _, err := TOSession.GetSummaryStatsLastUpdated(tc.stat) - if tc.errExpected && err == nil { - t.Fatalf("expected to get error on getting stats_summary latest updated timestamp but received nil") - } - - if !tc.errExpected && err != nil { - t.Fatalf("received unexpected error getting stats_summary latest updated timestamp: %v", err) - } - if !tc.errExpected && tc.nullTimeStamp && tsr.Response.SummaryTime != nil { - t.Fatalf("expected to get null on latest timestamp but instead got %v", tsr.Response.SummaryTime) - } - if !tc.errExpected && !tc.nullTimeStamp && !tsr.Response.SummaryTime.Equal(tc.expectedTimestamp) { - t.Fatalf("received latest timestamp %v does not match up to expected timestamp %v", tsr.Response.SummaryTime, tc.expectedTimestamp) - } - }) - } -} diff --git a/traffic_ops/testing/api/v2/statuses_test.go b/traffic_ops/testing/api/v2/statuses_test.go deleted file mode 100644 index 9a11866f20..0000000000 --- a/traffic_ops/testing/api/v2/statuses_test.go +++ /dev/null @@ -1,129 +0,0 @@ -package v2 - -/* - - Licensed 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" - - tc "github.com/apache/trafficcontrol/lib/go-tc" -) - -func TestStatuses(t *testing.T) { - WithObjs(t, []TCObj{Parameters, Statuses}, func() { - UpdateTestStatuses(t) - GetTestStatuses(t) - }) -} - -func CreateTestStatuses(t *testing.T) { - for _, status := range testData.Statuses { - resp, _, err := TOSession.CreateStatusNullable(status) - t.Log("Response: ", resp) - if err != nil { - t.Errorf("could not CREATE status: %v", err) - } - } -} - -func UpdateTestStatuses(t *testing.T) { - - if len(testData.Statuses) < 1 { - t.Fatal("Need at least one Status to test updating a Status") - } - for _, status := range testData.Statuses { - if status.Name == nil { - t.Fatal("cannot update test statuses: test data status must have a name") - } - // Retrieve the Status by name so we can get the id for the Update - resp, _, err := TOSession.GetStatusByName(*status.Name) - if err != nil { - t.Errorf("cannot GET Status by name: %s - %v", *status.Name, err) - } - remoteStatus := resp[0] - expectedStatusDesc := "new description" - remoteStatus.Description = expectedStatusDesc - var alert tc.Alerts - alert, _, err = TOSession.UpdateStatusByID(remoteStatus.ID, remoteStatus) - - if tc.IsReservedStatus(*status.Name) { - if err == nil { - t.Errorf("expected an error about while updating a reserved status, but got nothing") - } - } else { - if err != nil { - t.Errorf("cannot UPDATE Status by id: %d, err: %v - %v", remoteStatus.ID, err, alert) - } - - // Retrieve the Status to check Status name got updated - resp, _, err = TOSession.GetStatusByID(remoteStatus.ID) - if err != nil { - t.Errorf("cannot GET Status by ID: %d - %v", remoteStatus.ID, err) - } - respStatus := resp[0] - if respStatus.Description != expectedStatusDesc { - t.Errorf("results do not match actual: %s, expected: %s", respStatus.Name, expectedStatusDesc) - } - } - } -} - -func GetTestStatuses(t *testing.T) { - - for _, status := range testData.Statuses { - if status.Name == nil { - t.Fatal("cannot get ftest statuses: test data statuses must have names") - } - resp, _, err := TOSession.GetStatusByName(*status.Name) - if err != nil { - t.Errorf("cannot GET Status by name: %v - %v", err, resp) - } - } -} - -func DeleteTestStatuses(t *testing.T) { - - for _, status := range testData.Statuses { - if status.Name == nil { - t.Error("Found status in testing data with null or undefined Name") - continue - } - - // Retrieve the Status by name so we can get the id for the Update - resp, _, err := TOSession.GetStatusByName(*status.Name) - if err != nil { - t.Errorf("cannot GET Status by name: %s - %v", *status.Name, err) - } - if len(resp) != 1 { - t.Errorf("Expected exactly one Status to exist with name '%s', found: %d", *status.Name, len(resp)) - continue - } - respStatus := resp[0] - - delResp, _, err := TOSession.DeleteStatusByID(respStatus.ID) - if err != nil { - t.Errorf("cannot DELETE Status by ID: %v - %v", err, delResp) - } - - // Retrieve the Status to see if it got deleted - statuses, _, err := TOSession.GetStatusByName(*status.Name) - if err != nil { - t.Errorf("error getting status by name: %s, err: %v", *status.Name, err) - } - if len(statuses) > 0 { - t.Errorf("expected Status name: %s to be deleted", *status.Name) - } - } -} diff --git a/traffic_ops/testing/api/v2/steering_test.go b/traffic_ops/testing/api/v2/steering_test.go deleted file mode 100644 index 279b4b0d7b..0000000000 --- a/traffic_ops/testing/api/v2/steering_test.go +++ /dev/null @@ -1,67 +0,0 @@ -package v2 - -/* - - Licensed 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 TestSteering(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Tenants, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, Servers, DeliveryServices, Users, SteeringTargets}, func() { - GetTestSteering(t) - }) -} - -func GetTestSteering(t *testing.T) { - if len(testData.SteeringTargets) < 1 { - t.Error("get steering: no steering target test data") - } - st := testData.SteeringTargets[0] - if st.DeliveryService == nil { - t.Error("get steering: test data missing ds") - } - - steerings, _, err := TOSession.Steering() - if err != nil { - t.Errorf("steering get: getting steering: %v", err) - } - - if len(steerings) != len(testData.SteeringTargets) { - t.Errorf("steering get: expected %v actual %v", len(testData.SteeringTargets), len(steerings)) - } - - if steerings[0].ClientSteering { - t.Errorf("steering get: ClientSteering expected %v actual %v", false, true) - } - if len(steerings[0].Targets) != 1 { - t.Errorf("steering get: Targets expected %v actual %v", 1, len(steerings[0].Targets)) - } - if steerings[0].Targets[0].Order != 0 { - t.Errorf("steering get: Targets Order expected %v actual %v", 0, steerings[0].Targets[0].Order) - } - if testData.SteeringTargets[0].Value != nil && steerings[0].Targets[0].Weight != int32(*testData.SteeringTargets[0].Value) { - t.Errorf("steering get: Targets Order expected %v actual %v", testData.SteeringTargets[0].Value, steerings[0].Targets[0].Weight) - } - if steerings[0].Targets[0].GeoOrder != nil { - t.Errorf("steering get: Targets Order expected %v actual %+v", nil, *steerings[0].Targets[0].GeoOrder) - } - if steerings[0].Targets[0].Longitude != nil { - t.Errorf("steering get: Targets Order expected %v actual %+v", nil, *steerings[0].Targets[0].Longitude) - } - if steerings[0].Targets[0].Latitude != nil { - t.Errorf("steering get: Targets Order expected %v actual %+v", nil, *steerings[0].Targets[0].Latitude) - } -} diff --git a/traffic_ops/testing/api/v2/steeringtargets_test.go b/traffic_ops/testing/api/v2/steeringtargets_test.go deleted file mode 100644 index 78b58471ae..0000000000 --- a/traffic_ops/testing/api/v2/steeringtargets_test.go +++ /dev/null @@ -1,305 +0,0 @@ -package v2 - -/* - - Licensed 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" - "time" - - "github.com/apache/trafficcontrol/lib/go-util" - client "github.com/apache/trafficcontrol/traffic_ops/v2-client" -) - -var SteeringUserSession *client.Session - -func TestSteeringTargets(t *testing.T) { - - WithObjs(t, []TCObj{CDNs, Types, Tenants, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, Servers, DeliveryServices, Users, SteeringTargets}, func() { - GetTestSteeringTargets(t) - UpdateTestSteeringTargets(t) - }) - -} - -// SetupSteeringTargets calls the CreateSteeringTargets test. It also sets the steering user session -// with the logged in steering user. SteeringUserSession is used by steering target test functions. -// Running this function depends on CreateTestUsers. -func SetupSteeringTargets(t *testing.T) { - var err error - toReqTimeout := time.Second * time.Duration(Config.Default.Session.TimeoutInSecs) - SteeringUserSession, _, err = client.LoginWithAgent(TOSession.URL, "steering", "pa$$word", true, "to-api-v1-client-tests/steering", true, toReqTimeout) - if err != nil { - t.Fatalf("failed to get log in with steering user: %v", err.Error()) - } - - CreateTestSteeringTargets(t) -} - -func CreateTestSteeringTargets(t *testing.T) { - for _, st := range testData.SteeringTargets { - if st.Type == nil { - t.Fatal("creating steering target: test data missing type") - } - if st.DeliveryService == nil { - t.Fatal("creating steering target: test data missing ds") - } - if st.Target == nil { - t.Fatal("creating steering target: test data missing target") - } - - { - respTypes, _, err := SteeringUserSession.GetTypeByName(*st.Type) - if err != nil { - t.Fatalf("creating steering target: getting type: %v", err) - } else if len(respTypes) < 1 { - t.Fatal("creating steering target: getting type: not found") - } - st.TypeID = util.IntPtr(respTypes[0].ID) - } - { - respDS, _, err := SteeringUserSession.GetDeliveryServiceByXMLIDNullable(string(*st.DeliveryService)) - if err != nil { - t.Fatalf("creating steering target: getting ds: %v", err) - } else if len(respDS) < 1 { - t.Fatal("creating steering target: getting ds: not found") - } else if respDS[0].ID == nil { - t.Fatal("creating steering target: getting ds: nil ID returned") - } - dsID := uint64(*respDS[0].ID) - st.DeliveryServiceID = &dsID - } - { - respTarget, _, err := SteeringUserSession.GetDeliveryServiceByXMLIDNullable(string(*st.Target)) - if err != nil { - t.Fatalf("creating steering target: getting target ds: %v", err) - } else if len(respTarget) < 1 { - t.Fatal("creating steering target: getting target ds: not found") - } else if respTarget[0].ID == nil { - t.Fatal("creating steering target: getting target ds: nil ID returned") - } - targetID := uint64(*respTarget[0].ID) - st.TargetID = &targetID - } - - resp, _, err := SteeringUserSession.CreateSteeringTarget(st) - t.Log("Response: ", resp) - if err != nil { - t.Fatalf("creating steering target: %v", err) - } - } -} - -func UpdateTestSteeringTargets(t *testing.T) { - if len(testData.SteeringTargets) < 1 { - t.Fatal("updating steering target: no steering target test data") - } - st := testData.SteeringTargets[0] - if st.DeliveryService == nil { - t.Fatal("updating steering target: test data missing ds") - } - if st.Target == nil { - t.Fatal("updating steering target: test data missing target") - } - - respDS, _, err := SteeringUserSession.GetDeliveryServiceByXMLIDNullable(string(*st.DeliveryService)) - if err != nil { - t.Fatalf("updating steering target: getting ds: %v", err) - } - if len(respDS) < 1 { - t.Fatal("updating steering target: getting ds: not found") - } - if respDS[0].ID == nil { - t.Fatal("updating steering target: getting ds: nil id returned") - } - dsID := *respDS[0].ID - - sts, _, err := SteeringUserSession.GetSteeringTargets(dsID) - if err != nil { - t.Fatalf("updating steering targets: getting steering target: %v", err) - } - if len(sts) < 1 { - t.Fatal("updating steering targets: getting steering target: got 0") - } - st = sts[0] - - expected := util.JSONIntStr(-12345) - if st.Value != nil && *st.Value == expected { - expected++ - } - st.Value = &expected - - _, _, err = SteeringUserSession.UpdateSteeringTarget(st) - if err != nil { - t.Fatalf("updating steering targets: updating: %+v", err) - } - - sts, _, err = SteeringUserSession.GetSteeringTargets(dsID) - if err != nil { - t.Fatalf("updating steering targets: getting updated steering target: %v", err) - } - if len(sts) < 1 { - t.Fatal("updating steering targets: getting updated steering target: got 0") - } - actual := sts[0] - - if actual.DeliveryServiceID == nil { - t.Fatalf("steering target update: ds id expected %v actual %v", dsID, nil) - } else if *actual.DeliveryServiceID != uint64(dsID) { - t.Fatalf("steering target update: ds id expected %v actual %v", dsID, *actual.DeliveryServiceID) - } - if actual.TargetID == nil { - t.Fatalf("steering target update: ds id expected %v actual %v", dsID, nil) - } else if *actual.TargetID != *st.TargetID { - t.Fatalf("steering target update: ds id expected %v actual %v", *st.TargetID, *actual.TargetID) - } - if actual.TypeID == nil { - t.Fatalf("steering target update: ds id expected %v actual %v", *st.TypeID, nil) - } else if *actual.TypeID != *st.TypeID { - t.Fatalf("steering target update: ds id expected %v actual %v", *st.TypeID, *actual.TypeID) - } - if actual.DeliveryService == nil { - t.Fatalf("steering target update: ds expected %v actual %v", *st.DeliveryService, nil) - } else if *st.DeliveryService != *actual.DeliveryService { - t.Fatalf("steering target update: ds name expected %v actual %v", *st.DeliveryService, *actual.DeliveryService) - } - if actual.Target == nil { - t.Fatalf("steering target update: target expected %v actual %v", *st.Target, nil) - } else if *st.Target != *actual.Target { - t.Fatalf("steering target update: target expected %v actual %v", *st.Target, *actual.Target) - } - if actual.Type == nil { - t.Fatalf("steering target update: type expected %v actual %v", *st.Type, nil) - } else if *st.Type != *actual.Type { - t.Fatalf("steering target update: type expected %v actual %v", *st.Type, *actual.Type) - } - if actual.Value == nil { - t.Fatalf("steering target update: ds expected %v actual %v", *st.Value, nil) - } else if *st.Value != *actual.Value { - t.Fatalf("steering target update: value expected %v actual %v", *st.Value, actual.Value) - } -} - -func GetTestSteeringTargets(t *testing.T) { - if len(testData.SteeringTargets) < 1 { - t.Fatal("updating steering target: no steering target test data") - } - st := testData.SteeringTargets[0] - if st.DeliveryService == nil { - t.Fatal("updating steering target: test data missing ds") - } - - respDS, _, err := SteeringUserSession.GetDeliveryServiceByXMLIDNullable(string(*st.DeliveryService)) - if err != nil { - t.Fatalf("creating steering target: getting ds: %v", err) - } else if len(respDS) < 1 { - t.Fatal("steering target get: getting ds: not found") - } else if respDS[0].ID == nil { - t.Fatal("steering target get: getting ds: nil id returned") - } - dsID := *respDS[0].ID - - sts, _, err := SteeringUserSession.GetSteeringTargets(dsID) - if err != nil { - t.Fatalf("steering target get: getting steering target: %v", err) - } - - if len(sts) != len(testData.SteeringTargets) { - t.Fatalf("steering target get: expected %v actual %v", len(testData.SteeringTargets), len(sts)) - } - - expected := testData.SteeringTargets[0] - actual := sts[0] - - if actual.DeliveryServiceID == nil { - t.Fatalf("steering target get: ds id expected %v actual %v", dsID, nil) - } else if *actual.DeliveryServiceID != uint64(dsID) { - t.Fatalf("steering target get: ds id expected %v actual %v", dsID, *actual.DeliveryServiceID) - } - if actual.DeliveryService == nil { - t.Fatalf("steering target get: ds expected %v actual %v", expected.DeliveryService, nil) - } else if *expected.DeliveryService != *actual.DeliveryService { - t.Fatalf("steering target get: ds name expected %v actual %v", expected.DeliveryService, actual.DeliveryService) - } - if actual.Target == nil { - t.Fatalf("steering target get: target expected %v actual %v", expected.Target, nil) - } else if *expected.Target != *actual.Target { - t.Fatalf("steering target get: target expected %v actual %v", expected.Target, actual.Target) - } - if actual.Type == nil { - t.Fatalf("steering target get: type expected %v actual %v", expected.Type, nil) - } else if *expected.Type != *actual.Type { - t.Fatalf("steering target get: type expected %v actual %v", expected.Type, actual.Type) - } - if actual.Value == nil { - t.Fatalf("steering target get: ds expected %v actual %v", expected.Value, nil) - } else if *expected.Value != *actual.Value { - t.Fatalf("steering target get: value expected %v actual %v", *expected.Value, *actual.Value) - } -} - -func DeleteTestSteeringTargets(t *testing.T) { - dsIDs := []uint64{} - if SteeringUserSession == nil { - t.Fatal("Steering user session is nil") - } - for _, st := range testData.SteeringTargets { - if st.DeliveryService == nil { - t.Fatal("deleting steering target: test data missing ds") - } - if st.Target == nil { - t.Fatal("deleting steering target: test data missing target") - } - - respDS, _, err := SteeringUserSession.GetDeliveryServiceByXMLIDNullable(string(*st.DeliveryService)) - if err != nil { - t.Fatalf("deleting steering target: getting ds: %v", err) - } else if len(respDS) < 1 { - t.Fatal("deleting steering target: getting ds: not found") - } else if respDS[0].ID == nil { - t.Fatal("deleting steering target: getting ds: nil ID returned") - } - dsID := uint64(*respDS[0].ID) - st.DeliveryServiceID = &dsID - - dsIDs = append(dsIDs, dsID) - - respTarget, _, err := SteeringUserSession.GetDeliveryServiceByXMLIDNullable(string(*st.Target)) - if err != nil { - t.Fatalf("deleting steering target: getting target ds: %v", err) - } else if len(respTarget) < 1 { - t.Fatal("deleting steering target: getting target ds: not found") - } else if respTarget[0].ID == nil { - t.Fatal("deleting steering target: getting target ds: not found") - } - targetID := uint64(*respTarget[0].ID) - st.TargetID = &targetID - - _, _, err = SteeringUserSession.DeleteSteeringTarget(int(*st.DeliveryServiceID), int(*st.TargetID)) - if err != nil { - t.Fatalf("deleting steering target: deleting: %+v", err) - } - } - - for _, dsID := range dsIDs { - sts, _, err := SteeringUserSession.GetSteeringTargets(int(dsID)) - if err != nil { - t.Fatalf("deleting steering targets: getting steering target: %v", err) - } - if len(sts) != 0 { - t.Fatalf("deleting steering targets: after delete, getting steering target: expected 0 actual %+v", len(sts)) - } - } -} diff --git a/traffic_ops/testing/api/v2/tc-fixtures.json b/traffic_ops/testing/api/v2/tc-fixtures.json deleted file mode 100644 index 77467ff78c..0000000000 --- a/traffic_ops/testing/api/v2/tc-fixtures.json +++ /dev/null @@ -1,2714 +0,0 @@ -{ - "asns": [ - { - "asn": 8888, - "cachegroupName": "mid-northeast-group" - }, - { - "asn": 9999, - "cachegroupName": "edge_cg4" - } - ], - "cachegroups": [ - { - "latitude": 0, - "longitude": 0, - "name": "originCachegroup", - "shortName": "og1", - "typeName": "ORG_LOC" - }, - { - "latitude": 0, - "longitude": 0, - "name": "multiOriginCachegroup", - "shortName": "mog1", - "typeName": "ORG_LOC" - }, - { - "latitude": 0, - "longitude": 0, - "name": "parentCachegroup", - "shortName": "pg1", - "typeName": "MID_LOC" - }, - { - "latitude": 0, - "longitude": 0, - "name": "secondaryCachegroup", - "shortName": "sg1", - "typeName": "MID_LOC" - }, - { - "latitude": 0, - "longitude": 0, - "name": "cachegroup1", - "parentCachegroupName": "parentCachegroup", - "secondaryParentCachegroupName": "secondaryCachegroup", - "shortName": "cg1", - "localizationMethods": [ - "CZ", - "DEEP_CZ", - "GEO" - ], - "typeName": "EDGE_LOC" - }, - { - "latitude": 0, - "longitude": 0, - "name": "fallback1", - "parentCachegroupName": "parentCachegroup", - "secondaryParentCachegroupName": "secondaryCachegroup", - "shortName": "fb1", - "localizationMethods": [ - "CZ", - "DEEP_CZ", - "GEO" - ], - "typeName": "EDGE_LOC" - }, - { - "latitude": 0, - "longitude": 0, - "name": "fallback2", - "parentCachegroupName": "parentCachegroup", - "secondaryParentCachegroupName": "secondaryCachegroup", - "shortName": "fb2", - "localizationMethods": [ - "CZ", - "DEEP_CZ", - "GEO" - ], - "typeName": "EDGE_LOC" - }, - { - "latitude": 0, - "longitude": 0, - "name": "fallback3", - "parentCachegroupName": "parentCachegroup", - "secondaryParentCachegroupName": "secondaryCachegroup", - "shortName": "fb3", - "localizationMethods": [ - "CZ", - "DEEP_CZ", - "GEO" - ], - "typeName": "EDGE_LOC" - }, - { - "latitude": 24.1234, - "longitude": -121.1234, - "name": "cachegroup2", - "parentCachegroupName": "secondaryCachegroup", - "secondaryParentCachegroupName": "parentCachegroup", - "shortName": "cg2", - "typeName": "EDGE_LOC", - "fallbacks": [ - "fallback1", - "fallback2", - "fallback3" - ] - }, - { - "latitude": 0, - "longitude": 0, - "name": "cachegroup3", - "parentCachegroupName": "parentCachegroup", - "secondaryParentCachegroupName": "secondaryCachegroup", - "shortName": "cg3", - "typeName": "EDGE_LOC" - } - ], - "cdns": [ - { - "dnssecEnabled": false, - "domainName": "test.cdn1.net", - "name": "cdn1" - }, - { - "dnssecEnabled": false, - "domainName": "test.cdn2.net", - "name": "cdn2" - }, - { - "dnssecEnabled": false, - "domainName": "test.cdn3.net", - "name": "cdn3" - }, - { - "dnssecEnabled": false, - "domainName": "test.cdn4.net", - "name": "cdn4" - }, - { - "dnssecEnabled": false, - "domainName": "test.bar.net", - "name": "bar" - } - ], - "deliveryServiceRequestComments": [ - { - "value": "this is comment one" - }, - { - "value": "this is comment two" - }, - { - "value": "this is comment three" - }, - { - "value": "this is comment four" - } - ], - "deliveryServiceRequests": [ - { - "changeType": "create", - "deliveryService": { - "active": true, - "cdnName": "cdn1", - "ccrDnsTtl": 30, - "deepCachingType": "NEVER", - "displayName": "Good Kabletown CDN", - "dscp": 1, - "geoLimit": 1, - "geoProvider": 1, - "initialDispersion": 1, - "logsEnabled": true, - "longDesc": "long desc", - "regionalGeoBlocking": true, - "routingName": "goodroute", - "tenant": "tenant1", - "type": "HTTP", - "xmlId": "test-ds1" - }, - "status": "draft" - }, - { - "changeType": "create", - "deliveryService": { - "active": true, - "cdnName": "cdn1", - "ccrDnsTtl": 30, - "deepCachingType": "NEVER", - "displayName": "Bad Tenant", - "dscp": 0, - "geoLimit": 0, - "geoProvider": 0, - "initialDispersion": 3, - "logsEnabled": false, - "longDesc": "long desc", - "regionalGeoBlocking": false, - "tenant": "root", - "type": "HTTP", - "xmlId": "test-ds2" - }, - "status": "draft" - }, - { - "changeType": "create", - "deliveryService": { - "ccrDnsTtl": 30, - "deepCachingType": "NEVER", - "displayName": "Bad Test Case CDN", - "dscp": 0, - "geoLimit": 0, - "geoProvider": 1, - "infoUrl": "xxx", - "initialDispersion": 1, - "logsEnabled": true, - "longDesc": "long desc", - "orgServerFqdn": "xxx", - "regionalGeoBlocking": true, - "routingName": "x routing", - "tenant": "tenant1", - "type": "HTTP", - "xmlId": "test-ds3" - }, - "status": "draft" - }, - { - "changeType": "create", - "deliveryService": { - "active": false, - "cdnName": "cdn1", - "ccrDnsTtl": 30, - "deepCachingType": "NEVER", - "displayName": "Testing transitions", - "dscp": 3, - "geoLimit": 1, - "geoProvider": 1, - "initialDispersion": 1, - "logsEnabled": true, - "longDesc": "long desc", - "regionalGeoBlocking": true, - "routingName": "goodroute", - "tenant": "tenant1", - "type": "HTTP", - "xmlId": "test-transitions" - }, - "status": "draft" - } - ], - "deliveryServices": [ - { - "active": true, - "cdnName": "cdn1", - "cacheurl": "cacheUrl1", - "ccrDnsTtl": 3600, - "checkPath": "", - "consistentHashQueryParams": [], - "deepCachingType": "NEVER", - "displayName": "ds1DisplayName", - "dnsBypassCname": null, - "dnsBypassIp": "", - "dnsBypassIp6": "", - "dnsBypassTtl": 30, - "dscp": 40, - "edgeHeaderRewrite": "edgeHeader1\nedgeHeader2", - "exampleURLs": [ - "http://ccr.ds1.example.net", - "https://ccr.ds1.example.net" - ], - "fqPacingRate": 0, - "geoLimit": 0, - "geoLimitCountries": "", - "geoLimitRedirectURL": null, - "geoProvider": 0, - "globalMaxMbps": 0, - "globalMaxTps": 0, - "httpBypassFqdn": "", - "infoUrl": "TBD", - "initialDispersion": 1, - "ipv6RoutingEnabled": true, - "lastUpdated": "2018-04-06 16:48:51+00", - "logsEnabled": false, - "longDesc": "d s 1", - "longDesc1": "ds1", - "longDesc2": "ds1", - "matchList": [ - { - "pattern": ".*\\.ds1\\..*", - "setNumber": 0, - "type": "HOST_REGEXP" - } - ], - "maxDnsAnswers": 0, - "midHeaderRewrite": "midHeader1\nmidHeader2", - "missLat": 41.881944, - "missLong": -87.627778, - "multiSiteOrigin": false, - "orgServerFqdn": "http://origin.example.net", - "originShield": null, - "profileDescription": null, - "profileName": null, - "protocol": 2, - "qstringIgnore": 1, - "rangeRequestHandling": 0, - "regexRemap": "rr1\nrr2", - "regionalGeoBlocking": false, - "remapText": "@plugin=tslua.so @pparam=/opt/trafficserver/etc/trafficserver/remapPlugin1.lua", - "routingName": "ccr-ds1", - "signed": false, - "signingAlgorithm": "url_sig", - "sslKeyVersion": 2, - "tenant": "tenant1", - "tenantName": "tenant1", - "type": "HTTP_LIVE", - "xmlId": "ds1", - "anonymousBlockingEnabled": true - }, - { - "active": true, - "cdnName": "cdn1", - "cacheurl": "cacheUrl2", - "ccrDnsTtl": 3600, - "checkPath": "", - "consistentHashQueryParams": ["fmt", "limit", "somethingelse"], - "deepCachingType": "NEVER", - "displayName": "d s 1", - "dnsBypassCname": null, - "dnsBypassIp": "", - "dnsBypassIp6": "", - "dnsBypassTtl": 30, - "dscp": 40, - "edgeHeaderRewrite": "edgeRewrite1\nedgeHeader2", - "exampleURLs": [ - "http://ccr.ds2.example.net", - "https://ccr.ds2x.example.net" - ], - "fqPacingRate": 0, - "geoLimit": 0, - "geoLimitCountries": "", - "geoLimitRedirectURL": null, - "geoProvider": 0, - "globalMaxMbps": 0, - "globalMaxTps": 0, - "httpBypassFqdn": "", - "infoUrl": "TBD", - "initialDispersion": 1, - "ipv6RoutingEnabled": true, - "lastUpdated": "2018-04-06 16:48:51+00", - "logsEnabled": false, - "longDesc": "d s 1", - "longDesc1": "ds2", - "longDesc2": "ds2", - "matchList": [ - { - "pattern": ".*\\.ds2\\..*", - "setNumber": 0, - "type": "HOST_REGEXP" - } - ], - "maxDnsAnswers": 0, - "maxOriginConnections": -1, - "midHeaderRewrite": "midHeader1\nmidHeader2", - "missLat": 41.881944, - "missLong": -87.627778, - "multiSiteOrigin": false, - "orgServerFqdn": "http://origin.ds2.example.net", - "originShield": null, - "profileDescription": null, - "profileName": null, - "protocol": 2, - "qstringIgnore": 1, - "rangeRequestHandling": 0, - "regexRemap": "rr1\nrr2", - "regionalGeoBlocking": false, - "remapText": "@plugin=tslua.so @pparam=/opt/trafficserver/etc/trafficserver/ds2plugin.lua", - "routingName": "ccr-ds2", - "signed": false, - "signingAlgorithm": "url_sig", - "sslKeyVersion": 2, - "tenant": "tenant2", - "tenantName": "tenant2", - "type": "HTTP_LIVE", - "xmlId": "ds2", - "anonymousBlockingEnabled": true - }, - { - "active": true, - "cdnName": "cdn1", - "cacheurl": "cacheUrl3", - "ccrDnsTtl": 3600, - "checkPath": "", - "consistentHashQueryParams": null, - "deepCachingType": "NEVER", - "displayName": "d s 1", - "dnsBypassCname": null, - "dnsBypassIp": "", - "dnsBypassIp6": "", - "dnsBypassTtl": 30, - "dscp": 40, - "edgeHeaderRewrite": "edgeRewrite1\nedgeHeader2", - "exampleURLs": [ - "http://ccr.ds3.example.net", - "https://ccr.ds3x.example.net" - ], - "fqPacingRate": 0, - "geoLimit": 0, - "geoLimitCountries": "", - "geoLimitRedirectURL": null, - "geoProvider": 0, - "globalMaxMbps": 0, - "globalMaxTps": 0, - "httpBypassFqdn": "", - "infoUrl": "TBD", - "initialDispersion": 1, - "ipv6RoutingEnabled": true, - "lastUpdated": "2018-04-06 16:48:51+00", - "logsEnabled": false, - "longDesc": "d s 3", - "longDesc1": "ds3", - "longDesc2": "ds3", - "matchList": [ - { - "pattern": ".*\\.ds3\\..*", - "setNumber": 0, - "type": "HOST_REGEXP" - } - ], - "maxDnsAnswers": 0, - "maxOriginConnections": 0, - "midHeaderRewrite": "midHeader1\nmidHeader2", - "missLat": 41.881944, - "missLong": -87.627778, - "multiSiteOrigin": false, - "orgServerFqdn": "http://origin.ds3.example.net", - "originShield": null, - "profileDescription": null, - "profileName": null, - "protocol": 2, - "qstringIgnore": 1, - "rangeRequestHandling": 0, - "regexRemap": "rr1\nrr2", - "regionalGeoBlocking": false, - "remapText": "@plugin=tslua.so @pparam=/opt/trafficserver/etc/trafficserver/ds3plugin.lua", - "routingName": "ccr-ds3", - "signed": false, - "signingAlgorithm": "url_sig", - "sslKeyVersion": 2, - "tenant": "tenant3", - "tenantName": "tenant3", - "type": "HTTP_LIVE", - "xmlId": "ds3", - "anonymousBlockingEnabled": true - }, - { - "active": true, - "cdnName": "cdn1", - "cacheurl": "", - "ccrDnsTtl": 3600, - "checkPath": "", - "deepCachingType": "NEVER", - "displayName": "anymap-ds", - "dnsBypassCname": null, - "dnsBypassIp": "", - "dnsBypassIp6": "", - "dnsBypassTtl": 30, - "dscp": 40, - "edgeHeaderRewrite": "", - "exampleURLs": [], - "fqPacingRate": 0, - "geoLimit": 0, - "geoLimitCountries": "", - "geoLimitRedirectURL": null, - "geoProvider": 0, - "globalMaxMbps": 0, - "globalMaxTps": 0, - "httpBypassFqdn": "", - "infoUrl": "", - "initialDispersion": 1, - "ipv6RoutingEnabled": true, - "lastUpdated": "2018-04-06 16:48:51+00", - "logsEnabled": false, - "longDesc": "", - "longDesc1": "", - "longDesc2": "", - "matchList": [], - "maxDnsAnswers": 0, - "maxOriginConnections": 1, - "midHeaderRewrite": "", - "missLat": 41.881944, - "missLong": -87.627778, - "multiSiteOrigin": false, - "orgServerFqdn": "http://example.com", - "originShield": null, - "profileDescription": null, - "profileName": null, - "protocol": 2, - "qstringIgnore": 1, - "rangeRequestHandling": 0, - "regexRemap": "", - "regionalGeoBlocking": false, - "remapText": "map some raw remap text", - "routingName": "", - "signed": false, - "signingAlgorithm": "url_sig", - "sslKeyVersion": 2, - "tenant": "tenant3", - "tenantName": "tenant3", - "type": "ANY_MAP", - "xmlId": "anymap-ds", - "anonymousBlockingEnabled": true - }, - { - "active": true, - "cdnName": "cdn1", - "cacheurl": "cacheUrl1", - "ccrDnsTtl": 3600, - "checkPath": "", - "consistentHashQueryParams": ["a", "b", "c"], - "consistentHashRegex": "foo", - "deepCachingType": "ALWAYS", - "displayName": "ds-test-minor-versions", - "dnsBypassCname": null, - "dnsBypassIp": "", - "dnsBypassIp6": "", - "dnsBypassTtl": 30, - "dscp": 40, - "edgeHeaderRewrite": "edgeRewrite1\nedgeHeader2", - "fqPacingRate": 42, - "geoLimit": 0, - "geoLimitCountries": "", - "geoLimitRedirectURL": null, - "geoProvider": 0, - "globalMaxMbps": 0, - "globalMaxTps": 0, - "httpBypassFqdn": "", - "infoUrl": "TBD", - "initialDispersion": 1, - "ipv6RoutingEnabled": true, - "logsEnabled": false, - "longDesc": "d s 1", - "longDesc1": "ds1", - "longDesc2": "ds1", - "maxDnsAnswers": 0, - "maxOriginConnections": 1000, - "midHeaderRewrite": "midHeader1\nmidHeader2", - "missLat": 41.881944, - "missLong": -87.627778, - "multiSiteOrigin": false, - "orgServerFqdn": "http://origin-test-minor-version.example.net", - "originShield": null, - "profileDescription": null, - "profileName": null, - "protocol": 2, - "qstringIgnore": 1, - "rangeRequestHandling": 0, - "regexRemap": "rr1\nrr2", - "regionalGeoBlocking": false, - "remapText": "@plugin=tslua.so @pparam=/opt/trafficserver/etc/trafficserver/remapPlugin1.lua", - "routingName": "cdn", - "signed": true, - "signingAlgorithm": "url_sig", - "sslKeyVersion": 2, - "tenantId": 1, - "tenant": "root", - "trRequestHeaders": "X-Foo\nX-Bar", - "trResponseHeaders": "Access-Control-Allow-Origin: *\nContent-Type: text/html; charset=utf-8", - "type": "HTTP_LIVE", - "xmlId": "ds-test-minor-versions", - "anonymousBlockingEnabled": true - }, - { - "active": true, - "cdnName": "cdn1", - "cacheurl": "cacheUrl1", - "ccrDnsTtl": 3600, - "checkPath": "", - "consistentHashQueryParams": [], - "deepCachingType": "NEVER", - "displayName": "ds1DisplayName", - "dnsBypassCname": null, - "dnsBypassIp": "", - "dnsBypassIp6": "", - "dnsBypassTtl": 30, - "dscp": 40, - "edgeHeaderRewrite": "edgeRewrite1\nedgeHeader2", - "exampleURLs": [ - "http://ccr.msods1.example.net", - "https://ccr.msods1.example.net" - ], - "fqPacingRate": 0, - "geoLimit": 0, - "geoLimitCountries": "", - "geoLimitRedirectURL": null, - "geoProvider": 0, - "globalMaxMbps": 0, - "globalMaxTps": 0, - "httpBypassFqdn": "", - "infoUrl": "TBD", - "initialDispersion": 1, - "ipv6RoutingEnabled": true, - "lastUpdated": "2018-04-06 16:48:51+00", - "logsEnabled": false, - "longDesc": "mso DS 1", - "longDesc1": "msods1", - "longDesc2": "msods1", - "matchList": [ - { - "pattern": ".*\\.msods1\\..*", - "setNumber": 0, - "type": "HOST_REGEXP" - } - ], - "maxDnsAnswers": 0, - "midHeaderRewrite": "midHeader1\nmidHeader2", - "missLat": 41.881944, - "missLong": -87.627778, - "multiSiteOrigin": true, - "orgServerFqdn": "http://origin.example.net", - "originShield": null, - "profileDescription": null, - "profileName": null, - "protocol": 2, - "qstringIgnore": 1, - "rangeRequestHandling": 0, - "regexRemap": "rr1\nrr2", - "regionalGeoBlocking": false, - "remapText": "@plugin=tslua.so @pparam=/opt/trafficserver/etc/trafficserver/remapPlugin1.lua", - "routingName": "ccr-msods1", - "signed": false, - "signingAlgorithm": "url_sig", - "sslKeyVersion": 2, - "tenant": "tenant1", - "tenantName": "tenant1", - "type": "HTTP_LIVE", - "xmlId": "msods1", - "anonymousBlockingEnabled": true - }, - { - "active": true, - "cdnName": "cdn1", - "cacheurl": "cacheUrl1", - "ccrDnsTtl": 3600, - "checkPath": "", - "consistentHashQueryParams": [], - "deepCachingType": "NEVER", - "displayName": "ds1natDisplayName", - "dnsBypassCname": null, - "dnsBypassIp": "", - "dnsBypassIp6": "", - "dnsBypassTtl": 30, - "dscp": 40, - "edgeHeaderRewrite": "edgeRewrite1\nedgeHeader2", - "exampleURLs": [ - "http://ccr.ds1nat.example.net", - "https://ccr.ds1nat.example.net" - ], - "fqPacingRate": 0, - "geoLimit": 0, - "geoLimitCountries": "", - "geoLimitRedirectURL": null, - "geoProvider": 0, - "globalMaxMbps": 0, - "globalMaxTps": 0, - "httpBypassFqdn": "", - "infoUrl": "TBD", - "initialDispersion": 1, - "ipv6RoutingEnabled": true, - "lastUpdated": "2018-04-06 16:48:51+00", - "logsEnabled": false, - "longDesc": "d s 1", - "longDesc1": "ds1nat", - "longDesc2": "ds1nat", - "matchList": [ - { - "pattern": ".*\\.ds1nat\\..*", - "setNumber": 0, - "type": "HOST_REGEXP" - } - ], - "maxDnsAnswers": 0, - "midHeaderRewrite": "midHeader1\nmidHeader2", - "missLat": 41.881944, - "missLong": -87.627778, - "multiSiteOrigin": false, - "orgServerFqdn": "http://origin.example.net", - "originShield": null, - "profileDescription": null, - "profileName": null, - "protocol": 2, - "qstringIgnore": 1, - "rangeRequestHandling": 0, - "regexRemap": "rr1\nrr2", - "regionalGeoBlocking": false, - "remapText": "@plugin=tslua.so @pparam=/opt/trafficserver/etc/trafficserver/remapPlugin1.lua", - "routingName": "ccr-ds1nat", - "signed": false, - "signingAlgorithm": "url_sig", - "sslKeyVersion": 2, - "tenant": "tenant1", - "tenantName": "tenant1", - "type": "HTTP_LIVE_NATNL", - "xmlId": "ds1nat", - "anonymousBlockingEnabled": true - } - ], - "deliveryServicesRegexes": [ - { - "dsName": "ds1", - "typeName": "HOST_REGEXP", - "setNumber": 1, - "pattern" : ".*" - }, - { - "dsName": "ds1", - "typeName": "HOST_REGEXP", - "setNumber": 2, - "pattern" : "\\d+" - }, - { - "dsName": "ds2", - "typeName": "HOST_REGEXP", - "setNumber": 1, - "pattern" : ".*" - }, - { - "dsName": "ds1", - "typeName": "HOST_REGEXP", - "setNumber": 3, - "pattern" : "" - } - ], - "deliveryservicesRequiredCapabilities": [ - { - "xmlID": "ds1", - "RequiredCapability": "foo" - }, - { - "xmlID": "ds2", - "RequiredCapability": "bar" - }, - { - "xmlID": "msods1", - "RequiredCapability": "bar" - } - ], - "divisions": [ - { - "name": "division1" - }, - { - "name": "division2" - } - ], - "federations": [ - { - "cname": "the.cname.com.", - "ttl": 48, - "description": "the description", - "deliveryService": - { - "xmlId": "ds1" - } - }, - { - "cname": "booya.com.", - "ttl": 34, - "description": "fooya", - "deliveryService": - { - "xmlId": "ds1" - } - } - ], - "federation_resolvers": [ - { - "ipAddress": "1.2.3.4", - "type": "RESOLVE4", - "id": 1 - }, - { - "ipAddress": "0.0.0.0/12", - "type": "RESOLVE4", - "id": 2 - }, - { - "ipAddress": "dead::babe", - "type": "RESOLVE6", - "id": 3 - }, - { - "ipAddress": "::f1d0:f00d/123", - "type": "RESOLVE6", - "id": 4 - } - ], - "coordinates": [ - { - "latitude": 1.1, - "longitude": 2.2, - "name": "coordinate1" - }, - { - "latitude": 3.3, - "longitude": 4.4, - "name": "coordinate2" - } - ], - "origins": [ - { - "name": "origin1", - "cachegroup": "originCachegroup", - "deliveryService": "ds1", - "fqdn": "origin1.example.com", - "ipAddress": "1.2.3.4", - "ip6Address": "dead:beef:cafe::42", - "port": 1234, - "protocol": "http", - "tenant": "tenant1" - }, - { - "name": "origin2", - "cachegroup": "originCachegroup", - "deliveryService": "ds2", - "fqdn": "origin2.example.com", - "ipAddress": "5.6.7.8", - "ip6Address": "cafe::42", - "port": 5678, - "protocol": "https", - "tenant": "tenant1" - } - ], - "parameters": [ - { - "configFile": "rascal.properties", - "lastUpdated": "2018-01-19T19:01:21.489534+00:00", - "name": "history.count", - "secure": false, - "value": "30" - }, - { - "configFile": "records.config", - "lastUpdated": "2018-01-19T19:01:21.434425+00:00", - "name": "CONFIG proxy.config.allocator.enable_reclaim", - "secure": false, - "value": "INT 0" - }, - { - "configFile": "records.config", - "lastUpdated": "2018-01-19T19:01:21.435957+00:00", - "name": "CONFIG proxy.config.allocator.max_overage", - "secure": false, - "value": "INT 3" - }, - { - "configFile": "records.config", - "lastUpdated": "2018-01-19T19:01:21.437496+00:00", - "name": "CONFIG proxy.config.diags.show_location", - "secure": false, - "value": "INT 0" - }, - { - "configFile": "records.config", - "lastUpdated": "2018-01-19T19:01:21.439033+00:00", - "name": "CONFIG proxy.config.http.cache.allow_empty_doc", - "secure": false, - "value": "INT 0" - }, - { - "configFile": "records.config", - "lastUpdated": "2018-01-19T19:01:21.440502+00:00", - "name": "LOCAL proxy.config.cache.interim.storage", - "secure": false, - "value": "STRING NULL" - }, - { - "configFile": "records.config", - "lastUpdated": "2018-01-19T19:01:21.441933+00:00", - "name": "CONFIG proxy.config.http.parent_proxy.file", - "secure": false, - "value": "STRING parent.config" - }, - { - "configFile": "plugin.config", - "lastUpdated": "2018-01-19T19:01:21.447837+00:00", - "name": "astats_over_http.so", - "secure": false, - "value": "_astats 33.101.99.100,172.39.19.39,172.39.19.49,172.39.19.49,172.39.29.49" - }, - { - "configFile": "logs_xml.config", - "lastUpdated": "2018-01-19T19:01:21.461206+00:00", - "name": "LogFormat.Name", - "secure": false, - "value": "custom_ats_2" - }, - { - "configFile": "logs_xml.config", - "lastUpdated": "2018-01-19T19:01:21.462772+00:00", - "name": "LogObject.Format", - "secure": false, - "value": "custom_ats_2" - }, - { - "configFile": "logs_xml.config", - "lastUpdated": "2018-01-19T19:01:21.464259+00:00", - "name": "LogObject.Filename", - "secure": false, - "value": "custom_ats_2" - }, - { - "configFile": "records.config", - "lastUpdated": "2018-01-19T19:01:21.467349+00:00", - "name": "CONFIG proxy.config.cache.control.filename", - "secure": false, - "value": "STRING cache.config" - }, - { - "configFile": "plugin.config", - "lastUpdated": "2018-01-19T19:01:21.469075+00:00", - "name": "regex_revalidate.so", - "secure": false, - "value": "--config regex_revalidate.config" - }, - { - "configFile": "records.config", - "lastUpdated": "2018-01-19T19:01:21.49285+00:00", - "name": "CONFIG proxy.config.hostdb.storage_size", - "secure": false, - "value": "INT 33554432" - }, - { - "configFile": "regex_revalidate.config", - "lastUpdated": "2018-01-19T19:01:21.496195+00:00", - "name": "maxRevalDurationDays", - "secure": false, - "value": "90" - }, - { - "configFile": "package", - "lastUpdated": "2018-01-19T19:01:21.499423+00:00", - "name": "trafficserver", - "secure": false, - "value": "5.3.2-765.f4354b9.el7.centos.x86_64" - }, - { - "configFile": "global", - "lastUpdated": "2018-01-19T19:01:21.501151+00:00", - "name": "use_tenancy", - "secure": false, - "value": "1" - }, - { - "configFile": "global", - "lastUpdated": "2020-04-21T05:19:43.853831+00:00", - "name": "tm.instance_name", - "secure": false, - "value": "Traffic Ops API Tests" - } - ], - "physLocations": [ - { - "address": "1234 mile high circle", - "city": "Denver", - "comments": null, - "email": null, - "lastUpdated": "2018-01-19T21:19:32.081465+00:00", - "name": "Denver", - "phone": "303-111-1111", - "poc": null, - "region": "region1", - "shortName": "denver", - "state": "CO", - "zip": "80202" - }, - { - "address": "1234 green way", - "city": "Boulder", - "comments": null, - "email": null, - "lastUpdated": "2018-01-19T21:19:32.086195+00:00", - "name": "Boulder", - "phone": "303-222-2222", - "poc": null, - "region": "region1", - "shortName": "boulder", - "state": "CO", - "zip": "80301" - }, - { - "address": "1234 southern way", - "city": "Atlanta", - "comments": null, - "email": null, - "lastUpdated": "2018-01-19T21:19:32.089538+00:00", - "name": "HotAtlanta", - "phone": "404-222-2222", - "poc": null, - "region": "region1", - "shortName": "atlanta", - "state": "GA", - "zip": "30301" - } - ], - "profiles": [ - { - "cdnName": "cdn1", - "description": "Edge Cache - Apache Traffic Server", - "name": "ATS_EDGE_TIER_CACHE", - "routingDisabled": false, - "type": "ATS_PROFILE", - "params": [ - { - "configFile": "records.config", - "name": "CONFIG proxy.config.proxy_name", - "secure": false, - "value": "STRING __HOSTNAME__" - }, - { - "configFile": "records.config", - "name": "CONFIG proxy.config.config_dir", - "secure": false, - "value": "STRING /etc/trafficserver" - }, - { - "configFile": "records.config", - "name": "CONFIG proxy.config.admin.user_id", - "secure": false, - "value": "STRING ats" - }, - { - "configFile": "records.config", - "name": "CONFIG proxy.config.http.server_ports", - "secure": false, - "value": "STRING 80 80:ipv6" - }, - { - "configFile": "records.config", - "name": "CONFIG proxy.config.http.insert_response_via_str", - "secure": false, - "value": "INT 3" - }, - { - "configFile": "records.config", - "name": "CONFIG proxy.config.http.parent_proxy_routing_enable", - "secure": false, - "value": "INT 1" - }, - { - "configFile": "records.config", - "name": "CONFIG proxy.config.http.parent_proxy.retry_time", - "secure": false, - "value": "INT 60" - }, - { - "configFile": "records.config", - "name": "CONFIG proxy.config.http.connect_attempts_timeout", - "secure": false, - "value": "INT 10" - }, - { - "configFile": "records.config", - "name": "CONFIG proxy.config.http.cache.required_headers", - "secure": false, - "value": "INT 0" - }, - { - "configFile": "records.config", - "name": "CONFIG proxy.config.http.enable_http_stats", - "secure": false, - "value": "INT 1" - }, - { - "configFile": "records.config", - "name": "CONFIG proxy.config.dns.round_robin_nameservers", - "secure": false, - "value": "INT 0" - }, - { - "configFile": "records.config", - "name": "CONFIG proxy.config.log.max_space_mb_for_logs", - "secure": false, - "value": "INT 512" - }, - { - "configFile": "records.config", - "name": "CONFIG proxy.config.log.max_space_mb_headroom", - "secure": false, - "value": "INT 50" - }, - { - "configFile": "records.config", - "name": "CONFIG proxy.config.log.logfile_dir", - "secure": false, - "value": "STRING /var/log/trafficserver" - }, - { - "configFile": "records.config", - "name": "CONFIG proxy.config.reverse_proxy.enabled", - "secure": false, - "value": "INT 0" - }, - { - "configFile": "records.config", - "name": "CONFIG proxy.config.diags.debug.enabled", - "secure": false, - "value": "INT 1" - }, - { - "configFile": "records.config", - "name": "CONFIG proxy.config.http.slow.log.threshold", - "secure": false, - "value": "INT 10000" - }, - { - "configFile": "cache.config", - "name": "location", - "secure": false, - "value": "/etc/trafficserver/" - }, - { - "configFile": "hosting.config", - "name": "location", - "secure": false, - "value": "/etc/trafficserver/" - }, - { - "configFile": "parent.config", - "name": "location", - "secure": false, - "value": "/etc/trafficserver/" - }, - { - "configFile": "plugin.config", - "name": "location", - "secure": false, - "value": "/etc/trafficserver/" - }, - { - "configFile": "records.config", - "name": "location", - "secure": false, - "value": "/etc/trafficserver/" - }, - { - "configFile": "storage.config", - "name": "location", - "secure": false, - "value": "/etc/trafficserver/" - }, - { - "configFile": "volume.config", - "name": "location", - "secure": false, - "value": "/etc/trafficserver/" - }, - { - "configFile": "records.config", - "name": "CONFIG proxy.config.url_remap.remap_required", - "secure": false, - "value": "INT 0" - }, - { - "configFile": "rascal.properties", - "name": "health.threshold.queryTime", - "secure": false, - "value": "1000" - }, - { - "configFile": "rascal.properties", - "name": "health.polling.url", - "secure": false, - "value": "http://${hostname}/_astats?application=&inf.name=${interface_name}" - }, - { - "configFile": "storage.config", - "name": "Disk_Volume", - "secure": false, - "value": "1" - }, - { - "configFile": "rascal.properties", - "name": "health.connection.timeout", - "secure": false, - "value": "2000" - }, - { - "configFile": "chkconfig", - "name": "trafficserver", - "secure": false, - "value": "0:off\t1:off\t2:on\t3:on\t4:on\t5:on\t6:off" - }, - { - "configFile": "regex_revalidate.config", - "name": "location", - "secure": false, - "value": "/etc/trafficserver" - }, - { - "configFile": "records.config", - "name": "CONFIG proxy.config.exec_thread.autoconfig", - "secure": false, - "value": "INT 0" - }, - { - "configFile": "plugin.config", - "name": "astats_over_http.so", - "secure": false, - "value": "" - }, - { - "configFile": "astats.config", - "name": "allow_ip", - "secure": false, - "value": "127.0.0.1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16" - }, - { - "configFile": "astats.config", - "name": "allow_ip6", - "secure": false, - "value": "::1/128,fc01:9400:1000:8::/64" - }, - { - "configFile": "astats.config", - "name": "location", - "secure": false, - "value": "/etc/trafficserver" - }, - { - "configFile": "astats.config", - "name": "path", - "secure": false, - "value": "_astats" - }, - { - "configFile": "astats.config", - "name": "record_types", - "secure": false, - "value": "122" - }, - { - "configFile": "records.config", - "name": "CONFIG proxy.config.http.transaction_active_timeout_in", - "secure": false, - "value": "INT 0" - }, - { - "configFile": "records.config", - "name": "CONFIG proxy.config.body_factory.template_sets_dir", - "secure": false, - "value": "STRING /etc/trafficserver/body_factory" - }, - { - "configFile": "storage.config", - "name": "Drive_Letters", - "secure": false, - "value": "cache" - }, - { - "configFile": "ip_allow.config", - "name": "location", - "secure": false, - "value": "/etc/trafficserver" - }, - { - "configFile": "storage.config", - "name": "Drive_Prefix", - "secure": false, - "value": "/var/trafficserver/" - }, - { - "configFile": "set_dscp_0.config", - "name": "location", - "value": "/etc/trafficserver/dscp" - }, - { - "configFile": "set_dscp_10.config", - "name": "location", - "value": "/etc/trafficserver/dscp" - }, - { - "configFile": "set_dscp_12.config", - "name": "location", - "value": "/etc/trafficserver/dscp" - }, - { - "configFile": "set_dscp_14.config", - "name": "location", - "value": "/etc/trafficserver/dscp" - }, - { - "configFile": "set_dscp_18.config", - "name": "location", - "value": "/etc/trafficserver/dscp" - }, - { - "configFile": "set_dscp_20.config", - "name": "location", - "value": "/etc/trafficserver/dscp" - }, - { - "configFile": "set_dscp_22.config", - "name": "location", - "value": "/etc/trafficserver/dscp" - }, - { - "configFile": "set_dscp_26.config", - "name": "location", - "value": "/etc/trafficserver/dscp" - }, - { - "configFile": "set_dscp_28.config", - "name": "location", - "value": "/etc/trafficserver/dscp" - }, - { - "configFile": "set_dscp_30.config", - "name": "location", - "value": "/etc/trafficserver/dscp" - }, - { - "configFile": "set_dscp_34.config", - "name": "location", - "value": "/etc/trafficserver/dscp" - }, - { - "configFile": "set_dscp_36.config", - "name": "location", - "value": "/etc/trafficserver/dscp" - }, - { - "configFile": "set_dscp_38.config", - "name": "location", - "value": "/etc/trafficserver/dscp" - }, - { - "configFile": "set_dscp_8.config", - "name": "location", - "value": "/etc/trafficserver/dscp" - }, - { - "configFile": "set_dscp_16.config", - "name": "location", - "value": "/etc/trafficserver/dscp" - }, - { - "configFile": "set_dscp_24.config", - "name": "location", - "value": "/etc/trafficserver/dscp" - }, - { - "configFile": "set_dscp_32.config", - "name": "location", - "value": "/etc/trafficserver/dscp" - }, - { - "configFile": "set_dscp_40.config", - "name": "location", - "value": "/etc/trafficserver/dscp" - }, - { - "configFile": "set_dscp_48.config", - "name": "location", - "value": "/etc/trafficserver/dscp" - }, - { - "configFile": "set_dscp_56.config", - "name": "location", - "value": "/etc/trafficserver/dscp" - }, - { - "configFile": "set_dscp_37.config", - "name": "location", - "value": "/etc/trafficserver/dscp" - } - ] - }, - { - "cdnName": "cdn1", - "description": "edge1 description", - "lastUpdated": "2018-03-02T17:27:11.818418+00:00", - "name": "EDGE1", - "routing_disabled": false, - "type": "ATS_PROFILE", - "params": [ - { - "configFile": "rascal.properties", - "name": "health.threshold.loadavg", - "secure": false, - "value": "25.0" - }, - { - "configFile": "rascal.properties", - "name": "health.threshold.availableBandwidthInKbps", - "secure": false, - "value": ">1750000" - }, - { - "configFile": "rascal.properties", - "name": "health.threshold.queryTime", - "secure": false, - "value": "1000" - } - ] - }, - { - "cdnName": "cdn2", - "description": "edge2 description", - "lastUpdated": "2018-03-02T17:27:11.818418+00:00", - "name": "EDGEInCDN2", - "routing_disabled": false, - "type": "ATS_PROFILE" - }, - { - "cdnName": "cdn4", - "description": "edge2 description", - "lastUpdated": "2018-03-02T17:27:11.818418+00:00", - "name": "EDGE2", - "routing_disabled": false, - "type": "ATS_PROFILE" - }, - { - "cdnName": "cdn2", - "description": "cdn2 edge description", - "name": "CDN2_EDGE", - "routing_disabled": false, - "type": "ATS_PROFILE" - }, - { - "cdnName": "cdn1", - "description": "mid description", - "lastUpdated": "2018-03-02T17:27:11.80173+00:00", - "name": "MID1", - "routing_disabled": false, - "type": "ATS_PROFILE" - }, - { - "cdnName": "cdn1", - "description": "origin description", - "lastUpdated": "2018-03-02T17:27:11.80173+00:00", - "name": "ORIGIN1", - "routing_disabled": false, - "type": "ORG_PROFILE" - }, - { - "cdnName": "cdn1", - "description": "cdn1 description", - "lastUpdated": "2018-03-02T17:27:11.80452+00:00", - "name": "CCR1", - "routing_disabled": false, - "type": "TR_PROFILE" - }, - { - "cdnName": "cdn2", - "description": "cdn2 description", - "lastUpdated": "2018-03-02T17:27:11.807948+00:00", - "name": "CCR2", - "routing_disabled": false, - "type": "TR_PROFILE" - }, - { - "cdnName": "cdn1", - "description": "rascal description", - "lastUpdated": "2018-03-02T17:27:11.813052+00:00", - "name": "RASCAL1", - "routing_disabled": false, - "type": "TM_PROFILE", - "params": [ - { - "configFile": "rascal.properties", - "name": "health.threshold.queryTime", - "secure": false, - "value": "1000" - }, - { - "configFile": "rascal.properties", - "name": "health.polling.url", - "secure": false, - "value": "http://${hostname}/_astats?application=&inf.name=${interface_name}" - }, - { - "configFile": "rascal-config.txt", - "lastUpdated": "2018-01-19T19:01:21.472279+00:00", - "name": "peers.polling.interval", - "secure": false, - "value": "60" - }, - { - "configFile": "rascal-config.txt", - "lastUpdated": "2018-01-19T19:01:21.472279+00:00", - "name": "health.polling.interval", - "secure": false, - "value": "30" - } - ] - }, - { - "cdnName": "cdn1", - "description": "mso origin description", - "lastUpdated": "2018-03-02T17:27:11.80173+00:00", - "name": "MSO", - "routing_disabled": false, - "type": "ORG_PROFILE" - } - ], - "regions": [ - { - "divisionName": "division1", - "name": "region1" - }, - { - "divisionName": "division2", - "name": "region2" - } - ], - "roles": [ - { - "name": "new_admin", - "description": "super-user 2", - "privLevel": 30, - "capabilities": [ - "all-read", - "all-write" - ] - }, - { - "name": "bad_admin", - "description": "super-user 3", - "privLevel": 30, - "capabilities": [ - "all-read", - "all-write", - "invalid-capability" - ] - } - ], - "servers": [ - { - "cachegroup": "cachegroup1", - "cdnName": "cdn1", - "domainName": "ga.atlanta.kabletown.net", - "guid": null, - "hostName": "atlanta-edge-01", - "httpsPort": 443, - "iloIpAddress": "", - "iloIpGateway": "", - "iloIpNetmask": "", - "iloPassword": "", - "iloUsername": "", - "interfaceMtu": 9000, - "interfaceName": "bond0", - "ip6Address": "2345:1234:12:8::1/64", - "ip6Gateway": "2345:1234:12:8::1", - "ipAddress": "127.0.0.21", - "ipGateway": "127.0.0.21", - "ipIsService": true, - "ipNetmask": "255.255.255.252", - "lastUpdated": "2018-03-28T17:30:00.220351+00:00", - "mgmtIpAddress": "", - "mgmtIpGateway": "", - "mgmtIpNetmask": "", - "offlineReason": null, - "physLocation": "Denver", - "profile": "EDGE1", - "rack": "RR 119.02", - "revalPending": false, - "routerHostName": "", - "routerPortName": "", - "status": "REPORTED", - "tcpPort": 80, - "type": "EDGE", - "updPending": false, - "xmppId": "atlanta-edge-01\\\\@ocdn.kabletown.net", - "xmppPasswd": "X" - }, - { - "cachegroup": "cachegroup1", - "cdnName": "cdn2", - "domainName": "ga.atlanta.kabletown.net", - "guid": null, - "hostName": "cdn2-test-edge", - "httpsPort": 443, - "iloIpAddress": "", - "iloIpGateway": "", - "iloIpNetmask": "", - "iloPassword": "", - "iloUsername": "", - "interfaceMtu": 1500, - "interfaceName": "eth0", - "ip6Address": "", - "ip6Gateway": "", - "ipAddress": "0.0.0.0", - "ipGateway": "0.0.0.0", - "ipIsService": true, - "ipNetmask": "0.0.0.0", - "lastUpdated": "2018-03-28T17:30:00.220351+00:00", - "mgmtIpAddress": "", - "mgmtIpGateway": "", - "mgmtIpNetmask": "", - "offlineReason": null, - "physLocation": "Denver", - "profile": "EDGEInCDN2", - "rack": "", - "revalPending": false, - "routerHostName": "", - "routerPortName": "", - "status": "REPORTED", - "tcpPort": 80, - "type": "EDGE", - "updPending": false, - "xmppId": "", - "xmppPasswd": "" - }, - { - "cachegroup": "cachegroup1", - "cdnName": "cdn1", - "domainName": "kabletown.net", - "guid": null, - "hostName": "influxdb02", - "httpsPort": 443, - "iloIpAddress": "", - "iloIpGateway": "", - "iloIpNetmask": "", - "iloPassword": "", - "iloUsername": "", - "interfaceMtu": 1500, - "interfaceName": "eth1", - "ip6Address": "2345:1234:12:8::2/64", - "ip6Gateway": "2345:1234:12:8::2", - "ipAddress": "127.0.0.11", - "ipGateway": "127.0.0.11", - "ipIsService": true, - "ipNetmask": "255.255.252.0", - "lastUpdated": "2018-03-28T17:30:00.220351+00:00", - "mgmtIpAddress": "", - "mgmtIpGateway": "", - "mgmtIpNetmask": "", - "offlineReason": null, - "physLocation": "Denver", - "profile": "EDGE1", - "rack": "RR 119.02", - "revalPending": false, - "routerHostName": "", - "routerPortName": "", - "status": "REPORTED", - "tcpPort": 8086, - "type": "EDGE", - "updPending": false, - "xmppId": "", - "xmppPasswd": "" - }, - { - "cachegroup": "cachegroup1", - "cdnName": "cdn1", - "domainName": "ga.atlanta.kabletown.net", - "guid": null, - "hostName": "atlanta-router-01", - "httpsPort": 443, - "iloIpAddress": "", - "iloIpGateway": "", - "iloIpNetmask": "", - "iloPassword": "", - "iloUsername": "", - "interfaceMtu": 9000, - "interfaceName": "bond0", - "ip6Address": "2345:1234:12:8::3/64", - "ip6Gateway": "2345:1234:12:8::3", - "ipAddress": "127.0.0.12", - "ipGateway": "127.0.0.1", - "ipIsService": true, - "ipNetmask": "255.255.255.252", - "lastUpdated": "2018-03-28T17:30:00.220351+00:00", - "mgmtIpAddress": "", - "mgmtIpGateway": "", - "mgmtIpNetmask": "", - "offlineReason": null, - "physLocation": "Denver", - "profile": "EDGE1", - "rack": "RR 119.02", - "revalPending": false, - "routerHostName": "", - "routerPortName": "", - "status": "REPORTED", - "tcpPort": 80, - "type": "EDGE", - "updPending": false, - "xmppId": "atlanta-router-01\\\\@ocdn.kabletown.net", - "xmppPasswd": "X" - }, - { - "cachegroup": "cachegroup2", - "cdnName": "cdn1", - "domainName": "ga.atlanta.kabletown.net", - "guid": null, - "hostName": "atlanta-edge-03", - "httpsPort": 443, - "iloIpAddress": "", - "iloIpGateway": "", - "iloIpNetmask": "", - "iloPassword": "", - "iloUsername": "", - "interfaceMtu": 9000, - "interfaceName": "bond0", - "ip6Address": "2345:1234:12:2::4/64", - "ip6Gateway": "2345:1234:12:8::4", - "ipAddress": "127.0.0.13", - "ipGateway": "127.0.0.1", - "ipIsService": true, - "ipNetmask": "255.255.255.252", - "lastUpdated": "2018-03-28T17:30:00.220351+00:00", - "mgmtIpAddress": "", - "mgmtIpGateway": "", - "mgmtIpNetmask": "", - "offlineReason": null, - "physLocation": "Denver", - "profile": "EDGE1", - "rack": "RR 119.02", - "revalPending": false, - "routerHostName": "", - "routerPortName": "", - "status": "REPORTED", - "tcpPort": 80, - "type": "EDGE", - "updPending": false, - "xmppId": "atlanta-edge-03\\\\@ocdn.kabletown.net", - "xmppPasswd": "X" - }, - { - "cachegroup": "cachegroup1", - "cdnName": "cdn1", - "domainName": "ga.atlanta.kabletown.net", - "guid": null, - "hostName": "atlanta-edge-14", - "httpsPort": 443, - "iloIpAddress": "", - "iloIpGateway": "", - "iloIpNetmask": "", - "iloPassword": "", - "iloUsername": "", - "interfaceMtu": 9000, - "interfaceName": "bond0", - "ip6Address": "2345:1234:12:8::5/64", - "ip6Gateway": "2345:1234:12:8::5", - "ipAddress": "127.0.0.14", - "ipGateway": "127.0.0.1", - "ipIsService": true, - "ipNetmask": "255.255.255.252", - "lastUpdated": "2018-03-28T17:30:00.220351+00:00", - "mgmtIpAddress": "", - "mgmtIpGateway": "", - "mgmtIpNetmask": "", - "offlineReason": null, - "physLocation": "Denver", - "profile": "EDGE1", - "rack": "RR 119.02", - "revalPending": false, - "routerHostName": "", - "routerPortName": "", - "status": "REPORTED", - "tcpPort": 80, - "type": "EDGE", - "updPending": false, - "xmppId": "atlanta-edge-14\\\\@ocdn.kabletown.net", - "xmppPasswd": "X" - }, - { - "cachegroup": "cachegroup1", - "cdnName": "cdn1", - "domainName": "ga.atlanta.kabletown.net", - "guid": null, - "hostName": "atlanta-edge-15", - "httpsPort": 443, - "iloIpAddress": "", - "iloIpGateway": "", - "iloIpNetmask": "", - "iloPassword": "", - "iloUsername": "", - "interfaceMtu": 9000, - "interfaceName": "bond0", - "ip6Address": "2345:1234:12:d::6/64", - "ip6Gateway": "2345:1234:12:d::6", - "ipAddress": "127.0.0.15", - "ipGateway": "127.0.0.7", - "ipIsService": true, - "ipNetmask": "255.255.255.252", - "lastUpdated": "2018-03-28T17:30:00.220351+00:00", - "mgmtIpAddress": "", - "mgmtIpGateway": "", - "mgmtIpNetmask": "", - "offlineReason": null, - "physLocation": "Denver", - "profile": "EDGE1", - "rack": "RR 119.02", - "revalPending": false, - "routerHostName": "", - "routerPortName": "", - "status": "REPORTED", - "tcpPort": 80, - "type": "EDGE", - "updPending": false, - "xmppId": "atlanta-edge-15\\\\@ocdn.kabletown.net", - "xmppPasswd": "X" - }, - { - "cachegroup": "parentCachegroup", - "cdnName": "cdn1", - "domainName": "ga.atlanta.kabletown.net", - "guid": null, - "hostName": "atlanta-mid-16", - "httpsPort": 443, - "iloIpAddress": "", - "iloIpGateway": "", - "iloIpNetmask": "", - "iloPassword": "", - "iloUsername": "", - "interfaceMtu": 9000, - "interfaceName": "bond0", - "ip6Address": "2345:1234:12:d::7/64", - "ip6Gateway": "2345:1234:12:d::7", - "ipAddress": "127.0.0.16", - "ipGateway": "127.0.0.7", - "ipIsService": true, - "ipNetmask": "255.255.255.252", - "lastUpdated": "2018-03-28T17:30:00.220351+00:00", - "mgmtIpAddress": "", - "mgmtIpGateway": "", - "mgmtIpNetmask": "", - "offlineReason": null, - "physLocation": "Denver", - "profile": "EDGE1", - "rack": "RR 119.02", - "revalPending": false, - "routerHostName": "", - "routerPortName": "", - "status": "REPORTED", - "tcpPort": 80, - "type": "MID", - "updPending": false, - "xmppId": "atlanta-mid-16\\\\@ocdn.kabletown.net", - "xmppPasswd": "X" - }, - { - "cachegroup": "cachegroup1", - "cdnName": "cdn1", - "domainName": "ga.atlanta.kabletown.net", - "guid": null, - "hostName": "atlanta-org-1", - "httpsPort": 443, - "iloIpAddress": "", - "iloIpGateway": "", - "iloIpNetmask": "", - "iloPassword": "", - "iloUsername": "", - "interfaceMtu": 9000, - "interfaceName": "bond0", - "ip6Address": "2345:1234:12:d::8/64", - "ip6Gateway": "2345:1234:12:d::8", - "ipAddress": "127.0.0.17", - "ipGateway": "127.0.0.17", - "ipIsService": true, - "ipNetmask": "255.255.255.252", - "lastUpdated": "2018-03-28T17:30:00.220351+00:00", - "mgmtIpAddress": "", - "mgmtIpGateway": "", - "mgmtIpNetmask": "", - "offlineReason": null, - "physLocation": "Denver", - "profile": "EDGE1", - "rack": "RR 119.02", - "revalPending": false, - "routerHostName": "", - "routerPortName": "", - "status": "REPORTED", - "tcpPort": 80, - "type": "EDGE", - "updPending": false, - "xmppId": "atlanta-org-1\\\\@ocdn.kabletown.net", - "xmppPasswd": "X" - }, - { - "cachegroup": "cachegroup1", - "cdnName": "cdn1", - "domainName": "ga.atlanta.kabletown.net", - "guid": null, - "hostName": "atlanta-org-2", - "httpsPort": 443, - "iloIpAddress": "", - "iloIpGateway": "", - "iloIpNetmask": "", - "iloPassword": "", - "iloUsername": "", - "interfaceMtu": 9000, - "interfaceName": "bond0", - "ip6Address": "2345:1234:12:d::9/64", - "ip6Gateway": "2345:1234:12:d::9", - "ipAddress": "127.0.0.18", - "ipGateway": "127.0.0.18", - "ipIsService": true, - "ipNetmask": "255.255.255.252", - "lastUpdated": "2018-03-28T17:30:00.220351+00:00", - "mgmtIpAddress": "", - "mgmtIpGateway": "", - "mgmtIpNetmask": "", - "offlineReason": null, - "physLocation": "Denver", - "profile": "EDGE1", - "rack": "RR 119.02", - "revalPending": false, - "routerHostName": "", - "routerPortName": "", - "status": "REPORTED", - "tcpPort": 80, - "type": "EDGE", - "updPending": false, - "xmppId": "atlanta-org-1\\\\@ocdn.kabletown.net", - "xmppPasswd": "X" - }, - { - "cachegroup": "cachegroup1", - "cdnName": "cdn1", - "domainName": "ga.atlanta.kabletown.net", - "guid": null, - "hostName": "atlanta-mid-01", - "httpsPort": 443, - "iloIpAddress": "", - "iloIpGateway": "", - "iloIpNetmask": "", - "iloPassword": "", - "iloUsername": "", - "interfaceMtu": 9000, - "interfaceName": "bond0", - "ip6Address": "2345:1234:12:9::10/64", - "ip6Gateway": "2345:1234:12:9::10", - "ipAddress": "127.0.0.2", - "ipGateway": "127.0.0.2", - "ipIsService": true, - "ipNetmask": "255.255.255.252", - "lastUpdated": "2018-03-28T17:30:00.220351+00:00", - "mgmtIpAddress": "", - "mgmtIpGateway": "", - "mgmtIpNetmask": "", - "offlineReason": null, - "physLocation": "Denver", - "profile": "EDGE1", - "rack": "RR 119.02", - "revalPending": false, - "routerHostName": "", - "routerPortName": "", - "status": "REPORTED", - "tcpPort": 80, - "type": "MID", - "updPending": false, - "xmppId": "atlanta-mid-01\\\\@ocdn.kabletown.net", - "xmppPasswd": "X" - }, - { - "cachegroup": "cachegroup1", - "cdnName": "cdn1", - "domainName": "kabletown.net", - "guid": null, - "hostName": "rascal01", - "httpsPort": 443, - "iloIpAddress": "", - "iloIpGateway": "", - "iloIpNetmask": "", - "iloPassword": "", - "iloUsername": "", - "interfaceMtu": 9000, - "interfaceName": "bond0", - "ip6Address": "2345:1234:12:b::11/64", - "ip6Gateway": "2345:1234:12:b::11", - "ipAddress": "127.0.0.4", - "ipIsService": true, - "ipGateway": "127.0.0.4", - "ipNetmask": "255.255.255.252", - "lastUpdated": "2018-03-28T17:30:00.220351+00:00", - "mgmtIpAddress": "", - "mgmtIpGateway": "", - "mgmtIpNetmask": "", - "offlineReason": null, - "physLocation": "Denver", - "profile": "RASCAL1", - "rack": "RR 119.02", - "revalPending": false, - "routerHostName": "", - "routerPortName": "", - "status": "REPORTED", - "tcpPort": 81, - "type": "RASCAL", - "updPending": false, - "xmppId": "", - "xmppPasswd": "X" - }, - { - "cachegroup": "cachegroup2", - "cdnName": "cdn2", - "domainName": "kabletown2.net", - "guid": null, - "hostName": "edge1-cdn2", - "httpsPort": 443, - "iloIpAddress": "", - "iloIpGateway": "", - "iloIpNetmask": "", - "iloPassword": "", - "iloUsername": "", - "interfaceMtu": 9000, - "interfaceName": "bond0", - "ip6Address": "2345:1234:12:b::13/64", - "ip6Gateway": "2345:1234:12:b::13", - "ipAddress": "127.0.0.31", - "ipIsService": true, - "ipGateway": "127.0.0.4", - "ipNetmask": "255.255.255.0", - "mgmtIpAddress": "", - "mgmtIpGateway": "", - "mgmtIpNetmask": "", - "offlineReason": null, - "physLocation": "Denver", - "profile": "CDN2_EDGE", - "rack": "RR 119.02", - "revalPending": false, - "routerHostName": "", - "routerPortName": "", - "status": "REPORTED", - "tcpPort": 81, - "type": "EDGE", - "updPending": false, - "xmppId": "", - "xmppPasswd": "X" - }, - { - "cachegroup": "cachegroup1", - "cdnName": "cdn1", - "domainName": "local", - "guid": null, - "hostName": "riak", - "httpsPort": 8088, - "iloIpAddress": "", - "iloIpGateway": "", - "iloIpNetmask": "", - "iloPassword": "", - "iloUsername": "", - "interfaceMtu": 1500, - "interfaceName": "eth1", - "ip6Address": "2345:1234:12:b::12/64", - "ip6Gateway": "2345:1234:12:b::12", - "ipAddress": "127.0.0.1", - "ipIsService": true, - "ipGateway": "127.0.0.1", - "ipNetmask": "255.255.252.0", - "lastUpdated": "2018-03-28T17:30:00.220351+00:00", - "mgmtIpAddress": "", - "mgmtIpGateway": "", - "mgmtIpNetmask": "", - "offlineReason": null, - "physLocation": "Denver", - "profile": "EDGE1", - "rack": "RR 119.02", - "revalPending": false, - "routerHostName": "", - "routerPortName": "", - "status": "REPORTED", - "tcpPort": 8088, - "type": "RIAK", - "updPending": false, - "xmppId": "", - "xmppPasswd": "" - }, - { - "cachegroup": "multiOriginCachegroup", - "cdnName": "cdn1", - "domainName": "ga.denver.kabletown.net", - "guid": null, - "hostName": "denver-mso-org-01", - "httpsPort": 443, - "iloIpAddress": "", - "iloIpGateway": "", - "iloIpNetmask": "", - "iloPassword": "", - "iloUsername": "", - "interfaceMtu": 9000, - "interfaceName": "bond0", - "ip6Address": "2345:1234:12:8::20/64", - "ip6Gateway": "2345:1234:12:8::20", - "ipAddress": "127.0.0.1", - "ipIsService": true, - "ipGateway": "127.0.0.1", - "ipNetmask": "255.255.255.252", - "lastUpdated": "2018-03-28T17:30:00.220351+00:00", - "mgmtIpAddress": "", - "mgmtIpGateway": "", - "mgmtIpNetmask": "", - "offlineReason": null, - "physLocation": "Denver", - "profile": "MSO", - "rack": "RR 119.02", - "revalPending": false, - "routerHostName": "", - "routerPortName": "", - "status": "REPORTED", - "tcpPort": 80, - "type": "ORG", - "updPending": false, - "xmppId": "denver-mso-org-01\\\\@ocdn.kabletown.net", - "xmppPasswd": "X" - }, - { - "cachegroup": "cachegroup3", - "cdnName": "cdn1", - "domainName": "kabletown2.net", - "guid": null, - "hostName": "edge1-cdn1-cg3", - "httpsPort": 443, - "iloIpAddress": "", - "iloIpGateway": "", - "iloIpNetmask": "", - "iloPassword": "", - "iloUsername": "", - "interfaceMtu": 9000, - "interfaceName": "bond0", - "ip6Address": "::13/64", - "ip6Gateway": "2345:1234:12:b::13", - "ipAddress": "127.0.0.100", - "ipIsService": true, - "ipGateway": "127.0.0.4", - "ipNetmask": "255.255.255.0", - "mgmtIpAddress": "", - "mgmtIpGateway": "", - "mgmtIpNetmask": "", - "offlineReason": null, - "physLocation": "Denver", - "profile": "EDGE1", - "rack": "RR 119.02", - "revalPending": false, - "routerHostName": "", - "routerPortName": "", - "status": "REPORTED", - "tcpPort": 81, - "type": "EDGE", - "updPending": false, - "xmppId": "", - "xmppPasswd": "X" - }, - { - "cachegroup": "cachegroup3", - "cdnName": "cdn1", - "domainName": "kabletown2.net", - "guid": null, - "hostName": "edge2-cdn1-cg3", - "httpsPort": 443, - "iloIpAddress": "", - "iloIpGateway": "", - "iloIpNetmask": "", - "iloPassword": "", - "iloUsername": "", - "interfaceMtu": 9000, - "interfaceName": "bond0", - "ip6Address": "::14/64", - "ip6Gateway": "2345:1234:12:b::13", - "ipAddress": "127.0.0.101", - "ipIsService": true, - "ipGateway": "127.0.0.4", - "ipNetmask": "255.255.255.0", - "mgmtIpAddress": "", - "mgmtIpGateway": "", - "mgmtIpNetmask": "", - "offlineReason": null, - "physLocation": "Denver", - "profile": "EDGE1", - "rack": "RR 119.02", - "revalPending": false, - "routerHostName": "", - "routerPortName": "", - "status": "REPORTED", - "tcpPort": 81, - "type": "EDGE", - "updPending": false, - "xmppId": "", - "xmppPasswd": "X" - } - ], - "serverCapabilities": [ - { - "name": "foo" - }, - { - "name": "bar" - } - ], - "serverServerCapabilities": [ - { - "serverHostName": "atlanta-org-1", - "serverCapability": "foo" - }, - { - "serverHostName": "atlanta-org-2", - "serverCapability": "bar" - } - ], - "staticdnsentries": [ - { - "address": "192.168.0.1", - "cachegroup": "cachegroup2", - "deliveryservice": "ds1", - "host": "host2", - "type": "A_RECORD", - "ttl": 10 - }, - { - "address": "this.is.a.hostname.", - "cachegroup": "cachegroup1", - "deliveryservice": "ds1", - "host": "host1", - "type": "CNAME_RECORD", - "ttl": 0 - }, - { - "address": "2001:0db8:85a3:0000:0000:8a2e:0370:7334", - "cachegroup": "cachegroup2", - "deliveryservice": "ds1", - "host": "host3", - "ttl": 10, - "type": "AAAA_RECORD" - } - ], - "statuses": [ - { - "description": "Edge: 12M will not include caches in this state in CCR config files. Mid: N/A for now", - "name": "CCR_IGNORE" - }, - { - "name": "TEST_NULL_DESCRIPTION" - } - ], - "tenants": [ - { - "active": true, - "name": "tenant1", - "parentName": "root" - }, - { - "active": false, - "name": "tenant2", - "parentName": "tenant1" - }, - { - "active": true, - "name": "tenant3", - "parentName": "tenant2" - }, - { - "active": true, - "name": "tenant4", - "parentName": "root" - } - ], - "types": [ - { - "description": "Host header regular expression", - "lastUpdated": "2018-03-02T19:13:46.788583+00:00", - "name": "HOST_REGEXP", - "useInTable": "regex" - }, - { - "description": "DNS Content routing, RAM cache, National", - "lastUpdated": "2018-03-02T19:13:46.792319+00:00", - "name": "DNS_LIVE_NATNL", - "useInTable": "deliveryservice" - }, - { - "description": "Other CDN (CDS-IS, Akamai, etc)", - "lastUpdated": "2018-03-02T19:13:46.793921+00:00", - "name": "OTHER_CDN", - "useInTable": "server" - }, - { - "description": "Client-Controlled Steering Delivery Service", - "lastUpdated": "2018-03-02T19:13:46.795291+00:00", - "name": "CLIENT_STEERING", - "useInTable": "deliveryservice" - }, - { - "description": "influxdb type", - "lastUpdated": "2018-03-02T19:13:46.796707+00:00", - "name": "INFLUXDB", - "useInTable": "server" - }, - { - "description": "riak type", - "lastUpdated": "2018-03-02T19:13:46.798008+00:00", - "name": "RIAK", - "useInTable": "server" - }, - { - "description": "Origin", - "lastUpdated": "2018-03-02T19:13:46.799404+00:00", - "name": "ORG", - "useInTable": "server" - }, - { - "description": "HTTP Content routing cache in RAM ", - "lastUpdated": "2018-03-02T19:13:46.800738+00:00", - "name": "HTTP_LIVE", - "useInTable": "deliveryservice" - }, - { - "description": "Active Directory User", - "lastUpdated": "2018-03-02T19:13:46.802044+00:00", - "name": "ACTIVE_DIRECTORY", - "useInTable": "tm_user" - }, - { - "description": "federation type resolve4", - "lastUpdated": "2018-03-02T19:13:46.803471+00:00", - "name": "RESOLVE4", - "useInTable": "federation" - }, - { - "description": "Static DNS A entry", - "lastUpdated": "2018-03-02T19:13:46.804776+00:00", - "name": "A_RECORD", - "useInTable": "staticdnsentry" - }, - { - "description": "Local User", - "lastUpdated": "2018-03-02T19:13:46.806035+00:00", - "name": "LOCAL", - "useInTable": "tm_user" - }, - { - "description": "Weighted steering target", - "lastUpdated": "2018-03-02T19:13:46.80748+00:00", - "name": "STEERING_WEIGHT", - "useInTable": "steering_target" - }, - { - "description": "HTTP Content routing, RAM cache, National", - "lastUpdated": "2018-03-02T19:13:46.808911+00:00", - "name": "HTTP_LIVE_NATNL", - "useInTable": "deliveryservice" - }, - { - "description": "Ops hosts for management", - "lastUpdated": "2018-03-02T19:13:46.810576+00:00", - "name": "TOOLS_SERVER", - "useInTable": "server" - }, - { - "description": "Path regular expression", - "lastUpdated": "2018-03-02T19:13:46.812049+00:00", - "name": "PATH_REGEXP", - "useInTable": "regex" - }, - { - "description": "Static DNS CNAME entry", - "lastUpdated": "2018-03-02T19:13:46.813461+00:00", - "name": "CNAME_RECORD", - "useInTable": "staticdnsentry" - }, - { - "description": "Kabletown Content Router", - "lastUpdated": "2018-03-02T19:13:46.814833+00:00", - "name": "CCR", - "useInTable": "server" - }, - { - "description": "Origin Cachegroup", - "lastUpdated": "2018-03-02T19:13:46.816199+00:00", - "name": "ORG_LOC", - "useInTable": "cachegroup" - }, - { - "description": "Mid Cachegroup", - "lastUpdated": "2018-03-02T19:13:46.816199+00:00", - "name": "MID_LOC", - "useInTable": "cachegroup" - }, - { - "description": "Edge Cache", - "lastUpdated": "2018-03-02T19:13:46.817689+00:00", - "name": "EDGE", - "useInTable": "server" - }, - { - "description": "Ordered steering target", - "lastUpdated": "2018-03-02T19:13:46.81913+00:00", - "name": "STEERING_ORDER", - "useInTable": "steering_target" - }, - { - "description": "DNS Content Routing", - "lastUpdated": "2018-03-02T19:13:46.820528+00:00", - "name": "DNS", - "useInTable": "deliveryservice" - }, - { - "description": "federation type resolve6", - "lastUpdated": "2018-03-02T19:13:46.822161+00:00", - "name": "RESOLVE6", - "useInTable": "federation" - }, - { - "description": "Static DNS AAAA entry", - "lastUpdated": "2018-03-02T19:13:46.823506+00:00", - "name": "AAAA_RECORD", - "useInTable": "staticdnsentry" - }, - { - "description": "HTTP Content Routing, no caching", - "lastUpdated": "2018-03-02T19:13:46.824798+00:00", - "name": "HTTP_NO_CACHE", - "useInTable": "deliveryservice" - }, - { - "description": "any_map type", - "lastUpdated": "2018-03-02T19:13:46.826411+00:00", - "name": "ANY_MAP", - "useInTable": "deliveryservice" - }, - { - "description": "Steering Delivery Service", - "lastUpdated": "2018-03-02T19:13:46.827779+00:00", - "name": "STEERING", - "useInTable": "deliveryservice" - }, - { - "description": "Edge Cachegroup", - "lastUpdated": "2018-03-02T19:13:46.829249+00:00", - "name": "EDGE_LOC", - "useInTable": "cachegroup" - }, - { - "description": "HTTP Content routing cache ", - "lastUpdated": "2018-03-02T19:13:46.830862+00:00", - "name": "HTTP", - "useInTable": "deliveryservice" - }, - { - "description": "Mid Tier Cache", - "lastUpdated": "2018-03-02T19:13:46.832327+00:00", - "name": "MID", - "useInTable": "server" - }, - { - "description": "Traffic Monitor (Rascal)", - "lastUpdated": "2018-03-02T19:13:46.832327+00:00", - "name": "RASCAL", - "useInTable": "server" - } - ], - "users": [ - { - "addressLine1": "address of admin", - "addressLine2": "", - "city": "Anywhere", - "company": "Comcast", - "country": "USA", - "email": "admin@example.com", - "fullName": "Fred the admin", - "gid": 0, - "localPasswd": "pa$$word", - "confirmLocalPasswd": "pa$$word", - "newUser": false, - "phoneNumber": "810-555-9876", - "postalCode": "55443", - "publicSshKey": "", - "role": 4, - "stateOrProvince": "LA", - "tenant": "root", - "token": "test", - "uid": 0, - "username": "adminuser" - }, - { - "addressLine1": "address of disallowed", - "addressLine2": "place", - "city": "somewhere", - "company": "else", - "country": "UK", - "email": "disallowed@example.com", - "fullName": "Me me", - "gid": 0, - "localPasswd": "pa$$word", - "confirmLocalPasswd": "pa$$word", - "newUser": false, - "phoneNumber": "", - "postalCode": "", - "publicSshKey": "", - "registrationSent": "", - "role": 1, - "stateOrProvince": "", - "tenant": "tenant1", - "token": "quest", - "uid": 0, - "username": "disalloweduser" - }, - { - "addressLine1": "address of readonly", - "addressLine2": "place", - "city": "somewhere", - "company": "else", - "country": "UK", - "email": "readonly@example.com", - "fullName": "Readonly User", - "gid": 0, - "localPasswd": "pa$$word", - "confirmLocalPasswd": "pa$$word", - "newUser": false, - "phoneNumber": "", - "postalCode": "", - "publicSshKey": "", - "registrationSent": "", - "role": 2, - "stateOrProvince": "", - "tenant": "tenant1", - "uid": 0, - "username": "readonlyuser" - }, - { - "addressLine1": "address of admin", - "addressLine2": "", - "city": "Anywhere", - "company": "Comcast", - "country": "USA", - "email": "tenant3user@example.com", - "fullName": "Fred the admin", - "gid": 0, - "localPasswd": "pa$$word", - "confirmLocalPasswd": "pa$$word", - "newUser": false, - "phoneNumber": "810-555-9876", - "postalCode": "55443", - "publicSshKey": "", - "role": 4, - "stateOrProvince": "LA", - "tenant": "tenant3", - "uid": 0, - "username": "tenant3user" - }, - { - "addressLine1": "address of admin", - "addressLine2": "", - "city": "Anywhere", - "company": "Comcast", - "country": "USA", - "email": "tenant4user@example.com", - "fullName": "Fred the admin", - "gid": 0, - "localPasswd": "pa$$word", - "confirmLocalPasswd": "pa$$word", - "newUser": false, - "phoneNumber": "810-555-9876", - "postalCode": "55443", - "publicSshKey": "", - "role": 4, - "stateOrProvince": "LA", - "tenant": "tenant4", - "uid": 0, - "username": "tenant4user" - }, - { - "addressLine1": "address of ops", - "addressLine2": "place", - "city": "somewhere", - "company": "else", - "country": "UK", - "email": "ops@example.com", - "fullName": "Operations User", - "gid": 0, - "localPasswd": "pa$$word", - "confirmLocalPasswd": "pa$$word", - "newUser": false, - "phoneNumber": "", - "postalCode": "", - "publicSshKey": "", - "registrationSent": "", - "role": 3, - "stateOrProvince": "", - "tenant": "root", - "uid": 0, - "username": "opsuser" - }, - { - "addressLine1": "address of steering", - "addressLine2": "place", - "city": "somewhere", - "company": "else", - "country": "UK", - "email": "steering@example.com", - "fullName": "Steering User", - "gid": 0, - "localPasswd": "pa$$word", - "confirmLocalPasswd": "pa$$word", - "newUser": false, - "phoneNumber": "", - "postalCode": "", - "publicSshKey": "", - "registrationSent": "", - "role": 6, - "stateOrProvince": "", - "tenant": "root", - "uid": 0, - "username": "steering" - } - ], - "steeringTargets": [ - { - "deliveryService": "ds1", - "target": "ds2", - "value": 42, - "type": "STEERING_WEIGHT" - } - ], - "jobs": [ - { - "dsName": "ds1", - "request": { - "startTime": "2019-01-01 00:00:00", - "ttl": 80, - "regex": "/foo" - } - }, - { - "dsName": "ds2", - "request": { - "startTime": "2019-01-01 00:00:00", - "ttl": 80, - "regex": "/bar" - } - }, - { - "dsName": "ds1", - "request": { - "startTime": "2019-01-01 00:00:00", - "ttl": 80, - "regex": "/foo" - } - } - ], - "servercheck_extensions": [ - { - "name": "ILO_PING", - "version": "1.0.0", - "info_url": "-", - "script_file": "ToPingCheck.pl", - "isactive": 1, - "description": "", - "servercheck_short_name": "ILO", - "type": "CHECK_EXTENSION_BOOL" - }, - { - "name": "ORT_ERROR_COUNT", - "version": "1.0.0", - "info_url": "-", - "script_file": "ToORTCheck.pl", - "isactive": 1, - "description": "", - "servercheck_short_name": "ORT", - "type": "CHECK_EXTENSION_NUM" - } - ], - "serverchecks": [ - { - "servercheck_short_name": "ILO", - "host_name": "atlanta-edge-01", - "value": 1 - }, - { - "servercheck_short_name": "ORT", - "host_name": "atlanta-edge-01", - "value": 13 - } - ], - "invalidationJobs": [ - { - "deliveryService": "ds1", - "regex": "/.*", - "startTime": 4117118271000, - "ttl": "121m" - }, - { - "deliveryService": "ds2", - "regex": "\\/some-path?.+\\.jpg", - "startTime": "2100-06-19T13:57:51-06:00", - "ttl": 2.1 - } - ], - "statsSummaries": [ - { - "cdnName": "cdn1", - "deliveryServiceName": "all", - "statName": "daily_maxgbps", - "statValue": 5, - "summaryTime": "2019-01-01T00:00:00-06:00" - }, - { - "cdnName": "cdn1", - "deliveryServiceName": "all", - "statName": "daily_bytesserved", - "statValue": 1000, - "summaryTime": "2019-01-01T00:00:00-06:00" - } - ], - "capabilities": [ - { - "name": "test", - "description": "quest" - }, - { - "name": "foo", - "description": "bar" - } - ] -} diff --git a/traffic_ops/testing/api/v2/tenants_test.go b/traffic_ops/testing/api/v2/tenants_test.go deleted file mode 100644 index 8510ee017f..0000000000 --- a/traffic_ops/testing/api/v2/tenants_test.go +++ /dev/null @@ -1,318 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "strconv" - "strings" - "testing" - "time" - - "github.com/apache/trafficcontrol/lib/go-tc" - client "github.com/apache/trafficcontrol/traffic_ops/v2-client" -) - -func TestTenants(t *testing.T) { - WithObjs(t, []TCObj{Parameters, Tenants}, func() { - GetTestTenants(t) - UpdateTestTenants(t) - }) -} - -func CreateTestTenants(t *testing.T) { - for _, ten := range testData.Tenants { - resp, err := TOSession.CreateTenant(&ten) - - if err != nil { - t.Errorf("could not CREATE tenant %s: %v", ten.Name, err) - continue - } - if resp == nil { - t.Errorf("Traffic Ops returned null or undefined Tenant in creation response") - continue - } - if resp.Response.Name != ten.Name { - t.Errorf("expected tenant %+v; got %+v", ten, resp.Response) - } - } -} - -func GetTestTenants(t *testing.T) { - resp, _, err := TOSession.Tenants() - if err != nil { - t.Errorf("cannot GET all tenants: %v - %v", err, resp) - return - } - foundTenants := make(map[string]tc.Tenant, len(resp)) - for _, ten := range resp { - foundTenants[ten.Name] = ten - } - - // expect root and badTenant (defined in todb.go) + all defined in testData.Tenants - if len(resp) != 2+len(testData.Tenants) { - t.Errorf("expected %d tenants, got %d", 2+len(testData.Tenants), len(resp)) - } - - for _, ten := range testData.Tenants { - if ft, ok := foundTenants[ten.Name]; ok { - if ft.ParentName != ten.ParentName { - t.Errorf("tenant %s: expected parent %s, got %s", ten.Name, ten.ParentName, ft.ParentName) - } - } else { - t.Errorf("expected tenant %s: not found", ten.Name) - } - } -} - -func UpdateTestTenants(t *testing.T) { - - // Retrieve the Tenant by name so we can get the id for the Update - name := "tenant2" - parentName := "tenant1" - modTenant, _, err := TOSession.TenantByName(name) - if err != nil { - t.Errorf("cannot GET Tenant by name: %s - %v", name, err) - } - - newParent, _, err := TOSession.TenantByName(parentName) - if err != nil { - t.Errorf("cannot GET Tenant by name: %s - %v", parentName, err) - } - modTenant.ParentID = newParent.ID - - _, err = TOSession.UpdateTenant(strconv.Itoa(modTenant.ID), modTenant) - if err != nil { - t.Errorf("cannot UPDATE Tenant by id: %v", err) - } - - // Retrieve the Tenant to check Tenant parent name got updated - respTenant, _, err := TOSession.Tenant(strconv.Itoa(modTenant.ID)) - if err != nil { - t.Errorf("cannot GET Tenant by name: %v - %v", name, err) - } - if respTenant.ParentName != parentName { - t.Errorf("results do not match actual: %s, expected: %s", respTenant.ParentName, parentName) - } - -} - -func DeleteTestTenants(t *testing.T) { - - t1 := "tenant1" - tenant1, _, err := TOSession.TenantByName(t1) - - if err != nil { - t.Errorf("cannot GET Tenant by name: %v - %v", t1, err) - } - expectedChildDeleteErrMsg := `Tenant '` + strconv.Itoa(tenant1.ID) + `' has child tenants. Please update these child tenants and retry.` - if _, err := TOSession.DeleteTenant(strconv.Itoa(tenant1.ID)); err == nil { - t.Fatalf("%s has child tenants -- should not be able to delete", t1) - } else if !strings.Contains(err.Error(), expectedChildDeleteErrMsg) { - t.Errorf("expected error: %s; got %s", expectedChildDeleteErrMsg, err.Error()) - } - - deletedTenants := map[string]struct{}{} - for { - initLenDeleted := len(deletedTenants) - for _, tn := range testData.Tenants { - if _, ok := deletedTenants[tn.Name]; ok { - continue - } - - hasParent := false - for _, otherTenant := range testData.Tenants { - if _, ok := deletedTenants[otherTenant.Name]; ok { - continue - } - if otherTenant.ParentName == tn.Name { - hasParent = true - break - } - } - if hasParent { - continue - } - - toTenant, _, err := TOSession.TenantByName(tn.Name) - if err != nil { - t.Fatalf("getting tenant %s: %v", tn.Name, err) - } - if _, err = TOSession.DeleteTenant(strconv.Itoa(toTenant.ID)); err != nil { - t.Fatalf("deleting tenant %s: %v", toTenant.Name, err) - } - deletedTenants[tn.Name] = struct{}{} - - } - if len(deletedTenants) == len(testData.Tenants) { - break - } - if len(deletedTenants) == initLenDeleted { - t.Fatal("could not delete tenants: not tenant without an existing child found (cycle?)") - } - } -} - -func TestTenantsActive(t *testing.T) { - CreateTestCDNs(t) - CreateTestTypes(t) - CreateTestTenants(t) - CreateTestParameters(t) - CreateTestProfiles(t) - CreateTestStatuses(t) - CreateTestDivisions(t) - CreateTestRegions(t) - CreateTestPhysLocations(t) - CreateTestCacheGroups(t) - CreateTestServers(t) - CreateTestDeliveryServices(t) - CreateTestUsers(t) - - UpdateTestTenantsActive(t) - - ForceDeleteTestUsers(t) - DeleteTestDeliveryServices(t) - DeleteTestServers(t) - DeleteTestCacheGroups(t) - DeleteTestPhysLocations(t) - DeleteTestRegions(t) - DeleteTestDivisions(t) - DeleteTestStatuses(t) - DeleteTestProfiles(t) - DeleteTestParameters(t) - DeleteTestTenants(t) - DeleteTestTypes(t) - DeleteTestCDNs(t) -} - -func ExtractXMLID(ds *tc.DeliveryServiceNullable) string { - if ds.XMLID != nil { - return *ds.XMLID - } - return "nil" -} - -func UpdateTestTenantsActive(t *testing.T) { - originalTenants, _, err := TOSession.Tenants() - if err != nil { - t.Fatalf("getting tenants error expected: nil, actual: %+v", err) - } - - setTenantActive(t, "tenant1", true) - setTenantActive(t, "tenant2", true) - setTenantActive(t, "tenant3", false) - - // ds3 has tenant3. Even though tenant3 is inactive, we should still be able to get it, because our user is tenant1, which is active. - dses, _, err := TOSession.GetDeliveryServiceByXMLIDNullable("ds3") - if err != nil { - t.Fatal("failed to get delivery service, when the DS's tenant was inactive (even though our user's tenant was active)") - } else if len(dses) != 1 { - t.Error("admin user getting delivery service ds3 with tenant3, expected: ds, actual: empty") - } - - setTenantActive(t, "tenant1", true) - setTenantActive(t, "tenant2", false) - setTenantActive(t, "tenant3", true) - - // ds3 has tenant3. Even though tenant3's parent, tenant2, is inactive, we should still be able to get it, because our user is tenant1, which is active. - _, _, err = TOSession.GetDeliveryServiceByXMLIDNullable("ds3") - if err != nil { - t.Fatal("failed to get delivery service, when a parent tenant was inactive (even though our user's tenant was active)") - } - - toReqTimeout := time.Second * time.Duration(Config.Default.Session.TimeoutInSecs) - tenant3Session, _, err := client.LoginWithAgent(TOSession.URL, "tenant3user", "pa$$word", true, "to-api-v1-client-tests/tenant3user", true, toReqTimeout) - if err != nil { - t.Fatalf("failed to get log in with tenant3user: " + err.Error()) - } - - tenant4Session, _, err := client.LoginWithAgent(TOSession.URL, "tenant4user", "pa$$word", true, "to-api-v1-client-tests/tenant4user", true, toReqTimeout) - if err != nil { - t.Fatalf("failed to get log in with tenant4user: " + err.Error()) - } - - // tenant3user with tenant3 has no access to ds3 with tenant3 when parent tenant2 is inactive - dses, _, err = tenant3Session.GetDeliveryServiceByXMLIDNullable("ds3") - for _, ds := range dses { - t.Errorf("tenant3user got delivery service %+v with tenant3 but tenant3 parent tenant2 is inactive, expected: no ds", ExtractXMLID(&ds)) - } - - setTenantActive(t, "tenant1", true) - setTenantActive(t, "tenant2", true) - setTenantActive(t, "tenant3", false) - - // tenant3user with tenant3 has no access to ds3 with tenant3 when tenant3 is inactive - dses, _, err = tenant3Session.GetDeliveryServiceByXMLIDNullable("ds3") - for _, ds := range dses { - t.Errorf("tenant3user got delivery service %+v with tenant3 but tenant3 is inactive, expected: no ds", ExtractXMLID(&ds)) - } - - setTenantActive(t, "tenant1", true) - setTenantActive(t, "tenant2", true) - setTenantActive(t, "tenant3", true) - - // tenant3user with tenant3 has access to ds3 with tenant3 - dses, _, err = tenant3Session.GetDeliveryServiceByXMLIDNullable("ds3") - if err != nil { - t.Errorf("tenant3user getting delivery service ds3 error expected: nil, actual: %+v", err) - } else if len(dses) == 0 { - t.Error("tenant3user getting delivery service ds3 with tenant3, expected: ds, actual: empty") - } - - // 1. ds2 has tenant2. - // 2. tenant3user has tenant3. - // 3. tenant2 is not a child of tenant3 (tenant3 is a child of tenant2) - // 4. Therefore, tenant3user should not have access to ds2 - dses, _, _ = tenant3Session.GetDeliveryServiceByXMLIDNullable("ds2") - for _, ds := range dses { - t.Errorf("tenant3user got delivery service %+v with tenant2, expected: no ds", ExtractXMLID(&ds)) - } - - // 1. ds1 has tenant1. - // 2. tenant4user has tenant4. - // 3. tenant1 is not a child of tenant4 (tenant4 is unrelated to tenant1) - // 4. Therefore, tenant4user should not have access to ds1 - dses, _, _ = tenant4Session.GetDeliveryServiceByXMLIDNullable("ds1") - for _, ds := range dses { - t.Errorf("tenant4user got delivery service %+v with tenant1, expected: no ds", ExtractXMLID(&ds)) - } - - setTenantActive(t, "tenant3", false) - dses, _, _ = tenant3Session.GetDeliveryServiceByXMLIDNullable("ds3") - for _, ds := range dses { - t.Errorf("tenant3user was inactive, but got delivery service %+v with tenant3, expected: no ds", ExtractXMLID(&ds)) - } - - for _, tn := range originalTenants { - if tn.Name == "root" { - continue - } - if _, err := TOSession.UpdateTenant(strconv.Itoa(tn.ID), &tn); err != nil { - t.Fatalf("restoring original tenants: " + err.Error()) - } - } -} - -func setTenantActive(t *testing.T, name string, active bool) { - tn, _, err := TOSession.TenantByName(name) - if err != nil { - t.Fatalf("cannot GET Tenant by name: %s - %v", name, err) - } - tn.Active = active - _, err = TOSession.UpdateTenant(strconv.Itoa(tn.ID), tn) - if err != nil { - t.Fatalf("cannot UPDATE Tenant by id: %v", err) - } -} diff --git a/traffic_ops/testing/api/v2/todb_test.go b/traffic_ops/testing/api/v2/todb_test.go deleted file mode 100644 index 887bbcdb78..0000000000 --- a/traffic_ops/testing/api/v2/todb_test.go +++ /dev/null @@ -1,319 +0,0 @@ -/* - - Licensed 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. -*/ - -package v2 - -import ( - "database/sql" - "fmt" - "os" - - "github.com/apache/trafficcontrol/lib/go-log" - "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth" -) - -var ( - db *sql.DB -) - -// OpenConnection ... -func OpenConnection() (*sql.DB, error) { - var err error - sslStr := "require" - if !Config.TrafficOpsDB.SSL { - sslStr = "disable" - } - - db, err = sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=%s", Config.TrafficOpsDB.User, Config.TrafficOpsDB.Password, Config.TrafficOpsDB.Hostname, Config.TrafficOpsDB.Name, sslStr)) - - if err != nil { - log.Errorf("opening database: %v\n", err) - return nil, fmt.Errorf("transaction failed: %s", err) - } - return db, err -} - -// SetupTestData ... -// TODO error does not need returned as this function can never return a non-nil error -func SetupTestData(*sql.DB) error { - var err error - - err = SetupRoles(db) - if err != nil { - fmt.Printf("\nError setting up roles %s - %s, %v\n", Config.TrafficOps.URL, Config.TrafficOps.Users.Admin, err) - os.Exit(1) - } - - err = SetupCapabilities(db) - if err != nil { - fmt.Printf("\nError setting up capabilities %s - %s, %v\n", Config.TrafficOps.URL, Config.TrafficOps.Users.Admin, err) - os.Exit(1) - } - - err = SetupRoleCapabilities(db) - if err != nil { - fmt.Printf("\nError setting up roleCapabilities %s - %s, %v\n", Config.TrafficOps.URL, Config.TrafficOps.Users.Admin, err) - os.Exit(1) - } - - err = SetupAPICapabilities(db) - if err != nil { - fmt.Printf("\nError setting up APICapabilities %s - %s, %v\n", Config.TrafficOps.URL, Config.TrafficOps.Users.Admin, err) - os.Exit(1) - } - - err = SetupTenants(db) - if err != nil { - fmt.Printf("\nError setting up tenant %s - %s, %v\n", Config.TrafficOps.URL, Config.TrafficOps.Users.Admin, err) - os.Exit(1) - } - - err = SetupTmusers(db) - if err != nil { - fmt.Printf("\nError setting up tm_user %s - %s, %v\n", Config.TrafficOps.URL, Config.TrafficOps.Users.Admin, err) - os.Exit(1) - } - - err = SetupTypes(db) - if err != nil { - fmt.Printf("\nError setting up types %s - %s, %v\n", Config.TrafficOps.URL, Config.TrafficOps.Users.Admin, err) - os.Exit(1) - } - - err = SetupToExtensions(db) - if err != nil { - fmt.Printf("\nError setting up to_extensions %s - %s, %v\n", Config.TrafficOps.URL, Config.TrafficOps.Users.Admin, err) - os.Exit(1) - } - - return err -} - -// SetupRoles ... -func SetupRoles(db *sql.DB) error { - - sqlStmt := ` -INSERT INTO role (name, description, priv_level) VALUES ('disallowed','Block all access',0) ON CONFLICT DO NOTHING; -INSERT INTO role (name, description, priv_level) VALUES ('read-only','Block all access', 10) ON CONFLICT DO NOTHING; -INSERT INTO role (name, description, priv_level) VALUES ('operations','Block all access', 20) ON CONFLICT DO NOTHING; -INSERT INTO role (name, description, priv_level) VALUES ('admin','super-user', 30) ON CONFLICT DO NOTHING; -INSERT INTO role (name, description, priv_level) VALUES ('portal','Portal User', 2) ON CONFLICT DO NOTHING; -INSERT INTO role (name, description, priv_level) VALUES ('steering','Steering User', 15) ON CONFLICT DO NOTHING; -INSERT INTO role (name, description, priv_level) VALUES ('federation','Role for Secondary CZF', 15) ON CONFLICT DO NOTHING; -` - err := execSQL(db, sqlStmt) - if err != nil { - return fmt.Errorf("exec failed %v", err) - } - return nil -} - -func SetupCapabilities(db *sql.DB) error { - sqlStmt := ` -INSERT INTO capability (name, description) VALUES ('all-read','Full read access') ON CONFLICT DO NOTHING; -INSERT INTO capability (name, description) VALUES ('all-write','Full write access') ON CONFLICT DO NOTHING; -INSERT INTO capability (name, description) VALUES ('cdn-read','View CDN configuration') ON CONFLICT DO NOTHING; -INSERT INTO capability (name, description) VALUES ('asns-read', 'Read ASNs') ON CONFLICT DO NOTHING; -INSERT INTO capability (name, description) VALUES ('asns-write', 'Write ASNs') ON CONFLICT DO NOTHING; -INSERT INTO capability (name, description) VALUES ('cache-groups-read', 'Read CGs') ON CONFLICT DO NOTHING; -` - err := execSQL(db, sqlStmt) - if err != nil { - return fmt.Errorf("exec failed %v", err) - } - return nil -} - -func SetupAPICapabilities(db *sql.DB) error { - sqlStmt := ` -INSERT INTO api_capability (http_method, route, capability) VALUES ('GET', '/asns', 'asns-read') ON CONFLICT DO NOTHING; -INSERT INTO api_capability (http_method, route, capability) VALUES ('POST', '/asns', 'asns-write') ON CONFLICT DO NOTHING; -INSERT INTO api_capability (http_method, route, capability) VALUES ('GET', '/cachegroups', 'cache-groups-read') ON CONFLICT DO NOTHING; -` - - err := execSQL(db, sqlStmt) - if err != nil { - return fmt.Errorf("exec failed %v", err) - } - return nil -} - -func SetupRoleCapabilities(db *sql.DB) error { - sqlStmt := ` -INSERT INTO role_capability (role_id, cap_name) VALUES (4,'all-write') ON CONFLICT DO NOTHING; -INSERT INTO role_capability (role_id, cap_name) VALUES (4,'all-read') ON CONFLICT DO NOTHING; -` - err := execSQL(db, sqlStmt) - if err != nil { - return fmt.Errorf("exec failed %v", err) - } - return nil -} - -// SetupTmusers ... -func SetupTmusers(db *sql.DB) error { - - var err error - encryptedPassword, err := auth.DerivePassword(Config.TrafficOps.UserPassword) - if err != nil { - return fmt.Errorf("password encryption failed %v", err) - } - - // Creates users in different tenants - sqlStmt := ` -INSERT INTO tm_user (username, local_passwd, role, tenant_id) VALUES ('` + Config.TrafficOps.Users.Disallowed + `','` + encryptedPassword + `', 1, 1); -INSERT INTO tm_user (username, local_passwd, role, tenant_id) VALUES ('` + Config.TrafficOps.Users.ReadOnly + `','` + encryptedPassword + `', 2, 1); -INSERT INTO tm_user (username, local_passwd, role, tenant_id) VALUES ('` + Config.TrafficOps.Users.Operations + `','` + encryptedPassword + `', 3, 1); -INSERT INTO tm_user (username, local_passwd, role, tenant_id) VALUES ('` + Config.TrafficOps.Users.Admin + `','` + encryptedPassword + `', 4, 1); -INSERT INTO tm_user (username, local_passwd, role, tenant_id) VALUES ('` + Config.TrafficOps.Users.Portal + `','` + encryptedPassword + `', 5, 1); -INSERT INTO tm_user (username, local_passwd, role, tenant_id) VALUES ('` + Config.TrafficOps.Users.Federation + `','` + encryptedPassword + `', 6, 1); -INSERT INTO tm_user (username, local_passwd, role, tenant_id) VALUES ('` + Config.TrafficOps.Users.Extension + `','` + encryptedPassword + `', 3, 1); -` - err = execSQL(db, sqlStmt) - if err != nil { - return fmt.Errorf("exec failed %v", err) - } - return nil -} - -// SetupTenants ... -func SetupTenants(db *sql.DB) error { - - // TODO: root tenant must be present in initial database. "badtenant" is needed for now so tests can be done - // with a tenant outside the user's tenant. That should be removed once User API tests are in place rather than the SetupUsers defined above. - sqlStmt := ` -INSERT INTO tenant (name, active, parent_id, last_updated) VALUES ('root', true, null, '2018-01-19 19:01:21.327262'); -INSERT INTO tenant (name, active, parent_id, last_updated) VALUES ('badtenant', true, 1, '2018-01-19 19:01:21.327262'); -` - err := execSQL(db, sqlStmt) - if err != nil { - return fmt.Errorf("exec failed %v", err) - } - return nil -} - -// SetupJobs ... -func SetupJobs(db *sql.DB) error { - - sqlStmt := ` -INSERT INTO job (id, ttl_hr, asset_url, start_time, entered_time, job_user, last_updated, job_deliveryservice, invalidation_type) VALUES (100, 24, 'http://cdn2.edge/job1/.*', '2018-01-19 21:01:14.000000', '2018-01-19 21:01:14.000000', (SELECT id FROM tm_user where username = 'admin'), '2018-01-19 21:19:32.468643', 100, 'REFRESH'); -INSERT INTO job (id, ttl_hr, asset_url, start_time, entered_time, job_user, last_updated, job_deliveryservice, invalidation_type) VALUES (200, 36, 'http://cdn2.edge/job2/.*', '2018-01-19 21:09:34.000000', '2018-01-19 21:09:34.000000', (SELECT id FROM tm_user where username = 'admin'), '2018-01-19 21:19:32.450915', 200, 'REFETCH'); -INSERT INTO job (id, ttl_hr, asset_url, start_time, entered_time, job_user, last_updated, job_deliveryservice, invalidation_type) VALUES (300, 72, 'http://cdn2.edge/job3/.*', '2018-01-19 21:14:34.000000', '2018-01-19 21:14:34.000000', (SELECT id FROM tm_user where username = 'admin'), '2018-01-19 21:19:32.460870', 100, 'REFRESH'); -` - err := execSQL(db, sqlStmt) - if err != nil { - return fmt.Errorf("exec failed %v", err) - } - return nil -} - -// SetupTypes Set up to_extension types -func SetupTypes(db *sql.DB) error { - - sqlStmt := ` -INSERT INTO type (name, description, use_in_table) VALUES ('CHECK_EXTENSION_BOOL', 'Extension for checkmark in Server Check', 'to_extension'); -INSERT INTO type (name, description, use_in_table) VALUES ('CHECK_EXTENSION_NUM', 'Extension for int value in Server Check', 'to_extension'); -INSERT INTO type (name, description, use_in_table) VALUES ('CHECK_EXTENSION_OPEN_SLOT', 'Open slot for check in Server Status', 'to_extension'); -` - err := execSQL(db, sqlStmt) - if err != nil { - return fmt.Errorf("exec failed %v", err) - } - return nil -} - -// SetupToExtensions setup open slot in to_extension table -func SetupToExtensions(db *sql.DB) error { - - sqlStmt := ` -INSERT INTO to_extension (name, version, info_url, isactive, script_file, servercheck_column_name, type) VALUES ('OPEN', '1.0.0', '-', false, '', 'aa', (SELECT id FROM type WHERE name = 'CHECK_EXTENSION_OPEN_SLOT')); -INSERT INTO to_extension (name, version, info_url, isactive, script_file, servercheck_column_name, type) VALUES ('OPEN', '1.0.0', '-', false, '', 'ab', (SELECT id FROM type WHERE name = 'CHECK_EXTENSION_OPEN_SLOT')); - ` - err := execSQL(db, sqlStmt) - if err != nil { - return fmt.Errorf("exec failed %v", err) - } - return nil -} - -// Teardown - ensures that the data is cleaned up for a fresh run -func Teardown(db *sql.DB) error { - - sqlStmt := ` - DELETE FROM api_capability; - DELETE FROM deliveryservices_required_capability; - DELETE FROM server_server_capability; - DELETE FROM server_capability; - DELETE FROM to_extension; - DELETE FROM staticdnsentry; - DELETE FROM job; - DELETE FROM log; - DELETE FROM asn; - DELETE FROM tm_user; - DELETE FROM role; - DELETE FROM capability; - ALTER SEQUENCE role_id_seq RESTART WITH 1; - DELETE FROM deliveryservice_regex; - DELETE FROM regex; - DELETE FROM deliveryservice_server; - DELETE FROM deliveryservice; - DELETE FROM origin; - DELETE FROM ip_address; - DELETE FROM interface; - DELETE FROM server; - DELETE FROM phys_location; - DELETE FROM region; - DELETE FROM division; - DELETE FROM profile; - DELETE FROM parameter; - DELETE FROM profile_parameter; - DELETE FROM topology; - DELETE FROM cachegroup; - DELETE FROM coordinate; - DELETE FROM type; - DELETE FROM status s WHERE s.name NOT IN ('OFFLINE', 'ONLINE', 'PRE_PROD', 'ADMIN_DOWN', 'REPORTED'); - DELETE FROM snapshot; - DELETE FROM cdn; - DELETE FROM service_category; - DELETE FROM tenant; - ALTER SEQUENCE tenant_id_seq RESTART WITH 1; -` - err := execSQL(db, sqlStmt) - if err != nil { - return fmt.Errorf("exec failed %v", err) - } - return err -} - -// execSQL ... -func execSQL(db *sql.DB, sqlStmt string) error { - var err error - - tx, err := db.Begin() - if err != nil { - return fmt.Errorf("transaction begin failed %v %v ", err, tx) - } - - res, err := tx.Exec(sqlStmt) - if err != nil { - return fmt.Errorf("exec failed %v %v", err, res) - } - - err = tx.Commit() - if err != nil { - return fmt.Errorf("commit failed %v %v", err, res) - } - return nil -} diff --git a/traffic_ops/testing/api/v2/traffic_control_test.go b/traffic_ops/testing/api/v2/traffic_control_test.go deleted file mode 100644 index b0b41eeec4..0000000000 --- a/traffic_ops/testing/api/v2/traffic_control_test.go +++ /dev/null @@ -1,64 +0,0 @@ -/* - - Licensed 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. -*/ - -package v2 - -import ( - "github.com/apache/trafficcontrol/lib/go-tc" -) - -// TrafficControl - maps to the tc-fixtures.json file -type TrafficControl struct { - ASNs []tc.ASN `json:"asns"` - CDNs []tc.CDN `json:"cdns"` - CacheGroups []tc.CacheGroupNullable `json:"cachegroups"` - CacheGroupParameterRequests []tc.CacheGroupParameterRequest `json:"cachegroupParameters"` - Capabilities []tc.Capability `json:"capability"` - Coordinates []tc.Coordinate `json:"coordinates"` - DeliveryServicesRegexes []tc.DeliveryServiceRegexesTest `json:"deliveryServicesRegexes"` - DeliveryServiceRequests []tc.DeliveryServiceRequest `json:"deliveryServiceRequests"` - DeliveryServiceRequestComments []tc.DeliveryServiceRequestComment `json:"deliveryServiceRequestComments"` - DeliveryServices []tc.DeliveryServiceNullable `json:"deliveryservices"` - DeliveryServicesRequiredCapabilities []tc.DeliveryServicesRequiredCapability `json:"deliveryservicesRequiredCapabilities"` - Divisions []tc.Division `json:"divisions"` - Federations []tc.CDNFederation `json:"federations"` - FederationResolvers []tc.FederationResolver `json:"federation_resolvers"` - Origins []tc.Origin `json:"origins"` - Profiles []tc.Profile `json:"profiles"` - Parameters []tc.Parameter `json:"parameters"` - ProfileParameters []tc.ProfileParameter `json:"profileParameters"` - PhysLocations []tc.PhysLocation `json:"physLocations"` - Regions []tc.Region `json:"regions"` - Roles []tc.Role `json:"roles"` - Servers []tc.Server `json:"servers"` - ServerServerCapabilities []tc.ServerServerCapability `json:"serverServerCapabilities"` - ServerCapabilities []tc.ServerCapability `json:"serverCapabilities"` - Statuses []tc.StatusNullable `json:"statuses"` - StaticDNSEntries []tc.StaticDNSEntry `json:"staticdnsentries"` - StatsSummaries []tc.StatsSummary `json:"statsSummaries"` - Tenants []tc.Tenant `json:"tenants"` - ServerCheckExtensions []tc.ServerCheckExtensionNullable `json:"servercheck_extensions"` - Types []tc.Type `json:"types"` - SteeringTargets []tc.SteeringTargetNullable `json:"steeringTargets"` - Serverchecks []tc.ServercheckRequestNullable `json:"serverchecks"` - Users []tc.User `json:"users"` - Jobs []JobRequest `json:"jobs"` - InvalidationJobs []tc.InvalidationJobInput `json:"invalidationJobs"` -} - -type JobRequest struct { - DSName string `json:"dsName"` - Request tc.JobRequest `json:"request"` -} diff --git a/traffic_ops/testing/api/v2/traffic_ops_test.go b/traffic_ops/testing/api/v2/traffic_ops_test.go deleted file mode 100644 index 41f4df2eca..0000000000 --- a/traffic_ops/testing/api/v2/traffic_ops_test.go +++ /dev/null @@ -1,112 +0,0 @@ -// Package v2 provides tests for the Traffic Ops API. -package v2 - -/* - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import ( - "database/sql" - "flag" - "fmt" - "os" - "testing" - "time" - - "github.com/apache/trafficcontrol/lib/go-log" - "github.com/apache/trafficcontrol/traffic_ops/testing/api/config" - _ "github.com/lib/pq" -) - -var ( - Config config.Config - testData TrafficControl - includeSystemTests bool -) - -func TestMain(m *testing.M) { - configFileName := flag.String("cfg", "traffic-ops-test.conf", "The config file path") - tcFixturesFileName := flag.String("fixtures", "tc-fixtures.json", "The test fixtures for the API test tool") - cliIncludeSystemTests := *flag.Bool("includeSystemTests", false, "Whether to enable tests that have environment dependencies beyond a database") - flag.Parse() - - // Skip loading configuration when run with `go test -list=`. The -list - // flag does not actually run tests, so configuration data is not needed in - // that mode. If the user is just trying to list the available tests we - // don't want to abort with an error about a bad configuration the user - // doesn't care about yet. - if f := flag.Lookup("test.list"); f != nil { - if f.Value.String() != "" { - os.Exit(m.Run()) - } - } - - var err error - if Config, err = config.LoadConfig(*configFileName); err != nil { - fmt.Printf("Error Loading Config: %v\n", err) - os.Exit(1) - } - - // CLI option overrides config - includeSystemTests = Config.Default.IncludeSystemTests || cliIncludeSystemTests - - if err = log.InitCfg(Config); err != nil { - fmt.Printf("Error initializing loggers: %v\n", err) - os.Exit(1) - } - - log.Infof(`Using Config values: - TO Config File: %s - TO Fixtures: %s - TO URL: %s - TO Session Timeout In Secs: %d - DB Server: %s - DB User: %s - DB Name: %s - DB Ssl: %t`, *configFileName, *tcFixturesFileName, Config.TrafficOps.URL, Config.Default.Session.TimeoutInSecs, Config.TrafficOpsDB.Hostname, Config.TrafficOpsDB.User, Config.TrafficOpsDB.Name, Config.TrafficOpsDB.SSL) - - //Load the test data - LoadFixtures(*tcFixturesFileName) - - var db *sql.DB - db, err = OpenConnection() - if err != nil { - fmt.Printf("\nError opening connection to %s - %s, %v\n", Config.TrafficOps.URL, Config.TrafficOpsDB.User, err) - os.Exit(1) - } - defer db.Close() - - err = Teardown(db) - if err != nil { - fmt.Printf("\nError tearingdown data %s - %s, %v\n", Config.TrafficOps.URL, Config.TrafficOpsDB.User, err) - os.Exit(1) - } - - err = SetupTestData(db) - if err != nil { - fmt.Printf("\nError setting up data %s - %s, %v\n", Config.TrafficOps.URL, Config.TrafficOpsDB.User, err) - os.Exit(1) - } - - toReqTimeout := time.Second * time.Duration(Config.Default.Session.TimeoutInSecs) - err = SetupSession(toReqTimeout, Config.TrafficOps.URL, Config.TrafficOps.Users.Admin, Config.TrafficOps.UserPassword) - if err != nil { - fmt.Printf("\nError creating session to %s - %s, %v\n", Config.TrafficOps.URL, Config.TrafficOpsDB.User, err) - os.Exit(1) - } - - // Now run the test case - rc := m.Run() - os.Exit(rc) -} diff --git a/traffic_ops/testing/api/v2/types_test.go b/traffic_ops/testing/api/v2/types_test.go deleted file mode 100644 index 6390d135fb..0000000000 --- a/traffic_ops/testing/api/v2/types_test.go +++ /dev/null @@ -1,176 +0,0 @@ -package v2 - -/* - - Licensed 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 ( - "fmt" - "testing" - - tc "github.com/apache/trafficcontrol/lib/go-tc" -) - -func TestTypes(t *testing.T) { - WithObjs(t, []TCObj{Parameters, Types}, func() { - UpdateTestTypes(t) - GetTestTypes(t) - }) -} - -func CreateTestTypes(t *testing.T) { - t.Log("---- CreateTestTypes ----") - - db, err := OpenConnection() - if err != nil { - t.Fatal("cannot open db") - } - defer func() { - err := db.Close() - if err != nil { - t.Errorf("unable to close connection to db, error: %v", err) - } - }() - dbQueryTemplate := "INSERT INTO type (name, description, use_in_table) VALUES ('%v', '%v', '%v');" - - for _, typ := range testData.Types { - foundTypes, _, err := TOSession.GetTypeByName(typ.Name) - if err == nil && len(foundTypes) > 0 { - t.Logf("Type %v already exists (%v match(es))", typ.Name, len(foundTypes)) - continue - } - - if typ.UseInTable != "server" { - err = execSQL(db, fmt.Sprintf(dbQueryTemplate, typ.Name, typ.Description, typ.UseInTable)) - } else { - _, _, err = TOSession.CreateType(typ) - } - - if err != nil { - t.Fatalf("could not CREATE types: %v", err) - } - } -} - -func UpdateTestTypes(t *testing.T) { - t.Log("---- UpdateTestTypes ----") - - for i, typ := range testData.Types { - expectedTypeName := fmt.Sprintf("testType%v", i) - originalType := typ - resp, _, err := TOSession.GetTypeByName(originalType.Name) - if err != nil { - t.Fatalf("cannot GET Type by name: %v - %v", originalType.Name, err) - } - if len(resp) < 1 { - t.Fatalf("no types by name: %v", originalType.Name) - } - - remoteType := resp[0] - remoteType.Name = expectedTypeName - // Ensure TO checks DB for UseInTable value - remoteType.UseInTable = "server" - - var alert tc.Alerts - alert, _, err = TOSession.UpdateTypeByID(remoteType.ID, remoteType) - if originalType.UseInTable != "server" { - if err == nil { - t.Fatalf("expected UPDATE on type %v to fail", remoteType.ID) - } - continue - } else if err != nil { - t.Fatalf("cannot UPDATE Type by id: %v - %v", err, alert) - } - - // Retrieve the Type to check Type name got updated - resp, _, err = TOSession.GetTypeByID(remoteType.ID) - if err != nil { - t.Fatalf("cannot GET Type by ID: %v - %v", originalType.ID, err) - } - respType := resp[0] - if respType.Name != expectedTypeName { - t.Fatalf("results do not match actual: %s, expected: %s", respType.Name, expectedTypeName) - } - if respType.UseInTable != originalType.UseInTable { - t.Fatalf("use in table should never be updated, got: %v, expected %v", respType.UseInTable, originalType.UseInTable) - } - - // Revert name change - respType.Name = originalType.Name - alert, _, err = TOSession.UpdateTypeByID(respType.ID, respType) - if err != nil { - t.Fatalf("cannot restore UPDATE Type by id: %v - %v", err, alert) - } - } -} - -func GetTestTypes(t *testing.T) { - t.Log("---- GetTestTypes ----") - - for _, typ := range testData.Types { - resp, _, err := TOSession.GetTypeByName(typ.Name) - if err != nil { - t.Errorf("cannot GET Type by name: %v - %v", err, resp) - - } - - t.Log("Response: ", resp) - } -} - -func DeleteTestTypes(t *testing.T) { - t.Log("---- DeleteTestTypes ----") - - db, err := OpenConnection() - if err != nil { - t.Fatal("cannot open db") - } - defer func() { - err := db.Close() - if err != nil { - t.Errorf("unable to close connection to db, error: %v", err) - } - }() - dbDeleteTemplate := "DELETE FROM type WHERE name='%v';" - - for _, typ := range testData.Types { - // Retrieve the Type by name so we can get the id for the Update - resp, _, err := TOSession.GetTypeByName(typ.Name) - if err != nil || len(resp) == 0 { - t.Fatalf("cannot GET Type by name: %v - %v", typ.Name, err) - } - respType := resp[0] - - if respType.UseInTable != "server" { - err := execSQL(db, fmt.Sprintf(dbDeleteTemplate, respType.Name)) - if err != nil { - t.Fatalf("cannot DELETE Type by name: %v", err) - } - } else { - delResp, _, err := TOSession.DeleteTypeByID(respType.ID) - if err != nil { - t.Fatalf("cannot DELETE Type by name: %v - %v", err, delResp) - } - } - - // Retrieve the Type to see if it got deleted - types, _, err := TOSession.GetTypeByName(typ.Name) - if err != nil { - t.Errorf("error deleting Type name: %v", err) - } - if len(types) > 0 { - t.Errorf("expected Type name: %s to be deleted", typ.Name) - } - } -} diff --git a/traffic_ops/testing/api/v2/user_test.go b/traffic_ops/testing/api/v2/user_test.go deleted file mode 100644 index b3253e65d9..0000000000 --- a/traffic_ops/testing/api/v2/user_test.go +++ /dev/null @@ -1,468 +0,0 @@ -package v2 - -/* - Licensed 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 ( - "bytes" - "fmt" - "github.com/apache/trafficcontrol/lib/go-rfc" - "net/http" - "net/mail" - "strings" - "testing" - "time" - - "github.com/apache/trafficcontrol/lib/go-tc" - "github.com/apache/trafficcontrol/lib/go-util" - toclient "github.com/apache/trafficcontrol/traffic_ops/v2-client" -) - -func TestUsers(t *testing.T) { - WithObjs(t, []TCObj{CDNs, Types, Tenants, Parameters, Profiles, Statuses, Divisions, Regions, PhysLocations, CacheGroups, DeliveryServices, Users}, func() { - UpdateTestUsers(t) - RolenameCapitalizationTest(t) - OpsUpdateAdminTest(t) - UserSelfUpdateTest(t) - UserUpdateOwnRoleTest(t) - GetTestUsers(t) - GetTestUserCurrent(t) - UserTenancyTest(t) - if includeSystemTests { - // UserRegistrationTest deletes test users before registering new users, so it must come after the other user tests. - UserRegistrationTest(t) - } - }) -} - -const SessionUserName = "admin" // TODO make dynamic? - -func CreateTestUsers(t *testing.T) { - for _, user := range testData.Users { - - resp, _, err := TOSession.CreateUser(&user) - if err != nil { - t.Errorf("could not CREATE user: %v", err) - } - t.Log("Response: ", resp.Alerts) - } -} - -func RolenameCapitalizationTest(t *testing.T) { - - roles, _, _, err := TOSession.GetRoles() - if err != nil { - t.Errorf("could not get roles: %v", err) - } - if len(roles) == 0 { - t.Fatal("there should be at least one role to test the user") - } - - tenants, _, err := TOSession.Tenants() - if err != nil { - t.Errorf("could not get tenants: %v", err) - } - if len(tenants) == 0 { - t.Fatal("there should be at least one tenant to test the user") - } - - // this user never does anything, so the role and tenant aren't important - blob := fmt.Sprintf(` - { - "username": "test_user", - "email": "cooldude6@example.com", - "fullName": "full name is required", - "localPasswd": "better_twelve", - "confirmLocalPasswd": "better_twelve", - "role": %d, - "tenantId": %d - }`, *roles[0].ID, tenants[0].ID) - - reader := strings.NewReader(blob) - request, err := http.NewRequest("POST", fmt.Sprintf("%v/api/2.0/users", TOSession.URL), reader) - if err != nil { - t.Errorf("could not make new request: %v", err) - } - resp, err := TOSession.Client.Do(request) - if err != nil { - t.Errorf("could not do request: %v", err) - } - - buf := new(bytes.Buffer) - buf.ReadFrom(resp.Body) - strResp := buf.String() - if !strings.Contains(strResp, "roleName") { - t.Error("incorrect json was returned for POST") - } - - request, err = http.NewRequest("GET", fmt.Sprintf("%v/api/2.0/users?username=test_user", TOSession.URL), nil) - resp, err = TOSession.Client.Do(request) - - buf = new(bytes.Buffer) - buf.ReadFrom(resp.Body) - strResp = buf.String() - if !strings.Contains(strResp, "rolename") { - t.Error("incorrect json was returned for GET") - } - -} - -func OpsUpdateAdminTest(t *testing.T) { - toReqTimeout := time.Second * time.Duration(Config.Default.Session.TimeoutInSecs) - opsTOClient, _, err := toclient.LoginWithAgent(TOSession.URL, "opsuser", "pa$$word", true, "to-api-v2-client-tests/opsuser", true, toReqTimeout) - if err != nil { - t.Fatalf("failed to get log in with opsuser: %v", err.Error()) - } - - resp, _, err := TOSession.GetUserByUsername("admin") - if err != nil { - t.Errorf("cannot GET user by name: 'admin', %v", err) - } - user := resp[0] - - fullName := "oops" - email := "oops@ops.net" - user.FullName = &fullName - user.Email = &email - - _, _, err = opsTOClient.UpdateUserByID(*user.ID, &user) - if err == nil { - t.Error("ops user incorrectly updated an admin") - } -} - -func UserRegistrationTest(t *testing.T) { - ForceDeleteTestUsers(t) - var emails []string - for _, user := range testData.Users { - tenant, _, err := TOSession.TenantByName(*user.Tenant) - if err != nil { - t.Fatalf("could not get tenant %v: %v", *user.Tenant, err) - } - resp, _, err := TOSession.RegisterNewUser(uint(tenant.ID), uint(*user.Role), rfc.EmailAddress{Address: mail.Address{Address: *user.Email}}) - if err != nil { - t.Fatalf("could not register user: %v", err) - } - t.Log("Response: ", resp.Alerts) - emails = append(emails, fmt.Sprintf(`'%v'`, *user.Email)) - } - - db, err := OpenConnection() - if err != nil { - t.Error("cannot open db") - } - defer db.Close() - q := `DELETE FROM tm_user WHERE email IN (` + strings.Join(emails, ",") + `)` - if err := execSQL(db, q); err != nil { - t.Errorf("cannot execute SQL to delete registered users: %s; SQL is %s", err.Error(), q) - } -} - -func UserSelfUpdateTest(t *testing.T) { - toReqTimeout := time.Second * time.Duration(Config.Default.Session.TimeoutInSecs) - opsTOClient, _, err := toclient.LoginWithAgent(TOSession.URL, "opsuser", "pa$$word", true, "to-api-v2-client-tests/opsuser", true, toReqTimeout) - if err != nil { - t.Fatalf("failed to get log in with opsuser: %v", err.Error()) - } - - resp, _, err := TOSession.GetUserByUsername("opsuser") - if err != nil { - t.Fatalf("cannot GET user by name: 'opsuser', %v\n", err) - } - if len(resp) < 1 { - t.Fatalf("no users returned when requesting user 'opsuser'") - } - user := resp[0] - - if user.ID == nil { - t.Fatalf("user 'opsuser' has a null or missing ID - cannot proceed") - } - - user.FullName = util.StrPtr("Oops-man") - user.Email = util.StrPtr("operator@not.example.com") - - var updateResp *tc.UpdateUserResponse - updateResp, _, err = opsTOClient.UpdateUserByID(*user.ID, &user) - if err != nil { - t.Fatalf("cannot UPDATE user by id: %v - %v\n", err, updateResp) - } - - // Make sure it got updated - resp2, _, err := TOSession.GetUserByID(*user.ID) - if err != nil { - t.Fatalf("cannot GET user by id: '%d', %v\n", *user.ID, err) - } - if len(resp2) < 1 { - t.Fatalf("no results returned when requesting user #%d", *user.ID) - } - updatedUser := resp2[0] - - if updatedUser.FullName == nil { - t.Errorf("user was not correctly updated, FullName is null or missing") - } else if *updatedUser.FullName != "Oops-man" { - t.Errorf("results do not match actual: '%s', expected: 'Oops-man'\n", *updatedUser.FullName) - } - - if updatedUser.Email == nil { - t.Errorf("user was not correctly updated, Email is null or missing") - } else if *updatedUser.Email != "operator@not.example.com" { - t.Errorf("results do not match actual: '%s', expected: 'operator@not.example.com'\n", *updatedUser.Email) - } - - // Same thing using /user/current - user.FullName = util.StrPtr("ops-man") - user.Email = util.StrPtr("operator@example.com") - updateResp, _, err = opsTOClient.UpdateCurrentUser(user) - if err != nil { - t.Fatalf("error updating current user: %v - %v", err, updateResp) - } - - // Make sure it got updated - resp2, _, err = TOSession.GetUserByID(*user.ID) - if err != nil { - t.Fatalf("error getting user #%d: %v", *user.ID, err) - } - - if len(resp2) < 1 { - t.Fatalf("no user returned when requesting user #%d", *user.ID) - } - - if resp2[0].FullName == nil { - t.Errorf("FullName missing or null after update") - } else if *resp2[0].FullName != "ops-man" { - t.Errorf("Expected FullName to be 'ops-man', but it was '%s'", *resp2[0].FullName) - } - - if resp2[0].Email == nil { - t.Errorf("Email missing or null after update") - } else if *resp2[0].Email != "operator@example.com" { - t.Errorf("Expected Email to be restored to 'operator@example.com', but it was '%s'", *resp2[0].Email) - } - - // now test using an invalid email address - currentEmail := *user.Email - user.Email = new(string) - updateResp, _, err = TOSession.UpdateCurrentUser(user) - if err == nil { - t.Fatal("error was expected updating user with email: '' - got none") - } - - // Ensure it wasn't actually updated - resp2, _, err = TOSession.GetUserByID(*user.ID) - if err != nil { - t.Fatalf("error getting user #%d: %v", *user.ID, err) - } - - if len(resp2) < 1 { - t.Fatalf("no user returned when requesting user #%d", *user.ID) - } - - if resp2[0].Email == nil { - t.Errorf("Email missing or null after update") - } else if *resp2[0].Email != currentEmail { - t.Errorf("Expected Email to still be '%s', but it was '%s'", currentEmail, *resp2[0].Email) - } -} - -func UserUpdateOwnRoleTest(t *testing.T) { - resp, _, err := TOSession.GetUserByUsername(SessionUserName) - if err != nil { - t.Errorf("cannot GET user by name: '%s', %v", SessionUserName, err) - } - user := resp[0] - - *user.Role = *user.Role + 1 - _, _, err = TOSession.UpdateUserByID(*user.ID, &user) - if err == nil { - t.Error("user incorrectly updated their role") - } -} - -func UpdateTestUsers(t *testing.T) { - firstUsername := *testData.Users[0].Username - resp, _, err := TOSession.GetUserByUsername(firstUsername) - if err != nil { - t.Errorf("cannot GET user by name: '%s', %v", firstUsername, err) - } - user := resp[0] - newCity := "kidz kable kown" - *user.City = newCity - - var updateResp *tc.UpdateUserResponse - updateResp, _, err = TOSession.UpdateUserByID(*user.ID, &user) - if err != nil { - t.Errorf("cannot UPDATE user by id: %v - %v", err, updateResp.Alerts) - } - - // Make sure it got updated - resp2, _, err := TOSession.GetUserByID(*user.ID) - if err != nil { - t.Errorf("cannot GET user by id: '%d', %v", *user.ID, err) - } - updatedUser := resp2[0] - if *updatedUser.City != newCity { - t.Errorf("results do not match actual: %s, expected: %s", *updatedUser.City, newCity) - } -} - -func GetTestUsers(t *testing.T) { - _, _, err := TOSession.GetUsers() - if err != nil { - t.Errorf("cannot GET users: %v", err) - } -} - -func GetTestUserCurrent(t *testing.T) { - user, _, err := TOSession.GetUserCurrent() - if err != nil { - t.Errorf("cannot GET current user: %v", err) - } - if user.UserName == nil { - t.Errorf("current user expected: %v actual: %v", SessionUserName, nil) - } - if *user.UserName != SessionUserName { - t.Errorf("current user expected: %v actual: %v", SessionUserName, *user.UserName) - } -} - -func UserTenancyTest(t *testing.T) { - users, _, err := TOSession.GetUsers() - if err != nil { - t.Errorf("cannot GET users: %v", err) - } - tenant3Found := false - tenant4Found := false - tenant3Username := "tenant3user" - tenant4Username := "tenant4user" - tenant3User := tc.User{} - - // assert admin user can view tenant3user and tenant4user - for _, user := range users { - if *user.Username == tenant3Username { - tenant3Found = true - tenant3User = user - } else if *user.Username == tenant4Username { - tenant4Found = true - } - if tenant3Found && tenant4Found { - break - } - } - if !tenant3Found || !tenant4Found { - t.Error("expected admin to be able to view tenants: tenant3 and tenant4") - } - - toReqTimeout := time.Second * time.Duration(Config.Default.Session.TimeoutInSecs) - tenant4TOClient, _, err := toclient.LoginWithAgent(TOSession.URL, "tenant4user", "pa$$word", true, "to-api-v2-client-tests/tenant4user", true, toReqTimeout) - if err != nil { - t.Fatalf("failed to log in with tenant4user: %v", err.Error()) - } - - usersReadableByTenant4, _, err := tenant4TOClient.GetUsers() - if err != nil { - t.Error("tenant4user cannot GET users") - } - - tenant4canReadItself := false - for _, user := range usersReadableByTenant4 { - // assert that tenant4user cannot read tenant3user - if *user.Username == tenant3Username { - t.Error("expected tenant4user to be unable to read tenant3user") - } - // assert that tenant4user can read itself - if *user.Username == tenant4Username { - tenant4canReadItself = true - } - } - if !tenant4canReadItself { - t.Error("expected tenant4user to be able to read itself") - } - - // assert that tenant4user cannot update tenant3user - if _, _, err = tenant4TOClient.UpdateUserByID(*tenant3User.ID, &tenant3User); err == nil { - t.Error("expected tenant4user to be unable to update tenant4user") - } - - // assert that tenant4user cannot create a user outside of its tenant - rootTenant, _, err := TOSession.TenantByName("root") - if err != nil { - t.Error("expected to be able to GET the root tenant") - } - newUser := testData.Users[0] - newUser.Email = util.StrPtr("testusertenancy@example.com") - newUser.Username = util.StrPtr("testusertenancy") - newUser.TenantID = &rootTenant.ID - if _, _, err = tenant4TOClient.CreateUser(&newUser); err == nil { - t.Error("expected tenant4user to be unable to create a new user in the root tenant") - } -} - -// ForceDeleteTestUsers forcibly deletes the users from the db. -func ForceDeleteTestUsers(t *testing.T) { - - // NOTE: Special circumstances! This should *NOT* be done without a really good reason! - // Connects directly to the DB to remove users rather than going thru the client. - // This is required here because the DeleteUser action does not really delete users, but disables them. - db, err := OpenConnection() - if err != nil { - t.Error("cannot open db") - } - defer db.Close() - - var usernames []string - for _, user := range testData.Users { - usernames = append(usernames, `'`+*user.Username+`'`) - } - - // there is a constraint that prevents users from being deleted when they have a log - q := `DELETE FROM log WHERE NOT tm_user = (SELECT id FROM tm_user WHERE username = 'admin')` - err = execSQL(db, q) - if err != nil { - t.Errorf("cannot execute SQL: %s; SQL is %s", err.Error(), q) - } - - q = `DELETE FROM tm_user WHERE username IN (` + strings.Join(usernames, ",") + `)` - err = execSQL(db, q) - if err != nil { - t.Errorf("cannot execute SQL: %s; SQL is %s", err.Error(), q) - } -} - -func DeleteTestUsers(t *testing.T) { - for _, user := range testData.Users { - - resp, _, err := TOSession.GetUserByUsername(*user.Username) - if err != nil { - t.Errorf("cannot GET user by name: %v - %v", *user.Username, err) - } - - if resp != nil { - respUser := resp[0] - - _, _, err := TOSession.DeleteUserByID(*respUser.ID) - if err != nil { - t.Errorf("cannot DELETE user by name: '%s' %v", *respUser.Username, err) - } - - // Make sure it got deleted - resp, _, err := TOSession.GetUserByUsername(*user.Username) - if err != nil { - t.Errorf("error deleting user by name: %s", err.Error()) - } - if len(resp) > 0 { - t.Errorf("expected user: %s to be deleted", *user.Username) - } - } - } -} diff --git a/traffic_ops/testing/api/v2/withobjs_test.go b/traffic_ops/testing/api/v2/withobjs_test.go deleted file mode 100644 index 98f42dac0a..0000000000 --- a/traffic_ops/testing/api/v2/withobjs_test.go +++ /dev/null @@ -1,116 +0,0 @@ -/* - - Licensed 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. -*/ - -package v2 - -import ( - "testing" -) - -// WithObjs creates the objs in order, runs f, and defers deleting the objs in the same order. -// -// Because deletion is deferred, using this ensures objects will be cleaned up if f panics or calls t.Fatal, as much as possible. -// -// Note that f itself may still create things which are not cleaned up properly, and likewise, the object creation and deletion tests themselves may fail. -// All tests in the Traffic Ops API Testing framework use the same Traffic Ops instance, with persistent data. Because of this, when any test fails, all subsequent tests should be considered invalid, irrespective whether they pass or fail. Users are encouraged to use `go test -failfast`. -func WithObjs(t *testing.T, objs []TCObj, f func()) { - defer func() { - for index := len(objs) - 1; index >= 0; index-- { - obj := objs[index] - withFuncs[obj].Delete(t) - } - }() - for _, obj := range objs { - withFuncs[obj].Create(t) - } - f() -} - -type TCObj int - -const ( - CacheGroups TCObj = iota - CacheGroupsDeliveryServices - CacheGroupParameters - CDNs - CDNFederations - Coordinates - DeliveryServices - DeliveryServicesRegexes - DeliveryServiceRequests - DeliveryServiceRequestComments - DeliveryServicesRequiredCapabilities - Divisions - FederationResolvers - FederationUsers - Origins - Parameters - PhysLocations - Profiles - ProfileParameters - Regions - Roles - ServerCapabilities - ServerChecks - ServerServerCapabilities - Servers - Statuses - StaticDNSEntries - SteeringTargets - Tenants - ServerCheckExtensions - Types - Users -) - -type TCObjFuncs struct { - Create func(t *testing.T) - Delete func(t *testing.T) -} - -var withFuncs = map[TCObj]TCObjFuncs{ - CacheGroups: {CreateTestCacheGroups, DeleteTestCacheGroups}, - CacheGroupsDeliveryServices: {CreateTestCachegroupsDeliveryServices, DeleteTestCachegroupsDeliveryServices}, - CacheGroupParameters: {CreateTestCacheGroupParameters, DeleteTestCacheGroupParameters}, - CDNs: {CreateTestCDNs, DeleteTestCDNs}, - CDNFederations: {CreateTestCDNFederations, DeleteTestCDNFederations}, - Coordinates: {CreateTestCoordinates, DeleteTestCoordinates}, - DeliveryServices: {CreateTestDeliveryServices, DeleteTestDeliveryServices}, - DeliveryServicesRegexes: {CreateTestDeliveryServicesRegexes, DeleteTestDeliveryServicesRegexes}, - DeliveryServiceRequests: {CreateTestDeliveryServiceRequests, DeleteTestDeliveryServiceRequests}, - DeliveryServiceRequestComments: {CreateTestDeliveryServiceRequestComments, DeleteTestDeliveryServiceRequestComments}, - DeliveryServicesRequiredCapabilities: {CreateTestDeliveryServicesRequiredCapabilities, DeleteTestDeliveryServicesRequiredCapabilities}, - Divisions: {CreateTestDivisions, DeleteTestDivisions}, - FederationUsers: {CreateTestFederationUsers, DeleteTestFederationUsers}, - FederationResolvers: {CreateTestFederationResolvers, DeleteTestFederationResolvers}, - Origins: {CreateTestOrigins, DeleteTestOrigins}, - Parameters: {CreateTestParameters, DeleteTestParameters}, - PhysLocations: {CreateTestPhysLocations, DeleteTestPhysLocations}, - Profiles: {CreateTestProfiles, DeleteTestProfiles}, - ProfileParameters: {CreateTestProfileParameters, DeleteTestProfileParameters}, - Regions: {CreateTestRegions, DeleteTestRegions}, - Roles: {CreateTestRoles, DeleteTestRoles}, - ServerCapabilities: {CreateTestServerCapabilities, DeleteTestServerCapabilities}, - ServerChecks: {CreateTestServerChecks, DeleteTestServerChecks}, - ServerServerCapabilities: {CreateTestServerServerCapabilities, DeleteTestServerServerCapabilities}, - Servers: {CreateTestServers, DeleteTestServers}, - Statuses: {CreateTestStatuses, DeleteTestStatuses}, - StaticDNSEntries: {CreateTestStaticDNSEntries, DeleteTestStaticDNSEntries}, - SteeringTargets: {SetupSteeringTargets, DeleteTestSteeringTargets}, - Tenants: {CreateTestTenants, DeleteTestTenants}, - ServerCheckExtensions: {CreateTestServerCheckExtensions, DeleteTestServerCheckExtensions}, - Types: {CreateTestTypes, DeleteTestTypes}, - Users: {CreateTestUsers, ForceDeleteTestUsers}, -} From 989828a8349e81569ed90028ef04cd17307e4909 Mon Sep 17 00:00:00 2001 From: Zach Hoffman Date: Tue, 28 Jun 2022 09:33:36 -0600 Subject: [PATCH 02/14] Remove Traffic Ops v2 Go client library --- traffic_control/clients/README.md | 3 - traffic_ops/v2-client/README.md | 58 -- traffic_ops/v2-client/about.go | 43 -- traffic_ops/v2-client/api_capability.go | 60 --- traffic_ops/v2-client/asn.go | 132 ----- traffic_ops/v2-client/cachegroup.go | 191 ------- .../v2-client/cachegroup_parameters.go | 114 ---- traffic_ops/v2-client/capability.go | 61 --- traffic_ops/v2-client/cdn.go | 150 ------ traffic_ops/v2-client/cdn_domains.go | 29 - traffic_ops/v2-client/cdnfederations.go | 73 --- traffic_ops/v2-client/coordinate.go | 155 ------ traffic_ops/v2-client/crconfig.go | 84 --- traffic_ops/v2-client/deliveryservice.go | 383 -------------- .../v2-client/deliveryservice_regexes.go | 62 --- .../deliveryservice_request_comments.go | 115 ---- .../v2-client/deliveryservice_requests.go | 243 --------- .../deliveryservices_required_capabilities.go | 83 --- .../v2-client/deliveryserviceserver.go | 119 ----- traffic_ops/v2-client/division.go | 132 ----- traffic_ops/v2-client/dsuser.go | 57 -- traffic_ops/v2-client/endpoints.go | 18 - traffic_ops/v2-client/federation.go | 211 -------- .../federation_federation_resolver.go | 70 --- traffic_ops/v2-client/federation_resolver.go | 116 ---- traffic_ops/v2-client/iso.go | 54 -- traffic_ops/v2-client/job.go | 174 ------ traffic_ops/v2-client/log.go | 61 --- traffic_ops/v2-client/origin.go | 194 ------- traffic_ops/v2-client/parameter.go | 204 ------- traffic_ops/v2-client/phys_location.go | 144 ----- traffic_ops/v2-client/ping.go | 39 -- traffic_ops/v2-client/profile.go | 291 ---------- traffic_ops/v2-client/profile_parameter.go | 115 ---- traffic_ops/v2-client/region.go | 170 ------ traffic_ops/v2-client/role.go | 160 ------ traffic_ops/v2-client/server.go | 352 ------------- .../v2-client/server_server_capabilities.go | 83 --- traffic_ops/v2-client/server_update_status.go | 110 ---- traffic_ops/v2-client/servercapability.go | 104 ---- traffic_ops/v2-client/servercheck.go | 53 -- .../v2-client/servercheckextensions.go | 69 --- traffic_ops/v2-client/session.go | 498 ------------------ traffic_ops/v2-client/staticdnsentry.go | 180 ------- traffic_ops/v2-client/stats_summary.go | 77 --- traffic_ops/v2-client/status.go | 132 ----- traffic_ops/v2-client/steering.go | 38 -- traffic_ops/v2-client/steeringtarget.go | 96 ---- traffic_ops/v2-client/tenant.go | 122 ----- traffic_ops/v2-client/traffic_monitor.go | 65 --- traffic_ops/v2-client/traffic_stats.go | 29 - traffic_ops/v2-client/type.go | 153 ------ traffic_ops/v2-client/user.go | 202 ------- traffic_ops/v2-client/util.go | 71 --- 54 files changed, 6802 deletions(-) delete mode 100644 traffic_ops/v2-client/README.md delete mode 100644 traffic_ops/v2-client/about.go delete mode 100644 traffic_ops/v2-client/api_capability.go delete mode 100644 traffic_ops/v2-client/asn.go delete mode 100644 traffic_ops/v2-client/cachegroup.go delete mode 100644 traffic_ops/v2-client/cachegroup_parameters.go delete mode 100644 traffic_ops/v2-client/capability.go delete mode 100644 traffic_ops/v2-client/cdn.go delete mode 100644 traffic_ops/v2-client/cdn_domains.go delete mode 100644 traffic_ops/v2-client/cdnfederations.go delete mode 100644 traffic_ops/v2-client/coordinate.go delete mode 100644 traffic_ops/v2-client/crconfig.go delete mode 100644 traffic_ops/v2-client/deliveryservice.go delete mode 100644 traffic_ops/v2-client/deliveryservice_regexes.go delete mode 100644 traffic_ops/v2-client/deliveryservice_request_comments.go delete mode 100644 traffic_ops/v2-client/deliveryservice_requests.go delete mode 100644 traffic_ops/v2-client/deliveryservices_required_capabilities.go delete mode 100644 traffic_ops/v2-client/deliveryserviceserver.go delete mode 100644 traffic_ops/v2-client/division.go delete mode 100644 traffic_ops/v2-client/dsuser.go delete mode 100644 traffic_ops/v2-client/endpoints.go delete mode 100644 traffic_ops/v2-client/federation.go delete mode 100644 traffic_ops/v2-client/federation_federation_resolver.go delete mode 100644 traffic_ops/v2-client/federation_resolver.go delete mode 100644 traffic_ops/v2-client/iso.go delete mode 100644 traffic_ops/v2-client/job.go delete mode 100644 traffic_ops/v2-client/log.go delete mode 100644 traffic_ops/v2-client/origin.go delete mode 100644 traffic_ops/v2-client/parameter.go delete mode 100644 traffic_ops/v2-client/phys_location.go delete mode 100644 traffic_ops/v2-client/ping.go delete mode 100644 traffic_ops/v2-client/profile.go delete mode 100644 traffic_ops/v2-client/profile_parameter.go delete mode 100644 traffic_ops/v2-client/region.go delete mode 100644 traffic_ops/v2-client/role.go delete mode 100644 traffic_ops/v2-client/server.go delete mode 100644 traffic_ops/v2-client/server_server_capabilities.go delete mode 100644 traffic_ops/v2-client/server_update_status.go delete mode 100644 traffic_ops/v2-client/servercapability.go delete mode 100644 traffic_ops/v2-client/servercheck.go delete mode 100644 traffic_ops/v2-client/servercheckextensions.go delete mode 100644 traffic_ops/v2-client/session.go delete mode 100644 traffic_ops/v2-client/staticdnsentry.go delete mode 100644 traffic_ops/v2-client/stats_summary.go delete mode 100644 traffic_ops/v2-client/status.go delete mode 100644 traffic_ops/v2-client/steering.go delete mode 100644 traffic_ops/v2-client/steeringtarget.go delete mode 100644 traffic_ops/v2-client/tenant.go delete mode 100644 traffic_ops/v2-client/traffic_monitor.go delete mode 100644 traffic_ops/v2-client/traffic_stats.go delete mode 100644 traffic_ops/v2-client/type.go delete mode 100644 traffic_ops/v2-client/user.go delete mode 100644 traffic_ops/v2-client/util.go diff --git a/traffic_control/clients/README.md b/traffic_control/clients/README.md index d85441d1fa..f15be85241 100644 --- a/traffic_control/clients/README.md +++ b/traffic_control/clients/README.md @@ -8,9 +8,6 @@ There are two client libraries supported: * [Documentation](https://github.com/apache/trafficcontrol/tree/master/traffic_control/clients/python/trafficops) ## Golang -### TO API v2 _(Deprecated)_ -* [Documentation](https://github.com/apache/trafficcontrol/tree/master/traffic_ops/v2-client) - ### TO API v3 _(Deprecated)_ * [Documentation](https://github.com/apache/trafficcontrol/tree/master/traffic_ops/v3-client) diff --git a/traffic_ops/v2-client/README.md b/traffic_ops/v2-client/README.md deleted file mode 100644 index 53aec467c3..0000000000 --- a/traffic_ops/v2-client/README.md +++ /dev/null @@ -1,58 +0,0 @@ -# Traffic Ops Go Client - -## Deprecated -The version of the Traffic Ops API supported by this client is deprecated. -Please switch to the `github.com/apache/trafficcontrol/traffic_ops/v3-client` -package. - -## Getting Started -1. Obtain the latest version of the library - -`go get github.com/apache/trafficcontrol/traffic_ops/v2-client` - -2. Get a basic TO session started and fetch a list of CDNs -```go -package main - -import ( - "fmt" - "os" - "time" - - "github.com/apache/trafficcontrol/lib/go-tc" - toclient "github.com/apache/trafficcontrol/traffic_ops/v2-client" -) - -const TOURL = "http://localhost" -const TOUser = "user" -const TOPassword = "password" -const AllowInsecureConnections = true -const UserAgent = "MySampleApp" -const UseClientCache = false -const TrafficOpsRequestTimeout = time.Second * time.Duration(10) - -func main() { - session, remoteaddr, err := toclient.LoginWithAgent( - TOURL, - TOUser, - TOPassword, - AllowInsecureConnections, - UserAgent, - UseClientCache, - TrafficOpsRequestTimeout) - if err != nil { - fmt.Printf("An error occurred while logging in:\n\t%v\n", err) - os.Exit(1) - } - fmt.Println("Connected to: " + remoteaddr.String()) - var cdns []v13.CDN - cdns, _, err = session.GetCDNs() - if err != nil { - fmt.Printf("An error occurred while getting cdns:\n\t%v\n", err) - os.Exit(1) - } - for _, cdn := range cdns { - fmt.Println(cdn.Name) - } -} -``` diff --git a/traffic_ops/v2-client/about.go b/traffic_ops/v2-client/about.go deleted file mode 100644 index cf1e407654..0000000000 --- a/traffic_ops/v2-client/about.go +++ /dev/null @@ -1,43 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "net/http" -) - -const ( - API_ABOUT = apiBase + "/about" -) - -// GetAbout gets data about the TO instance. -func (to *Session) GetAbout() (map[string]string, ReqInf, error) { - route := API_ABOUT - resp, remoteAddr, err := to.request(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data map[string]string - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data, reqInf, nil -} diff --git a/traffic_ops/v2-client/api_capability.go b/traffic_ops/v2-client/api_capability.go deleted file mode 100644 index 81c3eb7ca2..0000000000 --- a/traffic_ops/v2-client/api_capability.go +++ /dev/null @@ -1,60 +0,0 @@ -package client - -import ( - "encoding/json" - "fmt" - "net/http" - "net/url" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -/* - Licensed 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. -*/ - -// GetAPICapabilities will retrieve API Capabilities. In the event that no capability parameter -// is supplied, it will return all existing. If a capability is supplied, it will return only -// those with an exact match. Order may be specified to change the default sort order. -func (to *Session) GetAPICapabilities(capability string, order string) (tc.APICapabilityResponse, ReqInf, error) { - var ( - vals = url.Values{} - path = fmt.Sprintf("%s/api_capabilities", apiBase) - reqInf = ReqInf{CacheHitStatus: CacheHitStatusMiss} - resp tc.APICapabilityResponse - ) - - if capability != "" { - vals.Set("capability", capability) - } - - if order != "" { - vals.Set("orderby", order) - } - - if len(vals) > 0 { - path = fmt.Sprintf("%s?%s", path, vals.Encode()) - } - - httpResp, remoteAddr, err := to.request(http.MethodGet, path, nil) - reqInf.RemoteAddr = remoteAddr - - if err != nil { - return tc.APICapabilityResponse{}, reqInf, err - } - defer httpResp.Body.Close() - - err = json.NewDecoder(httpResp.Body).Decode(&resp) - - return resp, reqInf, err -} diff --git a/traffic_ops/v2-client/asn.go b/traffic_ops/v2-client/asn.go deleted file mode 100644 index 7162eeeb4f..0000000000 --- a/traffic_ops/v2-client/asn.go +++ /dev/null @@ -1,132 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "fmt" - "net" - "net/http" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_ASNS = apiBase + "/asns" -) - -// Create a ASN -func (to *Session) CreateASN(entity tc.ASN) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(entity) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - resp, remoteAddr, err := to.request(http.MethodPost, API_ASNS, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// Update a ASN by ID -func (to *Session) UpdateASNByID(id int, entity tc.ASN) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(entity) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - route := fmt.Sprintf("%s/%d", API_ASNS, id) - resp, remoteAddr, err := to.request(http.MethodPut, route, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// Returns a list of ASNs -func (to *Session) GetASNs() ([]tc.ASN, ReqInf, error) { - resp, remoteAddr, err := to.request(http.MethodGet, API_ASNS, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ASNsResponse - err = json.NewDecoder(resp.Body).Decode(&data) - return data.Response, reqInf, nil -} - -// GET a ASN by the id -func (to *Session) GetASNByID(id int) ([]tc.ASN, ReqInf, error) { - route := fmt.Sprintf("%s?id=%d", API_ASNS, id) - resp, remoteAddr, err := to.request(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ASNsResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GET an ASN by the asn number -func (to *Session) GetASNByASN(asn int) ([]tc.ASN, ReqInf, error) { - url := fmt.Sprintf("%s?asn=%d", API_ASNS, asn) - resp, remoteAddr, err := to.request(http.MethodGet, url, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ASNsResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// DELETE an ASN by asn number -func (to *Session) DeleteASNByASN(asn int) (tc.Alerts, ReqInf, error) { - route := fmt.Sprintf("%s/asn/%d", API_ASNS, asn) - resp, remoteAddr, err := to.request(http.MethodDelete, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} diff --git a/traffic_ops/v2-client/cachegroup.go b/traffic_ops/v2-client/cachegroup.go deleted file mode 100644 index 30f495f152..0000000000 --- a/traffic_ops/v2-client/cachegroup.go +++ /dev/null @@ -1,191 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "errors" - "fmt" - "net" - "net/http" - "net/url" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_CACHEGROUPS = apiBase + "/cachegroups" -) - -// Create a CacheGroup. -func (to *Session) CreateCacheGroupNullable(cachegroup tc.CacheGroupNullable) (*tc.CacheGroupDetailResponse, ReqInf, error) { - if cachegroup.TypeID == nil && cachegroup.Type != nil { - ty, _, err := to.GetTypeByName(*cachegroup.Type) - if err != nil { - return nil, ReqInf{}, err - } - if len(ty) == 0 { - return nil, ReqInf{}, errors.New("no type named " + *cachegroup.Type) - } - cachegroup.TypeID = &ty[0].ID - } - - if cachegroup.ParentCachegroupID == nil && cachegroup.ParentName != nil { - p, _, err := to.GetCacheGroupNullableByName(*cachegroup.ParentName) - if err != nil { - return nil, ReqInf{}, err - } - if len(p) == 0 { - return nil, ReqInf{}, errors.New("no cachegroup named " + *cachegroup.ParentName) - } - cachegroup.ParentCachegroupID = p[0].ID - } - - if cachegroup.SecondaryParentCachegroupID == nil && cachegroup.SecondaryParentName != nil { - p, _, err := to.GetCacheGroupNullableByName(*cachegroup.SecondaryParentName) - if err != nil { - return nil, ReqInf{}, err - } - if len(p) == 0 { - return nil, ReqInf{}, errors.New("no cachegroup named " + *cachegroup.ParentName) - } - cachegroup.SecondaryParentCachegroupID = p[0].ID - } - - reqBody, err := json.Marshal(cachegroup) - if err != nil { - return nil, ReqInf{}, err - } - resp, remoteAddr, err := to.request(http.MethodPost, API_CACHEGROUPS, reqBody) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - var cachegroupResp tc.CacheGroupDetailResponse - if err = json.NewDecoder(resp.Body).Decode(&cachegroupResp); err != nil { - return nil, reqInf, err - } - return &cachegroupResp, reqInf, nil -} - -// Update a CacheGroup by ID. -func (to *Session) UpdateCacheGroupNullableByID(id int, cachegroup tc.CacheGroupNullable) (*tc.CacheGroupDetailResponse, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(cachegroup) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - route := fmt.Sprintf("%s/%d", API_CACHEGROUPS, id) - resp, remoteAddr, err := to.request(http.MethodPut, route, reqBody) - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - var cachegroupResp tc.CacheGroupDetailResponse - if err = json.NewDecoder(resp.Body).Decode(&cachegroupResp); err != nil { - return nil, reqInf, err - } - return &cachegroupResp, reqInf, nil -} - -// Returns a list of CacheGroups. -func (to *Session) GetCacheGroupsNullable() ([]tc.CacheGroupNullable, ReqInf, error) { - resp, remoteAddr, err := to.request(http.MethodGet, API_CACHEGROUPS, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.CacheGroupsNullableResponse - if err = json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - return data.Response, reqInf, nil -} - -// GET a CacheGroup by the CacheGroup ID. -func (to *Session) GetCacheGroupNullableByID(id int) ([]tc.CacheGroupNullable, ReqInf, error) { - route := fmt.Sprintf("%s?id=%v", API_CACHEGROUPS, id) - resp, remoteAddr, err := to.request(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.CacheGroupsNullableResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GET a CacheGroup by the CacheGroup name. -func (to *Session) GetCacheGroupNullableByName(name string) ([]tc.CacheGroupNullable, ReqInf, error) { - route := fmt.Sprintf("%s?name=%s", API_CACHEGROUPS, url.QueryEscape(name)) - resp, remoteAddr, err := to.request(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.CacheGroupsNullableResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GET a CacheGroup by the CacheGroup name. -func (to *Session) GetCacheGroupNullableByShortName(shortName string) ([]tc.CacheGroupNullable, ReqInf, error) { - route := fmt.Sprintf("%s?shortName=%s", API_CACHEGROUPS, url.QueryEscape(shortName)) - resp, remoteAddr, err := to.request(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.CacheGroupsNullableResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// DELETE a CacheGroup by ID. -func (to *Session) DeleteCacheGroupByID(id int) (tc.Alerts, ReqInf, error) { - route := fmt.Sprintf("%s/%d", API_CACHEGROUPS, id) - resp, remoteAddr, err := to.request(http.MethodDelete, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - if err = json.NewDecoder(resp.Body).Decode(&alerts); err != nil { - return tc.Alerts{}, reqInf, err - } - return alerts, reqInf, nil -} diff --git a/traffic_ops/v2-client/cachegroup_parameters.go b/traffic_ops/v2-client/cachegroup_parameters.go deleted file mode 100644 index 8dc7930cdd..0000000000 --- a/traffic_ops/v2-client/cachegroup_parameters.go +++ /dev/null @@ -1,114 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "fmt" - "net/http" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_CACHEGROUPPARAMETERS = apiBase + "/cachegroupparameters" -) - -// GetCacheGroupParameters Gets a Cache Group's Parameters -func (to *Session) GetCacheGroupParameters(cacheGroupID int) ([]tc.CacheGroupParameter, ReqInf, error) { - route := fmt.Sprintf("%s/%d/parameters", API_CACHEGROUPS, cacheGroupID) - return to.getCacheGroupParameters(route, "") -} - -// GetCacheGroupParametersByQueryParams Gets a Cache Group's Parameters with query parameters -func (to *Session) GetCacheGroupParametersByQueryParams(cacheGroupID int, queryParams string) ([]tc.CacheGroupParameter, ReqInf, error) { - route := fmt.Sprintf("%s/%d/parameters", API_CACHEGROUPS, cacheGroupID) - return to.getCacheGroupParameters(route, queryParams) -} - -func (to *Session) getCacheGroupParameters(route, queryParams string) ([]tc.CacheGroupParameter, ReqInf, error) { - r := fmt.Sprintf("%s%s", route, queryParams) - resp, remoteAddr, err := to.request(http.MethodGet, r, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.CacheGroupParametersResponse - if err = json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - return data.Response, reqInf, nil -} - -// GetAllCacheGroupParameters Gets all Cachegroup Parameter associations -func (to *Session) GetAllCacheGroupParameters() ([]tc.CacheGroupParametersResponseNullable, ReqInf, error) { - route := fmt.Sprintf("%s/", API_CACHEGROUPPARAMETERS) - resp, remoteAddr, err := to.request(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.AllCacheGroupParametersResponse - if err = json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - return data.Response.CacheGroupParameters, reqInf, nil -} - -// DeleteCacheGroupParameter Deassociates a Parameter with a Cache Group -func (to *Session) DeleteCacheGroupParameter(cacheGroupID, parameterID int) (tc.Alerts, ReqInf, error) { - route := fmt.Sprintf("%s/%d/%d", API_CACHEGROUPPARAMETERS, cacheGroupID, parameterID) - resp, remoteAddr, err := to.request(http.MethodDelete, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - - var alerts tc.Alerts - if err = json.NewDecoder(resp.Body).Decode(&alerts); err != nil { - return tc.Alerts{}, reqInf, err - } - return alerts, reqInf, nil -} - -// CreateCacheGroupParameter Associates a Parameter with a Cache Group -func (to *Session) CreateCacheGroupParameter(cacheGroupID, parameterID int) (*tc.CacheGroupParametersPostResponse, ReqInf, error) { - cacheGroupParameterReq := tc.CacheGroupParameterRequest{ - CacheGroupID: cacheGroupID, - ParameterID: parameterID, - } - reqBody, err := json.Marshal(cacheGroupParameterReq) - if err != nil { - return nil, ReqInf{}, err - } - resp, remoteAddr, err := to.request(http.MethodPost, API_CACHEGROUPPARAMETERS, reqBody) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.CacheGroupParametersPostResponse - if err = json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - return &data, reqInf, nil -} diff --git a/traffic_ops/v2-client/capability.go b/traffic_ops/v2-client/capability.go deleted file mode 100644 index 43bae247fe..0000000000 --- a/traffic_ops/v2-client/capability.go +++ /dev/null @@ -1,61 +0,0 @@ -package client - -/* - * Licensed 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 "encoding/json" -import "errors" -import "net/http" -import "net/url" - -import "github.com/apache/trafficcontrol/lib/go-tc" - -const API_CAPABILITIES = apiBase + "/capabilities" - -// GetCapabilities retrieves all capabilities. -func (to *Session) GetCapabilities() ([]tc.Capability, ReqInf, error) { - resp, remoteAddr, err := to.request(http.MethodGet, API_CAPABILITIES, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.CapabilitiesResponse - err = json.NewDecoder(resp.Body).Decode(&data) - return data.Response, reqInf, err -} - -// GetCapability retrieves only the capability named 'c'. -func (to *Session) GetCapability(c string) (tc.Capability, ReqInf, error) { - v := url.Values{} - v.Add("name", c) - endpoint := API_CAPABILITIES + "?" + v.Encode() - resp, remoteAddr, err := to.request(http.MethodGet, endpoint, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Capability{}, reqInf, err - } - defer resp.Body.Close() - - var data tc.CapabilitiesResponse - err = json.NewDecoder(resp.Body).Decode(&data) - if err != nil { - return tc.Capability{}, reqInf, err - } else if data.Response == nil || len(data.Response) < 1 { - return tc.Capability{}, reqInf, errors.New("Invalid response - no capability returned!") - } - - return data.Response[0], reqInf, nil -} diff --git a/traffic_ops/v2-client/cdn.go b/traffic_ops/v2-client/cdn.go deleted file mode 100644 index ad30062a75..0000000000 --- a/traffic_ops/v2-client/cdn.go +++ /dev/null @@ -1,150 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "fmt" - "net" - "net/http" - "net/url" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_CDNS = apiBase + "/cdns" -) - -// CreateCDN creates a CDN. -func (to *Session) CreateCDN(cdn tc.CDN) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(cdn) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - resp, remoteAddr, err := to.request(http.MethodPost, API_CDNS, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// UpdateCDNByID updates a CDN by ID. -func (to *Session) UpdateCDNByID(id int, cdn tc.CDN) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(cdn) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - route := fmt.Sprintf("%s/%d", API_CDNS, id) - resp, remoteAddr, err := to.request(http.MethodPut, route, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// GetCDNs eturns a list of CDNs. -func (to *Session) GetCDNs() ([]tc.CDN, ReqInf, error) { - resp, remoteAddr, err := to.request(http.MethodGet, API_CDNS, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.CDNsResponse - err = json.NewDecoder(resp.Body).Decode(&data) - return data.Response, reqInf, nil -} - -// GetCDNByID a CDN by the CDN ID. -func (to *Session) GetCDNByID(id int) ([]tc.CDN, ReqInf, error) { - route := fmt.Sprintf("%s?id=%v", API_CDNS, id) - resp, remoteAddr, err := to.request(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.CDNsResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GetCDNByName gets a CDN by the CDN name. -func (to *Session) GetCDNByName(name string) ([]tc.CDN, ReqInf, error) { - url := fmt.Sprintf("%s?name=%s", API_CDNS, url.QueryEscape(name)) - resp, remoteAddr, err := to.request(http.MethodGet, url, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.CDNsResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// DeleteCDNByID deletes a CDN by ID. -func (to *Session) DeleteCDNByID(id int) (tc.Alerts, ReqInf, error) { - route := fmt.Sprintf("%s/%d", API_CDNS, id) - resp, remoteAddr, err := to.request(http.MethodDelete, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -func (to *Session) GetCDNSSLKeys(name string) ([]tc.CDNSSLKeys, ReqInf, error) { - url := fmt.Sprintf("%s/name/%s/sslkeys", API_CDNS, name) - resp, remoteAddr, err := to.request(http.MethodGet, url, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.CDNSSLKeysResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} diff --git a/traffic_ops/v2-client/cdn_domains.go b/traffic_ops/v2-client/cdn_domains.go deleted file mode 100644 index 5e73db9b2f..0000000000 --- a/traffic_ops/v2-client/cdn_domains.go +++ /dev/null @@ -1,29 +0,0 @@ -package client - -import ( - "github.com/apache/trafficcontrol/lib/go-tc" -) - -/* - - Licensed 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. -*/ - -func (to *Session) GetDomains() ([]tc.Domain, ReqInf, error) { - var data tc.DomainsResponse - inf, err := get(to, apiBase+"/cdns/domains", &data) - if err != nil { - return nil, inf, err - } - return data.Response, inf, nil -} diff --git a/traffic_ops/v2-client/cdnfederations.go b/traffic_ops/v2-client/cdnfederations.go deleted file mode 100644 index 1e8c732115..0000000000 --- a/traffic_ops/v2-client/cdnfederations.go +++ /dev/null @@ -1,73 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "fmt" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -/* Internally, the CDNName is only used in the GET method. The CDNName - * seems to primarily be used to differentiate between `/federations` and - * `/cdns/:name/federations`. Although the behavior is odd, it is kept to - * keep the same behavior from perl. */ - -func (to *Session) CreateCDNFederationByName(f tc.CDNFederation, CDNName string) (*tc.CreateCDNFederationResponse, ReqInf, error) { - jsonReq, err := json.Marshal(f) - if err != nil { //There is no remoteAddr for ReqInf at this point - return nil, ReqInf{CacheHitStatus: CacheHitStatusMiss}, err - } - - data := tc.CreateCDNFederationResponse{} - url := fmt.Sprintf("%s/cdns/%s/federations", apiBase, CDNName) - inf, err := makeReq(to, "POST", url, jsonReq, &data) - return &data, inf, err -} - -func (to *Session) GetCDNFederationsByName(CDNName string) (*tc.CDNFederationResponse, ReqInf, error) { - data := tc.CDNFederationResponse{} - url := fmt.Sprintf("%s/cdns/%s/federations", apiBase, CDNName) - inf, err := get(to, url, &data) - return &data, inf, err -} - -func (to *Session) GetCDNFederationsByID(CDNName string, ID int) (*tc.CDNFederationResponse, ReqInf, error) { - data := tc.CDNFederationResponse{} - url := fmt.Sprintf("%s/cdns/%s/federations?id=%v", apiBase, CDNName, ID) - inf, err := get(to, url, &data) - return &data, inf, err -} - -func (to *Session) UpdateCDNFederationsByID(f tc.CDNFederation, CDNName string, ID int) (*tc.UpdateCDNFederationResponse, ReqInf, error) { - jsonReq, err := json.Marshal(f) - if err != nil { //There is no remoteAddr for ReqInf at this point - return nil, ReqInf{CacheHitStatus: CacheHitStatusMiss}, err - } - - data := tc.UpdateCDNFederationResponse{} - url := fmt.Sprintf("%s/cdns/%s/federations/%d", apiBase, CDNName, ID) - inf, err := makeReq(to, "PUT", url, jsonReq, &data) - return &data, inf, err -} - -func (to *Session) DeleteCDNFederationByID(CDNName string, ID int) (*tc.DeleteCDNFederationResponse, ReqInf, error) { - data := tc.DeleteCDNFederationResponse{} - url := fmt.Sprintf("%s/cdns/%s/federations/%d", apiBase, CDNName, ID) - inf, err := makeReq(to, "DELETE", url, nil, &data) - return &data, inf, err -} diff --git a/traffic_ops/v2-client/coordinate.go b/traffic_ops/v2-client/coordinate.go deleted file mode 100644 index 7f1fc7623b..0000000000 --- a/traffic_ops/v2-client/coordinate.go +++ /dev/null @@ -1,155 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "errors" - "fmt" - "net" - "net/http" - "strconv" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_COORDINATES = apiBase + "/coordinates" -) - -// Create a Coordinate -func (to *Session) CreateCoordinate(coordinate tc.Coordinate) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(coordinate) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - resp, remoteAddr, err := to.request(http.MethodPost, API_COORDINATES, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// Update a Coordinate by ID -func (to *Session) UpdateCoordinateByID(id int, coordinate tc.Coordinate) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(coordinate) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - route := fmt.Sprintf("%s?id=%d", API_COORDINATES, id) - resp, remoteAddr, err := to.request(http.MethodPut, route, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// Returns a list of Coordinates -func (to *Session) GetCoordinates() ([]tc.Coordinate, ReqInf, error) { - resp, remoteAddr, err := to.request(http.MethodGet, API_COORDINATES, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.CoordinatesResponse - err = json.NewDecoder(resp.Body).Decode(&data) - return data.Response, reqInf, nil -} - -// GET a Coordinate by the Coordinate id -func (to *Session) GetCoordinateByID(id int) ([]tc.Coordinate, ReqInf, error) { - route := fmt.Sprintf("%s?id=%d", API_COORDINATES, id) - resp, remoteAddr, err := to.request(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.CoordinatesResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GET a Coordinate by the Coordinate name -func (to *Session) GetCoordinateByName(name string) ([]tc.Coordinate, ReqInf, error) { - url := fmt.Sprintf("%s?name=%s", API_COORDINATES, name) - resp, remoteAddr, err := to.request(http.MethodGet, url, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.CoordinatesResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// DELETE a Coordinate by ID -func (to *Session) DeleteCoordinateByID(id int) (tc.Alerts, ReqInf, error) { - route := fmt.Sprintf("%s?id=%d", API_COORDINATES, id) - resp, remoteAddr, err := to.request(http.MethodDelete, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -func (to *Session) SetCachegroupDeliveryServices(cgID int, dsIDs []int) (tc.CacheGroupPostDSRespResponse, ReqInf, error) { - uri := apiBase + `/cachegroups/` + strconv.Itoa(cgID) + `/deliveryservices` - req := tc.CachegroupPostDSReq{DeliveryServices: dsIDs} - reqBody, err := json.Marshal(req) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss} - if err != nil { - return tc.CacheGroupPostDSRespResponse{}, reqInf, err - } - reqResp, _, err := to.request(http.MethodPost, uri, reqBody) - if err != nil { - return tc.CacheGroupPostDSRespResponse{}, reqInf, errors.New("requesting from Traffic Ops: " + err.Error()) - } - defer reqResp.Body.Close() - - resp := tc.CacheGroupPostDSRespResponse{} - if err := json.NewDecoder(reqResp.Body).Decode(&resp); err != nil { - return tc.CacheGroupPostDSRespResponse{}, reqInf, errors.New("decoding response: " + err.Error()) - } - return resp, reqInf, nil -} diff --git a/traffic_ops/v2-client/crconfig.go b/traffic_ops/v2-client/crconfig.go deleted file mode 100644 index a8414ad6dd..0000000000 --- a/traffic_ops/v2-client/crconfig.go +++ /dev/null @@ -1,84 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "fmt" - "github.com/apache/trafficcontrol/lib/go-tc" - "net/http" - "net/url" -) - -const ( - API_SNAPSHOT = apiBase + "/snapshot" -) - -type OuterResponse struct { - Response json.RawMessage `json:"response"` -} - -// GetCRConfig returns the raw JSON bytes of the CRConfig from Traffic Ops, and whether the bytes were from the client's internal cache. -func (to *Session) GetCRConfig(cdn string) ([]byte, ReqInf, error) { - uri := apiBase + `/cdns/` + cdn + `/snapshot` - bts, reqInf, err := to.getBytesWithTTL(uri, tmPollingInterval) - if err != nil { - return nil, reqInf, err - } - - resp := OuterResponse{} - if err := json.Unmarshal(bts, &resp); err != nil { - return nil, reqInf, err - } - return []byte(resp.Response), reqInf, nil -} - -// GetCRConfigNew returns the raw JSON bytes of the latest CRConfig from Traffic Ops, and whether the bytes were from the client's internal cache. -func (to *Session) GetCRConfigNew(cdn string) ([]byte, ReqInf, error) { - uri := apiBase + `/cdns/` + cdn + `/snapshot/new` - bts, reqInf, err := to.getBytesWithTTL(uri, tmPollingInterval) - if err != nil { - return nil, reqInf, err - } - - resp := OuterResponse{} - if err := json.Unmarshal(bts, &resp); err != nil { - return nil, reqInf, err - } - return []byte(resp.Response), reqInf, nil -} - -// SnapshotCRConfig snapshots a CDN by name. -func (to *Session) SnapshotCRConfig(cdn string) (ReqInf, error) { - uri := fmt.Sprintf("%s?cdn=%s", API_SNAPSHOT, url.QueryEscape(cdn)) - _, remoteAddr, err := to.request(http.MethodPut, uri, nil) - reqInf := ReqInf{RemoteAddr: remoteAddr, CacheHitStatus: CacheHitStatusMiss} - return reqInf, err -} - -// SnapshotCDNByID snapshots a CDN by ID. -func (to *Session) SnapshotCRConfigByID(id int) (tc.Alerts, ReqInf, error) { - url := fmt.Sprintf("%s?cdnID=%d", API_SNAPSHOT, id) - resp, remoteAddr, err := to.request(http.MethodPut, url, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} diff --git a/traffic_ops/v2-client/deliveryservice.go b/traffic_ops/v2-client/deliveryservice.go deleted file mode 100644 index adca1f0e2b..0000000000 --- a/traffic_ops/v2-client/deliveryservice.go +++ /dev/null @@ -1,383 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "errors" - "fmt" - "strconv" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -// These are the API endpoints used by the various Delivery Service-related client methods. -const ( - // API_DELIVERY_SERVICES is the API path on which Traffic Ops serves Delivery Service - // information. More specific information is typically found on sub-paths of this. - // See Also: https://traffic-control-cdn.readthedocs.io/en/latest/api/v2/deliveryservices.html - API_DELIVERY_SERVICES = apiBase + "/deliveryservices" - - // API_DELIVERY_SERVICE_ID is the API path on which Traffic Ops serves information about - // a specific Delivery Service identified by an integral, unique identifier. It is - // intended to be used with fmt.Sprintf to insert its required path parameter (namely the ID - // of the Delivery Service of interest). - // See Also: https://traffic-control-cdn.readthedocs.io/en/latest/api/v2/deliveryservices_id.html - API_DELIVERY_SERVICE_ID = API_DELIVERY_SERVICES + "/%v" - - // API_DELIVERY_SERVICE_HEALTH is the API path on which Traffic Ops serves information about - // the 'health' of a specific Delivery Service identified by an integral, unique identifier. It is - // intended to be used with fmt.Sprintf to insert its required path parameter (namely the ID - // of the Delivery Service of interest). - // See Also: https://traffic-control-cdn.readthedocs.io/en/latest/api/v2/deliveryservices_id_health.html - API_DELIVERY_SERVICE_HEALTH = API_DELIVERY_SERVICE_ID + "/health" - - // API_DELIVERY_SERVICE_CAPACITY is the API path on which Traffic Ops serves information about - // the 'capacity' of a specific Delivery Service identified by an integral, unique identifier. It is - // intended to be used with fmt.Sprintf to insert its required path parameter (namely the ID - // of the Delivery Service of interest). - // See Also: https://traffic-control-cdn.readthedocs.io/en/latest/api/v2/deliveryservices_id_capacity.html - API_DELIVERY_SERVICE_CAPACITY = API_DELIVERY_SERVICE_ID + "/capacity" - - // API_DELIVERY_SERVICE_ELIGIBLE_SERVERS is the API path on which Traffic Ops serves information about - // the servers which are eligible to be assigned to a specific Delivery Service identified by an integral, - // unique identifier. It is intended to be used with fmt.Sprintf to insert its required path parameter - // (namely the ID of the Delivery Service of interest). - // See Also: https://traffic-control-cdn.readthedocs.io/en/latest/api/v2/deliveryservices_id_servers_eligible.html - API_DELIVERY_SERVICE_ELIGIBLE_SERVERS = API_DELIVERY_SERVICE_ID + "/servers/eligible" - - // API_DELIVERY_SERVICES_SAFE_UPDATE is the API path on which Traffic Ops provides the functionality to - // update the "safe" subset of properties of a Delivery Service identified by an integral, unique - // identifer. It is intended to be used with fmt.Sprintf to insert its required path parameter - // (namely the ID of the Delivery Service of interest). - // See Also: https://traffic-control-cdn.readthedocs.io/en/latest/api/v2/deliveryservices_id_safe.html - API_DELIVERY_SERVICES_SAFE_UPDATE = API_DELIVERY_SERVICE_ID + "/safe" - - // API_DELIVERY_SERVICE_XMLID_SSL_KEYS is the API path on which Traffic Ops serves information about - // and functionality relating to the SSL keys used by a Delivery Service identified by its XMLID. It is - // intended to be used with fmt.Sprintf to insert its required path parameter (namely the XMLID - // of the Delivery Service of interest). - // See Also: https://traffic-control-cdn.readthedocs.io/en/latest/api/v2/deliveryservices_xmlid_xmlid_sslkeys.html - API_DELIVERY_SERVICE_XMLID_SSL_KEYS = API_DELIVERY_SERVICES + "/xmlid/%s/sslkeys" - - // API_DELIVERY_SERVICE_URI_SIGNING_KEYS is the API path on which Traffic Ops serves information - // about and functionality relating to the URI-signing keys used by a Delivery Service identified - // by its XMLID. It is intended to be used with fmt.Sprintf to insert its required path parameter - // (namely the XMLID of the Delivery Service of interest). - // See Also: https://traffic-control-cdn.readthedocs.io/en/latest/api/v2/deliveryservices_xmlid_urisignkeys.html - API_DELIVERY_SERVICES_URI_SIGNING_KEYS = API_DELIVERY_SERVICES + "/%s/urisignkeys" - - // API_DELIVERY_SERVICES_URL_SIGNING_KEYS is the API path on which Traffic Ops serves information - // about and functionality relating to the URL-signing keys used by a Delivery Service identified - // by its XMLID. It is intended to be used with fmt.Sprintf to insert its required path parameter - // (namely the XMLID of the Delivery Service of interest). - // See Also: https://traffic-control-cdn.readthedocs.io/en/latest/api/v2/deliveryservices_xmlid_xmlid_urlkeys.html - API_DELIVERY_SERVICES_URL_SIGNING_KEYS = API_DELIVERY_SERVICES + "/xmlId/%s/urlkeys" - - // API_DELIVERY_SERVICES_REGEXES is the API path on which Traffic Ops serves Delivery Service - // 'regex' (Regular Expression) information. - // See Also: https://traffic-control-cdn.readthedocs.io/en/latest/api/v2/deliveryservices_regexes.html - API_DELIVERY_SERVICES_REGEXES = apiBase + "/deliveryservices_regexes" - - // API_SERVER_DELIVERY_SERVICES is the API path on which Traffic Ops serves functionality - // related to the associations a specific server and its assigned Delivery Services. It is - // intended to be used with fmt.Sprintf to insert its required path parameter (namely the ID - // of the server of interest). - // See Also: https://traffic-control-cdn.readthedocs.io/en/latest/api/v2/servers_id_deliveryservices.html - API_SERVER_DELIVERY_SERVICES = apiBase + "/servers/%d/deliveryservices" - - // API_DELIVERY_SERVICE_SERVER is the API path on which Traffic Ops serves functionality related - // to the associations between Delivery Services and their assigned Server(s). - // See Also: https://traffic-control-cdn.readthedocs.io/en/latest/api/v2/deliveryserviceserver.html - API_DELIVERY_SERVICE_SERVER = apiBase + "/deliveryserviceserver" -) - -// GetDeliveryServicesByServer returns all of the (tenant-visible) Delivery Services assigned to -// the server identified by the integral, unique identifier 'id'. -func (to *Session) GetDeliveryServicesByServer(id int) ([]tc.DeliveryServiceNullable, ReqInf, error) { - var data tc.DeliveryServicesNullableResponse - - reqInf, err := get(to, fmt.Sprintf(API_SERVER_DELIVERY_SERVICES, id), &data) - if err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GetDeliveryServicesNullable returns a slice of Delivery Services. -func (to *Session) GetDeliveryServicesNullable() ([]tc.DeliveryServiceNullable, ReqInf, error) { - data := struct { - Response []tc.DeliveryServiceNullable `json:"response"` - }{} - reqInf, err := get(to, API_DELIVERY_SERVICES, &data) - if err != nil { - return nil, reqInf, err - } - return data.Response, reqInf, nil -} - -// GetDeliveryServicesByCDNID returns the (tenant-visible) Delivery Services within the CDN identified -// by the integral, unique identifier 'cdnID'. -func (to *Session) GetDeliveryServicesByCDNID(cdnID int) ([]tc.DeliveryServiceNullable, ReqInf, error) { - data := struct { - Response []tc.DeliveryServiceNullable `json:"response"` - }{} - reqInf, err := get(to, API_DELIVERY_SERVICES+"?cdn="+strconv.Itoa(cdnID), &data) - if err != nil { - return nil, reqInf, err - } - return data.Response, reqInf, nil -} - -// GetDeliveryServiceNullable returns the Delivery Service identified by the integral, unique identifier -// 'id' (which must be passed as a string). -func (to *Session) GetDeliveryServiceNullable(id string) (*tc.DeliveryServiceNullable, ReqInf, error) { - data := struct { - Response []tc.DeliveryServiceNullable `json:"response"` - }{} - reqInf, err := get(to, API_DELIVERY_SERVICES+"?id="+id, &data) - if err != nil { - return nil, reqInf, err - } - if len(data.Response) == 0 { - return nil, reqInf, nil - } - return &data.Response[0], reqInf, nil -} - -// GetDeliveryServiceByXMLIDNullable returns the Delivery Service identified by the passed XMLID. -// The length of the returned slice should always be 1 when the request is succesful - if it isn't -// something very wicked has happened to Traffic Ops. -func (to *Session) GetDeliveryServiceByXMLIDNullable(XMLID string) ([]tc.DeliveryServiceNullable, ReqInf, error) { - var data tc.DeliveryServicesNullableResponse - reqInf, err := get(to, API_DELIVERY_SERVICES+"?xmlId="+XMLID, &data) - if err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// CreateDeliveryServiceNullable creates the DeliveryService it's passed. -func (to *Session) CreateDeliveryServiceNullable(ds *tc.DeliveryServiceNullable) (*tc.CreateDeliveryServiceNullableResponse, error) { - if ds.TypeID == nil && ds.Type != nil { - ty, _, err := to.GetTypeByName(ds.Type.String()) - if err != nil { - return nil, err - } - if len(ty) == 0 { - return nil, errors.New("no type named " + ds.Type.String()) - } - ds.TypeID = &ty[0].ID - } - - if ds.CDNID == nil && ds.CDNName != nil { - cdns, _, err := to.GetCDNByName(*ds.CDNName) - if err != nil { - return nil, err - } - if len(cdns) == 0 { - return nil, errors.New("no CDN named " + *ds.CDNName) - } - ds.CDNID = &cdns[0].ID - } - - if ds.ProfileID == nil && ds.ProfileName != nil { - profiles, _, err := to.GetProfileByName(*ds.ProfileName) - if err != nil { - return nil, err - } - if len(profiles) == 0 { - return nil, errors.New("no Profile named " + *ds.ProfileName) - } - ds.ProfileID = &profiles[0].ID - } - - if ds.TenantID == nil && ds.Tenant != nil { - ten, _, err := to.TenantByName(*ds.Tenant) - if err != nil { - return nil, err - } - ds.TenantID = &ten.ID - } - - var data tc.CreateDeliveryServiceNullableResponse - jsonReq, err := json.Marshal(ds) - if err != nil { - return nil, err - } - _, err = post(to, API_DELIVERY_SERVICES, jsonReq, &data) - if err != nil { - return nil, err - } - - return &data, nil -} - -// UpdateDeliveryServiceNullable updates the DeliveryService matching the ID it's -// passed with the DeliveryService it is passed. -func (to *Session) UpdateDeliveryServiceNullable(id string, ds *tc.DeliveryServiceNullable) (*tc.UpdateDeliveryServiceNullableResponse, error) { - var data tc.UpdateDeliveryServiceNullableResponse - jsonReq, err := json.Marshal(ds) - if err != nil { - return nil, err - } - _, err = put(to, fmt.Sprintf(API_DELIVERY_SERVICE_ID, id), jsonReq, &data) - if err != nil { - return nil, err - } - - return &data, nil -} - -// DeleteDeliveryService deletes the DeliveryService matching the ID it's passed. -func (to *Session) DeleteDeliveryService(id string) (*tc.DeleteDeliveryServiceResponse, error) { - var data tc.DeleteDeliveryServiceResponse - _, err := del(to, fmt.Sprintf(API_DELIVERY_SERVICE_ID, id), &data) - if err != nil { - return nil, err - } - - return &data, nil -} - -// GetDeliveryServiceHealth gets the 'health' of the Delivery Service identified by the -// integral, unique identifier 'id' (which must be passed as a string). -func (to *Session) GetDeliveryServiceHealth(id string) (*tc.DeliveryServiceHealth, ReqInf, error) { - var data tc.DeliveryServiceHealthResponse - reqInf, err := get(to, fmt.Sprintf(API_DELIVERY_SERVICE_HEALTH, id), &data) - if err != nil { - return nil, reqInf, err - } - - return &data.Response, reqInf, nil -} - -// GetDeliveryServiceCapacity gets the 'capacity' of the Delivery Service identified by the -// integral, unique identifier 'id' (which must be passed as a string). -func (to *Session) GetDeliveryServiceCapacity(id string) (*tc.DeliveryServiceCapacity, ReqInf, error) { - var data tc.DeliveryServiceCapacityResponse - reqInf, err := get(to, fmt.Sprintf(API_DELIVERY_SERVICE_CAPACITY, id), &data) - if err != nil { - return nil, reqInf, err - } - - return &data.Response, reqInf, nil -} - -// GetDeliveryServiceServer returns associations between Delivery Services and servers using the -// provided pagination controls. -func (to *Session) GetDeliveryServiceServer(page, limit string) ([]tc.DeliveryServiceServer, ReqInf, error) { - var data tc.DeliveryServiceServerResponse - reqInf, err := get(to, API_DELIVERY_SERVICE_SERVER+"?page="+page+"&limit="+limit, &data) - if err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GetDeliveryServiceRegexes returns the "Regexes" (Regular Expressions) used by all (tenant-visible) -// Delivery Services. -func (to *Session) GetDeliveryServiceRegexes() ([]tc.DeliveryServiceRegexes, ReqInf, error) { - var data tc.DeliveryServiceRegexResponse - reqInf, err := get(to, API_DELIVERY_SERVICES_REGEXES, &data) - if err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GetDeliveryServiceSSLKeysByID returns information about the SSL Keys used by the Delivery -// Service identified by the passed XMLID. -func (to *Session) GetDeliveryServiceSSLKeysByID(XMLID string) (*tc.DeliveryServiceSSLKeys, ReqInf, error) { - var data tc.DeliveryServiceSSLKeysResponse - reqInf, err := get(to, fmt.Sprintf(API_DELIVERY_SERVICE_XMLID_SSL_KEYS, XMLID), &data) - if err != nil { - return nil, reqInf, err - } - - return &data.Response, reqInf, nil -} - -// GetDeliveryServicesEligible returns the servers eligible for assignment to the Delivery -// Service identified by the integral, unique identifier 'dsID'. -func (to *Session) GetDeliveryServicesEligible(dsID int) ([]tc.DSServerV11, ReqInf, error) { - resp := struct { - Response []tc.DSServerV11 `json:"response"` - }{Response: []tc.DSServerV11{}} - - reqInf, err := get(to, fmt.Sprintf(API_DELIVERY_SERVICE_ELIGIBLE_SERVERS, dsID), &resp) - if err != nil { - return nil, reqInf, err - } - return resp.Response, reqInf, nil -} - -// GetDeliveryServiceURLSigKeys returns the URL-signing keys used by the Delivery Service -// identified by the XMLID 'dsName'. -func (to *Session) GetDeliveryServiceURLSigKeys(dsName string) (tc.URLSigKeys, ReqInf, error) { - data := struct { - Response tc.URLSigKeys `json:"response"` - }{} - - reqInf, err := get(to, fmt.Sprintf(API_DELIVERY_SERVICES_URL_SIGNING_KEYS, dsName), &data) - if err != nil { - return tc.URLSigKeys{}, reqInf, err - } - return data.Response, reqInf, nil -} - -// GetDeliveryServiceURISigningKeys returns the URI-signing keys used by the Delivery Service -// identified by the XMLID 'dsName'. The result is not parsed. -func (to *Session) GetDeliveryServiceURISigningKeys(dsName string) ([]byte, ReqInf, error) { - data := json.RawMessage{} - reqInf, err := get(to, fmt.Sprintf(API_DELIVERY_SERVICES_URI_SIGNING_KEYS, dsName), &data) - if err != nil { - return []byte{}, reqInf, err - } - return []byte(data), reqInf, nil -} - -// UpdateDeliveryServiceSafe updates the given Delivery Service identified by 'id' with the given "safe" fields. -func (to *Session) UpdateDeliveryServiceSafe(id int, ds tc.DeliveryServiceSafeUpdateRequest) ([]tc.DeliveryServiceNullable, ReqInf, error) { - var reqInf ReqInf - var resp tc.DeliveryServiceSafeUpdateResponse - - req, err := json.Marshal(ds) - if err != nil { - return resp.Response, reqInf, err - } - - if reqInf, err = put(to, fmt.Sprintf(API_DELIVERY_SERVICES_SAFE_UPDATE, id), req, &resp); err != nil { - return resp.Response, reqInf, err - } - - if len(resp.Response) < 1 { - err = errors.New("Traffic Ops returned success, but response was missing the Delivery Service") - } - return resp.Response, reqInf, err -} - -// GetAccessibleDeliveryServicesByTenant gets all delivery services associated with the given tenant, and all of -// it's children. -func (to *Session) GetAccessibleDeliveryServicesByTenant(tenantId int) ([]tc.DeliveryServiceNullable, ReqInf, error) { - data := tc.DeliveryServicesNullableResponse{} - reqInf, err := get(to, fmt.Sprintf("%v?accessibleTo=%v", API_DELIVERY_SERVICES, tenantId), &data) - return data.Response, reqInf, err -} diff --git a/traffic_ops/v2-client/deliveryservice_regexes.go b/traffic_ops/v2-client/deliveryservice_regexes.go deleted file mode 100644 index 85901e2428..0000000000 --- a/traffic_ops/v2-client/deliveryservice_regexes.go +++ /dev/null @@ -1,62 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "fmt" - "net" - "net/http" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - // See: https://traffic-control-cdn.readthedocs.io/en/latest/api/v2/deliveryservices_id_regexes.html - API_DS_REGEXES = apiBase + "/deliveryservices/%v/regexes" -) - -// GetDeliveryServiceRegexesByDSID gets DeliveryServiceRegexes by a DS id -// also accepts an optional map of query parameters -func (to *Session) GetDeliveryServiceRegexesByDSID(dsID int, params map[string]string) ([]tc.DeliveryServiceIDRegex, ReqInf, error) { - response := struct { - Response []tc.DeliveryServiceIDRegex `json:"response"` - }{} - - reqInf, err := get(to, fmt.Sprintf(API_DS_REGEXES, dsID)+mapToQueryParameters(params), &response) - if err != nil { - return []tc.DeliveryServiceIDRegex{}, reqInf, err - } - return response.Response, reqInf, nil -} - -func (to *Session) PostDeliveryServiceRegexesByDSID(dsID int, regex tc.DeliveryServiceRegexPost) (tc.Alerts, ReqInf, error) { - var alerts tc.Alerts - var remoteAddr net.Addr - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - reqBody, err := json.Marshal(regex) - if err != nil { - return alerts, reqInf, err - } - - _, remoteAddr, err = to.request(http.MethodPost, fmt.Sprintf(API_DS_REGEXES, dsID), reqBody) - reqInf.RemoteAddr = remoteAddr - if err != nil { - return alerts, reqInf, err - } - - return alerts, reqInf, nil -} diff --git a/traffic_ops/v2-client/deliveryservice_request_comments.go b/traffic_ops/v2-client/deliveryservice_request_comments.go deleted file mode 100644 index 231d77a3d2..0000000000 --- a/traffic_ops/v2-client/deliveryservice_request_comments.go +++ /dev/null @@ -1,115 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "net" - "net/http" - - "github.com/apache/trafficcontrol/lib/go-tc" - - "fmt" -) - -const ( - API_DELIVERY_SERVICE_REQUEST_COMMENTS = apiBase + "/deliveryservice_request_comments" -) - -// Create a delivery service request comment -func (to *Session) CreateDeliveryServiceRequestComment(comment tc.DeliveryServiceRequestComment) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(comment) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - resp, remoteAddr, err := to.request(http.MethodPost, API_DELIVERY_SERVICE_REQUEST_COMMENTS, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// Update a delivery service request by ID -func (to *Session) UpdateDeliveryServiceRequestCommentByID(id int, comment tc.DeliveryServiceRequestComment) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(comment) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - route := fmt.Sprintf("%s?id=%d", API_DELIVERY_SERVICE_REQUEST_COMMENTS, id) - resp, remoteAddr, err := to.request(http.MethodPut, route, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// Returns a list of delivery service request comments -func (to *Session) GetDeliveryServiceRequestComments() ([]tc.DeliveryServiceRequestComment, ReqInf, error) { - resp, remoteAddr, err := to.request(http.MethodGet, API_DELIVERY_SERVICE_REQUEST_COMMENTS, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.DeliveryServiceRequestCommentsResponse - err = json.NewDecoder(resp.Body).Decode(&data) - return data.Response, reqInf, nil -} - -// GET a delivery service request comment by ID -func (to *Session) GetDeliveryServiceRequestCommentByID(id int) ([]tc.DeliveryServiceRequestComment, ReqInf, error) { - route := fmt.Sprintf("%s?id=%d", API_DELIVERY_SERVICE_REQUEST_COMMENTS, id) - resp, remoteAddr, err := to.request(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.DeliveryServiceRequestCommentsResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// DELETE a delivery service request comment by ID -func (to *Session) DeleteDeliveryServiceRequestCommentByID(id int) (tc.Alerts, ReqInf, error) { - route := fmt.Sprintf("%s?id=%d", API_DELIVERY_SERVICE_REQUEST_COMMENTS, id) - resp, remoteAddr, err := to.request(http.MethodDelete, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} diff --git a/traffic_ops/v2-client/deliveryservice_requests.go b/traffic_ops/v2-client/deliveryservice_requests.go deleted file mode 100644 index d59536f4c8..0000000000 --- a/traffic_ops/v2-client/deliveryservice_requests.go +++ /dev/null @@ -1,243 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net" - "net/http" - "net/url" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_DS_REQUESTS = apiBase + "/deliveryservice_requests" -) - -// CreateDeliveryServiceRequest creates a Delivery Service Request. -func (to *Session) CreateDeliveryServiceRequest(dsr tc.DeliveryServiceRequest) (tc.Alerts, ReqInf, error) { - var alerts tc.Alerts - var remoteAddr net.Addr - if dsr.AssigneeID == 0 && dsr.Assignee != "" { - res, reqInf, err := to.GetUserByUsername(dsr.Assignee) - if err != nil { - return alerts, reqInf, err - } - if len(res) == 0 { - return alerts, reqInf, errors.New("no user with name " + dsr.Assignee) - } - dsr.AssigneeID = *res[0].ID - } - - if dsr.AuthorID == 0 && dsr.Author != "" { - res, reqInf, err := to.GetUserByUsername(dsr.Author) - if err != nil { - return alerts, reqInf, err - } - if len(res) == 0 { - return alerts, reqInf, errors.New("no user with name " + dsr.Author) - } - dsr.AuthorID = tc.IDNoMod(*res[0].ID) - } - - if dsr.DeliveryService.TypeID == 0 && dsr.DeliveryService.Type.String() != "" { - ty, reqInf, err := to.GetTypeByName(dsr.DeliveryService.Type.String()) - if err != nil || len(ty) == 0 { - return alerts, reqInf, errors.New("no type named " + dsr.DeliveryService.Type.String()) - } - dsr.DeliveryService.TypeID = ty[0].ID - } - - if dsr.DeliveryService.CDNID == 0 && dsr.DeliveryService.CDNName != "" { - cdns, reqInf, err := to.GetCDNByName(dsr.DeliveryService.CDNName) - if err != nil || len(cdns) == 0 { - return alerts, reqInf, errors.New("no CDN named " + dsr.DeliveryService.CDNName) - } - dsr.DeliveryService.CDNID = cdns[0].ID - } - - if dsr.DeliveryService.ProfileID == 0 && dsr.DeliveryService.ProfileName != "" { - profiles, reqInf, err := to.GetProfileByName(dsr.DeliveryService.ProfileName) - if err != nil || len(profiles) == 0 { - return alerts, reqInf, errors.New("no Profile named " + dsr.DeliveryService.ProfileName) - } - dsr.DeliveryService.ProfileID = profiles[0].ID - } - - if dsr.DeliveryService.TenantID == 0 && dsr.DeliveryService.Tenant != "" { - ten, reqInf, err := to.TenantByName(dsr.DeliveryService.Tenant) - if err != nil || ten == nil { - return alerts, reqInf, errors.New("no Tenant named " + dsr.DeliveryService.Tenant) - } - dsr.DeliveryService.TenantID = ten.ID - } - - reqBody, err := json.Marshal(dsr) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return alerts, reqInf, err - } - resp, remoteAddr, err := to.RawRequest(http.MethodPost, API_DS_REQUESTS, reqBody) - defer resp.Body.Close() - - if err == nil { - body, readErr := ioutil.ReadAll(resp.Body) - if readErr != nil { - return alerts, reqInf, readErr - } - if err = json.Unmarshal(body, &alerts); err != nil { - return alerts, reqInf, err - } - } - - return alerts, reqInf, err -} - -// GetDeliveryServiceRequests retrieves all deliveryservices available to session user. -func (to *Session) GetDeliveryServiceRequests() ([]tc.DeliveryServiceRequest, ReqInf, error) { - resp, remoteAddr, err := to.request(http.MethodGet, API_DS_REQUESTS, nil) - - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - data := struct { - Response []tc.DeliveryServiceRequest `json:"response"` - }{} - if err = json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GET a DeliveryServiceRequest by the DeliveryServiceRequest XMLID -func (to *Session) GetDeliveryServiceRequestByXMLID(XMLID string) ([]tc.DeliveryServiceRequest, ReqInf, error) { - route := fmt.Sprintf("%s?xmlId=%s", API_DS_REQUESTS, url.QueryEscape(XMLID)) - resp, remoteAddr, err := to.request(http.MethodGet, route, nil) - - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - data := struct { - Response []tc.DeliveryServiceRequest `json:"response"` - }{} - if err = json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GET a DeliveryServiceRequest by the DeliveryServiceRequest id -func (to *Session) GetDeliveryServiceRequestByID(id int) ([]tc.DeliveryServiceRequest, ReqInf, error) { - route := fmt.Sprintf("%s?id=%d", API_DS_REQUESTS, id) - resp, remoteAddr, err := to.request(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - data := struct { - Response []tc.DeliveryServiceRequest `json:"response"` - }{} - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// Update a DeliveryServiceRequest by ID -func (to *Session) UpdateDeliveryServiceRequestByID(id int, dsr tc.DeliveryServiceRequest) (tc.Alerts, ReqInf, error) { - - route := fmt.Sprintf("%s?id=%d", API_DS_REQUESTS, id) - - var remoteAddr net.Addr - reqBody, err := json.Marshal(dsr) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - resp, remoteAddr, err := to.request(http.MethodPut, route, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// DELETE a DeliveryServiceRequest by DeliveryServiceRequest assignee -func (to *Session) DeleteDeliveryServiceRequestByID(id int) (tc.Alerts, ReqInf, error) { - route := fmt.Sprintf("%s?id=%d", API_DS_REQUESTS, id) - resp, remoteAddr, err := to.RawRequest(http.MethodDelete, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -/* - -// Returns a list of DeliveryServiceRequests -func (to *Session) GetDeliveryServiceRequests() ([]tc.DeliveryServiceRequest, ReqInf, error) { - resp, remoteAddr, err := to.request(http.MethodGet, API_DS_REQUESTS, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.DeliveryServiceRequestsResponse - err = json.NewDecoder(resp.Body).Decode(&data) - return data.Response, reqInf, nil -} - -// GET a DeliveryServiceRequest by the DeliveryServiceRequest assignee -func (to *Session) GetDeliveryServiceRequestByAssignee(assignee string) ([]tc.DeliveryServiceRequest, ReqInf, error) { - url := fmt.Sprintf("%s/assignee/%s", API_DS_REQUESTS, assignee) - resp, remoteAddr, err := to.request(http.MethodGet, url, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.DeliveryServiceRequestsResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -*/ diff --git a/traffic_ops/v2-client/deliveryservices_required_capabilities.go b/traffic_ops/v2-client/deliveryservices_required_capabilities.go deleted file mode 100644 index 1a96410587..0000000000 --- a/traffic_ops/v2-client/deliveryservices_required_capabilities.go +++ /dev/null @@ -1,83 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "fmt" - "net" - "net/url" - "strconv" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_DELIVERY_SERVICES_REQUIRED_CAPABILITIES = apiBase + "/deliveryservices_required_capabilities" -) - -// CreateDeliveryServicesRequiredCapability assigns a Required Capability to a Delivery Service -func (to *Session) CreateDeliveryServicesRequiredCapability(capability tc.DeliveryServicesRequiredCapability) (tc.Alerts, ReqInf, error) { - var alerts tc.Alerts - var remoteAddr net.Addr - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - reqBody, err := json.Marshal(capability) - if err != nil { - return tc.Alerts{}, reqInf, err - } - reqInf, err = post(to, API_DELIVERY_SERVICES_REQUIRED_CAPABILITIES, reqBody, &alerts) - return alerts, reqInf, err -} - -// DeleteDeliveryServicesRequiredCapability unassigns a Required Capability from a Delivery Service -func (to *Session) DeleteDeliveryServicesRequiredCapability(deliveryserviceID int, capability string) (tc.Alerts, ReqInf, error) { - var alerts tc.Alerts - param := url.Values{} - param.Add("deliveryServiceID", strconv.Itoa(deliveryserviceID)) - param.Add("requiredCapability", capability) - url := fmt.Sprintf("%s?%s", API_DELIVERY_SERVICES_REQUIRED_CAPABILITIES, param.Encode()) - reqInf, err := del(to, url, &alerts) - return alerts, reqInf, err -} - -// GetDeliveryServicesRequiredCapabilities retrieves a list of Required Capabilities that are assigned to a Delivery Service -// Callers can filter the results by delivery service id, xml id and/or required capability via the optional parameters -func (to *Session) GetDeliveryServicesRequiredCapabilities(deliveryServiceID *int, xmlID, capability *string) ([]tc.DeliveryServicesRequiredCapability, ReqInf, error) { - param := url.Values{} - if deliveryServiceID != nil { - param.Add("deliveryServiceID", strconv.Itoa(*deliveryServiceID)) - } - if xmlID != nil { - param.Add("xmlID", *xmlID) - } - if capability != nil { - param.Add("requiredCapability", *capability) - } - - url := API_DELIVERY_SERVICES_REQUIRED_CAPABILITIES - if len(param) > 0 { - url = fmt.Sprintf("%s?%s", url, param.Encode()) - } - - resp := struct { - Response []tc.DeliveryServicesRequiredCapability `json:"response"` - }{} - reqInf, err := get(to, url, &resp) - if err != nil { - return nil, reqInf, err - } - return resp.Response, reqInf, nil -} diff --git a/traffic_ops/v2-client/deliveryserviceserver.go b/traffic_ops/v2-client/deliveryserviceserver.go deleted file mode 100644 index cb81ff3823..0000000000 --- a/traffic_ops/v2-client/deliveryserviceserver.go +++ /dev/null @@ -1,119 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "errors" - "net/http" - "net/url" - "strconv" - "strings" - - "github.com/apache/trafficcontrol/lib/go-tc" - "github.com/apache/trafficcontrol/lib/go-util" -) - -// CreateDeliveryServiceServers associates the given servers with the given delivery services. If replace is true, it deletes any existing associations for the given delivery service. -func (to *Session) CreateDeliveryServiceServers(dsID int, serverIDs []int, replace bool) (*tc.DSServerIDs, error) { - path := apiBase + `/deliveryserviceserver` - req := tc.DSServerIDs{ - DeliveryServiceID: util.IntPtr(dsID), - ServerIDs: serverIDs, - Replace: util.BoolPtr(replace), - } - jsonReq, err := json.Marshal(&req) - if err != nil { - return nil, err - } - resp := struct { - Response tc.DSServerIDs `json:"response"` - }{} - if _, err := post(to, path, jsonReq, &resp); err != nil { - return nil, err - } - return &resp.Response, nil -} - -func (to *Session) DeleteDeliveryServiceServer(dsID int, serverID int) (tc.Alerts, ReqInf, error) { - route := apiBase + `/deliveryserviceserver/` + strconv.Itoa(dsID) + "/" + strconv.Itoa(serverID) - reqResp, remoteAddr, err := to.request(http.MethodDelete, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, errors.New("requesting from Traffic Ops: " + err.Error()) - } - defer reqResp.Body.Close() - resp := tc.Alerts{} - if err = json.NewDecoder(reqResp.Body).Decode(&resp); err != nil { - return tc.Alerts{}, reqInf, errors.New("decoding response: " + err.Error()) - } - return resp, reqInf, nil -} - -// GetDeliveryServiceServers gets all delivery service servers, with the default API limit. -func (to *Session) GetDeliveryServiceServers() (tc.DeliveryServiceServerResponse, ReqInf, error) { - return to.getDeliveryServiceServers(url.Values{}) -} - -// GetDeliveryServiceServersN gets all delivery service servers, with a limit of n. -func (to *Session) GetDeliveryServiceServersN(n int) (tc.DeliveryServiceServerResponse, ReqInf, error) { - return to.getDeliveryServiceServers(url.Values{"limit": []string{strconv.Itoa(n)}}) -} - -// GetDeliveryServiceServersWithLimits gets all delivery service servers, allowing specifying the limit of mappings to return, the delivery services to return, and the servers to return. -// The limit may be 0, in which case the default limit will be applied. The deliveryServiceIDs and serverIDs may be nil or empty, in which case all delivery services and/or servers will be returned. -func (to *Session) GetDeliveryServiceServersWithLimits(limit int, deliveryServiceIDs []int, serverIDs []int) (tc.DeliveryServiceServerResponse, ReqInf, error) { - vals := url.Values{} - if limit != 0 { - vals.Set("limit", strconv.Itoa(limit)) - } - - if len(deliveryServiceIDs) != 0 { - dsIDStrs := []string{} - for _, dsID := range deliveryServiceIDs { - dsIDStrs = append(dsIDStrs, strconv.Itoa(dsID)) - } - vals.Set("deliveryserviceids", strings.Join(dsIDStrs, ",")) - } - - if len(serverIDs) != 0 { - serverIDStrs := []string{} - for _, serverID := range serverIDs { - serverIDStrs = append(serverIDStrs, strconv.Itoa(serverID)) - } - vals.Set("serverids", strings.Join(serverIDStrs, ",")) - } - - return to.getDeliveryServiceServers(vals) -} - -func (to *Session) getDeliveryServiceServers(urlQuery url.Values) (tc.DeliveryServiceServerResponse, ReqInf, error) { - route := apiBase + `/deliveryserviceserver` - if qry := urlQuery.Encode(); qry != "" { - route += `?` + qry - } - reqResp, remoteAddr, err := to.request(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.DeliveryServiceServerResponse{}, reqInf, errors.New("requesting from Traffic Ops: " + err.Error()) - } - defer reqResp.Body.Close() - resp := tc.DeliveryServiceServerResponse{} - if err = json.NewDecoder(reqResp.Body).Decode(&resp); err != nil { - return tc.DeliveryServiceServerResponse{}, reqInf, errors.New("decoding response: " + err.Error()) - } - return resp, reqInf, nil -} diff --git a/traffic_ops/v2-client/division.go b/traffic_ops/v2-client/division.go deleted file mode 100644 index 4fea812d80..0000000000 --- a/traffic_ops/v2-client/division.go +++ /dev/null @@ -1,132 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "fmt" - "net" - "net/http" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_DIVISIONS = apiBase + "/divisions" -) - -// Create a Division -func (to *Session) CreateDivision(division tc.Division) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(division) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - resp, remoteAddr, err := to.request(http.MethodPost, API_DIVISIONS, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// Update a Division by ID -func (to *Session) UpdateDivisionByID(id int, division tc.Division) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(division) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - route := fmt.Sprintf("%s/%d", API_DIVISIONS, id) - resp, remoteAddr, err := to.request(http.MethodPut, route, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// Returns a list of Divisions -func (to *Session) GetDivisions() ([]tc.Division, ReqInf, error) { - resp, remoteAddr, err := to.request(http.MethodGet, API_DIVISIONS, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.DivisionsResponse - err = json.NewDecoder(resp.Body).Decode(&data) - return data.Response, reqInf, nil -} - -// GET a Division by the Division id -func (to *Session) GetDivisionByID(id int) ([]tc.Division, ReqInf, error) { - route := fmt.Sprintf("%s?id=%d", API_DIVISIONS, id) - resp, remoteAddr, err := to.request(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.DivisionsResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GET a Division by the Division name -func (to *Session) GetDivisionByName(name string) ([]tc.Division, ReqInf, error) { - url := fmt.Sprintf("%s?name=%s", API_DIVISIONS, name) - resp, remoteAddr, err := to.request(http.MethodGet, url, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.DivisionsResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// DELETE a Division by Division id -func (to *Session) DeleteDivisionByID(id int) (tc.Alerts, ReqInf, error) { - route := fmt.Sprintf("%s/%d", API_DIVISIONS, id) - resp, remoteAddr, err := to.request(http.MethodDelete, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} diff --git a/traffic_ops/v2-client/dsuser.go b/traffic_ops/v2-client/dsuser.go deleted file mode 100644 index 8c21b8f156..0000000000 --- a/traffic_ops/v2-client/dsuser.go +++ /dev/null @@ -1,57 +0,0 @@ -package client - -/* - - Licensed 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 ( - "encoding/json" - "strconv" - - tc "github.com/apache/trafficcontrol/lib/go-tc" -) - -// SetUserDeliveryService associates the given Delivery Services with the given -// user. -// -// Deprecated: This method doesn't work, as Traffic Ops API version 2 and later -// do not actually provide this functionality. -func (to *Session) SetDeliveryServiceUser(userID int, dses []int, replace bool) (*tc.UserDeliveryServicePostResponse, error) { - uri := apiBase + `/deliveryservice_user` - ds := tc.DeliveryServiceUserPost{UserID: &userID, DeliveryServices: &dses, Replace: &replace} - jsonReq, err := json.Marshal(ds) - if err != nil { - return nil, err - } - resp := tc.UserDeliveryServicePostResponse{} - _, err = post(to, uri, jsonReq, &resp) - if err != nil { - return nil, err - } - return &resp, nil -} - -// DeleteDeliveryServiceUser deletes the association between the given Delivery -// Service and user -// -// Deprecated: This method doesn't work, as Traffic Ops API version 2 and later -// do not actually provide this functionality. -func (to *Session) DeleteDeliveryServiceUser(userID int, dsID int) (*tc.UserDeliveryServiceDeleteResponse, error) { - uri := apiBase + `/deliveryservice_user/` + strconv.Itoa(dsID) + `/` + strconv.Itoa(userID) - resp := tc.UserDeliveryServiceDeleteResponse{} - if _, err := del(to, uri, &resp); err != nil { - return nil, err - } - return &resp, nil -} diff --git a/traffic_ops/v2-client/endpoints.go b/traffic_ops/v2-client/endpoints.go deleted file mode 100644 index ee228bae9e..0000000000 --- a/traffic_ops/v2-client/endpoints.go +++ /dev/null @@ -1,18 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -const apiBase = "/api/2.0" diff --git a/traffic_ops/v2-client/federation.go b/traffic_ops/v2-client/federation.go deleted file mode 100644 index 9b509ca6b2..0000000000 --- a/traffic_ops/v2-client/federation.go +++ /dev/null @@ -1,211 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "errors" - "fmt" - "net/http" - "strconv" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -func (to *Session) Federations() ([]tc.AllDeliveryServiceFederationsMapping, ReqInf, error) { - type FederationResponse struct { - Response []tc.AllDeliveryServiceFederationsMapping `json:"response"` - } - data := FederationResponse{} - inf, err := get(to, apiBase+"/federations", &data) - return data.Response, inf, err -} - -func (to *Session) AllFederations() ([]tc.AllDeliveryServiceFederationsMapping, ReqInf, error) { - type FederationResponse struct { - Response []tc.AllDeliveryServiceFederationsMapping `json:"response"` - } - data := FederationResponse{} - inf, err := get(to, apiBase+"/federations/all", &data) - return data.Response, inf, err -} - -func (to *Session) AllFederationsForCDN(cdnName string) ([]tc.AllDeliveryServiceFederationsMapping, ReqInf, error) { - // because the Federations JSON array is heterogeneous (array members may be a AllFederation or AllFederationCDN), we have to try decoding each separately. - type FederationResponse struct { - Response []json.RawMessage `json:"response"` - } - data := FederationResponse{} - inf, err := get(to, apiBase+"/federations/all?cdnName="+cdnName, &data) - if err != nil { - return nil, inf, err - } - - feds := []tc.AllDeliveryServiceFederationsMapping{} - for _, raw := range data.Response { - fed := tc.AllDeliveryServiceFederationsMapping{} - if err := json.Unmarshal([]byte(raw), &fed); err != nil { - // we don't actually need the CDN, but we want to return an error if we got something unexpected - cdnFed := tc.AllFederationCDN{} - if err := json.Unmarshal([]byte(raw), &cdnFed); err != nil { - return nil, inf, errors.New("Traffic Ops returned an unexpected object: '" + string(raw) + "'") - } - } - feds = append(feds, fed) - } - return feds, inf, nil -} - -func (to *Session) CreateFederationDeliveryServices(federationID int, deliveryServiceIDs []int, replace bool) (ReqInf, error) { - req := tc.FederationDSPost{DSIDs: deliveryServiceIDs, Replace: &replace} - jsonReq, err := json.Marshal(req) - if err != nil { - return ReqInf{CacheHitStatus: CacheHitStatusMiss}, err - } - resp := map[string]interface{}{} - inf, err := makeReq(to, http.MethodPost, apiBase+`/federations/`+strconv.Itoa(federationID)+`/deliveryservices`, jsonReq, &resp) - return inf, err -} - -// GetFederationDeliveryServices Returns a given Federation's Delivery Services -func (to *Session) GetFederationDeliveryServices(federationID int) ([]tc.FederationDeliveryServiceNullable, ReqInf, error) { - type FederationDSesResponse struct { - Response []tc.FederationDeliveryServiceNullable `json:"response"` - } - data := FederationDSesResponse{} - inf, err := get(to, fmt.Sprintf("%s/federations/%v/deliveryservices", apiBase, federationID), &data) - return data.Response, inf, err -} - -// DeleteFederationDeliveryService Deletes a given Delivery Service from a Federation -func (to *Session) DeleteFederationDeliveryService(federationID, deliveryServiceID int) (tc.Alerts, ReqInf, error) { - route := fmt.Sprintf("%s/federations/%v/deliveryservices/%v", apiBase, federationID, deliveryServiceID) - resp, remoteAddr, err := to.request(http.MethodDelete, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - if err = json.NewDecoder(resp.Body).Decode(&alerts); err != nil { - return tc.Alerts{}, reqInf, err - } - return alerts, reqInf, nil -} - -// GetFederationUsers Associates the given Users' IDs to a Federation -func (to *Session) CreateFederationUsers(federationID int, userIDs []int, replace bool) (tc.Alerts, ReqInf, error) { - req := tc.FederationUserPost{IDs: userIDs, Replace: &replace} - jsonReq, err := json.Marshal(req) - if err != nil { - return tc.Alerts{}, ReqInf{CacheHitStatus: CacheHitStatusMiss}, err - } - var alerts tc.Alerts - inf, err := makeReq(to, http.MethodPost, fmt.Sprintf("%s/federations/%v/users", apiBase, federationID), jsonReq, &alerts) - return alerts, inf, err -} - -// GetFederationUsers Returns a given Federation's Users -func (to *Session) GetFederationUsers(federationID int) ([]tc.FederationUser, ReqInf, error) { - type FederationUsersResponse struct { - Response []tc.FederationUser `json:"response"` - } - data := FederationUsersResponse{} - inf, err := get(to, fmt.Sprintf("%s/federations/%v/users", apiBase, federationID), &data) - return data.Response, inf, err -} - -// DeleteFederationUser Deletes a given User from a Federation -func (to *Session) DeleteFederationUser(federationID, userID int) (tc.Alerts, ReqInf, error) { - route := fmt.Sprintf("%s/federations/%v/users/%v", apiBase, federationID, userID) - resp, remoteAddr, err := to.request(http.MethodDelete, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - if err = json.NewDecoder(resp.Body).Decode(&alerts); err != nil { - return tc.Alerts{}, reqInf, err - } - return alerts, reqInf, nil -} - -// AddFederationResolverMappingsForCurrentUser adds Federation Resolver mappings to one or more -// Delivery Services for the current user. -func (to *Session) AddFederationResolverMappingsForCurrentUser(mappings tc.DeliveryServiceFederationResolverMappingRequest) (tc.Alerts, ReqInf, error) { - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss} - var alerts tc.Alerts - - bts, err := json.Marshal(mappings) - if err != nil { - return alerts, reqInf, err - } - - resp, remoteAddr, err := to.request(http.MethodPost, apiBase+"/federations", bts) - reqInf.RemoteAddr = remoteAddr - if err != nil { - return alerts, reqInf, err - } - defer resp.Body.Close() - - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, err -} - -// DeleteFederationResolverMappingsForCurrentUser removes ALL Federation Resolver mappings for ALL -// Federations assigned to the currently authenticated user, as well as deleting ALL of the -// Federation Resolvers themselves. -func (to *Session) DeleteFederationResolverMappingsForCurrentUser() (tc.Alerts, ReqInf, error) { - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss} - var alerts tc.Alerts - - resp, remoteAddr, err := to.request(http.MethodDelete, apiBase+"/federations", nil) - reqInf.RemoteAddr = remoteAddr - if err != nil { - return alerts, reqInf, err - } - defer resp.Body.Close() - - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, err -} - -// ReplaceFederationResolverMappingsForCurrentUser replaces any and all Federation Resolver mappings -// on all Federations assigned to the currently authenticated user. This will first remove ALL -// Federation Resolver mappings for ALL Federations assigned to the currently authenticated user, as -// well as deleting ALL of the Federation Resolvers themselves. In other words, calling this is -// equivalent to a call to DeleteFederationResolverMappingsForCurrentUser followed by a call to -// AddFederationResolverMappingsForCurrentUser . -func (to *Session) ReplaceFederationResolverMappingsForCurrentUser(mappings tc.DeliveryServiceFederationResolverMappingRequest) (tc.Alerts, ReqInf, error) { - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss} - var alerts tc.Alerts - - bts, err := json.Marshal(mappings) - if err != nil { - return alerts, reqInf, err - } - - resp, remoteAddr, err := to.request(http.MethodPut, apiBase+"/federations", bts) - reqInf.RemoteAddr = remoteAddr - if err != nil { - return alerts, reqInf, err - } - defer resp.Body.Close() - - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, err -} diff --git a/traffic_ops/v2-client/federation_federation_resolver.go b/traffic_ops/v2-client/federation_federation_resolver.go deleted file mode 100644 index 4aaff34981..0000000000 --- a/traffic_ops/v2-client/federation_federation_resolver.go +++ /dev/null @@ -1,70 +0,0 @@ -package client - -/* - Licensed 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 ( - "encoding/json" - "fmt" - "net/http" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -// GetFederationFederationResolversByID retrieves all Federation Resolvers belonging to Federation of ID. -func (to *Session) GetFederationFederationResolversByID(id int) (tc.FederationFederationResolversResponse, ReqInf, error) { - var ( - path = fmt.Sprintf("%s/federations/%d/federation_resolvers", apiBase, id) - reqInf = ReqInf{CacheHitStatus: CacheHitStatusMiss} - resp tc.FederationFederationResolversResponse - ) - httpResp, remoteAddr, err := to.request(http.MethodGet, path, nil) - reqInf.RemoteAddr = remoteAddr - if err != nil { - return resp, reqInf, err - } - defer httpResp.Body.Close() - - err = json.NewDecoder(httpResp.Body).Decode(&resp) - - return resp, reqInf, err -} - -// AssignFederationFederationResolver creates the Federation Resolver 'fr'. -func (to *Session) AssignFederationFederationResolver(fedID int, resolverIDs []int, replace bool) (tc.AssignFederationFederationResolversResponse, ReqInf, error) { - var ( - path = fmt.Sprintf("%s/federations/%d/federation_resolvers", apiBase, fedID) - req = tc.AssignFederationResolversRequest{ - Replace: replace, - FedResolverIDs: resolverIDs, - } - reqInf = ReqInf{CacheHitStatus: CacheHitStatusMiss} - resp tc.AssignFederationFederationResolversResponse - ) - - reqBody, err := json.Marshal(req) - if err != nil { - return resp, reqInf, err - } - - httpResp, remoteAddr, err := to.request(http.MethodPost, path, reqBody) - reqInf.RemoteAddr = remoteAddr - if err != nil { - return resp, reqInf, err - } - defer httpResp.Body.Close() - - err = json.NewDecoder(httpResp.Body).Decode(&resp) - - return resp, reqInf, err -} diff --git a/traffic_ops/v2-client/federation_resolver.go b/traffic_ops/v2-client/federation_resolver.go deleted file mode 100644 index e0a2dd8624..0000000000 --- a/traffic_ops/v2-client/federation_resolver.go +++ /dev/null @@ -1,116 +0,0 @@ -package client - -/* - Licensed 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 "encoding/json" -import "fmt" -import "net/http" -import "net/url" -import "strconv" - -import "github.com/apache/trafficcontrol/lib/go-tc" - -func (to *Session) getFederationResolvers(id *uint, ip *string, t *string) ([]tc.FederationResolver, ReqInf, error) { - var vals = url.Values{} - if id != nil { - vals.Set("id", strconv.FormatUint(uint64(*id), 10)) - } - if ip != nil { - vals.Set("ipAddress", *ip) - } - if t != nil { - vals.Set("type", *t) - } - - var path = apiBase + "/federation_resolvers" - if len(vals) > 0 { - path = fmt.Sprintf("%s?%s", path, vals.Encode()) - } - - var data struct { - Response []tc.FederationResolver `json:"response"` - } - inf, err := get(to, path, &data) - return data.Response, inf, err -} - -// GetFederationResolvers retrieves all Federation Resolvers from Traffic Ops -func (to *Session) GetFederationResolvers() ([]tc.FederationResolver, ReqInf, error) { - return to.getFederationResolvers(nil, nil, nil) -} - -// GetFederationResolverByID retrieves a single Federation Resolver identified by ID. -func (to *Session) GetFederationResolverByID(ID uint) (tc.FederationResolver, ReqInf, error) { - var fr tc.FederationResolver - frs, inf, err := to.getFederationResolvers(&ID, nil, nil) - if len(frs) > 0 { - fr = frs[0] - } - return fr, inf, err -} - -// GetFederationResolverByIPAddress retrieves the Federation Resolver that uses the IP address or -// CIDR-notation subnet 'ip'. -func (to *Session) GetFederationResolverByIPAddress(ip string) (tc.FederationResolver, ReqInf, error) { - var fr tc.FederationResolver - frs, inf, err := to.getFederationResolvers(nil, &ip, nil) - if len(frs) > 0 { - fr = frs[0] - } - return fr, inf, err -} - -// GetFederationResolversByType gets all Federation Resolvers that are of the Type named 't'. -func (to *Session) GetFederationResolversByType(t string) ([]tc.FederationResolver, ReqInf, error) { - return to.getFederationResolvers(nil, nil, &t) -} - -// CreateFederationResolver creates the Federation Resolver 'fr'. -func (to *Session) CreateFederationResolver(fr tc.FederationResolver) (tc.Alerts, ReqInf, error) { - var reqInf = ReqInf{CacheHitStatus: CacheHitStatusMiss} - var alerts tc.Alerts - - req, err := json.Marshal(fr) - if err != nil { - return alerts, reqInf, err - } - - var resp *http.Response - resp, reqInf.RemoteAddr, err = to.request(http.MethodPost, apiBase+"/federation_resolvers", req) - if err != nil { - return alerts, reqInf, err - } - defer resp.Body.Close() - - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, err -} - -// DeleteFederationResolver deletes the Federation Resolver identified by 'id'. -func (to *Session) DeleteFederationResolver(id uint) (tc.Alerts, ReqInf, error) { - var reqInf = ReqInf{CacheHitStatus: CacheHitStatusMiss} - var alerts tc.Alerts - - var path = fmt.Sprintf("%s/federation_resolvers?id=%d", apiBase, id) - var resp *http.Response - var err error - resp, reqInf.RemoteAddr, err = to.request(http.MethodDelete, path, nil) - if err != nil { - return alerts, reqInf, err - } - defer resp.Body.Close() - - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, err -} diff --git a/traffic_ops/v2-client/iso.go b/traffic_ops/v2-client/iso.go deleted file mode 100644 index 233a8954ad..0000000000 --- a/traffic_ops/v2-client/iso.go +++ /dev/null @@ -1,54 +0,0 @@ -package client - -/* - * 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 ( - "encoding/json" - "net/http" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_OSVERSIONS = apiBase + "/osversions" -) - -// GetOSVersions GETs all available Operating System (OS) versions for ISO generation, -// as well as the name of the directory where the "kickstarter" files are found. -// Structure of returned map: -// key: Name of OS -// value: Directory where the ISO source can be found -func (to *Session) GetOSVersions() (map[string]string, ReqInf, error) { - resp, remoteAddr, err := to.request(http.MethodGet, API_OSVERSIONS, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data struct { - Versions tc.OSVersionsResponse `json:"response"` - } - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Versions, reqInf, nil -} diff --git a/traffic_ops/v2-client/job.go b/traffic_ops/v2-client/job.go deleted file mode 100644 index 34fb238586..0000000000 --- a/traffic_ops/v2-client/job.go +++ /dev/null @@ -1,174 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "errors" - "fmt" - "net" - "net/http" - "strconv" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -// Creates a new Content Invalidation Job -func (to *Session) CreateInvalidationJob(job tc.InvalidationJobInput) (tc.Alerts, ReqInf, error) { - remoteAddr := (net.Addr)(nil) - reqBody, err := json.Marshal(job) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - resp, remoteAddr, err := to.request(http.MethodPost, apiBase+`/jobs`, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, err -} - -// GetJobs returns a list of Jobs. -// If deliveryServiceID or userID are not nil, only jobs for that delivery service or belonging to -// that user are returned. Both deliveryServiceID and userID may be nil. -// -// Deprecated, use GetInvalidationJobs instead -func (to *Session) GetJobs(deliveryServiceID *int, userID *int) ([]tc.Job, ReqInf, error) { - path := apiBase + "/jobs" - if deliveryServiceID != nil || userID != nil { - path += "?" - if deliveryServiceID != nil { - path += "dsId=" + strconv.Itoa(*deliveryServiceID) - if userID != nil { - path += "&" - } - } - if userID != nil { - path += "userId=" + strconv.Itoa(*userID) - } - } - - resp, remoteAddr, err := to.request(http.MethodGet, path, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - data := struct { - Response []tc.Job `json:"response"` - }{} - err = json.NewDecoder(resp.Body).Decode(&data) - return data.Response, reqInf, err -} - -// Returns a list of Content Invalidation Jobs visible to your Tenant, filtered according to -// ds and user -// -// Either or both of ds and user may be nil, but when they are not they cause filtering of the -// returned jobs by Delivery Service and Traffic Ops user, respectively. -// -// ds may be a uint, int, or float64 indicating the integral, unique identifier of the desired -// Delivery Service (in the case of a float64 the fractional part is dropped, e.g. 3.45 -> 3), or -// it may be a string, in which case it should be the xml_id of the desired Delivery Service, or it -// may be an actual tc.DeliveryService or tc.DeliveryServiceNullable structure. -// -// Likewise, user may be a uint, int or float64 indicating the integral, unique identifier of the -// desired user (in the case of a float64 the fractional part is dropped, e.g. 3.45 -> 3), or it may -// be a string, in which case it should be the username of the desired user, or it may be an actual -// tc.User or tc.UserCurrent structure. -func (to *Session) GetInvalidationJobs(ds *interface{}, user *interface{}) ([]tc.InvalidationJob, ReqInf, error) { - path := apiBase + "/jobs" - if ds != nil || user != nil { - path += "?" - - if ds != nil { - d := *ds - switch t := d.(type) { - case uint: - path += "dsId=" + strconv.FormatUint(uint64(d.(uint)), 10) - case float64: - path += "dsId=" + strconv.FormatInt(int64(d.(float64)), 10) - case int: - path += "dsId=" + strconv.FormatInt(int64(d.(int)), 10) - case string: - path += "deliveryService=" + d.(string) - case tc.DeliveryServiceNullable: - if d.(tc.DeliveryServiceNullable).XMLID != nil { - path += "deliveryService=" + *d.(tc.DeliveryServiceNullable).XMLID - } else if d.(tc.DeliveryServiceNullable).ID != nil { - path += "dsId=" + strconv.FormatInt(int64(*d.(tc.DeliveryServiceNullable).ID), 10) - } else { - return nil, ReqInf{}, errors.New("No non-nil identifier on passed Delivery Service!") - } - default: - return nil, ReqInf{}, fmt.Errorf("Invalid type for argument 'ds': %T*", t) - } - - if user != nil { - path += "&" - } - } - - if user != nil { - u := *user - switch t := u.(type) { - case uint: - path += "userId=" + strconv.FormatUint(uint64(u.(uint)), 10) - case float64: - path += "userId=" + strconv.FormatInt(int64(u.(float64)), 10) - case int: - path += "userId=" + strconv.FormatInt(int64(u.(int64)), 10) - case string: - path += "createdBy=" + u.(string) - case tc.User: - if u.(tc.User).Username != nil { - path += "createdBy=" + *u.(tc.User).Username - } else if u.(tc.User).ID != nil { - path += "userId=" + strconv.FormatInt(int64(*u.(tc.User).ID), 10) - } else { - return nil, ReqInf{}, errors.New("No non-nil identifier on passed User!") - } - case tc.UserCurrent: - if u.(tc.UserCurrent).UserName != nil { - path += "createdBy=" + *u.(tc.UserCurrent).UserName - } else if u.(tc.UserCurrent).ID != nil { - path += "userId=" + strconv.FormatInt(int64(*u.(tc.UserCurrent).ID), 10) - } else { - return nil, ReqInf{}, errors.New("No non-nil identifier on passed UserCurrent!") - } - default: - return nil, ReqInf{}, fmt.Errorf("Invalid type for argument 'user': %T*", t) - } - } - } - - resp, remoteAddr, err := to.request(http.MethodGet, path, nil) - reqInf := ReqInf{CacheHitStatusMiss, remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - data := struct { - Response []tc.InvalidationJob `json:"response"` - }{} - err = json.NewDecoder(resp.Body).Decode(&data) - return data.Response, reqInf, err -} diff --git a/traffic_ops/v2-client/log.go b/traffic_ops/v2-client/log.go deleted file mode 100644 index cff6b46d72..0000000000 --- a/traffic_ops/v2-client/log.go +++ /dev/null @@ -1,61 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "fmt" - "net/http" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_LOGS = apiBase + "/logs" -) - -// GetLogsByQueryParams gets a list of logs filtered by query params. -func (to *Session) GetLogsByQueryParams(queryParams string) ([]tc.Log, ReqInf, error) { - URI := API_LOGS + queryParams - resp, remoteAddr, err := to.request(http.MethodGet, URI, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.LogsResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GetLogs gets a list of logs. -func (to *Session) GetLogs() ([]tc.Log, ReqInf, error) { - return to.GetLogsByQueryParams("") -} - -// GetLogsByLimit gets a list of logs limited to a certain number of logs. -func (to *Session) GetLogsByLimit(limit int) ([]tc.Log, ReqInf, error) { - return to.GetLogsByQueryParams(fmt.Sprintf("?limit=%d", limit)) -} - -// GetLogsByDays gets a list of logs limited to a certain number of days. -func (to *Session) GetLogsByDays(days int) ([]tc.Log, ReqInf, error) { - return to.GetLogsByQueryParams(fmt.Sprintf("?days=%d", days)) -} diff --git a/traffic_ops/v2-client/origin.go b/traffic_ops/v2-client/origin.go deleted file mode 100644 index 488b57da7d..0000000000 --- a/traffic_ops/v2-client/origin.go +++ /dev/null @@ -1,194 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "errors" - "fmt" - "net" - "net/http" - "net/url" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_ORIGINS = apiBase + "/origins" -) - -func originIDs(to *Session, origin *tc.Origin) error { - if origin.CachegroupID == nil && origin.Cachegroup != nil { - p, _, err := to.GetCacheGroupNullableByName(*origin.Cachegroup) - if err != nil { - return err - } - if len(p) == 0 { - return errors.New("no cachegroup named " + *origin.Cachegroup) - } - origin.CachegroupID = p[0].ID - } - - if origin.DeliveryServiceID == nil && origin.DeliveryService != nil { - dses, _, err := to.GetDeliveryServiceByXMLIDNullable(*origin.DeliveryService) - if err != nil { - return err - } - if len(dses) == 0 { - return errors.New("no deliveryservice with name " + *origin.DeliveryService) - } - origin.DeliveryServiceID = dses[0].ID - } - - if origin.ProfileID == nil && origin.Profile != nil { - profiles, _, err := to.GetProfileByName(*origin.Profile) - if err != nil { - return err - } - if len(profiles) == 0 { - return errors.New("no profile with name " + *origin.Profile) - } - origin.ProfileID = &profiles[0].ID - } - - if origin.CoordinateID == nil && origin.Coordinate != nil { - coordinates, _, err := to.GetCoordinateByName(*origin.Coordinate) - if err != nil { - return err - } - if len(coordinates) == 0 { - return errors.New("no coordinate with name " + *origin.Coordinate) - } - origin.CoordinateID = &coordinates[0].ID - } - - if origin.TenantID == nil && origin.Tenant != nil { - tenant, _, err := to.TenantByName(*origin.Tenant) - if err != nil { - return err - } - origin.TenantID = &tenant.ID - } - - return nil -} - -// Create an Origin -func (to *Session) CreateOrigin(origin tc.Origin) (*tc.OriginDetailResponse, ReqInf, error) { - var remoteAddr net.Addr - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - - err := originIDs(to, &origin) - if err != nil { - return nil, reqInf, err - } - - reqBody, err := json.Marshal(origin) - if err != nil { - return nil, reqInf, err - } - resp, remoteAddr, err := to.request(http.MethodPost, API_ORIGINS, reqBody) - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - var originResp tc.OriginDetailResponse - if err = json.NewDecoder(resp.Body).Decode(&originResp); err != nil { - return nil, reqInf, err - } - return &originResp, reqInf, nil -} - -// Update an Origin by ID -func (to *Session) UpdateOriginByID(id int, origin tc.Origin) (*tc.OriginDetailResponse, ReqInf, error) { - var remoteAddr net.Addr - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - - err := originIDs(to, &origin) - if err != nil { - return nil, reqInf, err - } - - reqBody, err := json.Marshal(origin) - if err != nil { - return nil, reqInf, err - } - route := fmt.Sprintf("%s?id=%d", API_ORIGINS, id) - resp, remoteAddr, err := to.request(http.MethodPut, route, reqBody) - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - var originResp tc.OriginDetailResponse - if err = json.NewDecoder(resp.Body).Decode(&originResp); err != nil { - return nil, reqInf, err - } - return &originResp, reqInf, nil -} - -// GET a list of Origins by a query parameter string -func (to *Session) GetOriginsByQueryParams(queryParams string) ([]tc.Origin, ReqInf, error) { - URI := API_ORIGINS + queryParams - resp, remoteAddr, err := to.request(http.MethodGet, URI, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.OriginsResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// Returns a list of Origins -func (to *Session) GetOrigins() ([]tc.Origin, ReqInf, error) { - return to.GetOriginsByQueryParams("") -} - -// GET an Origin by the Origin ID -func (to *Session) GetOriginByID(id int) ([]tc.Origin, ReqInf, error) { - return to.GetOriginsByQueryParams(fmt.Sprintf("?id=%d", id)) -} - -// GET an Origin by the Origin name -func (to *Session) GetOriginByName(name string) ([]tc.Origin, ReqInf, error) { - return to.GetOriginsByQueryParams(fmt.Sprintf("?name=%s", url.QueryEscape(name))) -} - -// GET a list of Origins by Delivery Service ID -func (to *Session) GetOriginsByDeliveryServiceID(id int) ([]tc.Origin, ReqInf, error) { - return to.GetOriginsByQueryParams(fmt.Sprintf("?deliveryservice=%d", id)) -} - -// DELETE an Origin by ID -func (to *Session) DeleteOriginByID(id int) (tc.Alerts, ReqInf, error) { - route := fmt.Sprintf("%s?id=%d", API_ORIGINS, id) - resp, remoteAddr, err := to.request(http.MethodDelete, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - if err = json.NewDecoder(resp.Body).Decode(&alerts); err != nil { - return tc.Alerts{}, reqInf, err - } - return alerts, reqInf, nil -} diff --git a/traffic_ops/v2-client/parameter.go b/traffic_ops/v2-client/parameter.go deleted file mode 100644 index c4cc19ac07..0000000000 --- a/traffic_ops/v2-client/parameter.go +++ /dev/null @@ -1,204 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "fmt" - "net" - "net/http" - "net/url" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_PARAMETERS = apiBase + "/parameters" -) - -// CreateParameter performs a POST to create a Parameter. -func (to *Session) CreateParameter(pl tc.Parameter) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(pl) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - resp, remoteAddr, err := to.request(http.MethodPost, API_PARAMETERS, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// CreateMultipleParameters performs a POST to create multiple Parameters at once. -func (to *Session) CreateMultipleParameters(pls []tc.Parameter) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(pls) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - resp, remoteAddr, err := to.request(http.MethodPost, API_PARAMETERS, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// UpdateParameterByID performs a PUT to update a Parameter by ID. -func (to *Session) UpdateParameterByID(id int, pl tc.Parameter) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(pl) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - route := fmt.Sprintf("%s/%d", API_PARAMETERS, id) - resp, remoteAddr, err := to.request(http.MethodPut, route, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// GetParameters returns a list of Parameters. -func (to *Session) GetParameters() ([]tc.Parameter, ReqInf, error) { - resp, remoteAddr, err := to.request(http.MethodGet, API_PARAMETERS, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ParametersResponse - err = json.NewDecoder(resp.Body).Decode(&data) - return data.Response, reqInf, nil -} - -// GetParameterByID GETs a Parameter by the Parameter ID. -func (to *Session) GetParameterByID(id int) ([]tc.Parameter, ReqInf, error) { - route := fmt.Sprintf("%s?id=%d", API_PARAMETERS, id) - resp, remoteAddr, err := to.request(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ParametersResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GetParameterByName GETs a Parameter by the Parameter name. -func (to *Session) GetParameterByName(name string) ([]tc.Parameter, ReqInf, error) { - URI := API_PARAMETERS + "?name=" + url.QueryEscape(name) - resp, remoteAddr, err := to.request(http.MethodGet, URI, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ParametersResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GetParameterByConfigFile GETs a Parameter by the Parameter ConfigFile. -func (to *Session) GetParameterByConfigFile(configFile string) ([]tc.Parameter, ReqInf, error) { - URI := API_PARAMETERS + "?configFile=" + url.QueryEscape(configFile) - resp, remoteAddr, err := to.request(http.MethodGet, URI, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ParametersResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GetParameterByNameAndConfigFile GETs a Parameter by the Parameter Name and ConfigFile. -func (to *Session) GetParameterByNameAndConfigFile(name string, configFile string) ([]tc.Parameter, ReqInf, error) { - URI := fmt.Sprintf("%s?name=%s&configFile=%s", API_PARAMETERS, url.QueryEscape(name), url.QueryEscape(configFile)) - resp, remoteAddr, err := to.request(http.MethodGet, URI, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ParametersResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GetParameterByNameAndConfigFileAndValue GETs a Parameter by the Parameter Name and ConfigFile and Value. -// TODO: API should support all 3, but does not support filter by value -// currently. Until then, loop through hits until you find one with that value. -func (to *Session) GetParameterByNameAndConfigFileAndValue(name, configFile, value string) ([]tc.Parameter, ReqInf, error) { - params, reqInf, err := to.GetParameterByNameAndConfigFile(name, configFile) - if err != nil { - return params, reqInf, err - } - for _, p := range params { - if p.Value == value { - return []tc.Parameter{p}, reqInf, err - } - } - return nil, reqInf, err -} - -// DeleteParameterByID DELETEs a Parameter by ID. -func (to *Session) DeleteParameterByID(id int) (tc.Alerts, ReqInf, error) { - URI := fmt.Sprintf("%s/%d", API_PARAMETERS, id) - resp, remoteAddr, err := to.request(http.MethodDelete, URI, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} diff --git a/traffic_ops/v2-client/phys_location.go b/traffic_ops/v2-client/phys_location.go deleted file mode 100644 index b82f1c9f68..0000000000 --- a/traffic_ops/v2-client/phys_location.go +++ /dev/null @@ -1,144 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "errors" - "fmt" - "net" - "net/http" - "net/url" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_PHYS_LOCATIONS = apiBase + "/phys_locations" -) - -// CreatePhysLocation creates a PhysLocation. -func (to *Session) CreatePhysLocation(pl tc.PhysLocation) (tc.Alerts, ReqInf, error) { - if pl.RegionID == 0 && pl.RegionName != "" { - regions, _, err := to.GetRegionByName(pl.RegionName) - if err != nil { - return tc.Alerts{}, ReqInf{}, err - } - if len(regions) == 0 { - return tc.Alerts{}, ReqInf{}, errors.New("no region with name " + pl.RegionName) - } - pl.RegionID = regions[0].ID - } - var remoteAddr net.Addr - reqBody, err := json.Marshal(pl) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - resp, remoteAddr, err := to.request(http.MethodPost, API_PHYS_LOCATIONS, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// Update a PhysLocation by ID -func (to *Session) UpdatePhysLocationByID(id int, pl tc.PhysLocation) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(pl) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - route := fmt.Sprintf("%s/%d", API_PHYS_LOCATIONS, id) - resp, remoteAddr, err := to.request(http.MethodPut, route, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// Returns a list of PhysLocations with optional query parameters applied -func (to *Session) GetPhysLocations(params map[string]string) ([]tc.PhysLocation, ReqInf, error) { - path := API_PHYS_LOCATIONS + mapToQueryParameters(params) - resp, remoteAddr, err := to.request(http.MethodGet, path, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.PhysLocationsResponse - err = json.NewDecoder(resp.Body).Decode(&data) - return data.Response, reqInf, nil -} - -// GET a PhysLocation by the PhysLocation ID -func (to *Session) GetPhysLocationByID(id int) ([]tc.PhysLocation, ReqInf, error) { - route := fmt.Sprintf("%s?id=%d", API_PHYS_LOCATIONS, id) - resp, remoteAddr, err := to.request(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.PhysLocationsResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GET a PhysLocation by the PhysLocation name -func (to *Session) GetPhysLocationByName(name string) ([]tc.PhysLocation, ReqInf, error) { - url := fmt.Sprintf("%s?name=%s", API_PHYS_LOCATIONS, url.QueryEscape(name)) - resp, remoteAddr, err := to.request(http.MethodGet, url, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.PhysLocationsResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// DELETE a PhysLocation by ID -func (to *Session) DeletePhysLocationByID(id int) (tc.Alerts, ReqInf, error) { - route := fmt.Sprintf("%s/%d", API_PHYS_LOCATIONS, id) - resp, remoteAddr, err := to.request(http.MethodDelete, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} diff --git a/traffic_ops/v2-client/ping.go b/traffic_ops/v2-client/ping.go deleted file mode 100644 index db38b52b2a..0000000000 --- a/traffic_ops/v2-client/ping.go +++ /dev/null @@ -1,39 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "net/http" -) - -const ( - API_PING = apiBase + "/ping" -) - -// Ping returns a static json object to show that traffic_ops is responsive -func (to *Session) Ping() (map[string]string, ReqInf, error) { - resp, remoteAddr, err := to.request(http.MethodGet, API_PING, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data map[string]string - err = json.NewDecoder(resp.Body).Decode(&data) - return data, reqInf, nil -} diff --git a/traffic_ops/v2-client/profile.go b/traffic_ops/v2-client/profile.go deleted file mode 100644 index e74d87df20..0000000000 --- a/traffic_ops/v2-client/profile.go +++ /dev/null @@ -1,291 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "fmt" - "net/http" - "net/url" - "strconv" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_PROFILES = apiBase + "/profiles" - API_PROFILES_NAME_PARAMETERS = API_PROFILES + "/name/%v/parameters" -) - -// CreateProfile creates a Profile. -func (to *Session) CreateProfile(pl tc.Profile) (tc.Alerts, ReqInf, error) { - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss} - - if pl.CDNID == 0 && pl.CDNName != "" { - cdns, _, err := to.GetCDNByName(pl.CDNName) - if err != nil { - return tc.Alerts{}, ReqInf{}, err - } - if len(cdns) == 0 { - return tc.Alerts{ - Alerts: []tc.Alert{ - tc.Alert{ - Text: fmt.Sprintf("no CDN with name %s", pl.CDNName), - Level: "error", - }, - }, - }, - ReqInf{}, - fmt.Errorf("no CDN with name %s", pl.CDNName) - } - pl.CDNID = cdns[0].ID - } - - reqBody, err := json.Marshal(pl) - if err != nil { - return tc.Alerts{}, reqInf, err - } - - resp, remoteAddr, err := to.request(http.MethodPost, API_PROFILES, reqBody) - reqInf.RemoteAddr = remoteAddr - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - - return alerts, reqInf, err -} - -// UpdateProfileByID updates a Profile by ID. -func (to *Session) UpdateProfileByID(id int, pl tc.Profile) (tc.Alerts, ReqInf, error) { - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss} - - reqBody, err := json.Marshal(pl) - if err != nil { - return tc.Alerts{}, reqInf, err - } - - route := fmt.Sprintf("%s/%d", API_PROFILES, id) - resp, remoteAddr, err := to.request(http.MethodPut, route, reqBody) - reqInf.RemoteAddr = remoteAddr - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - - return alerts, reqInf, err -} - -// GetParametersByProfileName gets all of the Parameters assigned to the Profile named 'profileName'. -func (to *Session) GetParametersByProfileName(profileName string) ([]tc.Parameter, ReqInf, error) { - url := fmt.Sprintf(API_PROFILES_NAME_PARAMETERS, profileName) - resp, remoteAddr, err := to.request(http.MethodGet, url, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ParametersResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GetProfiles returns a list of Profiles. -func (to *Session) GetProfiles() ([]tc.Profile, ReqInf, error) { - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss} - - resp, remoteAddr, err := to.request(http.MethodGet, API_PROFILES, nil) - reqInf.RemoteAddr = remoteAddr - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ProfilesResponse - err = json.NewDecoder(resp.Body).Decode(&data) - - return data.Response, reqInf, err -} - -// GetProfileByID GETs a Profile by the Profile ID. -func (to *Session) GetProfileByID(id int) ([]tc.Profile, ReqInf, error) { - route := fmt.Sprintf("%s?id=%d", API_PROFILES, id) - resp, remoteAddr, err := to.request(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ProfilesResponse - err = json.NewDecoder(resp.Body).Decode(&data) - - return data.Response, reqInf, err -} - -// GetProfileByName GETs a Profile by the Profile name. -func (to *Session) GetProfileByName(name string) ([]tc.Profile, ReqInf, error) { - URI := fmt.Sprintf("%s?name=%s", API_PROFILES, url.QueryEscape(name)) - resp, remoteAddr, err := to.request(http.MethodGet, URI, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ProfilesResponse - err = json.NewDecoder(resp.Body).Decode(&data) - - return data.Response, reqInf, err -} - -// GetProfileByParameter GETs a Profile by the Profile "param". -func (to *Session) GetProfileByParameter(param string) ([]tc.Profile, ReqInf, error) { - URI := fmt.Sprintf("%s?param=%s", API_PROFILES, url.QueryEscape(param)) - resp, remoteAddr, err := to.request(http.MethodGet, URI, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ProfilesResponse - err = json.NewDecoder(resp.Body).Decode(&data) - - return data.Response, reqInf, err -} - -// GetProfileByParameterId GETs a Profile by Parameter ID -func (to *Session) GetProfileByParameterId(param int) ([]tc.Profile, ReqInf, error) { - URI := fmt.Sprintf("%s?param=%d", API_PROFILES, param) - resp, remoteAddr, err := to.request(http.MethodGet, URI, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ProfilesResponse - err = json.NewDecoder(resp.Body).Decode(&data) - - return data.Response, reqInf, err -} - -// GetProfileByCDNID GETs a Profile by the Profile CDN ID. -func (to *Session) GetProfileByCDNID(cdnID int) ([]tc.Profile, ReqInf, error) { - URI := fmt.Sprintf("%s?cdn=%s", API_PROFILES, strconv.Itoa(cdnID)) - resp, remoteAddr, err := to.request(http.MethodGet, URI, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ProfilesResponse - err = json.NewDecoder(resp.Body).Decode(&data) - - return data.Response, reqInf, err -} - -// DeleteProfileByID DELETEs a Profile by ID. -func (to *Session) DeleteProfileByID(id int) (tc.Alerts, ReqInf, error) { - URI := fmt.Sprintf("%s/%d", API_PROFILES, id) - resp, remoteAddr, err := to.request(http.MethodDelete, URI, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - - return alerts, reqInf, err -} - -// ExportProfile Returns an exported Profile. -func (to *Session) ExportProfile(id int) (*tc.ProfileExportResponse, ReqInf, error) { - route := fmt.Sprintf("%s/%d/export", API_PROFILES, id) - resp, remoteAddr, err := to.request(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ProfileExportResponse - err = json.NewDecoder(resp.Body).Decode(&data) - - return &data, reqInf, err -} - -// ImportProfile imports an exported Profile. -func (to *Session) ImportProfile(importRequest *tc.ProfileImportRequest) (*tc.ProfileImportResponse, ReqInf, error) { - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss} - - route := fmt.Sprintf("%s/import", API_PROFILES) - reqBody, err := json.Marshal(importRequest) - if err != nil { - return nil, reqInf, err - } - - resp, remoteAddr, err := to.request(http.MethodPost, route, reqBody) - reqInf.RemoteAddr = remoteAddr - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ProfileImportResponse - err = json.NewDecoder(resp.Body).Decode(&data) - - return &data, reqInf, err -} - -// CopyProfile creates a new profile from an existing profile. -func (to *Session) CopyProfile(p tc.ProfileCopy) (tc.ProfileCopyResponse, ReqInf, error) { - var ( - path = fmt.Sprintf("%s/name/%s/copy/%s", API_PROFILES, p.Name, p.ExistingName) - reqInf = ReqInf{CacheHitStatus: CacheHitStatusMiss} - resp tc.ProfileCopyResponse - ) - - reqBody, err := json.Marshal(p) - if err != nil { - return tc.ProfileCopyResponse{}, ReqInf{}, err - } - - httpResp, remoteAddr, err := to.request(http.MethodPost, path, reqBody) - reqInf.RemoteAddr = remoteAddr - if err != nil { - return tc.ProfileCopyResponse{}, reqInf, err - } - defer httpResp.Body.Close() - - err = json.NewDecoder(httpResp.Body).Decode(&resp) - - return resp, reqInf, err -} diff --git a/traffic_ops/v2-client/profile_parameter.go b/traffic_ops/v2-client/profile_parameter.go deleted file mode 100644 index fde2336ba0..0000000000 --- a/traffic_ops/v2-client/profile_parameter.go +++ /dev/null @@ -1,115 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "fmt" - "net" - "net/http" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_PROFILE_PARAMETERS = apiBase + "/profileparameters" - ProfileIdQueryParam = "profileId" - ParameterIdQueryParam = "parameterId" -) - -// Create a ProfileParameter -func (to *Session) CreateProfileParameter(pp tc.ProfileParameter) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(pp) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - resp, remoteAddr, err := to.request(http.MethodPost, API_PROFILE_PARAMETERS, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// CreateMultipleProfileParameters creates multiple ProfileParameters at once. -func (to *Session) CreateMultipleProfileParameters(pps []tc.ProfileParameter) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(pps) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - resp, remoteAddr, err := to.request(http.MethodPost, API_PROFILE_PARAMETERS, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// Returns a list of Profile Parameters -func (to *Session) GetProfileParameters() ([]tc.ProfileParameter, ReqInf, error) { - resp, remoteAddr, err := to.request(http.MethodGet, API_PROFILE_PARAMETERS, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ProfileParametersResponse - err = json.NewDecoder(resp.Body).Decode(&data) - return data.Response, reqInf, nil -} - -// GET a Profile Parameter by the Parameter -func (to *Session) GetProfileParameterByQueryParams(queryParams string) ([]tc.ProfileParameter, ReqInf, error) { - URI := API_PROFILE_PARAMETERS + queryParams - resp, remoteAddr, err := to.request(http.MethodGet, URI, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ProfileParametersResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// DELETE a Parameter by Parameter -func (to *Session) DeleteParameterByProfileParameter(profile int, parameter int) (tc.Alerts, ReqInf, error) { - URI := fmt.Sprintf("%s/%d/%d", API_PROFILE_PARAMETERS, profile, parameter) - resp, remoteAddr, err := to.request(http.MethodDelete, URI, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} diff --git a/traffic_ops/v2-client/region.go b/traffic_ops/v2-client/region.go deleted file mode 100644 index 616c5b075b..0000000000 --- a/traffic_ops/v2-client/region.go +++ /dev/null @@ -1,170 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "errors" - "fmt" - "net" - "net/http" - "net/url" - "strconv" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_REGIONS = apiBase + "/regions" -) - -// CreateRegion creates a Region. -func (to *Session) CreateRegion(region tc.Region) (tc.Alerts, ReqInf, error) { - if region.Division == 0 && region.DivisionName != "" { - divisions, _, err := to.GetDivisionByName(region.DivisionName) - if err != nil { - return tc.Alerts{}, ReqInf{}, err - } - if len(divisions) == 0 { - return tc.Alerts{}, ReqInf{}, errors.New("no division with name " + region.DivisionName) - } - region.Division = divisions[0].ID - } - - var remoteAddr net.Addr - reqBody, err := json.Marshal(region) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - resp, remoteAddr, err := to.request(http.MethodPost, API_REGIONS, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// UpdateRegionByID updates a Region by ID. -func (to *Session) UpdateRegionByID(id int, region tc.Region) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(region) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - route := fmt.Sprintf("%s/%d", API_REGIONS, id) - resp, remoteAddr, err := to.request(http.MethodPut, route, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// GetRegions returns a list of regions. -func (to *Session) GetRegions() ([]tc.Region, ReqInf, error) { - resp, remoteAddr, err := to.request(http.MethodGet, API_REGIONS, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.RegionsResponse - err = json.NewDecoder(resp.Body).Decode(&data) - return data.Response, reqInf, nil -} - -// GetRegionByID GETs a Region by the Region ID. -func (to *Session) GetRegionByID(id int) ([]tc.Region, ReqInf, error) { - route := fmt.Sprintf("%s?id=%d", API_REGIONS, id) - resp, remoteAddr, err := to.request(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.RegionsResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GetRegionByName GETs a Region by the Region name. -func (to *Session) GetRegionByName(name string) ([]tc.Region, ReqInf, error) { - url := fmt.Sprintf("%s?name=%s", API_REGIONS, url.QueryEscape(name)) - resp, remoteAddr, err := to.request(http.MethodGet, url, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.RegionsResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// DeleteRegionByID DELETEs a Region by ID. -func (to *Session) DeleteRegionByID(id int) (tc.Alerts, ReqInf, error) { - route := fmt.Sprintf("%s?id=%d", API_REGIONS, id) - resp, remoteAddr, err := to.request(http.MethodDelete, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// DeleteRegion lets you DELETE a Region. Only 1 parameter is required, not both. -func (to *Session) DeleteRegion(id *int, name *string) (tc.Alerts, ReqInf, error) { - v := url.Values{} - if id != nil { - v.Add("id", strconv.Itoa(*id)) - } - if name != nil { - v.Add("name", *name) - } - URI := apiBase + "/regions" - if qStr := v.Encode(); len(qStr) > 0 { - URI = fmt.Sprintf("%s?%s", URI, qStr) - } - - resp, remoteAddr, err := to.request(http.MethodDelete, URI, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, err -} diff --git a/traffic_ops/v2-client/role.go b/traffic_ops/v2-client/role.go deleted file mode 100644 index 7b2fb48b9f..0000000000 --- a/traffic_ops/v2-client/role.go +++ /dev/null @@ -1,160 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "fmt" - "net" - "net/http" - "net/url" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_ROLES = apiBase + "/roles" -) - -// CreateRole creates a Role. -func (to *Session) CreateRole(region tc.Role) (tc.Alerts, ReqInf, int, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(region) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, 0, err - } - resp, remoteAddr, errClient := to.RawRequest(http.MethodPost, API_ROLES, reqBody) - if resp != nil { - defer resp.Body.Close() - var alerts tc.Alerts - if err = json.NewDecoder(resp.Body).Decode(&alerts); err != nil { - return alerts, reqInf, resp.StatusCode, err - } - return alerts, reqInf, resp.StatusCode, errClient - } - return tc.Alerts{}, reqInf, 0, errClient -} - -// UpdateRoleByID updates a Role by ID. -func (to *Session) UpdateRoleByID(id int, region tc.Role) (tc.Alerts, ReqInf, int, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(region) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, 0, err - } - route := fmt.Sprintf("%s/?id=%d", API_ROLES, id) - resp, remoteAddr, errClient := to.RawRequest(http.MethodPut, route, reqBody) - if resp != nil { - defer resp.Body.Close() - var alerts tc.Alerts - if err = json.NewDecoder(resp.Body).Decode(&alerts); err != nil { - return alerts, reqInf, resp.StatusCode, err - } - return alerts, reqInf, resp.StatusCode, errClient - } - return tc.Alerts{}, reqInf, 0, errClient -} - -// GetRoles returns a list of roles. -func (to *Session) GetRoles() ([]tc.Role, ReqInf, int, error) { - resp, remoteAddr, errClient := to.RawRequest(http.MethodGet, API_ROLES, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if resp != nil { - defer resp.Body.Close() - - var data tc.RolesResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return data.Response, reqInf, resp.StatusCode, err - } - return data.Response, reqInf, resp.StatusCode, errClient - } - return []tc.Role{}, reqInf, 0, errClient -} - -// GetRoleByID GETs a Role by the Role ID. -func (to *Session) GetRoleByID(id int) ([]tc.Role, ReqInf, int, error) { - route := fmt.Sprintf("%s/?id=%d", API_ROLES, id) - resp, remoteAddr, errClient := to.RawRequest(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if resp != nil { - defer resp.Body.Close() - - var data tc.RolesResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return data.Response, reqInf, resp.StatusCode, err - } - return data.Response, reqInf, resp.StatusCode, errClient - } - return []tc.Role{}, reqInf, 0, errClient -} - -// GetRoleByName GETs a Role by the Role name. -func (to *Session) GetRoleByName(name string) ([]tc.Role, ReqInf, int, error) { - route := fmt.Sprintf("%s?name=%s", API_ROLES, url.QueryEscape(name)) - resp, remoteAddr, errClient := to.RawRequest(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if resp != nil { - defer resp.Body.Close() - - var data tc.RolesResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return data.Response, reqInf, resp.StatusCode, err - } - return data.Response, reqInf, resp.StatusCode, errClient - } - return []tc.Role{}, reqInf, 0, errClient -} - -// GetRoleByQueryParams gets a Role by the Role query parameters. -func (to *Session) GetRoleByQueryParams(queryParams map[string]string) ([]tc.Role, ReqInf, int, error) { - route := fmt.Sprintf("%s?", API_ROLES) - for param, val := range queryParams { - route += fmt.Sprintf("%s=%s&", url.QueryEscape(param), url.QueryEscape(val)) - } - resp, remoteAddr, errClient := to.RawRequest(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if resp != nil { - defer resp.Body.Close() - - var data tc.RolesResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return data.Response, reqInf, resp.StatusCode, err - } - return data.Response, reqInf, resp.StatusCode, errClient - } - return []tc.Role{}, reqInf, 0, errClient -} - -// DeleteRoleByID DELETEs a Role by ID. -func (to *Session) DeleteRoleByID(id int) (tc.Alerts, ReqInf, int, error) { - route := fmt.Sprintf("%s/?id=%d", API_ROLES, id) - resp, remoteAddr, errClient := to.RawRequest(http.MethodDelete, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if resp != nil { - defer resp.Body.Close() - - var alerts tc.Alerts - if err := json.NewDecoder(resp.Body).Decode(&alerts); err != nil { - return alerts, reqInf, resp.StatusCode, err - } - return alerts, reqInf, resp.StatusCode, errClient - } - return tc.Alerts{}, reqInf, 0, errClient -} diff --git a/traffic_ops/v2-client/server.go b/traffic_ops/v2-client/server.go deleted file mode 100644 index eb50dcb35d..0000000000 --- a/traffic_ops/v2-client/server.go +++ /dev/null @@ -1,352 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "errors" - "fmt" - "net" - "net/http" - "net/url" - "strings" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_SERVERS = apiBase + "/servers" - API_SERVERS_DETAILS = apiBase + "/servers/details" - API_SERVER_ASSIGN_DELIVERY_SERVICES = API_SERVER_DELIVERY_SERVICES + "?replace=%t" -) - -// CreateServer creates a Server. -func (to *Session) CreateServer(server tc.Server) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - - if server.CachegroupID == 0 && server.Cachegroup != "" { - cg, _, err := to.GetCacheGroupNullableByName(server.Cachegroup) - if err != nil { - return tc.Alerts{}, ReqInf{}, errors.New("no cachegroup named " + server.Cachegroup + ":" + err.Error()) - } - if len(cg) == 0 { - return tc.Alerts{}, ReqInf{}, errors.New("no cachegroup named " + server.Cachegroup) - } - if cg[0].ID == nil { - return tc.Alerts{}, ReqInf{}, errors.New("Cachegroup named " + server.Cachegroup + " has a nil ID") - } - server.CachegroupID = *cg[0].ID - } - if server.CDNID == 0 && server.CDNName != "" { - c, _, err := to.GetCDNByName(server.CDNName) - if err != nil { - return tc.Alerts{}, ReqInf{}, errors.New("no CDN named " + server.CDNName + ":" + err.Error()) - } - if len(c) == 0 { - return tc.Alerts{}, ReqInf{}, errors.New("no CDN named " + server.CDNName) - } - server.CDNID = c[0].ID - } - if server.PhysLocationID == 0 && server.PhysLocation != "" { - ph, _, err := to.GetPhysLocationByName(server.PhysLocation) - if err != nil { - return tc.Alerts{}, ReqInf{}, errors.New("no physlocation named " + server.PhysLocation + ":" + err.Error()) - } - if len(ph) == 0 { - return tc.Alerts{}, ReqInf{}, errors.New("no physlocation named " + server.PhysLocation) - } - server.PhysLocationID = ph[0].ID - } - if server.ProfileID == 0 && server.Profile != "" { - pr, _, err := to.GetProfileByName(server.Profile) - if err != nil { - return tc.Alerts{}, ReqInf{}, errors.New("no profile named " + server.Profile + ":" + err.Error()) - } - if len(pr) == 0 { - return tc.Alerts{}, ReqInf{}, errors.New("no profile named " + server.Profile) - } - server.ProfileID = pr[0].ID - } - if server.StatusID == 0 && server.Status != "" { - st, _, err := to.GetStatusByName(server.Status) - if err != nil { - return tc.Alerts{}, ReqInf{}, errors.New("no status named " + server.Status + ":" + err.Error()) - } - if len(st) == 0 { - return tc.Alerts{}, ReqInf{}, errors.New("no status named " + server.Status) - } - server.StatusID = st[0].ID - } - if server.TypeID == 0 && server.Type != "" { - ty, _, err := to.GetTypeByName(server.Type) - if err != nil { - return tc.Alerts{}, ReqInf{}, errors.New("no type named " + server.Type + ":" + err.Error()) - } - if len(ty) == 0 { - return tc.Alerts{}, ReqInf{}, errors.New("no type named " + server.Type) - } - server.TypeID = ty[0].ID - } - reqBody, err := json.Marshal(server) - if err != nil { - return tc.Alerts{}, reqInf, err - } - - resp, remoteAddr, err := to.request(http.MethodPost, API_SERVERS, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// UpdateServerByID updates a Server by ID. -func (to *Session) UpdateServerByID(id int, server tc.Server) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(server) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - route := fmt.Sprintf("%s/%d", API_SERVERS, id) - resp, remoteAddr, err := to.request(http.MethodPut, route, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// GetServers returns a list of Servers. -func (to *Session) GetServers() ([]tc.Server, ReqInf, error) { - resp, remoteAddr, err := to.request(http.MethodGet, API_SERVERS, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ServersResponse - err = json.NewDecoder(resp.Body).Decode(&data) - return data.Response, reqInf, nil -} - -// GetServerByID GETs a Server by the Server ID. -func (to *Session) GetServerByID(id int) ([]tc.Server, ReqInf, error) { - route := fmt.Sprintf("%s?id=%d", API_SERVERS, id) - resp, remoteAddr, err := to.request(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ServersResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GetServerByHostName GETs Servers by the Server hostname. -func (to *Session) GetServerByHostName(hostName string) ([]tc.Server, ReqInf, error) { - v := url.Values{} - v.Add("hostName", hostName) - url := API_SERVERS + "?" + v.Encode() - - resp, remoteAddr, err := to.request(http.MethodGet, url, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ServersResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GetServerDetailsByHostName GETs Servers by the Server hostname. -func (to *Session) GetServerDetailsByHostName(hostName string) ([]tc.ServerDetailV11, ReqInf, error) { - v := url.Values{} - v.Add("hostName", hostName) - url := API_SERVERS_DETAILS + "?" + v.Encode() - - resp, remoteAddr, err := to.request(http.MethodGet, url, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ServersV1DetailResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// DeleteServerByID DELETEs a Server by ID. -func (to *Session) DeleteServerByID(id int) (tc.Alerts, ReqInf, error) { - route := fmt.Sprintf("%s/%d", API_SERVERS, id) - resp, remoteAddr, err := to.request(http.MethodDelete, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// GetServersByType returns all servers that match the given query parameter filters, NOT -// - as the name might imply - all servers of a specific type (though type can be specified -// in the query parameters). -func (to *Session) GetServersByType(qparams url.Values) ([]tc.Server, ReqInf, error) { - url := fmt.Sprintf("%s?%s", API_SERVERS, qparams.Encode()) - resp, remoteAddr, err := to.request(http.MethodGet, url, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ServersResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GetServerFQDN returns the Fully Qualified Domain Name (FQDN) of the first server found to -// have the Host Name 'n'. -func (to *Session) GetServerFQDN(n string) (string, ReqInf, error) { - // TODO fix to only request one server - fdn := "" - servers, reqInf, err := to.GetServers() - if err != nil { - return "Error", reqInf, err - } - - for _, server := range servers { - if server.HostName == n { - fdn = fmt.Sprintf("%s.%s", server.HostName, server.DomainName) - } - } - if fdn == "" { - return "Error", reqInf, fmt.Errorf("No Server %s found", n) - } - return fdn, reqInf, nil -} - -// GetServersShortNameSearch returns all of the Host Names of servers that contain 'shortname'. -func (to *Session) GetServersShortNameSearch(shortname string) ([]string, ReqInf, error) { - var serverlst []string - servers, reqInf, err := to.GetServers() - if err != nil { - serverlst = append(serverlst, "N/A") - return serverlst, reqInf, err - } - for _, server := range servers { - if strings.Contains(server.HostName, shortname) { - serverlst = append(serverlst, server.HostName) - } - } - if len(serverlst) == 0 { - serverlst = append(serverlst, "N/A") - return serverlst, reqInf, fmt.Errorf("No Servers Found") - } - return serverlst, reqInf, nil -} - -// AssignDeliveryServiceIDsToServerID assigns a set of Delivery Services to a single server, optionally -// replacing any and all existing assignments. 'server' should be the requested server's ID, 'dsIDs' -// should be a slice of the requested Delivery Services' IDs. If 'replace' is 'true', existing -// assignments to the server will be replaced. -func (to *Session) AssignDeliveryServiceIDsToServerID(server int, dsIDs []int, replace bool) (tc.Alerts, ReqInf, error) { - // datatypes here match the library tc.Server's and tc.DeliveryService's ID fields - - var remoteAddr net.Addr - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - - endpoint := fmt.Sprintf(API_SERVER_ASSIGN_DELIVERY_SERVICES, server, replace) - - reqBody, err := json.Marshal(dsIDs) - if err != nil { - return tc.Alerts{}, reqInf, err - } - - resp, remoteAddr, err := to.request(http.MethodPost, endpoint, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - reqInf.RemoteAddr = remoteAddr - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, err -} - -// GetServerIDDeliveryServices returns all of the Delivery Services assigned to the server identified -// by the integral, unique identifier 'server'. -func (to *Session) GetServerIDDeliveryServices(server int) ([]tc.DeliveryServiceNullable, ReqInf, error) { - endpoint := fmt.Sprintf(API_SERVER_DELIVERY_SERVICES, server) - - resp, remoteAddr, err := to.request(http.MethodGet, endpoint, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.DeliveryServicesNullableResponse - err = json.NewDecoder(resp.Body).Decode(&data) - return data.Response, reqInf, err -} - -// GetServerUpdateStatus GETs the Server Update Status by the Server hostname. -func (to *Session) GetServerUpdateStatus(hostName string) (tc.ServerUpdateStatus, ReqInf, error) { - path := API_SERVERS + `/` + hostName + `/update_status` - resp, remoteAddr, err := to.request(http.MethodGet, path, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.ServerUpdateStatus{}, reqInf, err - } - defer resp.Body.Close() - - data := []tc.ServerUpdateStatus{} - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return tc.ServerUpdateStatus{}, reqInf, err - } - if len(data) == 0 { - return tc.ServerUpdateStatus{}, reqInf, errors.New("Traffic Ops returned no update statuses for that server") - } - return data[0], reqInf, nil -} diff --git a/traffic_ops/v2-client/server_server_capabilities.go b/traffic_ops/v2-client/server_server_capabilities.go deleted file mode 100644 index a2f9973e04..0000000000 --- a/traffic_ops/v2-client/server_server_capabilities.go +++ /dev/null @@ -1,83 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "fmt" - "net" - "net/url" - "strconv" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_SERVER_SERVER_CAPABILITIES = apiBase + "/server_server_capabilities" -) - -// CreateServerServerCapability assigns a Server Capability to a Server -func (to *Session) CreateServerServerCapability(ssc tc.ServerServerCapability) (tc.Alerts, ReqInf, error) { - var alerts tc.Alerts - var remoteAddr net.Addr - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - reqBody, err := json.Marshal(ssc) - if err != nil { - return tc.Alerts{}, reqInf, err - } - reqInf, err = post(to, API_SERVER_SERVER_CAPABILITIES, reqBody, &alerts) - return alerts, reqInf, err -} - -// DeleteServerServerCapability unassigns a Server Capability from a Server -func (to *Session) DeleteServerServerCapability(serverID int, serverCapability string) (tc.Alerts, ReqInf, error) { - var alerts tc.Alerts - v := url.Values{} - v.Add("serverId", strconv.Itoa(serverID)) - v.Add("serverCapability", serverCapability) - qStr := v.Encode() - queryURL := fmt.Sprintf("%s?%s", API_SERVER_SERVER_CAPABILITIES, qStr) - reqInf, err := del(to, queryURL, &alerts) - return alerts, reqInf, err -} - -// GetServerServerCapabilities retrieves a list of Server Capabilities that are assigned to a Server -// Callers can filter the results by server id, server host name and/or server capability via the optional parameters -func (to *Session) GetServerServerCapabilities(serverID *int, serverHostName, serverCapability *string) ([]tc.ServerServerCapability, ReqInf, error) { - v := url.Values{} - if serverID != nil { - v.Add("serverId", strconv.Itoa(*serverID)) - } - if serverHostName != nil { - v.Add("serverHostName", *serverHostName) - } - if serverCapability != nil { - v.Add("serverCapability", *serverCapability) - } - queryURL := API_SERVER_SERVER_CAPABILITIES - if qStr := v.Encode(); len(qStr) > 0 { - queryURL = fmt.Sprintf("%s?%s", queryURL, qStr) - } - - resp := struct { - Response []tc.ServerServerCapability `json:"response"` - }{} - reqInf, err := get(to, queryURL, &resp) - if err != nil { - return nil, reqInf, err - } - return resp.Response, reqInf, nil -} diff --git a/traffic_ops/v2-client/server_update_status.go b/traffic_ops/v2-client/server_update_status.go deleted file mode 100644 index 3aef33f746..0000000000 --- a/traffic_ops/v2-client/server_update_status.go +++ /dev/null @@ -1,110 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "errors" - "fmt" - "net/http" - "strconv" - "strings" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -// UpdateServerStatus updates a server's status and returns the response. -func (to *Session) UpdateServerStatus(serverID int, req tc.ServerPutStatus) (*tc.Alerts, ReqInf, error) { - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss} - - reqBody, err := json.Marshal(req) - if err != nil { - return nil, reqInf, err - } - - path := fmt.Sprintf("%s/servers/%d/status", apiBase, serverID) - resp, remoteAddr, err := to.request(http.MethodPut, path, reqBody) - reqInf.RemoteAddr = remoteAddr - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - alerts := tc.Alerts{} - if err = json.NewDecoder(resp.Body).Decode(&alerts); err != nil { - return nil, reqInf, err - } - - return &alerts, reqInf, nil -} - -var queueUpdateActions = map[bool]string{ - false: "dequeue", - true: "queue", -} - -// SetServerQueueUpdate updates a server's status and returns the response. -func (to *Session) SetServerQueueUpdate(serverID int, queueUpdate bool) (tc.ServerQueueUpdateResponse, ReqInf, error) { - var ( - req = tc.ServerQueueUpdateRequest{Action: queueUpdateActions[queueUpdate]} - reqInf = ReqInf{CacheHitStatus: CacheHitStatusMiss} - resp tc.ServerQueueUpdateResponse - ) - - reqBody, err := json.Marshal(req) - if err != nil { - return resp, reqInf, err - } - - path := fmt.Sprintf("%s/servers/%d/queue_update", apiBase, serverID) - httpResp, remoteAddr, err := to.request(http.MethodPost, path, reqBody) - reqInf.RemoteAddr = remoteAddr - if err != nil { - return resp, reqInf, err - } - defer httpResp.Body.Close() - - err = json.NewDecoder(httpResp.Body).Decode(&resp) - - return resp, reqInf, err -} - -// SetUpdateServerStatuses updates a server's queue status and/or reval status. -// Either updateStatus or revalStatus may be nil, in which case that status isn't updated (but not both, because that wouldn't do anything). -func (to *Session) SetUpdateServerStatuses(serverName string, updateStatus *bool, revalStatus *bool) (ReqInf, error) { - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss} - if updateStatus == nil && revalStatus == nil { - return reqInf, errors.New("either updateStatus or revalStatus must be non-nil; nothing to do") - } - - path := apiBase + `/servers/` + serverName + `/update?` - queryParams := []string{} - if updateStatus != nil { - queryParams = append(queryParams, `updated=`+strconv.FormatBool(*updateStatus)) - } - if revalStatus != nil { - queryParams = append(queryParams, `reval_updated=`+strconv.FormatBool(*revalStatus)) - } - path += strings.Join(queryParams, `&`) - - resp, remoteAddr, err := to.request(http.MethodPost, path, nil) - reqInf.RemoteAddr = remoteAddr - if err != nil { - return reqInf, err - } - resp.Body.Close() - return reqInf, nil -} diff --git a/traffic_ops/v2-client/servercapability.go b/traffic_ops/v2-client/servercapability.go deleted file mode 100644 index 4975076451..0000000000 --- a/traffic_ops/v2-client/servercapability.go +++ /dev/null @@ -1,104 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "fmt" - "net" - "net/http" - "net/url" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_SERVER_CAPABILITIES = apiBase + "/server_capabilities" -) - -// CreateServerCapability creates a server capability and returns the response. -func (to *Session) CreateServerCapability(sc tc.ServerCapability) (*tc.ServerCapabilityDetailResponse, ReqInf, error) { - var remoteAddr net.Addr - reqBody, err := json.Marshal(sc) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - resp, remoteAddr, err := to.request(http.MethodPost, API_SERVER_CAPABILITIES, reqBody) - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - var scResp tc.ServerCapabilityDetailResponse - if err = json.NewDecoder(resp.Body).Decode(&scResp); err != nil { - return nil, reqInf, err - } - return &scResp, reqInf, nil -} - -// GetServerCapabilities returns all the server capabilities. -func (to *Session) GetServerCapabilities() ([]tc.ServerCapability, ReqInf, error) { - resp, remoteAddr, err := to.request(http.MethodGet, API_SERVER_CAPABILITIES, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ServerCapabilitiesResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GetServerCapability returns the given server capability by name. -func (to *Session) GetServerCapability(name string) (*tc.ServerCapability, ReqInf, error) { - reqUrl := fmt.Sprintf("%s?name=%s", API_SERVER_CAPABILITIES, url.QueryEscape(name)) - resp, remoteAddr, err := to.request(http.MethodGet, reqUrl, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.ServerCapabilitiesResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - if len(data.Response) == 1 { - return &data.Response[0], reqInf, nil - } - return nil, reqInf, fmt.Errorf("expected one server capability in response, instead got: %+v", data.Response) -} - -// DeleteServerCapability deletes the given server capability by name. -func (to *Session) DeleteServerCapability(name string) (tc.Alerts, ReqInf, error) { - reqUrl := fmt.Sprintf("%s?name=%s", API_SERVER_CAPABILITIES, url.QueryEscape(name)) - resp, remoteAddr, err := to.request(http.MethodDelete, reqUrl, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - if err = json.NewDecoder(resp.Body).Decode(&alerts); err != nil { - return tc.Alerts{}, reqInf, err - } - return alerts, reqInf, nil -} diff --git a/traffic_ops/v2-client/servercheck.go b/traffic_ops/v2-client/servercheck.go deleted file mode 100644 index 97942a487e..0000000000 --- a/traffic_ops/v2-client/servercheck.go +++ /dev/null @@ -1,53 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "net" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const API_SERVERCHECK = apiBase + "/servercheck" - -// InsertServerCheckStatus Will insert/update the servercheck value based on if it already exists or not. -func (to *Session) InsertServerCheckStatus(status tc.ServercheckRequestNullable) (*tc.ServercheckPostResponse, ReqInf, error) { - uri := API_SERVERCHECK - var remoteAddr net.Addr - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - jsonReq, err := json.Marshal(status) - if err != nil { - return nil, reqInf, err - } - resp := tc.ServercheckPostResponse{} - reqInf, err = post(to, uri, jsonReq, &resp) - if err != nil { - return nil, reqInf, err - } - return &resp, reqInf, nil -} - -// GetServersChecks fetches check and meta information about servers from /servercheck. -func (to *Session) GetServersChecks() ([]tc.GenericServerCheck, tc.Alerts, ReqInf, error) { - var response struct { - tc.Alerts - Response []tc.GenericServerCheck `json:"response"` - } - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss} - reqInf, err := get(to, API_SERVERCHECK, &response) - return response.Response, response.Alerts, reqInf, err -} diff --git a/traffic_ops/v2-client/servercheckextensions.go b/traffic_ops/v2-client/servercheckextensions.go deleted file mode 100644 index 7d07db947c..0000000000 --- a/traffic_ops/v2-client/servercheckextensions.go +++ /dev/null @@ -1,69 +0,0 @@ -/* - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "fmt" - "net" - "net/http" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const API_TO_EXTENSION = apiBase + "/servercheck/extensions" - -// CreateServerCheckExtension creates a servercheck extension. -func (to *Session) CreateServerCheckExtension(ServerCheckExtension tc.ServerCheckExtensionNullable) (tc.Alerts, ReqInf, error) { - var remoteAddr net.Addr - reqBody, err := json.Marshal(ServerCheckExtension) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - resp, remoteAddr, err := to.request(http.MethodPost, API_TO_EXTENSION, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, err -} - -// DeleteServerCheckExtension deletes a servercheck extension. -func (to *Session) DeleteServerCheckExtension(id int) (tc.Alerts, ReqInf, error) { - URI := fmt.Sprintf("%s/%d", API_TO_EXTENSION, id) - resp, remoteAddr, err := to.request(http.MethodDelete, URI, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, err -} - -// GetServerCheckExtensions gets all servercheck extensions. -func (to *Session) GetServerCheckExtensions() (tc.ServerCheckExtensionResponse, ReqInf, error) { - resp, remoteAddr, err := to.request(http.MethodGet, API_TO_EXTENSION, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.ServerCheckExtensionResponse{}, reqInf, err - } - defer resp.Body.Close() - var toExtResp tc.ServerCheckExtensionResponse - err = json.NewDecoder(resp.Body).Decode(&toExtResp) - return toExtResp, reqInf, err -} diff --git a/traffic_ops/v2-client/session.go b/traffic_ops/v2-client/session.go deleted file mode 100644 index 9915a080c1..0000000000 --- a/traffic_ops/v2-client/session.go +++ /dev/null @@ -1,498 +0,0 @@ -/* - - Licensed 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. -*/ - -// Package client provides Go bindings to the Traffic Ops RPC API. -package client - -import ( - "bytes" - "crypto/tls" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net" - "net/http" - "net/http/cookiejar" - "net/http/httptrace" - "strconv" - "strings" - "sync" - "time" - - tc "github.com/apache/trafficcontrol/lib/go-tc" - - "golang.org/x/net/publicsuffix" -) - -// Session ... -type Session struct { - UserName string - Password string - URL string - Client *http.Client - cache map[string]CacheEntry - cacheMutex *sync.RWMutex - useCache bool - UserAgentStr string -} - -func NewSession(user, password, url, userAgent string, client *http.Client, useCache bool) *Session { - return &Session{ - UserName: user, - Password: password, - URL: url, - Client: client, - cache: map[string]CacheEntry{}, - cacheMutex: &sync.RWMutex{}, - useCache: useCache, - UserAgentStr: userAgent, - } -} - -const DefaultTimeout = time.Second * time.Duration(30) - -// HTTPError is returned on Update Session failure. -type HTTPError struct { - HTTPStatusCode int - HTTPStatus string - URL string - Body string -} - -// Error implements the error interface for our customer error type. -func (e *HTTPError) Error() string { - return fmt.Sprintf("%s[%d] - Error requesting Traffic Ops %s %s", e.HTTPStatus, e.HTTPStatusCode, e.URL, e.Body) -} - -// CacheEntry ... -type CacheEntry struct { - Entered int64 - Bytes []byte - RemoteAddr net.Addr -} - -// TODO JvD -const tmPollingInterval = 60 - -// loginCreds gathers login credentials for Traffic Ops. -func loginCreds(toUser string, toPasswd string) ([]byte, error) { - credentials := tc.UserCredentials{ - Username: toUser, - Password: toPasswd, - } - - js, err := json.Marshal(credentials) - if err != nil { - err := fmt.Errorf("Error creating login json: %v", err) - return nil, err - } - return js, nil -} - -// loginToken gathers token login credentials for Traffic Ops. -func loginToken(token string) ([]byte, error) { - form := tc.UserToken{ - Token: token, - } - - j, e := json.Marshal(form) - if e != nil { - e := fmt.Errorf("Error creating token login json: %v", e) - return nil, e - } - return j, nil -} - -// login tries to log in to Traffic Ops, and set the auth cookie in the Session. Returns the IP address of the remote Traffic Ops. -func (to *Session) login() (net.Addr, error) { - credentials, err := loginCreds(to.UserName, to.Password) - if err != nil { - return nil, errors.New("creating login credentials: " + err.Error()) - } - - path := apiBase + "/user/login" - resp, remoteAddr, err := to.RawRequest("POST", path, credentials) - resp, remoteAddr, err = to.ErrUnlessOK(resp, remoteAddr, err, path) - if err != nil { - return remoteAddr, errors.New("requesting: " + err.Error()) - } - defer resp.Body.Close() - - var alerts tc.Alerts - if err := json.NewDecoder(resp.Body).Decode(&alerts); err != nil { - return remoteAddr, errors.New("decoding response JSON: " + err.Error()) - } - - success := false - for _, alert := range alerts.Alerts { - if alert.Level == "success" && alert.Text == "Successfully logged in." { - success = true - break - } - } - - if !success { - return remoteAddr, fmt.Errorf("Login failed, alerts string: %+v", alerts) - } - - return remoteAddr, nil -} - -func (to *Session) loginWithToken(token []byte) (net.Addr, error) { - path := apiBase + "/user/login/token" - resp, remoteAddr, err := to.RawRequest(http.MethodPost, path, token) - resp, remoteAddr, err = to.ErrUnlessOK(resp, remoteAddr, err, path) - if err != nil { - return remoteAddr, fmt.Errorf("requesting: %v", err) - } - defer resp.Body.Close() - - var alerts tc.Alerts - if err := json.NewDecoder(resp.Body).Decode(&alerts); err != nil { - return remoteAddr, fmt.Errorf("decoding response JSON: %v", err) - } - - for _, alert := range alerts.Alerts { - if alert.Level == tc.SuccessLevel.String() && alert.Text == "Successfully logged in." { - return remoteAddr, nil - } - } - - return remoteAddr, fmt.Errorf("Login failed, alerts string: %+v", alerts) -} - -// logout of Traffic Ops -func (to *Session) logout() (net.Addr, error) { - credentials, err := loginCreds(to.UserName, to.Password) - if err != nil { - return nil, errors.New("creating login credentials: " + err.Error()) - } - - path := apiBase + "/user/logout" - resp, remoteAddr, err := to.RawRequest("POST", path, credentials) - resp, remoteAddr, err = to.ErrUnlessOK(resp, remoteAddr, err, path) - if err != nil { - return remoteAddr, errors.New("requesting: " + err.Error()) - } - defer resp.Body.Close() - - var alerts tc.Alerts - if err := json.NewDecoder(resp.Body).Decode(&alerts); err != nil { - return remoteAddr, errors.New("decoding response JSON: " + err.Error()) - } - - success := false - for _, alert := range alerts.Alerts { - if alert.Level == "success" && alert.Text == "Successfully logged in." { - success = true - break - } - } - - if !success { - return remoteAddr, fmt.Errorf("Logout failed, alerts string: %+v", alerts) - } - - return remoteAddr, nil -} - -// Login to traffic_ops, the response should set the cookie for this session -// automatically. Start with -// to := traffic_ops.Login("user", "passwd", true) -// subsequent calls like to.GetData("datadeliveryservice") will be authenticated. -// Returns the logged in client, the remote address of Traffic Ops which was translated and used to log in, and any error. If the error is not nil, the remote address may or may not be nil, depending whether the error occurred before the login request. -func LoginWithAgent(toURL string, toUser string, toPasswd string, insecure bool, userAgent string, useCache bool, requestTimeout time.Duration) (*Session, net.Addr, error) { - options := cookiejar.Options{ - PublicSuffixList: publicsuffix.List, - } - - jar, err := cookiejar.New(&options) - if err != nil { - return nil, nil, err - } - - to := NewSession(toUser, toPasswd, toURL, userAgent, &http.Client{ - Timeout: requestTimeout, - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}, - }, - Jar: jar, - }, useCache) - - remoteAddr, err := to.login() - if err != nil { - return nil, remoteAddr, errors.New("logging in: " + err.Error()) - } - return to, remoteAddr, nil -} - -func LoginWithToken(toURL string, token string, insecure bool, userAgent string, useCache bool, requestTimeout time.Duration) (*Session, net.Addr, error) { - options := cookiejar.Options{ - PublicSuffixList: publicsuffix.List, - } - - jar, err := cookiejar.New(&options) - if err != nil { - return nil, nil, err - } - - client := http.Client{ - Timeout: requestTimeout, - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}, - }, - Jar: jar, - } - - to := NewSession("", "", toURL, userAgent, &client, useCache) - tBts, err := loginToken(token) - if err != nil { - return nil, nil, fmt.Errorf("logging in: %v", err) - } - - remoteAddr, err := to.loginWithToken(tBts) - if err != nil { - return nil, remoteAddr, fmt.Errorf("logging in: %v", err) - } - return to, remoteAddr, nil -} - -// Logout of traffic_ops -func LogoutWithAgent(toURL string, toUser string, toPasswd string, insecure bool, userAgent string, useCache bool, requestTimeout time.Duration) (*Session, net.Addr, error) { - options := cookiejar.Options{ - PublicSuffixList: publicsuffix.List, - } - - jar, err := cookiejar.New(&options) - if err != nil { - return nil, nil, err - } - - to := NewSession(toUser, toPasswd, toURL, userAgent, &http.Client{ - Timeout: requestTimeout, - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}, - }, - Jar: jar, - }, useCache) - - remoteAddr, err := to.logout() - if err != nil { - return nil, remoteAddr, errors.New("logging out: " + err.Error()) - } - return to, remoteAddr, nil -} - -// NewNoAuthSession returns a new Session without logging in -// this can be used for querying unauthenticated endpoints without requiring a login -func NewNoAuthSession(toURL string, insecure bool, userAgent string, useCache bool, requestTimeout time.Duration) *Session { - return NewSession("", "", toURL, userAgent, &http.Client{ - Timeout: requestTimeout, - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}, - }, - }, useCache) -} - -// ErrUnlessOk returns nil and an error if the given Response's status code is anything but 200 OK. This includes reading the Response.Body and Closing it. Otherwise, the given response and error are returned unchanged. -func (to *Session) ErrUnlessOK(resp *http.Response, remoteAddr net.Addr, err error, path string) (*http.Response, net.Addr, error) { - if err != nil { - return resp, remoteAddr, err - } - if resp.StatusCode < 300 { - return resp, remoteAddr, err - } - - defer resp.Body.Close() - - if resp.StatusCode == http.StatusNotImplemented { - return nil, remoteAddr, errors.New("Traffic Ops Server returned 'Not Implemented', this client is probably newer than Traffic Ops, and you probably need to either upgrade Traffic Ops, or use a client whose version matches your Traffic Ops version.") - } - - body, readErr := ioutil.ReadAll(resp.Body) - if readErr != nil { - return nil, remoteAddr, readErr - } - return nil, remoteAddr, errors.New(resp.Status + "[" + strconv.Itoa(resp.StatusCode) + "] - Error requesting Traffic Ops " + to.getURL(path) + " " + string(body)) -} - -func (to *Session) getURL(path string) string { return to.URL + path } - -// request performs the HTTP request to Traffic Ops, trying to refresh the cookie if an Unauthorized or Forbidden code is received. It only tries once. If the login fails, the original Unauthorized/Forbidden response is returned. If the login succeeds and the subsequent re-request fails, the re-request's response is returned even if it's another Unauthorized/Forbidden. -// Returns the response, the remote address of the Traffic Ops instance used, and any error. -// The returned net.Addr is guaranteed to be either nil or valid, even if the returned error is not nil. Callers are encouraged to check and use the net.Addr if an error is returned, and use the remote address in their own error messages. This violates the Go idiom that a non-nil error implies all other values are undefined, but it's more straightforward than alternatives like typecasting. -func (to *Session) request(method, path string, body []byte) (*http.Response, net.Addr, error) { - r, remoteAddr, err := to.RawRequest(method, path, body) - if err != nil { - return r, remoteAddr, err - } - if r.StatusCode != http.StatusUnauthorized && r.StatusCode != http.StatusForbidden { - return to.ErrUnlessOK(r, remoteAddr, err, path) - } - if _, lerr := to.login(); lerr != nil { - return to.ErrUnlessOK(r, remoteAddr, err, path) // if re-logging-in fails, return the original request's response - } - - // return second request, even if it's another Unauthorized or Forbidden. - r, remoteAddr, err = to.RawRequest(method, path, body) - return to.ErrUnlessOK(r, remoteAddr, err, path) -} - -// RawRequest performs the actual HTTP request to Traffic Ops, simply, without trying to refresh the cookie if an Unauthorized code is returned. -// Returns the response, the remote address of the Traffic Ops instance used, and any error. -// The returned net.Addr is guaranteed to be either nil or valid, even if the returned error is not nil. Callers are encouraged to check and use the net.Addr if an error is returned, and use the remote address in their own error messages. This violates the Go idiom that a non-nil error implies all other values are undefined, but it's more straightforward than alternatives like typecasting. -func (to *Session) RawRequest(method, path string, body []byte) (*http.Response, net.Addr, error) { - url := to.getURL(path) - - var req *http.Request - var err error - remoteAddr := net.Addr(nil) - - if body != nil { - req, err = http.NewRequest(method, url, bytes.NewBuffer(body)) - if err != nil { - return nil, remoteAddr, err - } - req.Header.Set("Content-Type", "application/json") - } else { - req, err = http.NewRequest(method, url, nil) - if err != nil { - return nil, remoteAddr, err - } - } - - trace := &httptrace.ClientTrace{ - GotConn: func(connInfo httptrace.GotConnInfo) { - remoteAddr = connInfo.Conn.RemoteAddr() - }, - } - req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace)) - - req.Header.Set("User-Agent", to.UserAgentStr) - - resp, err := to.Client.Do(req) - if err != nil { - return nil, remoteAddr, err - } - - return resp, remoteAddr, nil -} - -type ReqInf struct { - CacheHitStatus CacheHitStatus - RemoteAddr net.Addr -} - -type CacheHitStatus string - -const CacheHitStatusHit = CacheHitStatus("hit") -const CacheHitStatusExpired = CacheHitStatus("expired") -const CacheHitStatusMiss = CacheHitStatus("miss") -const CacheHitStatusInvalid = CacheHitStatus("") - -func (s CacheHitStatus) String() string { - return string(s) -} - -func StringToCacheHitStatus(s string) CacheHitStatus { - s = strings.ToLower(s) - switch s { - case "hit": - return CacheHitStatusHit - case "expired": - return CacheHitStatusExpired - case "miss": - return CacheHitStatusMiss - default: - return CacheHitStatusInvalid - } -} - -// setCache Sets the given cache key and value. This is threadsafe for multiple goroutines. -func (to *Session) setCache(path string, entry CacheEntry) { - if !to.useCache { - return - } - to.cacheMutex.Lock() - defer to.cacheMutex.Unlock() - to.cache[path] = entry -} - -// getCache gets the cache value at the given key, or false if it doesn't exist. This is threadsafe for multiple goroutines. -func (to *Session) getCache(path string) (CacheEntry, bool) { - to.cacheMutex.RLock() - defer to.cacheMutex.RUnlock() - cacheEntry, ok := to.cache[path] - return cacheEntry, ok -} - -//if cacheEntry, ok := to.Cache[path]; ok { - -// getBytesWithTTL gets the path, and caches in the session. Returns bytes from the cache, if found and the TTL isn't expired. Otherwise, gets it and store it in cache -func (to *Session) getBytesWithTTL(path string, ttl int64) ([]byte, ReqInf, error) { - var body []byte - var err error - var cacheHitStatus CacheHitStatus - var remoteAddr net.Addr - - getFresh := false - if cacheEntry, ok := to.getCache(path); ok { - if cacheEntry.Entered > time.Now().Unix()-ttl { - cacheHitStatus = CacheHitStatusHit - body = cacheEntry.Bytes - remoteAddr = cacheEntry.RemoteAddr - } else { - cacheHitStatus = CacheHitStatusExpired - getFresh = true - } - } else { - cacheHitStatus = CacheHitStatusMiss - getFresh = true - } - - if getFresh { - body, remoteAddr, err = to.getBytes(path) - if err != nil { - return nil, ReqInf{CacheHitStatus: CacheHitStatusInvalid, RemoteAddr: remoteAddr}, err - } - - newEntry := CacheEntry{ - Entered: time.Now().Unix(), - Bytes: body, - RemoteAddr: remoteAddr, - } - to.setCache(path, newEntry) - } - - return body, ReqInf{CacheHitStatus: cacheHitStatus, RemoteAddr: remoteAddr}, nil -} - -// GetBytes - get []bytes array for a certain path on the to session. -// returns the raw body, the remote address the Traffic Ops URL resolved to, or any error. If the error is not nil, the RemoteAddr may or may not be nil, depending whether the error occurred before the request was executed. -func (to *Session) getBytes(path string) ([]byte, net.Addr, error) { - resp, remoteAddr, err := to.request("GET", path, nil) - if err != nil { - return nil, remoteAddr, err - } - defer resp.Body.Close() - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, remoteAddr, err - } - - return body, remoteAddr, nil -} diff --git a/traffic_ops/v2-client/staticdnsentry.go b/traffic_ops/v2-client/staticdnsentry.go deleted file mode 100644 index ba60d1d819..0000000000 --- a/traffic_ops/v2-client/staticdnsentry.go +++ /dev/null @@ -1,180 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "errors" - "fmt" - "net" - "net/http" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_STATIC_DNS_ENTRIES = apiBase + "/staticdnsentries" -) - -func staticDNSEntryIDs(to *Session, sdns *tc.StaticDNSEntry) error { - if sdns.CacheGroupID == 0 && sdns.CacheGroupName != "" { - p, _, err := to.GetCacheGroupNullableByName(sdns.CacheGroupName) - if err != nil { - return err - } - if len(p) == 0 { - return errors.New("no CacheGroup named " + sdns.CacheGroupName) - } - if p[0].ID == nil { - return errors.New("CacheGroup named " + sdns.CacheGroupName + " has a nil ID") - } - sdns.CacheGroupID = *p[0].ID - } - - if sdns.DeliveryServiceID == 0 && sdns.DeliveryService != "" { - dses, _, err := to.GetDeliveryServiceByXMLIDNullable(sdns.DeliveryService) - if err != nil { - return err - } - if len(dses) == 0 { - return errors.New("no deliveryservice with name " + sdns.DeliveryService) - } - if dses[0].ID == nil { - return errors.New("Deliveryservice with name " + sdns.DeliveryService + " has a nil ID") - } - sdns.DeliveryServiceID = *dses[0].ID - } - - if sdns.TypeID == 0 && sdns.Type != "" { - types, _, err := to.GetTypeByName(sdns.Type) - if err != nil { - return err - } - if len(types) == 0 { - return errors.New("no type with name " + sdns.Type) - } - sdns.TypeID = types[0].ID - } - - return nil -} - -// CreateStaticDNSEntry creates a Static DNS Entry. -func (to *Session) CreateStaticDNSEntry(sdns tc.StaticDNSEntry) (tc.Alerts, ReqInf, error) { - // fill in missing IDs from names - staticDNSEntryIDs(to, &sdns) - var remoteAddr net.Addr - reqBody, err := json.Marshal(sdns) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - resp, remoteAddr, err := to.request(http.MethodPost, API_STATIC_DNS_ENTRIES, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// UpdateStaticDNSEntryByID updates a Static DNS Entry by ID. -func (to *Session) UpdateStaticDNSEntryByID(id int, sdns tc.StaticDNSEntry) (tc.Alerts, ReqInf, int, error) { - // fill in missing IDs from names - staticDNSEntryIDs(to, &sdns) - var remoteAddr net.Addr - reqBody, err := json.Marshal(sdns) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, 0, err - } - route := fmt.Sprintf("%s?id=%d", API_STATIC_DNS_ENTRIES, id) - resp, remoteAddr, errClient := to.RawRequest(http.MethodPut, route, reqBody) - if resp != nil { - defer resp.Body.Close() - var alerts tc.Alerts - if err = json.NewDecoder(resp.Body).Decode(&alerts); err != nil { - return alerts, reqInf, resp.StatusCode, err - } - return alerts, reqInf, resp.StatusCode, errClient - } - return tc.Alerts{}, reqInf, 0, errClient -} - -// GetStaticDNSEntries returns a list of Static DNS Entrys. -func (to *Session) GetStaticDNSEntries() ([]tc.StaticDNSEntry, ReqInf, error) { - resp, remoteAddr, err := to.request(http.MethodGet, API_STATIC_DNS_ENTRIES, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.StaticDNSEntriesResponse - err = json.NewDecoder(resp.Body).Decode(&data) - return data.Response, reqInf, nil -} - -// GetStaticDNSEntryByID GETs a Static DNS Entry by the Static DNS Entry's ID. -func (to *Session) GetStaticDNSEntryByID(id int) ([]tc.StaticDNSEntry, ReqInf, error) { - route := fmt.Sprintf("%s?id=%d", API_STATIC_DNS_ENTRIES, id) - resp, remoteAddr, err := to.request(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.StaticDNSEntriesResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GetStaticDNSEntriesByHost GETs a Static DNS Entry by the Static DNS Entry's host. -func (to *Session) GetStaticDNSEntriesByHost(host string) ([]tc.StaticDNSEntry, ReqInf, error) { - url := fmt.Sprintf("%s?host=%s", API_STATIC_DNS_ENTRIES, host) - resp, remoteAddr, err := to.request(http.MethodGet, url, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.StaticDNSEntriesResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// DeleteStaticDNSEntryByID DELETEs a Static DNS Entry by ID. -func (to *Session) DeleteStaticDNSEntryByID(id int) (tc.Alerts, ReqInf, error) { - route := fmt.Sprintf("%s?id=%d", API_STATIC_DNS_ENTRIES, id) - resp, remoteAddr, err := to.request(http.MethodDelete, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} diff --git a/traffic_ops/v2-client/stats_summary.go b/traffic_ops/v2-client/stats_summary.go deleted file mode 100644 index cdf3122457..0000000000 --- a/traffic_ops/v2-client/stats_summary.go +++ /dev/null @@ -1,77 +0,0 @@ -/* - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "fmt" - "net" - "net/url" - - tc "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_STATS_SUMMARY = apiBase + "/stats_summary" -) - -// GetSummaryStats gets a list of summary stats with the ability to filter on cdn,deliveryService and/or stat -func (to *Session) GetSummaryStats(cdn, deliveryService, statName *string) (tc.StatsSummaryResponse, ReqInf, error) { - resp := tc.StatsSummaryResponse{} - - param := url.Values{} - if cdn != nil { - param.Add("cdnName", *cdn) - } - if deliveryService != nil { - param.Add("deliveryServiceName", *deliveryService) - } - if statName != nil { - param.Add("statName", *statName) - } - - url := API_STATS_SUMMARY - if len(param) > 0 { - url = fmt.Sprintf("%s?%s", API_STATS_SUMMARY, param.Encode()) - } - reqInf, err := get(to, url, &resp) - return resp, reqInf, err -} - -// GetSummaryStatsLastUpdated time of the last summary for a given stat -func (to *Session) GetSummaryStatsLastUpdated(statName *string) (tc.StatsSummaryLastUpdatedResponse, ReqInf, error) { - resp := tc.StatsSummaryLastUpdatedResponse{} - - param := url.Values{} - param.Add("lastSummaryDate", "true") - if statName != nil { - param.Add("statName", *statName) - } - url := fmt.Sprintf("%s?%s", API_STATS_SUMMARY, param.Encode()) - - reqInf, err := get(to, url, &resp) - return resp, reqInf, err -} - -// CreateSummaryStats creates a stats summary -func (to *Session) CreateSummaryStats(statsSummary tc.StatsSummary) (tc.Alerts, ReqInf, error) { - var alerts tc.Alerts - var remoteAddr net.Addr - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - reqBody, err := json.Marshal(statsSummary) - if err != nil { - return tc.Alerts{}, reqInf, err - } - reqInf, err = post(to, API_STATS_SUMMARY, reqBody, &alerts) - return alerts, reqInf, err -} diff --git a/traffic_ops/v2-client/status.go b/traffic_ops/v2-client/status.go deleted file mode 100644 index fa7f81acd7..0000000000 --- a/traffic_ops/v2-client/status.go +++ /dev/null @@ -1,132 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "fmt" - "net" - "net/http" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_STATUSES = apiBase + "/statuses" -) - -// CreateStatusNullable creates a new status, using the tc.StatusNullable structure. -func (to *Session) CreateStatusNullable(status tc.StatusNullable) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(status) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - resp, remoteAddr, err := to.request(http.MethodPost, API_STATUSES, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// UpdateStatusByID updates a Status by ID. -func (to *Session) UpdateStatusByID(id int, status tc.Status) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(status) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - route := fmt.Sprintf("%s/%d", API_STATUSES, id) - resp, remoteAddr, err := to.request(http.MethodPut, route, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// GetStatuses returns a list of Statuses. -func (to *Session) GetStatuses() ([]tc.Status, ReqInf, error) { - resp, remoteAddr, err := to.request(http.MethodGet, API_STATUSES, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.StatusesResponse - err = json.NewDecoder(resp.Body).Decode(&data) - return data.Response, reqInf, nil -} - -// GetStatusByID GETs a Status by the Status ID. -func (to *Session) GetStatusByID(id int) ([]tc.Status, ReqInf, error) { - route := fmt.Sprintf("%s?id=%d", API_STATUSES, id) - resp, remoteAddr, err := to.request(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.StatusesResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GetStatusByName GETs a Status by the Status name. -func (to *Session) GetStatusByName(name string) ([]tc.Status, ReqInf, error) { - url := fmt.Sprintf("%s?name=%s", API_STATUSES, name) - resp, remoteAddr, err := to.request(http.MethodGet, url, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.StatusesResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// DeleteStatusByID DELETEs a Status by ID. -func (to *Session) DeleteStatusByID(id int) (tc.Alerts, ReqInf, error) { - route := fmt.Sprintf("%s/%d", API_STATUSES, id) - resp, remoteAddr, err := to.request(http.MethodDelete, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} diff --git a/traffic_ops/v2-client/steering.go b/traffic_ops/v2-client/steering.go deleted file mode 100644 index 1d1b2327d7..0000000000 --- a/traffic_ops/v2-client/steering.go +++ /dev/null @@ -1,38 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "net/http" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -func (to *Session) Steering() ([]tc.Steering, ReqInf, error) { - resp, remoteAddr, err := to.request(http.MethodGet, apiBase+`/steering`, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - data := struct { - Response []tc.Steering `json:"response"` - }{} - err = json.NewDecoder(resp.Body).Decode(&data) - return data.Response, reqInf, err -} diff --git a/traffic_ops/v2-client/steeringtarget.go b/traffic_ops/v2-client/steeringtarget.go deleted file mode 100644 index a855ceccfc..0000000000 --- a/traffic_ops/v2-client/steeringtarget.go +++ /dev/null @@ -1,96 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "errors" - "net/http" - "strconv" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -func (to *Session) CreateSteeringTarget(st tc.SteeringTargetNullable) (tc.Alerts, ReqInf, error) { - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss} - if st.DeliveryServiceID == nil { - return tc.Alerts{}, reqInf, errors.New("missing delivery service id") - } - reqBody, err := json.Marshal(st) - if err != nil { - return tc.Alerts{}, reqInf, err - } - - resp := (*http.Response)(nil) - if resp, reqInf.RemoteAddr, err = to.request(http.MethodPost, apiBase+`/steering/`+strconv.Itoa(int(*st.DeliveryServiceID))+`/targets`, reqBody); err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - alerts := tc.Alerts{} - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, err -} - -func (to *Session) UpdateSteeringTarget(st tc.SteeringTargetNullable) (tc.Alerts, ReqInf, error) { - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss} - if st.DeliveryServiceID == nil { - return tc.Alerts{}, reqInf, errors.New("missing delivery service id") - } - if st.TargetID == nil { - return tc.Alerts{}, reqInf, errors.New("missing target id") - } - - reqBody, err := json.Marshal(st) - if err != nil { - return tc.Alerts{}, reqInf, err - } - resp := (*http.Response)(nil) - resp, reqInf.RemoteAddr, err = to.request(http.MethodPut, apiBase+`/steering/`+strconv.Itoa(int(*st.DeliveryServiceID))+`/targets/`+strconv.Itoa(int(*st.TargetID)), reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - alerts := tc.Alerts{} - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, err -} - -func (to *Session) GetSteeringTargets(dsID int) ([]tc.SteeringTargetNullable, ReqInf, error) { - resp, remoteAddr, err := to.request(http.MethodGet, apiBase+`/steering/`+strconv.Itoa(dsID)+`/targets`, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - data := struct { - Response []tc.SteeringTargetNullable `json:"response"` - }{} - err = json.NewDecoder(resp.Body).Decode(&data) - return data.Response, reqInf, err -} - -func (to *Session) DeleteSteeringTarget(dsID int, targetID int) (tc.Alerts, ReqInf, error) { - resp, remoteAddr, err := to.request(http.MethodDelete, apiBase+`/steering/`+strconv.Itoa(dsID)+`/targets/`+strconv.Itoa(targetID), nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - alerts := tc.Alerts{} - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, err -} diff --git a/traffic_ops/v2-client/tenant.go b/traffic_ops/v2-client/tenant.go deleted file mode 100644 index 9f8ca7c950..0000000000 --- a/traffic_ops/v2-client/tenant.go +++ /dev/null @@ -1,122 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "errors" - "fmt" - "net/url" - - tc "github.com/apache/trafficcontrol/lib/go-tc" -) - -const API_TENANTS = apiBase + "/tenants" -const API_TENANT_ID = API_TENANTS + "/%v" - -// Tenants gets an array of Tenants. -func (to *Session) Tenants() ([]tc.Tenant, ReqInf, error) { - var data tc.GetTenantsResponse - reqInf, err := get(to, API_TENANTS, &data) - if err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// Tenant gets the Tenant identified by the passed integral, unique identifer - which -// must be passed as a string. -func (to *Session) Tenant(id string) (*tc.Tenant, ReqInf, error) { - var data tc.GetTenantsResponse - reqInf, err := get(to, fmt.Sprintf("%s?id=%v", API_TENANTS, id), &data) - if err != nil { - return nil, reqInf, err - } - - return &data.Response[0], reqInf, nil -} - -// TenantByName gets the Tenant with the name it's passed. -func (to *Session) TenantByName(name string) (*tc.Tenant, ReqInf, error) { - var data tc.GetTenantsResponse - query := API_TENANTS + "?name=" + url.QueryEscape(name) - reqInf, err := get(to, query, &data) - if err != nil { - return nil, reqInf, err - } - - var ten *tc.Tenant - if len(data.Response) > 0 { - ten = &data.Response[0] - } else { - err = errors.New("no tenant found with name " + name) - } - return ten, reqInf, err -} - -// CreateTenant creates the Tenant it's passed. -func (to *Session) CreateTenant(t *tc.Tenant) (*tc.TenantResponse, error) { - if t.ParentID == 0 && t.ParentName != "" { - tenant, _, err := to.TenantByName(t.ParentName) - if err != nil { - return nil, err - } - if tenant == nil { - return nil, errors.New("no tenant with name " + t.ParentName) - } - t.ParentID = tenant.ID - } - - var data tc.TenantResponse - jsonReq, err := json.Marshal(t) - if err != nil { - return nil, err - } - _, err = post(to, API_TENANTS, jsonReq, &data) - if err != nil { - return nil, err - } - - return &data, nil -} - -// UpdateTenant updates the Tenant matching the ID it's passed with -// the Tenant it is passed. -func (to *Session) UpdateTenant(id string, t *tc.Tenant) (*tc.TenantResponse, error) { - var data tc.TenantResponse - jsonReq, err := json.Marshal(t) - if err != nil { - return nil, err - } - _, err = put(to, fmt.Sprintf(API_TENANT_ID, id), jsonReq, &data) - if err != nil { - return nil, err - } - - return &data, nil -} - -// DeleteTenant deletes the Tenant matching the ID it's passed. -func (to *Session) DeleteTenant(id string) (*tc.DeleteTenantResponse, error) { - var data tc.DeleteTenantResponse - _, err := del(to, fmt.Sprintf(API_TENANT_ID, id), &data) - if err != nil { - return nil, err - } - - return &data, nil -} diff --git a/traffic_ops/v2-client/traffic_monitor.go b/traffic_ops/v2-client/traffic_monitor.go deleted file mode 100644 index 52804a569a..0000000000 --- a/traffic_ops/v2-client/traffic_monitor.go +++ /dev/null @@ -1,65 +0,0 @@ -package client - -import ( - "encoding/json" - "fmt" - - "github.com/apache/trafficcontrol/lib/go-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. - */ - -// API_CDN_MONITORING_CONFIG is the API path on which Traffic Ops serves the CDN monitoring -// configuration information. It is meant to be used with fmt.Sprintf to insert the necessary -// path parameters (namely the Name of the CDN of interest). -// See Also: https://traffic-control-cdn.readthedocs.io/en/latest/api/v2/cdns_name_configs_monitoring.html -const API_CDN_MONITORING_CONFIG = apiBase + "/cdns/%s/configs/monitoring" - -// GetTrafficMonitorConfigMap is functionally identical to GetTrafficMonitorConfig, except that it -// coerces the value returned by the API to the tc.LegacyTrafficMonitorConfigMap structure. -func (to *Session) GetTrafficMonitorConfigMap(cdn string) (*tc.LegacyTrafficMonitorConfigMap, ReqInf, error) { - tmConfig, reqInf, err := to.GetTrafficMonitorConfig(cdn) - if err != nil { - return nil, reqInf, err - } - tmConfigMap, err := tc.LegacyTrafficMonitorTransformToMap(tmConfig) - if err != nil { - return tmConfigMap, reqInf, err - } - return tmConfigMap, reqInf, nil -} - -// GetTrafficMonitorConfig returns the monitoring configuration for the CDN named by 'cdn'. -func (to *Session) GetTrafficMonitorConfig(cdn string) (*tc.LegacyTrafficMonitorConfig, ReqInf, error) { - url := fmt.Sprintf(API_CDN_MONITORING_CONFIG, cdn) - resp, remoteAddr, err := to.request("GET", url, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.LegacyTMConfigResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return &data.Response, reqInf, nil -} diff --git a/traffic_ops/v2-client/traffic_stats.go b/traffic_ops/v2-client/traffic_stats.go deleted file mode 100644 index 8f163d9ca5..0000000000 --- a/traffic_ops/v2-client/traffic_stats.go +++ /dev/null @@ -1,29 +0,0 @@ -package client - -/* - Licensed 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 ( - "github.com/apache/trafficcontrol/lib/go-tc" -) - -// GetCurrentStats gets current stats for each CDNs and a total across them -func (to *Session) GetCurrentStats() (tc.TrafficStatsCDNStatsResponse, ReqInf, error) { - resp := tc.TrafficStatsCDNStatsResponse{} - reqInf, err := get(to, apiBase+"/current_stats", &resp) - if err != nil { - return resp, reqInf, err - } - return resp, reqInf, nil -} diff --git a/traffic_ops/v2-client/type.go b/traffic_ops/v2-client/type.go deleted file mode 100644 index a610255865..0000000000 --- a/traffic_ops/v2-client/type.go +++ /dev/null @@ -1,153 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "errors" - "fmt" - "net" - "net/http" - - "github.com/apache/trafficcontrol/lib/go-tc" -) - -const ( - API_TYPES = apiBase + "/types" -) - -// CreateType creates a Type. There should be a very good reason for doing this. -func (to *Session) CreateType(typ tc.Type) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(typ) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - resp, remoteAddr, err := to.request(http.MethodPost, API_TYPES, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// UpdateTypeByID updates a Type by ID. -func (to *Session) UpdateTypeByID(id int, typ tc.Type) (tc.Alerts, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(typ) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - route := fmt.Sprintf("%s/%d", API_TYPES, id) - resp, remoteAddr, err := to.request(http.MethodPut, route, reqBody) - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// GetTypes returns a list of Types. If a 'useInTable' parameter is passed, the returned Types -// are restricted to those with that exact 'useInTable' property. Only exactly 1 or exactly 0 -// 'useInTable' parameters may be passed; passing more will result in an error being returned. -func (to *Session) GetTypes(useInTable ...string) ([]tc.Type, ReqInf, error) { - if len(useInTable) > 1 { - return nil, ReqInf{}, errors.New("Please pass in a single value for the 'useInTable' parameter") - } - - resp, remoteAddr, err := to.request("GET", API_TYPES, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.TypesResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - var types []tc.Type - for _, d := range data.Response { - if useInTable != nil { - if d.UseInTable == useInTable[0] { - types = append(types, d) - } - } else { - types = append(types, d) - } - } - - return types, reqInf, nil -} - -// GetTypeByID GETs a Type by the Type ID. -func (to *Session) GetTypeByID(id int) ([]tc.Type, ReqInf, error) { - route := fmt.Sprintf("%s?id=%d", API_TYPES, id) - resp, remoteAddr, err := to.request(http.MethodGet, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.TypesResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// GetTypeByName GET a Type by the Type name. -func (to *Session) GetTypeByName(name string) ([]tc.Type, ReqInf, error) { - url := fmt.Sprintf("%s?name=%s", API_TYPES, name) - resp, remoteAddr, err := to.request(http.MethodGet, url, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var data tc.TypesResponse - if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { - return nil, reqInf, err - } - - return data.Response, reqInf, nil -} - -// DeleteTypeByID DELETEs a Type by ID. -func (to *Session) DeleteTypeByID(id int) (tc.Alerts, ReqInf, error) { - route := fmt.Sprintf("%s/%d", API_TYPES, id) - resp, remoteAddr, err := to.request(http.MethodDelete, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} diff --git a/traffic_ops/v2-client/user.go b/traffic_ops/v2-client/user.go deleted file mode 100644 index ebea67bb09..0000000000 --- a/traffic_ops/v2-client/user.go +++ /dev/null @@ -1,202 +0,0 @@ -package client - -/* - - Licensed 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 ( - "encoding/json" - "errors" - "fmt" - "net" - "net/http" - "net/url" - "strconv" - - "github.com/apache/trafficcontrol/lib/go-rfc" - "github.com/apache/trafficcontrol/lib/go-tc" -) - -// GetUsers returns all users accessible from current user -func (to *Session) GetUsers() ([]tc.User, ReqInf, error) { - data := tc.UsersResponse{} - route := fmt.Sprintf("%s/users", apiBase) - inf, err := get(to, route, &data) - return data.Response, inf, err -} - -// GetUsersByRole returns all users accessible from current user for a given role -func (to *Session) GetUsersByRole(roleName string) ([]tc.User, ReqInf, error) { - data := tc.UsersResponse{} - route := fmt.Sprintf("%s/users?role=%s", apiBase, url.QueryEscape(roleName)) - inf, err := get(to, route, &data) - return data.Response, inf, err -} - -func (to *Session) GetUserByID(id int) ([]tc.User, ReqInf, error) { - data := tc.UsersResponse{} - route := fmt.Sprintf("%s/users/%d", apiBase, id) - inf, err := get(to, route, &data) - return data.Response, inf, err -} - -func (to *Session) GetUserByUsername(username string) ([]tc.User, ReqInf, error) { - data := tc.UsersResponse{} - route := fmt.Sprintf("%s/users?username=%s", apiBase, username) - inf, err := get(to, route, &data) - return data.Response, inf, err -} - -// GetUserCurrent gets information about the current user -func (to *Session) GetUserCurrent() (*tc.UserCurrent, ReqInf, error) { - route := apiBase + `/user/current` - resp := tc.UserCurrentResponse{} - reqInf, err := get(to, route, &resp) - if err != nil { - return nil, reqInf, err - } - return &resp.Response, reqInf, nil -} - -// UpdateCurrentUser replaces the current user data with the provided tc.User structure. -func (to *Session) UpdateCurrentUser(u tc.User) (*tc.UpdateUserResponse, ReqInf, error) { - var a net.Addr - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: a} - - user := struct { - User tc.User `json:"user"` - }{u} - reqBody, err := json.Marshal(user) - if err != nil { - return nil, reqInf, err - } - - var resp *http.Response - resp, reqInf.RemoteAddr, err = to.request(http.MethodPut, apiBase+"/user/current", reqBody) - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - - var clientResp tc.UpdateUserResponse - err = json.NewDecoder(resp.Body).Decode(&clientResp) - return &clientResp, reqInf, err -} - -// CreateUser creates a user -func (to *Session) CreateUser(user *tc.User) (*tc.CreateUserResponse, ReqInf, error) { - if user.TenantID == nil && user.Tenant != nil { - tenant, _, err := to.TenantByName(*user.Tenant) - if err != nil { - return nil, ReqInf{}, err - } - if tenant == nil { - return nil, ReqInf{}, errors.New("no tenant with name " + *user.Tenant) - } - if err != nil { - return nil, ReqInf{}, err - } - user.TenantID = &tenant.ID - } - - if user.RoleName != nil && *user.RoleName != "" { - roles, _, _, err := to.GetRoleByName(*user.RoleName) - if err != nil { - return nil, ReqInf{}, err - } - if len(roles) == 0 || roles[0].ID == nil { - return nil, ReqInf{}, errors.New("no role with name " + *user.RoleName) - } - if err != nil { - return nil, ReqInf{}, err - } - user.Role = roles[0].ID - } - - var remoteAddr net.Addr - reqBody, err := json.Marshal(user) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - route := apiBase + "/users" - resp, remoteAddr, err := to.request(http.MethodPost, route, reqBody) - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - var clientResp tc.CreateUserResponse - err = json.NewDecoder(resp.Body).Decode(&clientResp) - return &clientResp, reqInf, nil -} - -// UpdateUserByID updates user with the given id -func (to *Session) UpdateUserByID(id int, u *tc.User) (*tc.UpdateUserResponse, ReqInf, error) { - - var remoteAddr net.Addr - reqBody, err := json.Marshal(u) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return nil, reqInf, err - } - route := apiBase + "/users/" + strconv.Itoa(id) - resp, remoteAddr, err := to.request(http.MethodPut, route, reqBody) - if err != nil { - return nil, reqInf, err - } - defer resp.Body.Close() - var clientResp tc.UpdateUserResponse - err = json.NewDecoder(resp.Body).Decode(&clientResp) - return &clientResp, reqInf, nil -} - -// DeleteUserByID updates user with the given id -func (to *Session) DeleteUserByID(id int) (tc.Alerts, ReqInf, error) { - route := apiBase + "/users/" + strconv.Itoa(id) - resp, remoteAddr, err := to.request(http.MethodDelete, route, nil) - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr} - if err != nil { - return tc.Alerts{}, reqInf, err - } - defer resp.Body.Close() - var alerts tc.Alerts - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, nil -} - -// RegisterNewUser requests the registration of a new user with the given tenant ID and role ID, -// through their email. -func (to *Session) RegisterNewUser(tenantID uint, roleID uint, email rfc.EmailAddress) (tc.Alerts, ReqInf, error) { - reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss} - var alerts tc.Alerts - - reqBody, err := json.Marshal(tc.UserRegistrationRequest{ - Email: email, - TenantID: tenantID, - Role: roleID, - }) - if err != nil { - return alerts, reqInf, err - } - - resp, remoteAddr, err := to.request(http.MethodPost, apiBase+"/users/register", reqBody) - reqInf.RemoteAddr = remoteAddr - if err != nil { - return alerts, reqInf, err - } - defer resp.Body.Close() - - err = json.NewDecoder(resp.Body).Decode(&alerts) - return alerts, reqInf, err -} diff --git a/traffic_ops/v2-client/util.go b/traffic_ops/v2-client/util.go deleted file mode 100644 index ec718c9cfc..0000000000 --- a/traffic_ops/v2-client/util.go +++ /dev/null @@ -1,71 +0,0 @@ -/* - - Licensed 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. -*/ - -package client - -import ( - "encoding/json" - "errors" - "io/ioutil" -) - -func get(to *Session, endpoint string, respStruct interface{}) (ReqInf, error) { - return makeReq(to, "GET", endpoint, nil, respStruct) -} - -func post(to *Session, endpoint string, body []byte, respStruct interface{}) (ReqInf, error) { - return makeReq(to, "POST", endpoint, body, respStruct) -} - -func put(to *Session, endpoint string, body []byte, respStruct interface{}) (ReqInf, error) { - return makeReq(to, "PUT", endpoint, body, respStruct) -} - -func del(to *Session, endpoint string, respStruct interface{}) (ReqInf, error) { - return makeReq(to, "DELETE", endpoint, nil, respStruct) -} - -func makeReq(to *Session, method, endpoint string, body []byte, respStruct interface{}) (ReqInf, error) { - resp, remoteAddr, err := to.request(method, endpoint, body) // TODO change to getBytesWithTTL - reqInf := ReqInf{RemoteAddr: remoteAddr, CacheHitStatus: CacheHitStatusMiss} - if err != nil { - return reqInf, err - } - defer resp.Body.Close() - - bts, err := ioutil.ReadAll(resp.Body) - if err != nil { - return reqInf, errors.New("reading body: " + err.Error()) - } - - if err := json.Unmarshal(bts, respStruct); err != nil { - return reqInf, errors.New("unmarshalling body '" + string(body) + "': " + err.Error()) - } - - return reqInf, nil -} - -func mapToQueryParameters(params map[string]string) string { - path := "" - for key, value := range params { - if path == "" { - path += "?" - } else { - path += "&" - } - path += key + "=" + value - } - return path -} From b9485faabc84672c1d463cc3d01deea3ac3ca20b Mon Sep 17 00:00:00 2001 From: Zach Hoffman Date: Thu, 7 Jul 2022 13:27:30 -0600 Subject: [PATCH 03/14] Use latest to-api-cdns-dnsseckeys-generate label in Python Traffic Ops client --- traffic_control/clients/python/trafficops/tosession.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/traffic_control/clients/python/trafficops/tosession.py b/traffic_control/clients/python/trafficops/tosession.py index 77d5fd846a..17b575f569 100644 --- a/traffic_control/clients/python/trafficops/tosession.py +++ b/traffic_control/clients/python/trafficops/tosession.py @@ -604,7 +604,7 @@ def delete_cdn_dns_sec_keys(self, cdn_name=None): def create_cdn_dns_sec_keys(self, data=None): """ Generates ZSK and KSK keypairs for a CDN and all associated Delivery Services - :ref:`to-api-v2-cdns-dnsseckeys-generate` + :ref:`to-api-cdns-dnsseckeys-generate` :param data: The parameter data to use for cachegroup creation. :type data: Dict[str, Any] :rtype: Tuple[Dict[str, Any], requests.Response] From ebd5eaeed9c78f86ef34e712cc4667d3d97627d8 Mon Sep 17 00:00:00 2001 From: Zach Hoffman Date: Tue, 28 Jun 2022 10:12:32 -0600 Subject: [PATCH 04/14] Remove Traffic Ops API v2 routes --- CHANGELOG.md | 1 + .../traffic_ops_golang/routing/routes.go | 364 ------------------ 2 files changed, 1 insertion(+), 364 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ddbbd227f..3c76258c0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -72,6 +72,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/). - Removed the Traffic Monitor `peer_polling_protocol` option. Traffic Monitor now just uses hostnames to request peer states, which can be handled via IPv4 or IPv6 depending on the underlying IP version in use. - Dropped CentOS 8 support - The `/servers/details` endpoint of the Traffic Ops API has been dropped in version 4.0, and marked deprecated in earlier versions. +- Remove Traffic Ops API version 2 ### Changed - [#6694](https://github.com/apache/trafficcontrol/issues/6694) Traffic Stats now uses the TO API 3.0 diff --git a/traffic_ops/traffic_ops_golang/routing/routes.go b/traffic_ops/traffic_ops_golang/routing/routes.go index bdcfa2d277..f5c3b7bcf0 100644 --- a/traffic_ops/traffic_ops_golang/routing/routes.go +++ b/traffic_ops/traffic_ops_golang/routing/routes.go @@ -912,370 +912,6 @@ func Routes(d ServerData) ([]Route, http.Handler, error) { // Plugins {Version: api.Version{Major: 3, Minor: 0}, Method: http.MethodGet, Path: `plugins/?$`, Handler: plugins.Get(d.Plugins), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2834985393}, - - /** - * 2.x API - */ - // API Capability - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `api_capabilities/?$`, Handler: apicapability.GetAPICapabilitiesHandler, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2813206589}, - - //ASNs - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `asns/?$`, Handler: api.UpdateHandler(&asn.TOASNV11{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2264172317}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `asns/?$`, Handler: api.DeleteHandler(&asn.TOASNV11{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 20204898}, - - //ASN: CRUD - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `asns/?$`, Handler: api.ReadHandler(&asn.TOASNV11{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 273877722}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `asns/{id}$`, Handler: api.UpdateHandler(&asn.TOASNV11{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2951198629}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `asns/?$`, Handler: api.CreateHandler(&asn.TOASNV11{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2999492188}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `asns/{id}$`, Handler: api.DeleteHandler(&asn.TOASNV11{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2672524769}, - - // Traffic Stats access - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `deliveryservice_stats`, Handler: trafficstats.GetDSStats, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2319569028}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `cache_stats`, Handler: trafficstats.GetCacheStats, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2497997906}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `current_stats/?$`, Handler: trafficstats.GetCurrentStats, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2785442893}, - - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `caches/stats/?$`, Handler: cachesstats.Get, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2813206588}, - - //CacheGroup: CRUD - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `cachegroups/?$`, Handler: api.ReadHandler(&cachegroup.TOCacheGroup{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 223079110}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `cachegroups/{id}$`, Handler: api.UpdateHandler(&cachegroup.TOCacheGroup{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 212954546}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `cachegroups/?$`, Handler: api.CreateHandler(&cachegroup.TOCacheGroup{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 22982665}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `cachegroups/{id}$`, Handler: api.DeleteHandler(&cachegroup.TOCacheGroup{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 227869365}, - - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `cachegroups/{id}/queue_update$`, Handler: cachegroup.QueueUpdates, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2071644110}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `cachegroups/{id}/deliveryservices/?$`, Handler: cachegroup.DSPostHandlerV31, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2520240431}, - - //CacheGroup Parameters: CRUD - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `cachegroupparameters/?$`, Handler: cachegroupparameter.ReadAllCacheGroupParameters, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 212449724}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `cachegroupparameters/?$`, Handler: cachegroupparameter.AddCacheGroupParameters, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 212449725}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `cachegroups/{id}/parameters/?$`, Handler: api.DeprecatedReadHandler(&cachegroupparameter.TOCacheGroupParameter{}, nil), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 212449723}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `cachegroupparameters/{cachegroupID}/{parameterId}$`, Handler: api.DeprecatedDeleteHandler(&cachegroupparameter.TOCacheGroupParameter{}, nil), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 212449733}, - - //Capabilities - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `capabilities/?$`, Handler: capabilities.Read, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2008135}, - - //CDN - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `cdns/name/{name}/sslkeys/?$`, Handler: cdn.GetSSLKeys, RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2278581772}, - - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `cdns/capacity$`, Handler: cdn.GetCapacity, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 297185281}, - - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `cdns/{name}/health/?$`, Handler: cdn.GetNameHealth, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2135348194}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `cdns/health/?$`, Handler: cdn.GetHealth, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2085381134}, - - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `cdns/domains/?$`, Handler: cdn.DomainsHandler, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 226902560}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `cdns/routing$`, Handler: crstats.GetCDNRouting, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 26722982}, - - //CDN: CRUD - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `cdns/name/{name}$`, Handler: cdn.DeleteName, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 208804959}, - - //CDN: queue updates - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `cdns/{id}/queue_update$`, Handler: cdn.Queue, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 221515980}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `cdns/dnsseckeys/generate?$`, Handler: cdn.CreateDNSSECKeys, RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 275336}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `cdns/name/{name}/dnsseckeys?$`, Handler: cdn.DeleteDNSSECKeys, RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 271104207}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `cdns/name/{name}/dnsseckeys/?$`, Handler: cdn.GetDNSSECKeys, RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 279010609}, - - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `cdns/dnsseckeys/refresh/?$`, Handler: cdn.RefreshDNSSECKeys, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2771997116}, - - //CDN: Monitoring: Traffic Monitor - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `cdns/{cdn}/configs/monitoring?$`, Handler: crconfig.SnapshotGetMonitoringLegacyHandler, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2240847892}, - - //Database dumps - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `dbdump/?`, Handler: dbdump.DBDump, RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 224016647}, - - //Division: CRUD - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `divisions/?$`, Handler: api.ReadHandler(&division.TODivision{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2085181534}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `divisions/{id}$`, Handler: api.UpdateHandler(&division.TODivision{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 206369140}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `divisions/?$`, Handler: api.CreateHandler(&division.TODivision{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 253713800}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `divisions/{id}$`, Handler: api.DeleteHandler(&division.TODivision{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2325382237}, - - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `logs/?$`, Handler: logs.Get, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 248340550}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `logs/newcount/?$`, Handler: logs.GetNewCount, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2405833012}, - - //Content invalidation jobs - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `jobs/?$`, Handler: api.ReadHandler(&invalidationjobs.InvalidationJob{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2966782041}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `jobs/?$`, Handler: invalidationjobs.Delete, RequiredPrivLevel: auth.PrivLevelPortal, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 216780776}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `jobs/?$`, Handler: invalidationjobs.Update, RequiredPrivLevel: auth.PrivLevelPortal, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 286134226}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `jobs/?`, Handler: invalidationjobs.Create, RequiredPrivLevel: auth.PrivLevelPortal, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 20450955}, - - //Login - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `user/login/?$`, Handler: login.LoginHandler(d.DB, d.Config), RequiredPrivLevel: auth.PrivLevelUnauthenticated, RequiredPermissions: nil, Authenticated: NoAuth, Middlewares: nil, ID: 2392670821}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `user/logout/?$`, Handler: login.LogoutHandler(d.Config.Secrets[0]), RequiredPrivLevel: auth.PrivLevelUnauthenticated, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 243434825}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `user/login/oauth/?$`, Handler: login.OauthLoginHandler(d.DB, d.Config), RequiredPrivLevel: auth.PrivLevelUnauthenticated, RequiredPermissions: nil, Authenticated: NoAuth, Middlewares: nil, ID: 2415886009}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `user/login/token/?$`, Handler: login.TokenLoginHandler(d.DB, d.Config), RequiredPrivLevel: auth.PrivLevelUnauthenticated, RequiredPermissions: nil, Authenticated: NoAuth, Middlewares: nil, ID: 202408841}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `user/reset_password/?$`, Handler: login.ResetPassword(d.DB, d.Config), RequiredPrivLevel: auth.PrivLevelUnauthenticated, RequiredPermissions: nil, Authenticated: NoAuth, Middlewares: nil, ID: 2292914630}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `users/register/?$`, Handler: login.RegisterUser, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2337}, - - //ISO - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `osversions/?$`, Handler: iso.GetOSVersions, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 276088657}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `isos/?$`, Handler: iso.ISOs, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 276033657}, - - //User: CRUD - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `users/?$`, Handler: api.ReadHandler(&user.TOUser{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2491929900}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `users/{id}$`, Handler: api.ReadHandler(&user.TOUser{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 213809980}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `users/{id}$`, Handler: api.UpdateHandler(&user.TOUser{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 235433404}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `users/?$`, Handler: api.CreateHandler(&user.TOUser{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 276244816}, - - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `user/current/?$`, Handler: user.Current, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2610701614}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `user/current/?$`, Handler: user.ReplaceCurrent, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 220}, - - //Parameter: CRUD - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `parameters/?$`, Handler: api.ReadHandler(¶meter.TOParameter{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2212554292}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `parameters/{id}$`, Handler: api.UpdateHandler(¶meter.TOParameter{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2873936115}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `parameters/?$`, Handler: api.CreateHandler(¶meter.TOParameter{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2669510859}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `parameters/{id}$`, Handler: api.DeleteHandler(¶meter.TOParameter{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 226277118}, - - //Phys_Location: CRUD - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `phys_locations/?$`, Handler: api.ReadHandler(&physlocation.TOPhysLocation{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 220405182}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `phys_locations/{id}$`, Handler: api.UpdateHandler(&physlocation.TOPhysLocation{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 222795021}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `phys_locations/?$`, Handler: api.CreateHandler(&physlocation.TOPhysLocation{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2246456648}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `phys_locations/{id}$`, Handler: api.DeleteHandler(&physlocation.TOPhysLocation{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 25614221}, - - //Ping - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `ping$`, Handler: ping.Handler, RequiredPrivLevel: auth.PrivLevelUnauthenticated, RequiredPermissions: nil, Authenticated: NoAuth, Middlewares: nil, ID: 2555661597}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `vault/ping/?$`, Handler: ping.Vault, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2884012114}, - - //Profile: CRUD - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `profiles/?$`, Handler: api.ReadHandler(&profile.TOProfile{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 268758589}, - - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `profiles/{id}$`, Handler: api.UpdateHandler(&profile.TOProfile{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 28439172}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `profiles/?$`, Handler: api.CreateHandler(&profile.TOProfile{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2540211556}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `profiles/{id}$`, Handler: api.DeleteHandler(&profile.TOProfile{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2205594465}, - - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `profiles/{id}/export/?$`, Handler: profile.ExportProfileHandler, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 20133517}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `profiles/import/?$`, Handler: profile.ImportProfileHandler, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 206143208}, - - // Copy Profile - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `profiles/name/{new_profile}/copy/{existing_profile}`, Handler: profile.CopyProfileHandler, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 206143209}, - - //Region: CRUDs - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `regions/?$`, Handler: api.ReadHandler(®ion.TORegion{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 210037085}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `regions/{id}$`, Handler: api.UpdateHandler(®ion.TORegion{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 222308224}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `regions/?$`, Handler: api.CreateHandler(®ion.TORegion{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2288334488}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `regions/?$`, Handler: api.DeleteHandler(®ion.TORegion{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2232626758}, - - // get all edge servers associated with a delivery service (from deliveryservice_server table) - - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `deliveryserviceserver/?$`, Handler: dsserver.ReadDSSHandler, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2946145033}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `deliveryserviceserver$`, Handler: dsserver.GetReplaceHandler, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 229799788}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `deliveryserviceserver/{dsid}/{serverid}`, Handler: dsserver.Delete, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2532184523}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `deliveryservices/{xml_id}/servers$`, Handler: dsserver.GetCreateHandler, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2428181206}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `servers/{id}/deliveryservices$`, Handler: api.ReadHandler(&dsserver.TODSSDeliveryService{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 233115411}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `servers/{id}/deliveryservices$`, Handler: server.AssignDeliveryServicesToServerHandler, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 280128253}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `deliveryservices/{id}/servers$`, Handler: dsserver.GetReadAssigned, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2345121223}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `deliveryservices/request`, Handler: deliveryservicerequests.Request, RequiredPrivLevel: auth.PrivLevelPortal, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 240875299}, - - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `deliveryservices/{id}/capacity/?$`, Handler: deliveryservice.GetCapacity, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2231409110}, - //Serverchecks - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `servercheck/?$`, Handler: servercheck.ReadServerCheck, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2796112922}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `servercheck/?$`, Handler: servercheck.CreateUpdateServercheck, RequiredPrivLevel: auth.PrivLevelInvalid, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2764281568}, - - // Servercheck Extensions - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `servercheck/extensions$`, Handler: extensions.Create, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 280498599}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `servercheck/extensions$`, Handler: extensions.Get, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 283498599}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `servercheck/extensions/{id}$`, Handler: extensions.Delete, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 280498299}, - - //Server Details - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `servers/details/?$`, Handler: server.GetDetailParamHandler, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2261264714}, - - //Server status - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `servers/{id}/status$`, Handler: server.UpdateStatusHandler, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 276663851}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `servers/{id}/queue_update$`, Handler: server.QueueUpdateHandler, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2189471}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `servers/{host_name}/update_status$`, Handler: server.GetServerUpdateStatusHandler, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 238451599}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `servers/{id-or-name}/update$`, Handler: server.UpdateHandler, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 14381323}, - - //Server: CRUD - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `servers/?$`, Handler: server.Read, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2720959285}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `servers/{id}$`, Handler: server.Update, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 258634103}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `servers/?$`, Handler: server.Create, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2225558061}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `servers/{id}$`, Handler: server.Delete, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 292322233}, - - //Server Capability - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `server_capabilities$`, Handler: api.ReadHandler(&servercapability.TOServerCapability{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 210407391}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `server_capabilities$`, Handler: api.CreateHandler(&servercapability.TOServerCapability{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2074470708}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `server_capabilities$`, Handler: api.DeleteHandler(&servercapability.TOServerCapability{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 236415038}, - - //Server Server Capabilities: CRUD - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `server_server_capabilities/?$`, Handler: api.ReadHandler(&server.TOServerServerCapability{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2800231889}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `server_server_capabilities/?$`, Handler: api.CreateHandler(&server.TOServerServerCapability{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2293166834}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `server_server_capabilities/?$`, Handler: api.DeleteHandler(&server.TOServerServerCapability{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2058714058}, - - //Status: CRUD - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `statuses/?$`, Handler: api.ReadHandler(&status.TOStatus{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2244905656}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `statuses/{id}$`, Handler: api.UpdateHandler(&status.TOStatus{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2207966504}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `statuses/?$`, Handler: api.CreateHandler(&status.TOStatus{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2369123612}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `statuses/{id}$`, Handler: api.DeleteHandler(&status.TOStatus{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 255111360}, - - //System - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `system/info/?$`, Handler: systeminfo.Get, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 221047475}, - - //Type: CRUD - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `types/?$`, Handler: api.ReadHandler(&types.TOType{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2226701823}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `types/{id}$`, Handler: api.UpdateHandler(&types.TOType{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 28860115}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `types/?$`, Handler: api.CreateHandler(&types.TOType{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2513308195}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `types/{id}$`, Handler: api.DeleteHandler(&types.TOType{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 23175773}, - - //About - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `about/?$`, Handler: about.Handler(), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2317501166}, - - //Coordinates - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `coordinates/?$`, Handler: api.ReadHandler(&coordinate.TOCoordinate{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 296700745}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `coordinates/?$`, Handler: api.UpdateHandler(&coordinate.TOCoordinate{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 268926174}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `coordinates/?$`, Handler: api.CreateHandler(&coordinate.TOCoordinate{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2428112157}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `coordinates/?$`, Handler: api.DeleteHandler(&coordinate.TOCoordinate{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2303849889}, - - //CDN generic handlers: - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `cdns/?$`, Handler: api.ReadHandler(&cdn.TOCDN{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2230318621}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `cdns/{id}$`, Handler: api.UpdateHandler(&cdn.TOCDN{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2311178934}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `cdns/?$`, Handler: api.CreateHandler(&cdn.TOCDN{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2160505289}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `cdns/{id}$`, Handler: api.DeleteHandler(&cdn.TOCDN{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 227694657}, - - //Delivery service requests - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `deliveryservice_requests/?$`, Handler: dsrequest.Get, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2681163935}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `deliveryservice_requests/?$`, Handler: dsrequest.Put, RequiredPrivLevel: auth.PrivLevelPortal, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2249907918}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `deliveryservice_requests/?$`, Handler: dsrequest.Post, RequiredPrivLevel: auth.PrivLevelPortal, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 29385039}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `deliveryservice_requests/?$`, Handler: dsrequest.Delete, RequiredPrivLevel: auth.PrivLevelPortal, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2296985025}, - - //Delivery service request: Actions - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `deliveryservice_requests/{id}/assign$`, Handler: dsrequest.PutAssignment, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2703160290}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `deliveryservice_requests/{id}/status$`, Handler: dsrequest.PutStatus, RequiredPrivLevel: auth.PrivLevelPortal, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 268415099}, - - //Delivery service request comment: CRUD - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `deliveryservice_request_comments/?$`, Handler: api.ReadHandler(&comment.TODeliveryServiceRequestComment{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2032650737}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `deliveryservice_request_comments/?$`, Handler: api.UpdateHandler(&comment.TODeliveryServiceRequestComment{}), RequiredPrivLevel: auth.PrivLevelPortal, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 260487847}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `deliveryservice_request_comments/?$`, Handler: api.CreateHandler(&comment.TODeliveryServiceRequestComment{}), RequiredPrivLevel: auth.PrivLevelPortal, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 227227672}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `deliveryservice_request_comments/?$`, Handler: api.DeleteHandler(&comment.TODeliveryServiceRequestComment{}), RequiredPrivLevel: auth.PrivLevelPortal, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 299504668}, - - //Delivery service uri signing keys: CRUD - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `deliveryservices/{xmlID}/urisignkeys$`, Handler: urisigning.GetURIsignkeysHandler, RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2293078558}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `deliveryservices/{xmlID}/urisignkeys$`, Handler: urisigning.SaveDeliveryServiceURIKeysHandler, RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 208466335}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `deliveryservices/{xmlID}/urisignkeys$`, Handler: urisigning.SaveDeliveryServiceURIKeysHandler, RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 27648969}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `deliveryservices/{xmlID}/urisignkeys$`, Handler: urisigning.RemoveDeliveryServiceURIKeysHandler, RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 229925417}, - - //Delivery Service Required Capabilities: CRUD - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `deliveryservices_required_capabilities/?$`, Handler: api.ReadHandler(&deliveryservice.RequiredCapability{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2158522227}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `deliveryservices_required_capabilities/?$`, Handler: api.CreateHandler(&deliveryservice.RequiredCapability{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2096873992}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `deliveryservices_required_capabilities/?$`, Handler: api.DeleteHandler(&deliveryservice.RequiredCapability{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2496289304}, - - // Federations by CDN (the actual table for federation) - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `cdns/{name}/federations/?$`, Handler: api.ReadHandler(&cdnfederation.TOCDNFederation{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 289225032}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `cdns/{name}/federations/?$`, Handler: api.CreateHandler(&cdnfederation.TOCDNFederation{}), RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2954894219}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `cdns/{name}/federations/{id}$`, Handler: api.UpdateHandler(&cdnfederation.TOCDNFederation{}), RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 226065466}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `cdns/{name}/federations/{id}$`, Handler: api.DeleteHandler(&cdnfederation.TOCDNFederation{}), RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2442852902}, - - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `cdns/{name}/dnsseckeys/ksk/generate$`, Handler: cdn.GenerateKSK, RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 272924281}, - - //Origins - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `origins/?$`, Handler: api.ReadHandler(&origin.TOOrigin{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 244649256}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `origins/?$`, Handler: api.UpdateHandler(&origin.TOOrigin{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 21567746}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `origins/?$`, Handler: api.CreateHandler(&origin.TOOrigin{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2099561643}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `origins/?$`, Handler: api.DeleteHandler(&origin.TOOrigin{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 260273263}, - - //Roles - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `roles/?$`, Handler: api.ReadHandler(&role.TORole{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 287088583}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `roles/?$`, Handler: api.UpdateHandler(&role.TORole{}), RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2612897489}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `roles/?$`, Handler: api.CreateHandler(&role.TORole{}), RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 230652406}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `roles/?$`, Handler: api.DeleteHandler(&role.TORole{}), RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2356705982}, - - //Delivery Services Regexes - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `deliveryservices_regexes/?$`, Handler: deliveryservicesregexes.Get, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 205501453}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `deliveryservices/{dsid}/regexes/?$`, Handler: deliveryservicesregexes.DSGet, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 277432763}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `deliveryservices/{dsid}/regexes/?$`, Handler: deliveryservicesregexes.Post, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 212737800}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `deliveryservices/{dsid}/regexes/{regexid}?$`, Handler: deliveryservicesregexes.Put, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2248339691}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `deliveryservices/{dsid}/regexes/{regexid}?$`, Handler: deliveryservicesregexes.Delete, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2246731663}, - - //StaticDNSEntries - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `staticdnsentries/?$`, Handler: api.ReadHandler(&staticdnsentry.TOStaticDNSEntry{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 228939477}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `staticdnsentries/?$`, Handler: api.UpdateHandler(&staticdnsentry.TOStaticDNSEntry{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 242457111}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `staticdnsentries/?$`, Handler: api.CreateHandler(&staticdnsentry.TOStaticDNSEntry{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2629148238}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `staticdnsentries/?$`, Handler: api.DeleteHandler(&staticdnsentry.TOStaticDNSEntry{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2846031132}, - - //ProfileParameters - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `profiles/{id}/parameters/?$`, Handler: profileparameter.GetProfileID, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 276464975}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `profiles/name/{name}/parameters/?$`, Handler: profileparameter.GetProfileName, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2267737832}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `profiles/name/{name}/parameters/?$`, Handler: profileparameter.PostProfileParamsByName, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2355945582}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `profiles/{id}/parameters/?$`, Handler: profileparameter.PostProfileParamsByID, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 216818708}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `profileparameters/?$`, Handler: api.ReadHandler(&profileparameter.TOProfileParameter{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 250609805}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `profileparameters/?$`, Handler: api.CreateHandler(&profileparameter.TOProfileParameter{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 228809693}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `profileparameter/?$`, Handler: profileparameter.PostProfileParam, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 224275}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `parameterprofile/?$`, Handler: profileparameter.PostParamProfile, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2080610861}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `profileparameters/{profileId}/{parameterId}$`, Handler: api.DeleteHandler(&profileparameter.TOProfileParameter{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 224839529}, - - //Tenants - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `tenants/?$`, Handler: api.ReadHandler(&apitenant.TOTenant{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2677967814}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `tenants/{id}$`, Handler: api.UpdateHandler(&apitenant.TOTenant{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2094131478}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `tenants/?$`, Handler: api.CreateHandler(&apitenant.TOTenant{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 217248013}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `tenants/{id}$`, Handler: api.DeleteHandler(&apitenant.TOTenant{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 216365558}, - - //CRConfig - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `cdns/{cdn}/snapshot/?$`, Handler: crconfig.SnapshotGetHandler, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2957273695}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `cdns/{cdn}/snapshot/new/?$`, Handler: crconfig.Handler, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 276716889}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `snapshot/?$`, Handler: crconfig.SnapshotHandler, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2969911829}, - - // Federations - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `federations/all/?$`, Handler: federations.GetAll, RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 21059986}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `federations/?$`, Handler: federations.Get, RequiredPrivLevel: auth.PrivLevelFederation, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 254954994}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `federations/?$`, Handler: federations.AddFederationResolverMappingsForCurrentUser, RequiredPrivLevel: auth.PrivLevelFederation, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2894064742}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `federations/?$`, Handler: federations.RemoveFederationResolverMappingsForCurrentUser, RequiredPrivLevel: auth.PrivLevelFederation, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 22098323}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `federations/?$`, Handler: federations.ReplaceFederationResolverMappingsForCurrentUser, RequiredPrivLevel: auth.PrivLevelFederation, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2283182516}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `federations/{id}/deliveryservices/?$`, Handler: federations.PostDSes, RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2682863513}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `federations/{id}/deliveryservices/?$`, Handler: api.ReadHandler(&federations.TOFedDSes{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 253773034}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `federations/{id}/deliveryservices/{dsID}/?$`, Handler: api.DeleteHandler(&federations.TOFedDSes{}), RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2417402570}, - - // Federation Resolvers - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `federation_resolvers/?$`, Handler: federation_resolvers.Create, RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2134373661}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `federation_resolvers/?$`, Handler: federation_resolvers.Read, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 256608759}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `federations/{id}/federation_resolvers/?$`, Handler: federations.AssignFederationResolversToFederationHandler, RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 256608760}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `federations/{id}/federation_resolvers/?$`, Handler: federations.GetFederationFederationResolversHandler, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 256608761}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `federation_resolvers/?$`, Handler: federation_resolvers.Delete, RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2001}, - - // Federations Users - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `federations/{id}/users/?$`, Handler: federations.PostUsers, RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2779334930}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `federations/{id}/users/?$`, Handler: api.ReadHandler(&federations.TOUsers{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 294075015}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `federations/{id}/users/{userID}/?$`, Handler: api.DeleteHandler(&federations.TOUsers{}), RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2949102882}, - - ////DeliveryServices - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `deliveryservices/?$`, Handler: api.ReadHandler(&deliveryservice.TODeliveryService{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2238317294}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `deliveryservices/?$`, Handler: deliveryservice.CreateV15, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 206431432}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `deliveryservices/{id}/?$`, Handler: deliveryservice.UpdateV15, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2766567527}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `deliveryservices/{id}/safe/?$`, Handler: deliveryservice.UpdateSafe, RequiredPrivLevel: auth.PrivLevelUnauthenticated, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 247210931}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `deliveryservices/{id}/?$`, Handler: api.DeleteHandler(&deliveryservice.TODeliveryService{}), RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 222642074}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `deliveryservices/{id}/servers/eligible/?$`, Handler: deliveryservice.GetServersEligible, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 274761584}, - - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `deliveryservices/xmlId/{xmlid}/sslkeys$`, Handler: deliveryservice.GetSSLKeysByXMLID, RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2135772907}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `deliveryservices/sslkeys/add$`, Handler: deliveryservice.AddSSLKeys, RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2872878583}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `deliveryservices/xmlId/{xmlid}/sslkeys$`, Handler: deliveryservice.DeleteSSLKeys, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2926734}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `deliveryservices/sslkeys/generate/?$`, Handler: deliveryservice.GenerateSSLKeys, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 253439051}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `deliveryservices/xmlId/{name}/urlkeys/copyFromXmlId/{copy-name}/?$`, Handler: deliveryservice.CopyURLKeys, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2262501076}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `deliveryservices/xmlId/{name}/urlkeys/generate/?$`, Handler: deliveryservice.GenerateURLKeys, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2530482824}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `deliveryservices/xmlId/{name}/urlkeys/?$`, Handler: deliveryservice.GetURLKeysByName, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2202719211}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `deliveryservices/{id}/urlkeys/?$`, Handler: deliveryservice.GetURLKeysByID, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 293197114}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `vault/bucket/{bucket}/key/{key}/values/?$`, Handler: vault.GetBucketKeyDeprecated, RequiredPrivLevel: auth.PrivLevelAdmin, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2220510801}, - - //Delivery service LetsEncrypt - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `deliveryservices/sslkeys/generate/letsencrypt/?$`, Handler: deliveryservice.GenerateLetsEncryptCertificates, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 253439052}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `letsencrypt/dnsrecords/?$`, Handler: deliveryservice.GetDnsChallengeRecords, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 253439055}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `letsencrypt/autorenew/?$`, Handler: deliveryservice.RenewCertificates, RequiredPrivLevel: auth.PrivLevelOperations, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 253439056}, - - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `deliveryservices/{id}/health/?$`, Handler: deliveryservice.GetHealth, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2234590101}, - - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `deliveryservices/{id}/routing$`, Handler: crstats.GetDSRouting, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 66733983}, - - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `steering/{deliveryservice}/targets/?$`, Handler: api.ReadHandler(&steeringtargets.TOSteeringTargetV11{}), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2569607824}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `steering/{deliveryservice}/targets/?$`, Handler: api.CreateHandler(&steeringtargets.TOSteeringTargetV11{}), RequiredPrivLevel: auth.PrivLevelSteering, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2338216397}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPut, Path: `steering/{deliveryservice}/targets/{target}/?$`, Handler: api.UpdateHandler(&steeringtargets.TOSteeringTargetV11{}), RequiredPrivLevel: auth.PrivLevelSteering, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2438608295}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodDelete, Path: `steering/{deliveryservice}/targets/{target}/?$`, Handler: api.DeleteHandler(&steeringtargets.TOSteeringTargetV11{}), RequiredPrivLevel: auth.PrivLevelSteering, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2288021515}, - - // Stats Summary - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `stats_summary/?$`, Handler: trafficstats.GetStatsSummary, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 280498598}, - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `stats_summary/?$`, Handler: trafficstats.CreateStatsSummary, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 280491598}, - - //Pattern based consistent hashing endpoint - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodPost, Path: `consistenthash/?$`, Handler: consistenthash.Post, RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 260755076}, - - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `steering/?$`, Handler: steering.Get, RequiredPrivLevel: auth.PrivLevelSteering, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 2174852457}, - - // Plugins - {Version: api.Version{Major: 2, Minor: 0}, Method: http.MethodGet, Path: `plugins/?$`, Handler: plugins.Get(d.Plugins), RequiredPrivLevel: auth.PrivLevelReadOnly, RequiredPermissions: nil, Authenticated: Authenticated, Middlewares: nil, ID: 283498539}, } // sanity check to make sure all Route IDs are unique From 6030ea071d0f3e401a51891cd46c2b7ea642642e Mon Sep 17 00:00:00 2001 From: Zach Hoffman Date: Thu, 7 Jul 2022 12:53:16 -0600 Subject: [PATCH 05/14] Remove newly-unused handlers --- .../traffic_ops_golang/crconfig/handler.go | 26 ---------- .../deliveryservice/deliveryservices.go | 52 ------------------- 2 files changed, 78 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/crconfig/handler.go b/traffic_ops/traffic_ops_golang/crconfig/handler.go index 764f0e8525..87fce08e62 100644 --- a/traffic_ops/traffic_ops_golang/crconfig/handler.go +++ b/traffic_ops/traffic_ops_golang/crconfig/handler.go @@ -89,32 +89,6 @@ func SnapshotGetHandler(w http.ResponseWriter, r *http.Request) { api.WriteResp(w, r, decoded) } -func SnapshotGetMonitoringLegacyHandler(w http.ResponseWriter, r *http.Request) { - inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"cdn"}, nil) - if userErr != nil || sysErr != nil { - api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr) - return - } - defer inf.Close() - - snapshot, cdnExists, err := GetSnapshotMonitoring(inf.Tx.Tx, inf.Params["cdn"]) - if err != nil { - api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New("getting snapshot: "+err.Error())) - return - } - if !cdnExists { - api.HandleErr(w, r, inf.Tx.Tx, http.StatusNotFound, errors.New("CDN not found"), nil) - return - } - - var data tc.TrafficMonitorConfig - if err := json.Unmarshal([]byte(snapshot), &data); err != nil { - api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New("getting snapshot: "+err.Error())) - return - } - api.WriteResp(w, r, data.ToLegacyConfig()) -} - // SnapshotGetMonitoringHandler gets and serves the CRConfig from the snapshot table. func SnapshotGetMonitoringHandler(w http.ResponseWriter, r *http.Request) { inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"cdn"}, nil) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go index 3966186eeb..bb91823208 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go @@ -128,34 +128,6 @@ func GetDSTLSVersions(dsID int, tx *sql.Tx) ([]string, error) { return vers, err } -// CreateV15 is the POST handler for APIv2's deliveryservices endpoint, named -// with "V15" for legacy reasons. -// TODO allow users to post names (type, cdn, etc) and get the IDs from the -// names. This isn't trivial to do in a single query, without dynamically -// building the entire insert query, and ideally inserting would be one query. -// But it'd be much more convenient for users. Alternatively, remove IDs from -// the database entirely and use real candidate keys. -func CreateV15(w http.ResponseWriter, r *http.Request) { - inf, userErr, sysErr, errCode := api.NewInfo(r, nil, nil) - if userErr != nil || sysErr != nil { - api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr) - return - } - defer inf.Close() - - ds := tc.DeliveryServiceNullableV15{} - if err := json.NewDecoder(r.Body).Decode(&ds); err != nil { - api.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, errors.New("decoding: "+err.Error()), nil) - return - } - - res, status, userErr, sysErr := createV15(w, r, inf, ds) - if userErr != nil || sysErr != nil { - api.HandleErr(w, r, inf.Tx.Tx, status, userErr, sysErr) - return - } - api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Delivery Service creation was successful", []tc.DeliveryServiceNullableV15{*res}) -} func CreateV30(w http.ResponseWriter, r *http.Request) { inf, userErr, sysErr, errCode := api.NewInfo(r, nil, nil) if userErr != nil || sysErr != nil { @@ -621,30 +593,6 @@ func (ds *TODeliveryService) Read(h http.Header, useIMS bool) ([]interface{}, er return returnable, nil, nil, errCode, maxTime } -func UpdateV15(w http.ResponseWriter, r *http.Request) { - inf, userErr, sysErr, errCode := api.NewInfo(r, nil, []string{"id"}) - if userErr != nil || sysErr != nil { - api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr) - return - } - defer inf.Close() - - id := inf.IntParams["id"] - - ds := tc.DeliveryServiceNullableV15{} - if err := json.NewDecoder(r.Body).Decode(&ds); err != nil { - api.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, errors.New("malformed JSON: "+err.Error()), nil) - return - } - ds.ID = &id - - res, status, userErr, sysErr := updateV15(w, r, inf, &ds) - if userErr != nil || sysErr != nil { - api.HandleErr(w, r, inf.Tx.Tx, status, userErr, sysErr) - return - } - api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Delivery Service update was successful", []tc.DeliveryServiceNullableV15{*res}) -} func UpdateV30(w http.ResponseWriter, r *http.Request) { inf, userErr, sysErr, errCode := api.NewInfo(r, nil, []string{"id"}) if userErr != nil || sysErr != nil { From b43471bedf819d0112a466e5b0a86f5bab7a81d4 Mon Sep 17 00:00:00 2001 From: Zach Hoffman Date: Thu, 7 Jul 2022 15:34:07 -0600 Subject: [PATCH 06/14] Remove API v2-specific logic --- .../deliveryservice/eligible.go | 32 +- .../deliveryservice/servers/servers.go | 28 +- .../traffic_ops_golang/server/detail.go | 31 +- .../traffic_ops_golang/server/servers.go | 348 ------------------ 4 files changed, 3 insertions(+), 436 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/eligible.go b/traffic_ops/traffic_ops_golang/deliveryservice/eligible.go index bfefdaf33b..d863aa423b 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/eligible.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/eligible.go @@ -65,37 +65,7 @@ func GetServersEligible(w http.ResponseWriter, r *http.Request) { return } - if inf.Version.Major <= 2 { - v11ServerList := []tc.DSServerV11{} - for _, srv := range servers { - routerHostName := "" - routerPort := "" - interfaces := *srv.ServerInterfaces - // All interfaces should have the same router name/port when they were upgraded from v1/2/3 to v4, so we can just choose any of them - if len(interfaces) != 0 { - routerHostName = interfaces[0].RouterHostName - routerPort = interfaces[0].RouterPortName - } - legacyInterface, err := tc.V4InterfaceInfoToLegacyInterfaces(interfaces) - if err != nil { - api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New("converting to server detail v11: "+err.Error())) - return - } - v11server := tc.DSServerV11{} - if len(srv.ProfileNames) == 0 { - api.HandleErr(w, r, inf.Tx.Tx, http.StatusNotFound, errors.New("profile name for server: "+*srv.HostName+" not found"), nil) - return - } - pid, pdesc := dbhelpers.GetProfileIDDesc(inf.Tx.Tx, srv.ProfileNames[0]) - v11server.DSServerBase = srv.DSServerBaseV4.ToDSServerBase(&routerHostName, &routerPort, &pdesc, &pid) - - v11server.LegacyInterfaceDetails = legacyInterface - - v11ServerList = append(v11ServerList, v11server) - } - api.WriteResp(w, r, v11ServerList) - return - } else if inf.Version.Major <= 3 { + if inf.Version.Major == 3 { v3ServerList := []tc.DSServer{} for _, srv := range servers { routerHostName := "" diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/servers/servers.go b/traffic_ops/traffic_ops_golang/deliveryservice/servers/servers.go index 39a5f0dfc1..6c0f353c61 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/servers/servers.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/servers/servers.go @@ -697,33 +697,7 @@ func GetReadAssigned(w http.ResponseWriter, r *http.Request) { return } - if inf.Version.Major <= 2 { - v11ServerList := []tc.DSServerV11{} - for _, srv := range servers { - routerHostName := "" - routerPort := "" - interfaces := *srv.ServerInterfaces - // All interfaces should have the same router name/port when they were upgraded from v1/2/3 to v4, so we can just choose any of them - if len(interfaces) != 0 { - routerHostName = interfaces[0].RouterHostName - routerPort = interfaces[0].RouterPortName - } - legacyInterface, err := tc.V4InterfaceInfoToLegacyInterfaces(interfaces) - if err != nil { - api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New("converting to server detail v11: "+err.Error())) - return - } - v11server := tc.DSServerV11{} - pid, pdesc := dbhelpers.GetProfileIDDesc(inf.Tx.Tx, srv.ProfileNames[0]) - v11server.DSServerBase = srv.DSServerBaseV4.ToDSServerBase(&routerHostName, &routerPort, &pdesc, &pid) - - v11server.LegacyInterfaceDetails = legacyInterface - - v11ServerList = append(v11ServerList, v11server) - } - api.WriteAlertsObj(w, r, http.StatusOK, alerts, v11ServerList) - return - } else if inf.Version.Major <= 3 { + if inf.Version.Major == 3 { v3ServerList := []tc.DSServer{} for _, srv := range servers { routerHostName := "" diff --git a/traffic_ops/traffic_ops_golang/server/detail.go b/traffic_ops/traffic_ops_golang/server/detail.go index a327a40595..f06fbd74f3 100644 --- a/traffic_ops/traffic_ops_golang/server/detail.go +++ b/traffic_ops/traffic_ops_golang/server/detail.go @@ -85,36 +85,7 @@ func GetDetailParamHandler(w http.ResponseWriter, r *http.Request) { var resp interface{} size := len(servers) - if inf.Version.Major <= 2 { - v11ServerList := make([]tc.ServerDetailV11, 0, size) - for _, server := range servers { - interfaces := server.ServerInterfaces - routerHostName := "" - routerPortName := "" - // All interfaces should have the same router name/port when they were upgraded from v1/2/3 to v4, so we can just choose any of them - if len(interfaces) != 0 { - routerHostName = interfaces[0].RouterHostName - routerPortName = interfaces[0].RouterPortName - } - v11server := tc.ServerDetailV11{} - v11server.ServerDetail, err = dbhelpers.GetServerDetailFromV4(server, inf.Tx.Tx) - if err != nil { - api.HandleDeprecatedErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, fmt.Errorf("failed to GetServerDetailFromV4: %w", err), &alt) - return - } - v11server.RouterHostName = &routerHostName - v11server.RouterPortName = &routerPortName - legacyInterface, err := tc.V4InterfaceInfoToLegacyInterfaces(interfaces) - if err != nil { - api.HandleDeprecatedErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, fmt.Errorf("converting to server detail v11: %w", err), &alt) - return - } - v11server.LegacyInterfaceDetails = legacyInterface - - v11ServerList = append(v11ServerList, v11server) - } - resp = v11ServerList - } else if inf.Version.Major <= 3 { + if inf.Version.Major == 3 { v3ServerList := make([]tc.ServerDetailV30, 0, size) for _, server := range servers { v3Server := tc.ServerDetailV30{} diff --git a/traffic_ops/traffic_ops_golang/server/servers.go b/traffic_ops/traffic_ops_golang/server/servers.go index 457efc4cb3..8be177d01b 100644 --- a/traffic_ops/traffic_ops_golang/server/servers.go +++ b/traffic_ops/traffic_ops_golang/server/servers.go @@ -46,7 +46,6 @@ import ( "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/util/ims" validation "github.com/go-ozzo/ozzo-validation" - "github.com/go-ozzo/ozzo-validation/is" "github.com/google/uuid" "github.com/jmoiron/sqlx" "github.com/lib/pq" @@ -282,57 +281,6 @@ INSERT INTO server ( type AS server_type_id ` -const insertQuery = ` -INSERT INTO server ( - cachegroup, - cdn_id, - domain_name, - host_name, - https_port, - ilo_ip_address, - ilo_ip_netmask, - ilo_ip_gateway, - ilo_username, - ilo_password, - mgmt_ip_address, - mgmt_ip_netmask, - mgmt_ip_gateway, - offline_reason, - phys_location, - profile, - rack, - status, - tcp_port, - type, - xmpp_id, - xmpp_passwd -) VALUES ( - :cachegroup_id, - :cdn_id, - :domain_name, - :host_name, - :https_port, - :ilo_ip_address, - :ilo_ip_netmask, - :ilo_ip_gateway, - :ilo_username, - :ilo_password, - :mgmt_ip_address, - :mgmt_ip_netmask, - :mgmt_ip_gateway, - :offline_reason, - :phys_location_id, - :profile_id, - :rack, - :status_id, - :tcp_port, - :server_type_id, - :xmpp_id, - :xmpp_passwd -) RETURNING - id -` - const updateQuery = ` UPDATE server SET cachegroup=:cachegroup_id, @@ -496,66 +444,6 @@ func validateCommonV40(s *tc.ServerV40, tx *sql.Tx) ([]error, error) { return errs, nil } -func validateV1(s *tc.ServerNullableV11, tx *sql.Tx) (error, error) { - if s.IP6Address != nil && len(strings.TrimSpace(*s.IP6Address)) == 0 { - s.IP6Address = nil - } - - errs := []error{} - if (s.IPAddress == nil || *s.IPAddress == "") && s.IP6Address == nil { - errs = append(errs, tc.NeedsAtLeastOneIPError) - } - - validateErrs := validation.Errors{ - "interfaceMtu": validation.Validate(s.InterfaceMtu, validation.NotNil), - "interfaceName": validation.Validate(s.InterfaceName, validation.NotNil), - } - - if s.IPAddress != nil && *s.IPAddress != "" { - validateErrs["ipAddress"] = validation.Validate(s.IPAddress, is.IPv4) - validateErrs["ipNetmask"] = validation.Validate(s.IPNetmask, validation.NotNil) - validateErrs["ipGateway"] = validation.Validate(s.IPGateway, validation.NotNil) - } - if s.IP6Address != nil && *s.IP6Address != "" { - validateErrs["ip6Address"] = validation.Validate(s.IP6Address, validation.By(tovalidate.IsValidIPv6CIDROrAddress)) - } - - errs = append(errs, tovalidate.ToErrors(validateErrs)...) - commonErrs, sysErr := validateCommon(&s.CommonServerProperties, tx) - errs = append(errs, commonErrs...) - - return util.JoinErrs(errs), sysErr -} - -func validateV2(s *tc.ServerNullableV2, tx *sql.Tx) (error, error) { - var errs []error - - if userErr, sysErr := validateV1(&s.ServerNullableV11, tx); userErr != nil || sysErr != nil { - return userErr, sysErr - } - - // default boolean value is false - if s.IPIsService == nil { - s.IPIsService = new(bool) - } - if s.IP6IsService == nil { - s.IP6IsService = new(bool) - } - - if !*s.IPIsService && !*s.IP6IsService { - errs = append(errs, tc.NeedsAtLeastOneServiceAddressError) - } - - if *s.IPIsService && (s.IPAddress == nil || *s.IPAddress == "") { - errs = append(errs, tc.EmptyAddressCannotBeAServiceAddressError) - } - - if *s.IP6IsService && (s.IP6Address == nil || *s.IP6Address == "") { - errs = append(errs, tc.EmptyAddressCannotBeAServiceAddressError) - } - return util.JoinErrs(errs), nil -} - func validateMTU(mtu interface{}) error { m, ok := mtu.(*uint64) if !ok { @@ -1499,7 +1387,6 @@ func Update(w http.ResponseWriter, r *http.Request) { var server tc.ServerV40 var serverV3 tc.ServerV30 - var legacyServer tc.ServerNullableV2 var statusLastUpdatedTime time.Time if inf.Version.Major >= 4 { @@ -1568,40 +1455,6 @@ func Update(w http.ResponseWriter, r *http.Request) { api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, sysErr) return } - } else { - legacyServer.ID = new(int) - *legacyServer.ID = inf.IntParams["id"] - if err := json.NewDecoder(r.Body).Decode(&legacyServer); err != nil { - api.HandleErr(w, r, tx, http.StatusBadRequest, err, nil) - return - } - userErr, sysErr := validateV2(&legacyServer, tx) - if userErr != nil || sysErr != nil { - code := http.StatusBadRequest - if sysErr != nil { - code = http.StatusInternalServerError - } - api.HandleErr(w, r, tx, code, userErr, sysErr) - return - } - - profileName, exists, err := dbhelpers.GetProfileNameFromID(*legacyServer.ProfileID, tx) - if err != nil { - api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, err) - return - } - if !exists { - api.HandleErr(w, r, inf.Tx.Tx, http.StatusNotFound, errors.New("profile does not exist"), nil) - return - } - profileNames := []string{profileName} - - server, err = legacyServer.UpgradeToV40(profileNames) - if err != nil { - sysErr = fmt.Errorf("error upgrading valid V2 server to V3 structure: %v", err) - api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, sysErr) - return - } } if *original.CachegroupID != *server.CachegroupID || *original.CDNID != *server.CDNID { @@ -1695,11 +1548,6 @@ func Update(w http.ResponseWriter, r *http.Request) { api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, fmt.Errorf("failed to update server_profile: %w", err)) return } - } else { - if err = dbhelpers.UpdateServerProfileTableForV2V3(legacyServer.ID, legacyServer.ProfileID, (original.ProfileNames)[0], tx); err != nil { - api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, fmt.Errorf("failed to update server_profile: %w", err)) - return - } } serverID, errCode, userErr, sysErr := updateServer(inf.Tx, server) @@ -1785,27 +1633,6 @@ func Update(w http.ResponseWriter, r *http.Request) { return } api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Server updated", srvr) - } else { - csp, err := dbhelpers.GetCommonServerPropertiesFromV4(server, tx) - if err != nil { - api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, fmt.Errorf("failed to get common server properties from V4 server struct: %w", err)) - return - } - if err != nil { - api.HandleErr(w, r, tx, http.StatusBadRequest, nil, fmt.Errorf("failed to update server_profile: %w", err)) - return - } - v2Server, err := srvr.ToServerV2FromV4(csp) - if err != nil { - sysErr = fmt.Errorf("converting valid v3 server to a v2 structure: %v", err) - api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, sysErr) - return - } - if inf.Version.Major <= 1 { - api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Server updated", v2Server.ServerNullableV11) - } else { - api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Server updated", v2Server) - } } changeLogMsg := fmt.Sprintf("SERVER: %s.%s, ID: %d, ACTION: updated", *srvr.HostName, *srvr.DomainName, *srvr.ID) @@ -1888,147 +1715,6 @@ func insertServerProfile(id int, pName []string, tx *sql.Tx) (error, error, int) return nil, nil, http.StatusOK } -func createV2(inf *api.APIInfo, w http.ResponseWriter, r *http.Request) { - var server tc.ServerNullableV2 - - if err := json.NewDecoder(r.Body).Decode(&server); err != nil { - api.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, err, nil) - return - } - - if server.ID != nil { - var prevID int - err := inf.Tx.Tx.QueryRow("SELECT id from server where id = $1", server.ID).Scan(&prevID) - if err != nil && err != sql.ErrNoRows { - api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, fmt.Errorf("checking if server with id %d exists", *server.ID)) - return - } - if prevID != 0 { - api.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, fmt.Errorf("server with id %d already exists. Please do not provide an id", *server.ID), nil) - return - } - } - - server.XMPPID = newUUID() - - if userErr, sysErr := validateV2(&server, inf.Tx.Tx); userErr != nil || sysErr != nil { - code := http.StatusBadRequest - if sysErr != nil { - code = http.StatusInternalServerError - } - api.HandleErr(w, r, inf.Tx.Tx, code, userErr, sysErr) - return - } - - if server.CDNName != nil { - userErr, sysErr, statusCode := dbhelpers.CheckIfCurrentUserCanModifyCDN(inf.Tx.Tx, *server.CDNName, inf.User.UserName) - if userErr != nil || sysErr != nil { - api.HandleErr(w, r, inf.Tx.Tx, statusCode, userErr, sysErr) - return - } - } else if server.CDNID != nil { - userErr, sysErr, statusCode := dbhelpers.CheckIfCurrentUserCanModifyCDNWithID(inf.Tx.Tx, int64(*server.CDNID), inf.User.UserName) - if userErr != nil || sysErr != nil { - api.HandleErr(w, r, inf.Tx.Tx, statusCode, userErr, sysErr) - return - } - } - - serverID, err := createServerV2(inf.Tx, server) - if err != nil { - userErr, sysErr, errCode := api.ParseDBError(err) - api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr) - return - } - - ifaces, err := server.LegacyInterfaceDetails.ToInterfacesV4(*server.IPIsService, *server.IP6IsService, server.RouterHostName, server.RouterPortName) - if err != nil { - api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, err) - return - } - - if userErr, sysErr, errCode := createInterfaces(int(serverID), ifaces, inf.Tx.Tx); userErr != nil || sysErr != nil { - api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr) - return - } - - var origProfile string - err = inf.Tx.Tx.QueryRow("SELECT name from profile where id = $1", server.ProfileID).Scan(&origProfile) - if err != nil && err != sql.ErrNoRows { - api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, fmt.Errorf("retreiving profile with id %d", *server.ProfileID)) - return - } - var origProfiles = []string{origProfile} - - userErr, sysErr, statusCode := insertServerProfile(int(serverID), origProfiles, inf.Tx.Tx) - if userErr != nil || sysErr != nil { - api.HandleErr(w, r, inf.Tx.Tx, statusCode, userErr, sysErr) - return - } - - where := `WHERE s.id = $1` - selquery := selectQuery + where - var s4 tc.ServerV40 - err = inf.Tx.QueryRow(selquery, serverID).Scan(&s4.Cachegroup, - &s4.CachegroupID, - &s4.CDNID, - &s4.CDNName, - &s4.DomainName, - &s4.GUID, - &s4.HostName, - &s4.HTTPSPort, - &s4.ID, - &s4.ILOIPAddress, - &s4.ILOIPGateway, - &s4.ILOIPNetmask, - &s4.ILOPassword, - &s4.ILOUsername, - &s4.LastUpdated, - &s4.MgmtIPAddress, - &s4.MgmtIPGateway, - &s4.MgmtIPNetmask, - &s4.OfflineReason, - &s4.PhysLocation, - &s4.PhysLocationID, - pq.Array(&s4.ProfileNames), - &s4.Rack, - &s4.RevalPending, - &s4.RevalUpdateTime, - &s4.RevalApplyTime, - &s4.Status, - &s4.StatusID, - &s4.TCPPort, - &s4.Type, - &s4.TypeID, - &s4.UpdPending, - &s4.ConfigUpdateTime, - &s4.ConfigApplyTime, - &s4.XMPPID, - &s4.XMPPPasswd, - &s4.StatusLastUpdated) - if err != nil { - api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, err) - return - } - s4.Interfaces = ifaces - - csp, err := dbhelpers.GetCommonServerPropertiesFromV4(s4, inf.Tx.Tx) - if err != nil { - api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, err) - } - srvr, err := s4.ToServerV2FromV4(csp) - if err != nil { - api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, err) - return - } - - alerts := tc.CreateAlerts(tc.SuccessLevel, "server was created.") - api.WriteAlertsObj(w, r, http.StatusOK, alerts, srvr) - - changeLogMsg := fmt.Sprintf("SERVER: %s.%s, ID: %d, ACTION: created", *srvr.HostName, *srvr.DomainName, *srvr.ID) - api.CreateChangeLogRawTx(api.ApiChange, changeLogMsg, inf.User, inf.Tx.Tx) -} - func createV3(inf *api.APIInfo, w http.ResponseWriter, r *http.Request) { var server tc.ServerV30 @@ -2389,31 +2075,6 @@ func createServerV3(tx *sqlx.Tx, server tc.ServerV30) (int64, error) { return serverID, nil } -func createServerV2(tx *sqlx.Tx, server tc.ServerNullableV2) (int64, error) { - rows, err := tx.NamedQuery(insertQuery, server) - if err != nil { - return 0, err - } - defer log.Close(rows, "failed to close rows for createServerV2") - - rowsAffected := 0 - var serverID int64 - for rows.Next() { - rowsAffected++ - if err := rows.Scan(&serverID); err != nil { - return 0, err - } - } - - if rowsAffected == 0 { - return 0, errors.New("server create: no server was inserted, no id was returned") - } else if rowsAffected > 1 { - return 0, fmt.Errorf("too many ids returned from server insert: %d", rowsAffected) - } - - return serverID, nil -} - // Create is the handler for POST requests to /servers. func Create(w http.ResponseWriter, r *http.Request) { inf, userErr, sysErr, errCode := api.NewInfo(r, nil, nil) @@ -2424,8 +2085,6 @@ func Create(w http.ResponseWriter, r *http.Request) { defer inf.Close() switch { - case inf.Version.Major <= 2: - createV2(inf, w, r) case inf.Version.Major == 3: createV3(inf, w, r) default: @@ -2599,13 +2258,6 @@ func Delete(w http.ResponseWriter, r *http.Request) { return } api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Server deleted", serverv3) - } else { - serverV2, err := server.ToServerV2FromV4(csp) - if err != nil { - api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, err) - return - } - api.WriteRespAlertObj(w, r, tc.SuccessLevel, "server was deleted.", serverV2) } } From e858cd5011c650be384a93be25d8258974c53ca8 Mon Sep 17 00:00:00 2001 From: Zach Hoffman Date: Thu, 7 Jul 2022 16:31:01 -0600 Subject: [PATCH 07/14] Remove more API v2-specific logic --- .../dbhelpers/db_helpers.go | 4 +- .../deliveryservice/deliveryservices.go | 6 -- .../deliveryservice/servers/servers.go | 5 +- .../traffic_ops_golang/server/servers.go | 80 ++++++------------- 4 files changed, 29 insertions(+), 66 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/dbhelpers/db_helpers.go b/traffic_ops/traffic_ops_golang/dbhelpers/db_helpers.go index 3e0b508390..73d4db0a9c 100644 --- a/traffic_ops/traffic_ops_golang/dbhelpers/db_helpers.go +++ b/traffic_ops/traffic_ops_golang/dbhelpers/db_helpers.go @@ -2123,8 +2123,8 @@ func UpdateServerProfilesForV4(id int, profile []string, tx *sql.Tx) error { return nil } -// UpdateServerProfileTableForV2V3 updates CommonServerPropertiesV40 struct and server_profile table via Update (server) function for API v2/v3. -func UpdateServerProfileTableForV2V3(id *int, newProfileId *int, origProfile string, tx *sql.Tx) error { +// UpdateServerProfileTableForV3 updates CommonServerPropertiesV40 struct and server_profile table via Update (server) function for API v3. +func UpdateServerProfileTableForV3(id *int, newProfileId *int, origProfile string, tx *sql.Tx) error { newProfile, _, err := GetProfileNameFromID(*newProfileId, tx) if err != nil && err != sql.ErrNoRows { return fmt.Errorf("selecting profile by name: %w", err) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go index bb91823208..399e6e3ee2 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go @@ -580,12 +580,6 @@ func (ds *TODeliveryService) Read(h http.Header, useIMS bool) ([]interface{}, er // NOTE: it's required to handle minor version cases in a descending >= manner case version.Major > 3: returnable = append(returnable, ds.RemoveLD1AndLD2()) - case version.Major > 2 && version.Minor >= 1: - returnable = append(returnable, ds.DowngradeToV31()) - case version.Major > 2: - returnable = append(returnable, ds.DowngradeToV31().DeliveryServiceV30) - case version.Major > 1: - returnable = append(returnable, ds.DowngradeToV31().DeliveryServiceNullableV15) default: return nil, nil, fmt.Errorf("TODeliveryService.Read called with invalid API version: %d.%d", version.Major, version.Minor), http.StatusInternalServerError, nil } diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/servers/servers.go b/traffic_ops/traffic_ops_golang/deliveryservice/servers/servers.go index 6c0f353c61..2662446010 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/servers/servers.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/servers/servers.go @@ -933,7 +933,7 @@ func (dss *TODSSDeliveryService) Read(h http.Header, useIMS bool) ([]interface{} if version.Major > 3 && version.Minor >= 0 { ds = ds.RemoveLD1AndLD2() returnable = append(returnable, ds) - } else if version.Major > 2 { + } else { if version.Minor > 0 { dsV31 := ds.DowngradeToV31() returnable = append(returnable, dsV31) @@ -941,9 +941,6 @@ func (dss *TODSSDeliveryService) Read(h http.Header, useIMS bool) ([]interface{} dsV30 := ds.DowngradeToV31().DeliveryServiceV30 returnable = append(returnable, dsV30) } - } else { - dsV2 := ds.DowngradeToV31().DeliveryServiceNullableV15 - returnable = append(returnable, dsV2) } } return returnable, nil, nil, http.StatusOK, &maxTime diff --git a/traffic_ops/traffic_ops_golang/server/servers.go b/traffic_ops/traffic_ops_golang/server/servers.go index 8be177d01b..6373e22b63 100644 --- a/traffic_ops/traffic_ops_golang/server/servers.go +++ b/traffic_ops/traffic_ops_golang/server/servers.go @@ -716,40 +716,22 @@ func Read(w http.ResponseWriter, r *http.Request) { api.WriteRespWithSummary(w, r, servers, serverCount) return } - if version.Major >= 3 { - v3Servers := make([]tc.ServerV30, 0) - for _, server := range servers { - csp, err := dbhelpers.GetCommonServerPropertiesFromV4(server, tx) - if err != nil { - api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, fmt.Errorf("failed to get common server properties from V4 server struct: %w", err)) - return - } - v3Server, err := server.ToServerV3FromV4(csp) - if err != nil { - api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, fmt.Errorf("failed to convert servers to V3 format: %w", err)) - return - } - v3Servers = append(v3Servers, v3Server) - } - api.WriteRespWithSummary(w, r, v3Servers, serverCount) - return - } - - legacyServers := make([]tc.ServerNullableV2, 0, len(servers)) + v3Servers := make([]tc.ServerV30, 0) for _, server := range servers { csp, err := dbhelpers.GetCommonServerPropertiesFromV4(server, tx) if err != nil { api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, fmt.Errorf("failed to get common server properties from V4 server struct: %w", err)) return } - legacyServer, err := server.ToServerV2FromV4(csp) + v3Server, err := server.ToServerV3FromV4(csp) if err != nil { - api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, fmt.Errorf("failed to convert servers to legacy format: %v", err)) + api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, fmt.Errorf("failed to convert servers to V3 format: %w", err)) return } - legacyServers = append(legacyServers, legacyServer) + v3Servers = append(v3Servers, v3Server) } - api.WriteResp(w, r, legacyServers) + api.WriteRespWithSummary(w, r, v3Servers, serverCount) + return } func selectMaxLastUpdatedQuery(queryAddition string, where string) string { @@ -796,14 +778,12 @@ func getServers(h http.Header, params map[string]string, tx *sqlx.Tx, user *auth "dsId": {Column: "dss.deliveryservice", Checker: nil}, } - if version.Major >= 3 { - queryParamsToSQLCols["cachegroupName"] = dbhelpers.WhereColumnInfo{ - Column: "cg.name", - Checker: nil, - } + queryParamsToSQLCols["cachegroupName"] = dbhelpers.WhereColumnInfo{ + Column: "cg.name", + Checker: nil, } - if version.Major <= 3 { + if version.Major == 3 { queryParamsToSQLCols["profileId"] = dbhelpers.WhereColumnInfo{ Column: "s.profile", Checker: api.IsInt, @@ -842,15 +822,11 @@ func getServers(h http.Header, params map[string]string, tx *sqlx.Tx, user *auth } var joinSubQuery string - if version.Major >= 3 { - if err = tx.QueryRow(deliveryservice.HasRequiredCapabilitiesQuery, dsID).Scan(&dsHasRequiredCapabilities); err != nil { - err = fmt.Errorf("unable to get required capabilities for deliveryservice %d: %s", dsID, err) - return nil, 0, nil, err, http.StatusInternalServerError, nil - } - joinSubQuery = dssTopologiesJoinSubquery - } else { - joinSubQuery = "" + if err = tx.QueryRow(deliveryservice.HasRequiredCapabilitiesQuery, dsID).Scan(&dsHasRequiredCapabilities); err != nil { + err = fmt.Errorf("unable to get required capabilities for deliveryservice %d: %s", dsID, err) + return nil, 0, nil, err, http.StatusInternalServerError, nil } + joinSubQuery = dssTopologiesJoinSubquery // only if dsId is part of params: add join on deliveryservice_server table queryAddition = fmt.Sprintf(deliveryServiceServersJoin, joinSubQuery) @@ -1413,7 +1389,7 @@ func Update(w http.ResponseWriter, r *http.Request) { api.HandleErr(w, r, tx, errCode, userErr, sysErr) return } - } else if inf.Version.Major >= 3 { + } else { serverV3.ID = new(int) *serverV3.ID = inf.IntParams["id"] if err := json.NewDecoder(r.Body).Decode(&serverV3); err != nil { @@ -1543,8 +1519,8 @@ func Update(w http.ResponseWriter, r *http.Request) { api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr) return } - } else if inf.Version.Major >= 3 { - if err = dbhelpers.UpdateServerProfileTableForV2V3(serverV3.ID, serverV3.ProfileID, (original.ProfileNames)[0], tx); err != nil { + } else { + if err = dbhelpers.UpdateServerProfileTableForV3(serverV3.ID, serverV3.ProfileID, (original.ProfileNames)[0], tx); err != nil { api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, fmt.Errorf("failed to update server_profile: %w", err)) return } @@ -1627,13 +1603,11 @@ func Update(w http.ResponseWriter, r *http.Request) { } } - if inf.Version.Major >= 3 { - if userErr, sysErr, errCode = updateStatusLastUpdatedTime(id, &statusLastUpdatedTime, tx); userErr != nil || sysErr != nil { - api.HandleErr(w, r, tx, errCode, userErr, sysErr) - return - } - api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Server updated", srvr) + if userErr, sysErr, errCode = updateStatusLastUpdatedTime(id, &statusLastUpdatedTime, tx); userErr != nil || sysErr != nil { + api.HandleErr(w, r, tx, errCode, userErr, sysErr) + return } + api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Server updated", srvr) changeLogMsg := fmt.Sprintf("SERVER: %s.%s, ID: %d, ACTION: updated", *srvr.HostName, *srvr.DomainName, *srvr.ID) api.CreateChangeLogRawTx(api.ApiChange, changeLogMsg, inf.User, tx) @@ -2251,14 +2225,12 @@ func Delete(w http.ResponseWriter, r *http.Request) { api.HandleErr(w, r, tx, errCode, userErr, sysErr) return } - if inf.Version.Major >= 3 { - serverv3, err := server.ToServerV3FromV4(csp) - if err != nil { - api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, err) - return - } - api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Server deleted", serverv3) + serverv3, err := server.ToServerV3FromV4(csp) + if err != nil { + api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, err) + return } + api.WriteRespAlertObj(w, r, tc.SuccessLevel, "Server deleted", serverv3) } changeLogMsg := fmt.Sprintf("SERVER: %s.%s, ID: %d, ACTION: deleted", *server.HostName, *server.DomainName, *server.ID) From 4b0ece290b2554caa5495523e08d3eaa11d18319 Mon Sep 17 00:00:00 2001 From: Zach Hoffman Date: Thu, 7 Jul 2022 16:34:10 -0600 Subject: [PATCH 08/14] Re-add API v3 handling for DSes --- .../traffic_ops_golang/deliveryservice/deliveryservices.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go index 399e6e3ee2..95c369f74b 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go @@ -580,6 +580,8 @@ func (ds *TODeliveryService) Read(h http.Header, useIMS bool) ([]interface{}, er // NOTE: it's required to handle minor version cases in a descending >= manner case version.Major > 3: returnable = append(returnable, ds.RemoveLD1AndLD2()) + case version.Major == 3 && version.Minor >= 1: + returnable = append(returnable, ds.DowngradeToV31()) default: return nil, nil, fmt.Errorf("TODeliveryService.Read called with invalid API version: %d.%d", version.Major, version.Minor), http.StatusInternalServerError, nil } From 9e4ad3037394d9a445e73197d28d988ec860576d Mon Sep 17 00:00:00 2001 From: Zach Hoffman Date: Fri, 8 Jul 2022 11:38:07 -0600 Subject: [PATCH 09/14] Re-add API v3 Delivery Service Read() handling --- .../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 95c369f74b..96fbfc79db 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go @@ -580,8 +580,10 @@ func (ds *TODeliveryService) Read(h http.Header, useIMS bool) ([]interface{}, er // NOTE: it's required to handle minor version cases in a descending >= manner case version.Major > 3: returnable = append(returnable, ds.RemoveLD1AndLD2()) - case version.Major == 3 && version.Minor >= 1: + case version.Major >= 3 && version.Minor >= 1: returnable = append(returnable, ds.DowngradeToV31()) + case version.Major >= 3: + returnable = append(returnable, ds.DowngradeToV31().DeliveryServiceV30) default: return nil, nil, fmt.Errorf("TODeliveryService.Read called with invalid API version: %d.%d", version.Major, version.Minor), http.StatusInternalServerError, nil } From 2f7626f611e523db4e2ac1dfea37782072dae66e Mon Sep 17 00:00:00 2001 From: Zach Hoffman Date: Fri, 8 Jul 2022 11:51:29 -0600 Subject: [PATCH 10/14] Remove more lines in the Dockerfile referencing the API v2 tests and client --- .../cdn-in-a-box/traffic_ops_integration_test/Dockerfile | 2 -- 1 file changed, 2 deletions(-) diff --git a/infrastructure/cdn-in-a-box/traffic_ops_integration_test/Dockerfile b/infrastructure/cdn-in-a-box/traffic_ops_integration_test/Dockerfile index 37c6e1edc4..3e02bae3ba 100644 --- a/infrastructure/cdn-in-a-box/traffic_ops_integration_test/Dockerfile +++ b/infrastructure/cdn-in-a-box/traffic_ops_integration_test/Dockerfile @@ -78,11 +78,9 @@ RUN apk add --no-cache --update \ COPY ./infrastructure/cdn-in-a-box/traffic_ops_integration_test/run.sh /opt/integration/app/ COPY ./infrastructure/cdn-in-a-box/traffic_ops/to-access.sh /opt/integration/app/ COPY ./infrastructure/cdn-in-a-box/traffic_ops_integration_test/config.sh /opt/integration/app/ -COPY ./traffic_ops/testing/api/v2/tc-fixtures.json /opt/integration/app/tc-fixtures-v2.json COPY ./traffic_ops/testing/api/v3/tc-fixtures.json /opt/integration/app/tc-fixtures-v3.json COPY ./traffic_ops/testing/api/v4/tc-fixtures.json /opt/integration/app/tc-fixtures-v4.json COPY --from=integration-builder \ - /go/src/github.com/apache/trafficcontrol/traffic_ops/testing/api/traffic_ops_v2_integration_test \ /go/src/github.com/apache/trafficcontrol/traffic_ops/testing/api/traffic_ops_v3_integration_test \ /go/src/github.com/apache/trafficcontrol/traffic_ops/testing/api/traffic_ops_v4_integration_test \ /opt/integration/app/ From 55cb74b94c6b8772f85632fe69d2b084dbed3a70 Mon Sep 17 00:00:00 2001 From: Zach Hoffman Date: Fri, 8 Jul 2022 11:59:58 -0600 Subject: [PATCH 11/14] Remove more unused functions --- .../deliveryservice/deliveryservices.go | 40 ------------------- 1 file changed, 40 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go index 96fbfc79db..3118eed2f2 100644 --- a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go +++ b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservices.go @@ -195,14 +195,6 @@ func CreateV40(w http.ResponseWriter, r *http.Request) { api.WriteAlertsObj(w, r, http.StatusCreated, alerts, []tc.DeliveryServiceV40{*res}) } -func createV15(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, reqDS tc.DeliveryServiceNullableV15) (*tc.DeliveryServiceNullableV15, int, error, error) { - dsV30 := tc.DeliveryServiceV30{DeliveryServiceNullableV15: reqDS} - res, status, userErr, sysErr := createV30(w, r, inf, dsV30) - if res != nil { - return &res.DeliveryServiceNullableV15, status, userErr, sysErr - } - return nil, status, userErr, sysErr -} func createV30(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, dsV30 tc.DeliveryServiceV30) (*tc.DeliveryServiceV30, int, error, error) { ds := tc.DeliveryServiceV31{DeliveryServiceV30: dsV30} res, status, userErr, sysErr := createV31(w, r, inf, ds) @@ -674,38 +666,6 @@ func UpdateV40(w http.ResponseWriter, r *http.Request) { api.WriteAlertsObj(w, r, http.StatusOK, alerts, []tc.DeliveryServiceV40{*res}) } -func updateV15(w http.ResponseWriter, r *http.Request, inf *api.APIInfo, reqDS *tc.DeliveryServiceNullableV15) (*tc.DeliveryServiceNullableV15, int, error, error) { - dsV30 := tc.DeliveryServiceV30{DeliveryServiceNullableV15: *reqDS} - // query the DB for existing 3.0 fields in order to "upgrade" this 1.5 request into a 3.0 request - query := ` -SELECT - ds.topology, - ds.first_header_rewrite, - ds.inner_header_rewrite, - ds.last_header_rewrite, - ds.service_category -FROM - deliveryservice ds -WHERE - ds.id = $1` - if err := inf.Tx.Tx.QueryRow(query, *reqDS.ID).Scan( - &dsV30.Topology, - &dsV30.FirstHeaderRewrite, - &dsV30.InnerHeaderRewrite, - &dsV30.LastHeaderRewrite, - &dsV30.ServiceCategory, - ); err != nil { - if err == sql.ErrNoRows { - return nil, http.StatusNotFound, fmt.Errorf("delivery service ID %d not found", *dsV30.ID), nil - } - return nil, http.StatusInternalServerError, nil, fmt.Errorf("querying delivery service ID %d: %s", *dsV30.ID, err.Error()) - } - res, status, userErr, sysErr := updateV30(w, r, inf, &dsV30) - if res != nil { - return &res.DeliveryServiceNullableV15, status, userErr, sysErr - } - return nil, status, userErr, sysErr -} 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 From e1534cc5a6ff00af205c41f68d801b1c6b3ab804 Mon Sep 17 00:00:00 2001 From: Zach Hoffman Date: Fri, 8 Jul 2022 12:18:48 -0600 Subject: [PATCH 12/14] Consolidate queryParam map --- traffic_ops/traffic_ops_golang/server/servers.go | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/traffic_ops/traffic_ops_golang/server/servers.go b/traffic_ops/traffic_ops_golang/server/servers.go index 6373e22b63..e9404fa333 100644 --- a/traffic_ops/traffic_ops_golang/server/servers.go +++ b/traffic_ops/traffic_ops_golang/server/servers.go @@ -768,6 +768,7 @@ func getServers(h http.Header, params map[string]string, tx *sqlx.Tx, user *auth queryParamsToSQLCols := map[string]dbhelpers.WhereColumnInfo{ "cachegroup": {Column: "s.cachegroup", Checker: api.IsInt}, "parentCachegroup": {Column: "cg.parent_cachegroup_id", Checker: api.IsInt}, + "cachegroupName": {Column: "cg.name", Checker: nil}, "cdn": {Column: "s.cdn_id", Checker: api.IsInt}, "id": {Column: "s.id", Checker: api.IsInt}, "hostName": {Column: "s.host_name", Checker: nil}, @@ -778,11 +779,6 @@ func getServers(h http.Header, params map[string]string, tx *sqlx.Tx, user *auth "dsId": {Column: "dss.deliveryservice", Checker: nil}, } - queryParamsToSQLCols["cachegroupName"] = dbhelpers.WhereColumnInfo{ - Column: "cg.name", - Checker: nil, - } - if version.Major == 3 { queryParamsToSQLCols["profileId"] = dbhelpers.WhereColumnInfo{ Column: "s.profile", From a712983cabd10f80d6d7183e4940b45ec4391137 Mon Sep 17 00:00:00 2001 From: Zach Hoffman Date: Fri, 8 Jul 2022 13:04:54 -0600 Subject: [PATCH 13/14] Remove API v2 tests gitignore --- traffic_ops/testing/api/v2/.gitignore | 18 ------------------ 1 file changed, 18 deletions(-) delete mode 100644 traffic_ops/testing/api/v2/.gitignore diff --git a/traffic_ops/testing/api/v2/.gitignore b/traffic_ops/testing/api/v2/.gitignore deleted file mode 100644 index 9d8757a3c8..0000000000 --- a/traffic_ops/testing/api/v2/.gitignore +++ /dev/null @@ -1,18 +0,0 @@ -# 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. -# -traffic-ops-test*.conf From fc419ac2ad3749c7b73e8ec06413d557ba487f8e Mon Sep 17 00:00:00 2001 From: Zach Hoffman Date: Fri, 8 Jul 2022 13:08:31 -0600 Subject: [PATCH 14/14] Remove mention of API v2 from comment --- traffic_ops/traffic_ops_golang/dbhelpers/db_helpers.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/traffic_ops/traffic_ops_golang/dbhelpers/db_helpers.go b/traffic_ops/traffic_ops_golang/dbhelpers/db_helpers.go index 73d4db0a9c..7f6407748f 100644 --- a/traffic_ops/traffic_ops_golang/dbhelpers/db_helpers.go +++ b/traffic_ops/traffic_ops_golang/dbhelpers/db_helpers.go @@ -2138,7 +2138,7 @@ func UpdateServerProfileTableForV3(id *int, newProfileId *int, origProfile strin return nil } -// GetServerDetailFromV4 function converts server details from V4 to V3/V2 +// GetServerDetailFromV4 function converts server details from V4 to V3 func GetServerDetailFromV4(sd tc.ServerDetailV40, tx *sql.Tx) (tc.ServerDetail, error) { var profileDesc *string if err := tx.QueryRow(`SELECT p.description FROM profile p WHERE p.name=$1`, sd.ProfileNames[0]).Scan(&profileDesc); err != nil {