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

 ##########
 File path: traffic_ops/traffic_ops_golang/deliveryservice/servers/servers.go
 ##########
 @@ -263,7 +243,409 @@ 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 {
+
+       selectStmt := `SELECT
+       s.deliveryService,
+       s.server,
+       s.last_updated
+       FROM deliveryservice_server s
+       ORDER BY `+ orderby +` LIMIT `+limit+` OFFSET `+offset+` ROWS`
+
+       return selectStmt
+}
+
+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) {
+               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
+               defer r.Body.Close()
+               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
+               }
+               rollbackTransaction = false
+               resAlerts := []tc.Alert{ tc.Alert{"sever 
assignement","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
+               }
+
+               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)
+               }
+
+               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
+                       }
+               }
+
+               row := db.QueryRow(selectDeliveryService(), xmlId)
+               var dsId int
+               row.Scan(&dsId)
+
+               // get list of server Ids to insert
+               defer r.Body.Close()
+               payload := GetServersRef()
+
+               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
+               }
+
+               payload.XmlId = xmlId
+               serverNames := payload.ServerNames
+               q, arg, err := sqlx.In(selectServerIds(), serverNames)
+
+               if err != nil {
+                       log.Error.Printf("Could not form IN query : %v", err)
+                       handleErrs(http.StatusInternalServerError, err)
+                       return
+               }
+               q = sqlx.Rebind(sqlx.DOLLAR, q)
+               serverIds, err := db.Query(q, arg...)
+               defer serverIds.Close()
+               if err != nil {
+                       log.Error.Printf("Could not select the ServerIds: %v", 
err)
+                       handleErrs(http.StatusInternalServerError, 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
+               }
+
+               // We have to get the server Ids and iterate through them 
because of a bug in the Go
+               // transaction which returns an error if you perform a Select 
after an Insert in
+               // the same transaction
+               for serverIds.Next() {
+                       var serverId int
+                       err := serverIds.Scan(&serverId)
+                       dtos := map[string]interface{}{"id":dsId, 
"server":serverId}
+                       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
+                       }
+                       resultRows.Next()
+               }
+
+               err = tx.Commit()
+               if err != nil {
+                       log.Errorln("Could not commit transaction: ", err)
+                       return
+               }
+               rollbackTransaction = false
+
+               // marshal the results to the response stream
+               tcPayload := tc.DeliveryServiceServers{payload.ServerNames, 
payload.XmlId}
+               payloadResp := tc.DSServersResponse{tcPayload}
+               respBts, err := json.Marshal(payloadResp)
+               if err != nil {
+                       log.Errorln("Could not marshal the response as 
expected: ", err)
+                       handleErrs(http.StatusInternalServerError, err)
+                       return
+               }
+
+               w.Header().Set(tc.ContentType, tc.ApplicationJson)
+               fmt.Fprintf(w, "%s", respBts)
+               return
+       }
+}
+
+func selectDeliveryService() string {
+       query := `SELECT id FROM deliveryservice WHERE xml_id = $1`
+       return query
+}
+
+func insertIdsQuery() string {
+       query := `INSERT INTO deliveryservice_server (deliveryservice, server) 
+VALUES (:id, :server )`
+       return query
+}
+
+func selectServerIds() string {
+       query := `SELECT id FROM server WHERE host_name in (?)`
+       return query
+}
+
+// api/1.1/deliveryservices/{id}/servers|unassigned_servers|eligible
+func GetReadHandler(db *sqlx.DB, filter string) http.HandlerFunc {
+       return func(w http.ResponseWriter, r *http.Request) {
+               handleErrs := tc.GetHandleErrorsFunc(w, r)
+               params, err := api.GetCombinedParams(r)
+               if err != nil {
+                       log.Errorf("unable to get parameters from request: %s", 
err)
+                       handleErrs(http.StatusInternalServerError, err)
+               }
+
+               where := `WHERE s.id in (select server from 
deliveryservice_server where deliveryservice = $1)`
+
+               if filter[0] == 'u' {
 
 Review comment:
   This will panic if filter is empty. Should be `if len(filter) > 0  && 
filter[0] == 'u' {`

----------------------------------------------------------------
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:
[email protected]


With regards,
Apache Git Services

Reply via email to