kdamichie commented on code in PR #7605:
URL: https://github.com/apache/trafficcontrol/pull/7605#discussion_r1281002989


##########
traffic_ops/traffic_ops_golang/cachegroup/cachegroups.go:
##########
@@ -897,3 +955,483 @@ last_updated`
 func DeleteQuery() string {
        return `DELETE FROM cachegroup WHERE id=$1`
 }
+
+// Get [Version : V5] function Process the *http.Request and writes the 
response. It uses GetCacheGroup function.
+func Get(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()
+
+       code := http.StatusOK
+       useIMS := false
+       config, e := api.GetConfig(r.Context())
+       if e == nil && config != nil {
+               useIMS = config.UseIMS
+       } else {
+               log.Warnf("Couldn't get config %v", e)
+       }
+
+       var maxTime time.Time
+       var usrErr error
+       var syErr error
+
+       var cgList []interface{}
+
+       tx := inf.Tx
+
+       cgList, maxTime, code, usrErr, syErr = GetCacheGroup(tx, inf.Params, 
useIMS, r.Header)
+       if code == http.StatusNotModified {
+               w.WriteHeader(code)
+               api.WriteResp(w, r, []tc.CacheGroupV5{})
+               return
+       }
+
+       if code == http.StatusBadRequest {
+               api.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, usrErr, 
nil)
+               return
+       }
+
+       if sysErr != nil {
+               api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, 
nil, syErr)
+               return
+       }
+
+       if maxTime != (time.Time{}) && api.SetLastModifiedHeader(r, useIMS) {
+               api.AddLastModifiedHdr(w, maxTime)
+       }
+
+       api.WriteResp(w, r, cgList)
+}
+
+// GetCacheGroup [Version : V5] receives transactions from Get function and 
returns cache groups list.
+func GetCacheGroup(tx *sqlx.Tx, params map[string]string, useIMS bool, header 
http.Header) ([]interface{}, time.Time, int, error, error) {
+       //func GetCacheGroup(tx *sqlx.Tx, params map[string]string, useIMS 
bool, header http.Header) ([]tc.CacheGroupV5, time.Time, int, error, error) {
+       var runSecond bool
+       var maxTime time.Time
+       cgList := []interface{}{}
+       //cgList := []tc.CacheGroupV5{}
+
+       // Query Parameters to Database Query column mappings
+       queryParamsToQueryCols := map[string]dbhelpers.WhereColumnInfo{
+               "id":        {Column: "cachegroup.id", Checker: api.IsInt},
+               "name":      {Column: "cachegroup.name"},
+               "shortName": {Column: "cachegroup.short_name"},
+               "type":      {Column: "cachegroup.type"},
+               "topology":  {Column: "topology_cachegroup.topology"},
+       }
+       if _, ok := params["orderby"]; !ok {
+               params["orderby"] = "name"
+       }
+       where, orderBy, pagination, queryValues, errs := 
dbhelpers.BuildWhereAndOrderByAndPagination(params, queryParamsToQueryCols)
+       if len(errs) > 0 {
+               return nil, time.Time{}, http.StatusBadRequest, 
util.JoinErrs(errs), nil
+       }
+
+       if useIMS {
+               runSecond, maxTime = ims.TryIfModifiedSinceQuery(tx, header, 
queryValues, selectMaxLastUpdatedQuery(where))
+               if !runSecond {
+                       log.Debugln("IMS HIT")
+                       return cgList, maxTime, http.StatusNotModified, nil, nil
+               }
+               log.Debugln("IMS MISS")
+       } else {
+               log.Debugln("Non IMS request")
+       }
+       baseSelect := SelectQuery()
+       if _, ok := params["topology"]; ok {
+               baseSelect += `
+               LEFT JOIN topology_cachegroup ON cachegroup.name = 
topology_cachegroup.cachegroup
+               `
+       }
+       // If the type cannot be converted to an int, return 400
+       if cgType, ok := params["type"]; ok {
+               _, err := strconv.Atoi(cgType)
+               if err != nil {
+                       return nil, time.Time{}, http.StatusBadRequest, nil, 
fmt.Errorf("cachegroup read: converting cachegroup type to integer " + 
err.Error())
+               }
+       }
+
+       query := baseSelect + where + orderBy + pagination
+       rows, err := tx.NamedQuery(query, queryValues)
+       if err != nil {
+               return nil, time.Time{}, http.StatusInternalServerError, nil, 
err
+       }
+       defer rows.Close()
+
+       for rows.Next() {
+               var cg TOCacheGroupV5
+               lms := make([]tc.LocalizationMethod, 0)
+               cgfs := make([]string, 0)
+               if err = rows.Scan(
+                       &cg.ID,
+                       &cg.Name,
+                       &cg.ShortName,
+                       &cg.Latitude,
+                       &cg.Longitude,
+                       pq.Array(&lms),
+                       &cg.ParentCachegroupID,
+                       &cg.ParentName,
+                       &cg.SecondaryParentCachegroupID,
+                       &cg.SecondaryParentName,
+                       &cg.Type,
+                       &cg.TypeID,
+                       &cg.LastUpdated,
+                       pq.Array(&cgfs),
+                       &cg.FallbackToClosest,
+               ); err != nil {
+                       return nil, time.Time{}, 
http.StatusInternalServerError, nil, err
+               }
+               cg.LocalizationMethods = &lms
+               cg.Fallbacks = &cgfs
+               cgList = append(cgList, cg)
+       }
+
+       return cgList, maxTime, http.StatusOK, nil, nil
+}
+
+// CreateCacheGroup [Version : V5] function creates the cache group with the 
passed name.
+func CreateCacheGroup(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()
+       tx := inf.Tx.Tx
+
+       cg, readValErr := readAndValidateJsonStruct(r)
+       if readValErr != nil {
+               api.HandleErr(w, r, tx, http.StatusBadRequest, readValErr, nil)
+               return
+       }
+
+       // check if cache group already exists
+       var exists bool
+       err := tx.QueryRow(`SELECT EXISTS(SELECT * from cachegroup where name = 
$1)`, cg.Name).Scan(&exists)
+       if err != nil {
+               api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, 
fmt.Errorf("error: %w, when checking if cache group with name %s exists", err, 
cg.Name))
+               return
+       }
+       if exists {
+               api.HandleErr(w, r, tx, http.StatusBadRequest, 
fmt.Errorf("cache group name '%s' already exists.", cg.Name), nil)
+               return
+       }
+
+       // create cache group
+       query := InsertQuery()
+
+       err = tx.QueryRow(
+               query,
+               cg.Name,
+               cg.ShortName,
+               cg.TypeID,
+               cg.ParentCachegroupID,
+               cg.SecondaryParentCachegroupID,
+               cg.FallbackToClosest,
+       ).Scan(
+               &cg.ID,
+               &cg.Type,
+               &cg.ParentName,
+               &cg.SecondaryParentName,
+       )
+       if err != nil {
+               if errors.Is(err, sql.ErrNoRows) {
+                       api.HandleErr(w, r, tx, http.StatusInternalServerError, 
fmt.Errorf("error: %w in creating cache group with name: %s", err, cg.Name), 
nil)
+                       return
+               }
+               usrErr, sysErr, code := api.ParseDBError(err)
+               api.HandleErr(w, r, tx, code, usrErr, sysErr)
+               return
+       }
+
+       dgCg := Downgrade(cg)
+       dgCg.ReqInfo = inf
+       coordinateID, err := dgCg.createCoordinate()
+       if err != nil {
+               api.HandleErr(w, r, tx, http.StatusInternalServerError, 
fmt.Errorf("cachegroup create: creating coord: "+err.Error()), nil)
+               return
+       }
+
+       checkLastUpdated := `UPDATE cachegroup SET coordinate=$1 WHERE id=$2 
RETURNING last_updated`
+
+       err = tx.QueryRow(
+               checkLastUpdated,
+               coordinateID,
+               *cg.ID,
+       ).Scan(
+               &cg.LastUpdated,
+       )
+
+       if err != nil {
+               api.HandleErr(w, r, tx, http.StatusInternalServerError, 
fmt.Errorf("followup update during cachegroup create: %v", err), nil)
+               return
+       }
+
+       if err = dgCg.createLocalizationMethods(); err != nil {
+               api.HandleErr(w, r, tx, http.StatusInternalServerError, 
fmt.Errorf("creating cachegroup: creating localization methods: "+err.Error()), 
nil)
+               return
+       }
+
+       if err = dgCg.createCacheGroupFallbacks(); err != nil {
+               api.HandleErr(w, r, tx, http.StatusInternalServerError, 
fmt.Errorf("creating cachegroup: creating cache group fallbacks: 
"+err.Error()), nil)
+               return
+       }
+
+       cg, err = dgCg.Upgrade()
+       if err != nil {
+               api.HandleErr(w, r, tx, http.StatusInternalServerError, 
fmt.Errorf("converting cachegroup: converting cache group upgrade: 
"+err.Error()), nil)
+               return
+       }
+
+       alerts := tc.CreateAlerts(tc.SuccessLevel, "cache group was created.")
+       w.Header().Set("Location", 
fmt.Sprintf("/api/%d.%d/cachegroups?name=%s", inf.Version.Major, 
inf.Version.Minor, cg.Name))

Review Comment:
   Fixed



-- 
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.

To unsubscribe, e-mail: issues-unsubscr...@trafficcontrol.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to