rob05c commented on a change in pull request #2282: Deliveryservice_Server API 
conversion to Go - formerly #2269
URL: 
https://github.com/apache/incubator-trafficcontrol/pull/2282#discussion_r189706518
 
 

 ##########
 File path: traffic_ops/traffic_ops_golang/deliveryservice/servers/servers.go
 ##########
 @@ -263,7 +243,428 @@ func (dss *TODeliveryServiceServer) Delete(db *sqlx.DB, 
user auth.CurrentUser) (
        rollbackTransaction = false
        return nil, tc.NoError
 }
-func selectQuery() string {
+
+func selectQuery(orderBy string, limit string, offset string) (string, error) {
+
+       selectStmt := `SELECT
+       s.deliveryService,
+       s.server,
+       s.last_updated
+       FROM deliveryservice_server s`
+
+       allowedOrderByCols := map[string]string{
+               "":                "",
+               "deliveryservice": "s.deliveryService",
+               "server":          "s.server",
+               "lastupdated":     "s.last_updated",
+               "deliveryService": "s.deliveryService",
+               "lastUpdated":     "s.last_updated",
+               "last_updated":    "s.last_updated",
+       }
+       orderBy, ok := allowedOrderByCols[orderBy]
+       if !ok {
+               return "", errors.New("orderBy '" + orderBy + "' not permitted")
+       }
+
+       if orderBy != "" {
+               selectStmt += ` ORDER BY ` + orderBy
+       }
+
+       selectStmt += ` LIMIT ` + limit + ` OFFSET ` + offset + ` ROWS`
+       return selectStmt, nil
+}
+
+func deleteQuery() string {
+       query := `DELETE FROM deliveryservice_server
+       WHERE deliveryservice=:deliveryservice and server=:server`
+       return query
+}
+
+type DSServers struct {
+       DsId    *int  `json:"dsId" db:"deliveryservice"`
+       Servers []int `json:"servers"`
+       Replace *bool `json:"replace"`
+}
+
+type TODSServers DSServers
+
+var dsserversRef = TODSServers(DSServers{})
+
+func GetServersForDsIdRef() *TODSServers {
+       return &dsserversRef
+}
+
+func GetReplaceHandler(db *sqlx.DB) http.HandlerFunc {
+       return func(w http.ResponseWriter, r *http.Request) {
+               defer r.Body.Close()
+               handleErrs := tc.GetHandleErrorsFunc(w, r)
+               ctx := r.Context()
+               user, err := auth.GetCurrentUser(ctx)
+               if err != nil {
+                       log.Errorf("unable to retrieve current user from 
context: %s", err)
+                       handleErrs(http.StatusInternalServerError, err)
+                       return
+               }
+
+               // get list of server Ids to insert
+               payload := GetServersForDsIdRef()
+               servers := payload.Servers
+               dsId := payload.DsId
+
+               if err := json.NewDecoder(r.Body).Decode(payload); err != nil {
+                       log.Errorf("Error trying to decode the request body: 
%s", err)
+                       handleErrs(http.StatusInternalServerError, err)
+                       return
+               }
+
+               // if the object has tenancy enabled, check that user is able 
to access the tenant
+               // check user tenancy access to this resource.
+               row := db.QueryRow("SELECT xml_id FROM deliveryservice WHERE id 
= $1", *dsId)
+               var xmlId string
+               row.Scan(&xmlId)
+               hasAccess, err, apiStatus := tenant.HasTenant(*user, xmlId, db)
+               if !hasAccess {
+                       switch apiStatus {
+                       case tc.SystemError:
+                               handleErrs(http.StatusInternalServerError, err)
+                               return
+                       case tc.DataMissingError:
+                               handleErrs(http.StatusBadRequest, err)
+                               return
+                       case tc.ForbiddenError:
+                               handleErrs(http.StatusForbidden, err)
+                               return
+                       }
+               }
+
+               // perform the insert transaction
+               rollbackTransaction := true
+               tx, err := db.Beginx()
+               defer func() {
+                       if tx == nil || !rollbackTransaction {
+                               return
+                       }
+                       err := tx.Rollback()
+                       if err != nil {
+                               log.Errorln(errors.New("rolling back 
transaction: " + err.Error()))
+                       }
+               }()
+
+               if err != nil {
+                       log.Error.Printf("could not begin transaction: %v", err)
+                       handleErrs(http.StatusInternalServerError, err)
+                       return
+               }
+
+               if *payload.Replace {
+                       // delete existing
+                       rows, err := db.Queryx("DELETE FROM 
deliveryservice_server WHERE deliveryservice = $1", *dsId)
+                       if err != nil {
+                               log.Errorf("unable to remove the existing 
servers assigned to the delivery service: %s", err)
+                               handleErrs(http.StatusInternalServerError, err)
+                               return
+                       }
+
+                       defer rows.Close()
+               }
+
+               i := 0
+               respServers := []int{}
+
+               for i < len(servers) {
+                       dtos := map[string]interface{}{"id": dsId, "server": 
servers[i]}
+                       resultRows, err := tx.NamedQuery(insertIdsQuery(), dtos)
+                       if err != nil {
+                               if pqErr, ok := err.(*pq.Error); ok {
+                                       err, eType := 
dbhelpers.ParsePQUniqueConstraintError(pqErr)
+                                       log.Error.Printf("could not begin 
transaction: %v", err)
+                                       if eType == tc.DataConflictError {
+                                               
handleErrs(http.StatusInternalServerError, err)
+                                               return
+                                       }
+                                       
handleErrs(http.StatusInternalServerError, err)
+                                       return
+                               }
+                               log.Errorf("received non pq error: %++v from 
create execution", err)
+                               return
+                       }
+                       respServers = append(respServers, servers[i])
+                       resultRows.Next()
+                       i++
+                       defer resultRows.Close()
+               }
+
+               err = tx.Commit()
+               if err != nil {
+                       log.Errorln("Could not commit transaction: ", err)
+                       return
+               }
+               resAlerts := []tc.Alert{tc.Alert{"server assignements 
complete", "success"}}
+               repRes := tc.DSSReplaceResponse{resAlerts, 
tc.DSSMapResponse{*dsId, *payload.Replace, respServers}}
+
+               // marshal the results to the response stream
+               respBts, err := json.Marshal(repRes)
+               if err != nil {
+                       log.Errorln("Could not marshal the response as 
expected: ", err)
+                       handleErrs(http.StatusInternalServerError, err)
+                       return
+               }
+
+               rollbackTransaction = false
+               w.Header().Set(tc.ContentType, tc.ApplicationJson)
+               fmt.Fprintf(w, "%s", respBts)
+               return
+       }
+}
+
+type TODeliveryServiceServers tc.DeliveryServiceServers
+
+var serversRef = TODeliveryServiceServers(tc.DeliveryServiceServers{})
+
+func GetServersRef() *TODeliveryServiceServers {
+       return &serversRef
+}
+
+// api/1.1/deliveryservices/{xml_id}/servers
+func GetCreateHandler(db *sqlx.DB) http.HandlerFunc {
+       return func(w http.ResponseWriter, r *http.Request) {
+               handleErrs := tc.GetHandleErrorsFunc(w, r)
+
+               // find the delivery service Id dsId matching the xml_id
+               params, err := api.GetCombinedParams(r)
+               if err != nil {
+                       log.Errorf("unable to get parameters from request: %s", 
err)
+                       handleErrs(http.StatusInternalServerError, err)
+                       return
+               }
+
+               xmlId, ok := params["xml_id"]
+               if !ok {
+                       log.Errorf("unable to get xml_id parameter from 
request: %s", err)
+                       handleErrs(http.StatusInternalServerError, err)
+                       return
+               }
+
+               ctx := r.Context()
+               user, err := auth.GetCurrentUser(ctx)
+               if err != nil {
+                       log.Errorf("unable to retrieve current user from 
context: %s", err)
+                       handleErrs(http.StatusInternalServerError, err)
+                       return
+               }
+
+               // if the object has tenancy enabled, check that user is able 
to access the tenant
+               // check user tenancy access to this resource.
+               hasAccess, err, apiStatus := tenant.HasTenant(*user, xmlId, db)
+               if !hasAccess {
+                       switch apiStatus {
+                       case tc.SystemError:
+                               handleErrs(http.StatusInternalServerError, err)
+                               return
+                       case tc.DataMissingError:
+                               handleErrs(http.StatusBadRequest, err)
+                               return
+                       case tc.ForbiddenError:
+                               handleErrs(http.StatusForbidden, err)
+                               return
+                       default:
+                               e := http.StatusInternalServerError
+                               handleErrs(e, err)
+                               return
+                       }
+               }
+
+               row := db.QueryRow(selectDeliveryService(), xmlId)
+               var dsId int
+               row.Scan(&dsId)
+
+               // get list of server Ids to insert
+               defer r.Body.Close()
+               payload := GetServersRef()
 
 Review comment:
   This is decoding a request into a pointer to a global variable. This isn't 
safe, it will decode multiple concurrent requests into the same object. 
   
   You can fix it by changing `GetServersRef()` to `s := 
TODeliveryServiceServers(tc.DeliveryServiceServers{}); return &s`, so every 
request gets a new object.

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


With regards,
Apache Git Services

Reply via email to