mhoppa commented on a change in pull request #3758: Rewrote 
deliveryservice_stats to Go
URL: https://github.com/apache/trafficcontrol/pull/3758#discussion_r330270574
 
 

 ##########
 File path: traffic_ops/traffic_ops_golang/trafficstats/trafficstats.go
 ##########
 @@ -0,0 +1,594 @@
+package trafficstats
+
+/*
+ * 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"
+import "encoding/json"
+import "errors"
+import "fmt"
+import "net/http"
+import "strconv"
+import "strings"
+import "time"
+
+import "github.com/apache/trafficcontrol/lib/go-tc"
+import "github.com/apache/trafficcontrol/lib/go-rfc"
+import "github.com/apache/trafficcontrol/lib/go-log"
+import "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
+import "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/tenant"
+
+import influx "github.com/influxdata/influxdb1-client/v2"
+
+var (
+       metricTypes = map[string]interface{}{
+               "kbps":      struct{}{},
+               "tps_total": struct{}{},
+               "tps_2xx":   struct{}{},
+               "tps_3xx":   struct{}{},
+               "tps_4xx":   struct{}{},
+               "tps_5xx":   struct{}{},
+       }
+
+       jsonWithRFCTimestamps = rfc.MimeType{
+               "application/json",
+               map[string]string{"timestamp": "rfc"},
+       }
+
+       jsonWithUnixTimestamps = rfc.MimeType{
+               "application/json",
+               map[string]string{"timestamp": "unix"},
+       }
+)
+
+const (
+       DEFAULT_INTERVAL         = tc.TrafficStatsDuration("1m")
+       dsTenantIDFromXMLIDQuery = `
+               SELECT tenant_id
+               FROM deliveryservice
+               WHERE xml_id = $1`
+
+       xmlidFromIDQuery = `
+               SELECT xml_id
+               FROM deliveryservice
+               WHERE id = $1`
+
+       // TODO: Pretty sure all of this could actually be calculated using the 
fetched data (assuming an
+       // interval is given). Check to see if that's faster than doing another 
synchronous HTTP request.
+       summaryQuery = `
+               SELECT mean(value) AS "average",
+                      percentile(value, 5) AS "fifthPercentile",
+                      percentile(value, 95) AS "ninetyFifthPercentile",
+                      percentile(value, 98) AS "ninetyEighthPercentile",
+                      min(value) AS "min",
+                      max(value) AS "max",
+                      count(value) AS "count"
+               FROM "%s"."monthly"."%s.ds.1min"
+               WHERE time >= $start
+               AND time <= $end
+               AND cachegroup = 'total'
+               AND deliveryservice = $xmlid`
+
+       seriesQuery = `
+               SELECT mean(value) AS "value"
+               FROM "%s"."monthly"."%s.ds.1min"
+               WHERE cachegroup = 'total'
+               AND deliveryservice = $xmlid
+               AND time >= $start
+               AND time <= $end
+               GROUP BY time(%s, %s), cachegroup%s`
+)
+
+func configFromRequest(r *http.Request, i *api.APIInfo) 
(tc.TrafficStatsConfig, error, int) {
+       var c tc.TrafficStatsConfig
+       var e error
+       if accept := r.Header.Get("Accept"); accept != "" {
+
+               mimes, err := rfc.MimeTypesFromAccept(accept)
+               if err != nil {
+                       log.Warnf("Failed to negotiate content, Accept line 
'%s', error: %v", accept, err)
+               } else {
+
+                       found := false
+                       for _, m := range mimes {
+                               if jsonWithRFCTimestamps.Satisfy(m) {
+                                       found = true
+                                       break
+                               }
+
+                               if jsonWithUnixTimestamps.Satisfy(m) {
+                                       found = true
+                                       c.Unix = true
+                                       break
+                               }
+                       }
+
+                       if !found {
+                               e = fmt.Errorf("Failed to negotiate content; 
cannot produce output satisfying %s", accept)
+                               return c, e, http.StatusNotAcceptable
+                       }
+               }
+       }
+
+       if limit, ok := i.Params["limit"]; ok {
+               lim, err := strconv.ParseUint(limit, 10, 64)
+               if err != nil {
+                       e = errors.New("Invalid limit!")
+                       return c, e, http.StatusBadRequest
+               }
+               c.Limit = &lim
+       }
+
+       if offset, ok := i.Params["offset"]; ok {
+               off, err := strconv.ParseUint(offset, 10, 64)
+               if err != nil {
+                       e = errors.New("Invalid offset!")
+                       return c, e, http.StatusBadRequest
+               }
+               c.Offset = &off
+       }
+
+       if orderby, ok := i.Params["orderby"]; ok {
+               if c.OrderBy = tc.OrderableFromString(orderby); c.OrderBy == 
nil {
+                       e = errors.New("Invalid orderby! Must be 'time' or 
'value'")
+                       return c, e, http.StatusBadRequest
+               }
+       }
+
+       if c.Start, e = parseTime(i.Params["startDate"]); e != nil {
+               log.Errorf("Parsing startDate: %v", e)
+               e = errors.New("Invalid startDate!")
+               return c, e, http.StatusBadRequest
+       }
+
+       if c.End, e = parseTime(i.Params["endDate"]); e != nil {
+               log.Errorf("Parsing endDate: %v", e)
+               e = errors.New("Invalid endDate!")
+               return c, e, http.StatusBadRequest
+       }
+
+       if interval, ok := i.Params["interval"]; !ok {
+               c.Interval = DEFAULT_INTERVAL
+       } else if c.Interval = tc.TrafficStatsDurationFromString(interval); 
c.Interval == tc.InvalidDuration {
+               log.Errorf("Error parsing 'interval' query parameter: %v", e)
+               e = errors.New("Invalid interval!")
+               return c, e, http.StatusBadRequest
+       }
+
+       if ex, ok := i.Params["exclude"]; ok {
+               switch tc.ExcludeFromString(ex) {
+               case tc.ExcludeSummary:
+                       c.ExcludeSummary = true
+               case tc.ExcludeSeries:
+                       c.ExcludeSeries = true
+               default:
+                       e = errors.New("Invalid exclude! Must be 'series' or 
'summary'")
+                       return c, e, http.StatusBadRequest
+               }
+       }
+
+       c.MetricType = i.Params["metricType"]
+       if _, ok := metricTypes[c.MetricType]; !ok {
+               e = fmt.Errorf("Unknown metric type: %s", c.MetricType)
+               return c, e, http.StatusBadRequest
+       }
+
+       var ok bool
+       if c.DeliveryService, ok = i.Params["deliveryServiceName"]; !ok {
+               if c.DeliveryService, ok = i.Params["deliveryService"]; !ok {
+                       e = errors.New("You must specify deliveryService or 
deliveryServiceName!")
+                       return c, e, http.StatusBadRequest
+               }
+
+               if dsID, err := strconv.ParseUint(c.DeliveryService, 10, 64); 
err != nil {
+                       // sql.ErrNoRows does not *necessarily* mean the DS 
doesn't exist - an XMLID can simply
+                       // be numeric, and so it was wrong to treat it as an ID 
in the first place.
+                       xmlid := c.DeliveryService
+                       var exists bool
+                       if exists, c.DeliveryService, err = 
getXMLIDFromID(dsID, i.Tx.Tx); err != nil {
+                               log.Errorf("Converting DSID to XMLID: %v", err)
+                               e = errors.New("Internal Server Error")
+                               return c, e, http.StatusInternalServerError
+                       } else if !exists {
+                               c.DeliveryService = xmlid
+                       }
+               }
+       }
+
+       return c, nil, http.StatusOK
+}
+
+func GetDSStats(w http.ResponseWriter, r *http.Request) {
+       // Perl didn't require "interval", but it would only return summary 
data if it was not given
+       inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"metricType", 
"startDate", "endDate"}, nil)
+       tx := inf.Tx.Tx
+       if userErr != nil || sysErr != nil {
+               api.HandleErr(w, r, tx, errCode, userErr, sysErr)
+               return
+       }
+       defer inf.Close()
+
+       var c tc.TrafficStatsConfig
+       if c, userErr, errCode = configFromRequest(r, inf); userErr != nil {
+               sysErr = fmt.Errorf("Unable to process deliveryservice_stats 
request: %v", userErr)
+               api.HandleErr(w, r, tx, errCode, userErr, sysErr)
+               return
+       }
+
+       client, err := inf.CreateInfluxClient()
+       if err != nil {
+               errCode = http.StatusInternalServerError
+               sysErr = err
+               api.HandleErr(w, r, tx, errCode, nil, sysErr)
+               return
+       } else if client == nil {
+               sysErr = errors.New("Traffic Stats is not configured, but DS 
stats were requested")
+               errCode = http.StatusInternalServerError
+               api.HandleErr(w, r, tx, errCode, nil, sysErr)
+               return
+       }
+       defer (*client).Close()
+
+       exists, dsTenant, err := dsTenantIDFromXMLID(c.DeliveryService, tx)
+       if err != nil {
+               sysErr = err
+               errCode = http.StatusInternalServerError
+               api.HandleErr(w, r, tx, errCode, nil, sysErr)
+               return
+       } else if !exists {
+               userErr = fmt.Errorf("No such Delivery Service: %s", 
c.DeliveryService)
+               errCode = http.StatusNotFound
+               api.HandleErr(w, r, tx, errCode, userErr, nil)
+               return
+       }
+
+       authorized, err := tenant.IsResourceAuthorizedToUserTx(int(dsTenant), 
inf.User, tx)
+       if err != nil {
+               api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, 
err)
+               return
+       } else if !authorized {
+               // If the Tenant is not authorized to use the resource, then we 
DON'T tell them that.
+               // Instead, we don't disclose that such a Delivery Service 
exists at all - in keeping with
+               // the behavior of /deliveryservices
+               // This is different from what Perl used to do, but then again 
Perl didn't check tenancy at
+               // all.
+               userErr = fmt.Errorf("No such Delivery Service: %s", 
c.DeliveryService)
+               sysErr = fmt.Errorf("GetDSStats: unauthorized Tenant (#%d) 
access", inf.User.TenantID)
+               errCode = http.StatusNotFound
+               api.HandleErr(w, r, tx, errCode, userErr, sysErr)
+               return
+       }
+
+       resp := struct{ Response tc.TrafficStatsResponse }{
 
 Review comment:
   this needs a json tag so the response is not capitalized on the return  

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

Reply via email to