rob05c commented on a change in pull request #2124: Add TO Go deliveryservices routes URL: https://github.com/apache/incubator-trafficcontrol/pull/2124#discussion_r184225789
########## File path: traffic_ops/traffic_ops_golang/deliveryservice/deliveryservicesv12.go ########## @@ -0,0 +1,300 @@ +package deliveryservice + +import ( + "database/sql" + "errors" + "fmt" + "regexp" + "strings" + + "github.com/apache/incubator-trafficcontrol/lib/go-tc" + "github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/api" + "github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/auth" + "github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/config" + "github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/tenant" + "github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/tovalidate" + + "github.com/asaskevich/govalidator" + "github.com/go-ozzo/ozzo-validation" + "github.com/jmoiron/sqlx" +) + +type TODeliveryServiceV12 struct { + DS *tc.DeliveryServiceNullableV12 + Cfg config.Config + DB *sqlx.DB +} + +func GetRefTypeV12(cfg config.Config, db *sqlx.DB) *TODeliveryServiceV12 { + return &TODeliveryServiceV12{Cfg: cfg, DB: db, DS: &tc.DeliveryServiceNullableV12{}} +} + +func (ds TODeliveryServiceV12) GetKeyFieldsInfo() []api.KeyFieldInfo { + return []api.KeyFieldInfo{{"id", api.GetIntKey}} +} + +func (tods TODeliveryServiceV12) GetKeys() (map[string]interface{}, bool) { + if tods.DS.ID == nil { + return map[string]interface{}{"id": 0}, false + } + return map[string]interface{}{"id": *tods.DS.ID}, true +} + +func (tods *TODeliveryServiceV12) SetKeys(keys map[string]interface{}) { + i, _ := keys["id"].(int) //this utilizes the non panicking type assertion, if the thrown away ok variable is false i will be the zero of the type, 0 here. + tods.DS.ID = &i +} + +func (tods *TODeliveryServiceV12) GetAuditName() string { + if tods.DS != nil && tods.DS.XMLID != nil { + return *tods.DS.XMLID + } + return "" +} + +func (tods *TODeliveryServiceV12) GetType() string { + return "ds" +} + +func ValidateV12(db *sqlx.DB, ds *tc.DeliveryServiceNullableV12) []error { + if ds == nil { + return []error{} + } + tods := TODeliveryServiceV12{DS: ds, DB: db} // TODO pass config? + return tods.Validate(db) +} + +func (tods *TODeliveryServiceV12) Sanitize(db *sqlx.DB) { + ds := tods.DS + if ds.GeoLimitCountries != nil { + *ds.GeoLimitCountries = strings.ToUpper(strings.Replace(*ds.GeoLimitCountries, " ", "", -1)) + } + if ds.ProfileID != nil && *ds.ProfileID == -1 { + ds.ProfileID = nil + } + if ds.EdgeHeaderRewrite != nil && strings.TrimSpace(*ds.EdgeHeaderRewrite) == "" { + ds.EdgeHeaderRewrite = nil + } + if ds.MidHeaderRewrite != nil && strings.TrimSpace(*ds.MidHeaderRewrite) == "" { + ds.MidHeaderRewrite = nil + } +} + +// LoadTenantID loads the DeliveryService's tenant ID from the database, using the DS ID or XMLID if either exists. Sets tods.DS.TenantID on success, and returns whether the delivery service was found, and any error. +func (tods *TODeliveryServiceV12) LoadTenantID(db *sqlx.DB) (bool, error) { + if tods.DS.ID != nil { + tenantID := 0 + if err := db.QueryRow(`SELECT tenant_id FROM deliveryservice where id = $1`, tods.DS.ID).Scan(&tenantID); err != nil { + if err == sql.ErrNoRows { + return false, nil + } + return false, fmt.Errorf("querying tenant ID for delivery service ID '%v': %v", *tods.DS.ID, err) + } + tods.DS.TenantID = &tenantID + return true, nil + } + if tods.DS.XMLID != nil { + tenantID := 0 + if err := db.QueryRow(`SELECT tenant_id FROM deliveryservice where xml_id = $1`, *tods.DS.XMLID).Scan(&tenantID); err != nil { + if err == sql.ErrNoRows { + return false, nil + } + return false, fmt.Errorf("querying tenant ID for delivery service xml_id '%v': %v", *tods.DS.XMLID, err) + } + tods.DS.TenantID = &tenantID + return true, nil + } + return false, errors.New("no id or xml_id") +} + +// LoadXMLID loads the DeliveryService's xml_id from the database, from the ID. Returns whether the delivery service was found, and any error. +func (tods *TODeliveryServiceV12) LoadXMLID(db *sqlx.DB) (bool, error) { + if tods.DS.ID == nil { + return false, errors.New("missing ID") + } + + xmlID := "" + if err := db.QueryRow(`SELECT xml_id FROM deliveryservice where id = $1`, tods.DS.ID).Scan(&xmlID); err != nil { + if err == sql.ErrNoRows { + return false, nil + } + return false, fmt.Errorf("querying xml_id for delivery service ID '%v': %v", *tods.DS.ID, err) + } + tods.DS.XMLID = &xmlID + return true, nil +} + +func (tods *TODeliveryServiceV12) IsTenantAuthorized(user auth.CurrentUser, db *sqlx.DB) (bool, error) { + tods.LoadTenantID(db) // try to load, but ignore errors and keep the user-set tenant ID on failure (which will happen with a Create) + // if tods.DS.TenantID == nil { + // tods.DS.TenantID = &user.TenantID + // return true, nil // TODO verify tenants are always authorized to make deliveryservices for themselves + // } + if *tods.DS.TenantID == user.TenantID { + return true, nil // TODO verify tenants are always authorized to make deliveryservices for themselves + } + return tenant.IsResourceAuthorizedToUser(*tods.DS.TenantID, user, db) +} + +func (tods *TODeliveryServiceV12) Validate(db *sqlx.DB) []error { + tods.Sanitize(db) + ds := tods.DS + // Custom Examples: + // Just add isCIDR as a parameter to Validate() + // isCIDR := validation.NewStringRule(govalidator.IsCIDR, "must be a valid CIDR address") + isHost := validation.NewStringRule(govalidator.IsHost, "must be a valid hostname") + noPeriods := validation.NewStringRule(tovalidate.NoPeriods, "cannot contain periods") + noSpaces := validation.NewStringRule(tovalidate.NoSpaces, "cannot contain spaces") + + // Validate that the required fields are sent first to prevent panics below + errs := validation.Errors{ + "active": validation.Validate(ds.Active, validation.NotNil), + "cdnId": validation.Validate(ds.CDNID, validation.Required), + "displayName": validation.Validate(ds.DisplayName, validation.Required, validation.Length(1, 48)), + "dscp": validation.Validate(ds.DSCP, validation.NotNil, validation.Min(0)), + "geoLimit": validation.Validate(ds.GeoLimit, validation.NotNil), + "geoProvider": validation.Validate(ds.GeoProvider, validation.NotNil), + "logsEnabled": validation.Validate(ds.LogsEnabled, validation.NotNil), + "regionalGeoBlocking": validation.Validate(ds.RegionalGeoBlocking, validation.NotNil), + "routingName": validation.Validate(ds.RoutingName, isHost, noPeriods, validation.Length(1, 48)), + "typeId": validation.Validate(ds.TypeID, validation.Required, validation.Min(1)), + "xmlId": validation.Validate(ds.XMLID, noSpaces, noPeriods, validation.Length(1, 48)), + } + + if errs != nil { + return tovalidate.ToErrors(errs) + } + + errsResponse := tods.validateTypeFields(db) + if errsResponse != nil { + return errsResponse + } + + return nil +} + +func (tods *TODeliveryServiceV12) validateTypeFields(db *sqlx.DB) []error { + ds := tods.DS + fmt.Printf("validateTypeFields\n") + // Validate the TypeName related fields below + var typeName string + var err error + DNSRegexType := "^DNS.*$" + HTTPRegexType := "^HTTP.*$" + SteeringRegexType := "^STEERING.*$" + + if db != nil && ds == nil || ds.TypeID != nil { + typeID := *ds.TypeID + typeName, err = getTypeName(db, typeID) + if err != nil { + return []error{err} + } + } + + if typeName != "" { + errs := validation.Errors{ + "initialDispersion": validation.Validate(ds.InitialDispersion, + validation.By(requiredIfMatchesTypeName([]string{DNSRegexType, HTTPRegexType}, typeName))), + "ipv6RoutingEnabled": validation.Validate(ds.IPV6RoutingEnabled, + validation.By(requiredIfMatchesTypeName([]string{SteeringRegexType, DNSRegexType, HTTPRegexType}, typeName))), + "missLat": validation.Validate(ds.MissLat, + validation.By(requiredIfMatchesTypeName([]string{DNSRegexType, HTTPRegexType}, typeName))), + "missLong": validation.Validate(ds.MissLong, + validation.By(requiredIfMatchesTypeName([]string{DNSRegexType, HTTPRegexType}, typeName))), + "multiSiteOrigin": validation.Validate(ds.MultiSiteOrigin, + validation.By(requiredIfMatchesTypeName([]string{DNSRegexType, HTTPRegexType}, typeName))), + "orgServerFqdn": validation.Validate(ds.OrgServerFQDN, + validation.By(requiredIfMatchesTypeName([]string{DNSRegexType, HTTPRegexType}, typeName))), + "protocol": validation.Validate(ds.Protocol, + validation.By(requiredIfMatchesTypeName([]string{SteeringRegexType, DNSRegexType, HTTPRegexType}, typeName))), + "qstringIgnore": validation.Validate(ds.QStringIgnore, + validation.By(requiredIfMatchesTypeName([]string{DNSRegexType, HTTPRegexType}, typeName))), + "rangeRequestHandling": validation.Validate(ds.RangeRequestHandling, + validation.By(requiredIfMatchesTypeName([]string{DNSRegexType, HTTPRegexType}, typeName))), + } + return tovalidate.ToErrors(errs) + } + return nil +} + +func requiredIfMatchesTypeName(patterns []string, typeName string) func(interface{}) error { + return func(value interface{}) error { + + pattern := strings.Join(patterns, "|") + var err error + var match bool + if typeName != "" { + match, err = regexp.MatchString(pattern, typeName) + if match { + return fmt.Errorf("is required if type is '%s'", typeName) + } + } + return err + } +} + +// TODO: drichardson - refactor to the types.go once implemented. +func getTypeName(db *sqlx.DB, typeID int) (string, error) { + + query := `SELECT name from type where id=$1` + + var rows *sqlx.Rows + var err error + + rows, err = db.Queryx(query, typeID) + if err != nil { + return "", err + } + defer rows.Close() + + typeResults := []tc.Type{} + for rows.Next() { + var s tc.Type + if err = rows.StructScan(&s); err != nil { + return "", fmt.Errorf("getting Type: %v", err) + } + typeResults = append(typeResults, s) + } + + typeName := typeResults[0].Name + return typeName, err +} + +func (tods *TODeliveryServiceV12) Create(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) { + v13 := &TODeliveryServiceV13{Cfg: tods.Cfg, DB: tods.DB, DS: &tc.DeliveryServiceNullableV13{DeliveryServiceNullableV12: tc.DeliveryServiceNullableV12(*tods.DS)}} + v13.Sanitize(db) // sanitize, to fill in new defaults + return v13.Create(db, user) +} + +func (tods *TODeliveryServiceV12) Read(db *sqlx.DB, params map[string]string, user auth.CurrentUser) ([]interface{}, []error, tc.ApiErrorType) { Review comment: It wasn't, is now https://github.com/apache/incubator-trafficcontrol/pull/2124/files#diff-4ba22360ce1913c644aec81f9e2eae4bR301 ---------------------------------------------------------------- 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