This is an automated email from the ASF dual-hosted git repository.

ocket8888 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/trafficcontrol.git


The following commit(s) were added to refs/heads/master by this push:
     new a5a4bb9  Add TO-Go /api/1.1/servers/status GET handler (#4013)
a5a4bb9 is described below

commit a5a4bb9012676125a160b9e7da0d6834f90b376e
Author: Rawlin Peters <[email protected]>
AuthorDate: Fri Oct 25 14:55:23 2019 -0600

    Add TO-Go /api/1.1/servers/status GET handler (#4013)
    
    * Add TO-Go /api/1.1/servers/status GET handler
    
    * Add client method and API tests
    
    * Add changelog entry
    
    * Add missing query params to API docs
    
    * Change from regex match to equals match
---
 CHANGELOG.md                                       |  1 +
 docs/source/api/servers_status.rst                 |  8 ++-
 traffic_ops/client/serversstatus.go                | 44 +++++++++++++
 traffic_ops/testing/api/v14/serversstatus_test.go  | 52 +++++++++++++++
 traffic_ops/traffic_ops_golang/routing/routes.go   |  2 +-
 .../traffic_ops_golang/server/status_count.go      | 76 ++++++++++++++++++++++
 6 files changed, 181 insertions(+), 2 deletions(-)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7e8719d..4458f00 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,7 @@ The format is based on [Keep a 
Changelog](http://keepachangelog.com/en/1.0.0/).
   - /api/1.1/deliveryservices/hostname/:hostname/sslkeys `GET`
   - /api/1.1/deliveryservices/sslkeys/add `POST`
   - /api/1.1/deliveryservices/xmlId/:xmlid/sslkeys/delete `GET`
+  - /api/1.1/servers/status `GET`
   - /api/1.4/cdns/dnsseckeys/refresh `GET`
   - /api/1.1/cdns/name/:name/dnsseckeys `GET`
   - /api/1.1/roles `GET`
diff --git a/docs/source/api/servers_status.rst 
b/docs/source/api/servers_status.rst
index 2d8f155..9d2b626 100644
--- a/docs/source/api/servers_status.rst
+++ b/docs/source/api/servers_status.rst
@@ -29,7 +29,13 @@ Retrieves an aggregated view of all server statuses across 
all CDNs
 
 Request Structure
 -----------------
-No parameters available.
+.. table:: Request Query Parameters
+
+    
+------------+----------+-------------------------------------------------------------------------------------------------------------------+
+    | Name       | Required | Description                                      
                                                                 |
+    
+============+==========+===================================================================================================================+
+    | type       | no       | Return status counts for only servers of this 
:term:`Type`                                                        |
+    
+------------+----------+-------------------------------------------------------------------------------------------------------------------+
 
 Response Structure
 ------------------
diff --git a/traffic_ops/client/serversstatus.go 
b/traffic_ops/client/serversstatus.go
new file mode 100644
index 0000000..65750b7
--- /dev/null
+++ b/traffic_ops/client/serversstatus.go
@@ -0,0 +1,44 @@
+/*
+
+   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 (
+       "fmt"
+       "net"
+       "net/url"
+)
+
+const APIServersStatus = apiBase + "/servers/status"
+
+// GetServerStatusCounts gets the counts of each server status in Traffic Ops.
+// If typeName is non-nil, only statuses of the given server type name will be 
counted.
+func (to *Session) GetServerStatusCounts(typeName *string) (map[string]int, 
ReqInf, error) {
+       var remoteAddr net.Addr
+       reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: 
remoteAddr}
+       reqUrl := APIServersStatus
+       if typeName != nil {
+               reqUrl += fmt.Sprintf("?type=%s", url.QueryEscape(*typeName))
+       }
+       resp := struct {
+               Response map[string]int `json:"response"`
+       }{make(map[string]int)}
+
+       reqInf, err := get(to, reqUrl, &resp)
+       if err != nil {
+               return nil, reqInf, err
+       }
+       return resp.Response, reqInf, nil
+}
diff --git a/traffic_ops/testing/api/v14/serversstatus_test.go 
b/traffic_ops/testing/api/v14/serversstatus_test.go
new file mode 100644
index 0000000..9837a1c
--- /dev/null
+++ b/traffic_ops/testing/api/v14/serversstatus_test.go
@@ -0,0 +1,52 @@
+package v14
+
+/*
+
+   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-util"
+)
+
+func TestServerStatusCounts(t *testing.T) {
+       WithObjs(t, []TCObj{CDNs, Types, Parameters, Profiles, Statuses, 
Divisions, Regions, PhysLocations, CacheGroups, Servers}, func() {
+               GetTestServerStatusCounts(t)
+       })
+}
+
+func GetTestServerStatusCounts(t *testing.T) {
+       servers, _, err := TOSession.GetServers()
+       if err != nil {
+               t.Errorf("cannot GET Servers: %v", err)
+       }
+       manualCounts := make(map[string]int)
+       manualEdgeCounts := make(map[string]int)
+       for _, server := range servers {
+               manualCounts[server.Status]++
+               if server.Type == "EDGE" {
+                       manualEdgeCounts[server.Status]++
+               }
+       }
+       apiCounts, _, err := TOSession.GetServerStatusCounts(nil)
+       if !reflect.DeepEqual(manualCounts, apiCounts) {
+               t.Errorf("expected server status counts: %v, actual: %v", 
manualCounts, apiCounts)
+       }
+       apiEdgeCounts, _, err := 
TOSession.GetServerStatusCounts(util.StrPtr("EDGE"))
+       if !reflect.DeepEqual(manualEdgeCounts, apiEdgeCounts) {
+               t.Errorf("expected EDGE server status counts: %v, actual: %v", 
manualEdgeCounts, apiEdgeCounts)
+       }
+}
diff --git a/traffic_ops/traffic_ops_golang/routing/routes.go 
b/traffic_ops/traffic_ops_golang/routing/routes.go
index 8c95196..2b4dde5 100644
--- a/traffic_ops/traffic_ops_golang/routing/routes.go
+++ b/traffic_ops/traffic_ops_golang/routing/routes.go
@@ -265,7 +265,7 @@ func Routes(d ServerData) ([]Route, []RawRoute, 
http.Handler, error) {
                {1.1, http.MethodGet, `deliveryservice_matches/?(\.json)?$`, 
deliveryservice.GetMatches, auth.PrivLevelReadOnly, Authenticated, nil},
 
                //Server
-               {1.1, http.MethodGet, `servers/status$`, 
handlerToFunc(proxyHandler), 0, NoAuth, []Middleware{}},
+               {1.1, http.MethodGet, `servers/status$`, 
server.GetServersStatusCountsHandler, auth.PrivLevelReadOnly, Authenticated, 
nil},
                {1.1, http.MethodGet, `servers/totals$`, 
handlerToFunc(proxyHandler), 0, NoAuth, []Middleware{}},
 
                //Serverchecks
diff --git a/traffic_ops/traffic_ops_golang/server/status_count.go 
b/traffic_ops/traffic_ops_golang/server/status_count.go
new file mode 100644
index 0000000..d268f2f
--- /dev/null
+++ b/traffic_ops/traffic_ops_golang/server/status_count.go
@@ -0,0 +1,76 @@
+package server
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+       "database/sql"
+       "errors"
+       "net/http"
+
+       "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
+)
+
+func GetServersStatusCountsHandler(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()
+
+       statusCounts, err := getServersStatusCounts(inf.Tx.Tx, 
inf.Params["type"])
+       if err != nil {
+               api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, 
nil, errors.New("getting servers status counts: "+err.Error()))
+               return
+       }
+       api.WriteResp(w, r, statusCounts)
+}
+
+func getServersStatusCounts(tx *sql.Tx, typeName string) (map[string]int, 
error) {
+       where := ""
+       args := make([]interface{}, 0, 1)
+       if typeName != "" {
+               where = "WHERE type.name = $1"
+               args = append(args, typeName)
+       }
+       q := `
+SELECT status.name, count(server.id)
+FROM server
+JOIN status ON server.status = status.id
+JOIN type ON server.type = type.id
+` + where + `
+GROUP BY status.id
+`
+       rows, err := tx.Query(q, args...)
+       if err != nil {
+               return nil, errors.New("querying server status counts: " + 
err.Error())
+       }
+       defer rows.Close()
+       statusCounts := map[string]int{}
+       for rows.Next() {
+               statusName := ""
+               count := 0
+               if err := rows.Scan(&statusName, &count); err != nil {
+                       return nil, errors.New("scanning server status counts: 
" + err.Error())
+               }
+               statusCounts[statusName] = count
+       }
+       return statusCounts, nil
+}

Reply via email to