You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@trafficcontrol.apache.org by da...@apache.org on 2018/07/04 02:39:27 UTC
[trafficcontrol] 02/15: all packages through origins
(alphabetically) refactored
This is an automated email from the ASF dual-hosted git repository.
dangogh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/trafficcontrol.git
commit 43f00c39d8fdf7241d4e80d9ebec45086f77c620
Author: Dylan Volz <Dy...@comcast.com>
AuthorDate: Tue Jun 26 16:56:56 2018 -0600
all packages through origins (alphabetically) refactored
---
traffic_ops/traffic_ops_golang/api/change_log.go | 14 +-
.../traffic_ops_golang/api/change_log_test.go | 3 +-
.../traffic_ops_golang/api/shared_handlers.go | 12 +-
.../traffic_ops_golang/api/shared_handlers_test.go | 109 +++++++--------
.../traffic_ops_golang/api/shared_interfaces.go | 4 +-
traffic_ops/traffic_ops_golang/asn/asns_test.go | 10 +-
.../traffic_ops_golang/cachegroup/cachegroups.go | 2 +-
.../cachegroup/cachegroups_test.go | 20 +--
.../traffic_ops_golang/cachegroup/queueupdate.go | 2 +-
traffic_ops/traffic_ops_golang/cdn/cdns_test.go | 20 +--
traffic_ops/traffic_ops_golang/cdn/queue.go | 2 +-
.../traffic_ops_golang/coordinate/coordinates.go | 100 +++-----------
.../coordinate/coordinates_test.go | 33 ++---
traffic_ops/traffic_ops_golang/crconfig/handler.go | 4 +-
.../deliveryservice/deliveryservicesv12.go | 10 +-
.../deliveryservice/deliveryservicesv13.go | 16 +--
.../deliveryservice/request/comment/comments.go | 105 +++------------
.../request/comment/comments_test.go | 7 +-
.../deliveryservice/request/requests.go | 4 +-
.../deliveryservice/request/requests_test.go | 4 +-
.../deliveryservicesregexes.go | 14 +-
.../traffic_ops_golang/division/divisions.go | 149 +++------------------
.../traffic_ops_golang/division/divisions_test.go | 8 +-
traffic_ops/traffic_ops_golang/origin/origins.go | 148 ++++++--------------
.../traffic_ops_golang/origin/origins_test.go | 17 +--
traffic_ops/traffic_ops_golang/routes.go | 58 ++++----
traffic_ops/traffic_ops_golang/tenant/tenancy.go | 6 +-
27 files changed, 289 insertions(+), 592 deletions(-)
diff --git a/traffic_ops/traffic_ops_golang/api/change_log.go b/traffic_ops/traffic_ops_golang/api/change_log.go
index 99f1c5e..b8117ec 100644
--- a/traffic_ops/traffic_ops_golang/api/change_log.go
+++ b/traffic_ops/traffic_ops_golang/api/change_log.go
@@ -51,7 +51,7 @@ const (
Deleted = "Deleted"
)
-func CreateChangeLog(level string, action string, i Identifier, user auth.CurrentUser, tx *sqlx.Tx) error {
+func CreateChangeLog(level string, action string, i Identifier, user *auth.CurrentUser, tx *sqlx.Tx) error {
t, ok := i.(ChangeLogger)
if !ok {
keys, _ := i.GetKeys()
@@ -66,7 +66,7 @@ func CreateChangeLog(level string, action string, i Identifier, user auth.Curren
return CreateChangeLogRawErr(level, msg, user, tx.Tx)
}
-func CreateChangeLogBuildMsg(level string, action string, user auth.CurrentUser, tx *sqlx.Tx, objType string, auditName string, keys map[string]interface{}) error {
+func CreateChangeLogBuildMsg(level string, action string, user *auth.CurrentUser, tx *sqlx.Tx, objType string, auditName string, keys map[string]interface{}) error {
keyStr := "{ "
for key, value := range keys {
keyStr += key + ":" + fmt.Sprintf("%v", value) + " "
@@ -76,12 +76,14 @@ func CreateChangeLogBuildMsg(level string, action string, user auth.CurrentUser,
return CreateChangeLogRawErr(level, msg, user, tx.Tx)
}
-func CreateChangeLogRawErr(level string, msg string, user auth.CurrentUser, tx *sql.Tx) error {
- _, err := tx.Exec(`INSERT INTO log (level, message, tm_user) VALUES ($1, $2, $3)`, level, msg, user.ID)
- return errors.New("Inserting change log level '" + level + "' message '" + msg + "' user '" + user.UserName + "': " + err.Error())
+func CreateChangeLogRawErr(level string, msg string, user *auth.CurrentUser, tx *sql.Tx) error {
+ if _, err := tx.Exec(`INSERT INTO log (level, message, tm_user) VALUES ($1, $2, $3)`, level, msg, user.ID); err != nil {
+ return errors.New("Inserting change log level '" + level + "' message '" + msg + "' user '" + user.UserName + "': " + err.Error())
+ }
+ return nil
}
-func CreateChangeLogRaw(level string, msg string, user auth.CurrentUser, db *sql.DB) {
+func CreateChangeLogRaw(level string, msg string, user *auth.CurrentUser, db *sql.DB) {
if _, err := db.Exec(`INSERT INTO log (level, message, tm_user) VALUES ($1, $2, $3)`, level, msg, user.ID); err != nil {
log.Errorln("Inserting change log level '" + level + "' message '" + msg + "' user '" + user.UserName + "': " + err.Error())
}
diff --git a/traffic_ops/traffic_ops_golang/api/change_log_test.go b/traffic_ops/traffic_ops_golang/api/change_log_test.go
index 190dfd8..38a44d5 100644
--- a/traffic_ops/traffic_ops_golang/api/change_log_test.go
+++ b/traffic_ops/traffic_ops_golang/api/change_log_test.go
@@ -62,9 +62,10 @@ func TestCreateChangeLog(t *testing.T) {
keys, _ := i.GetKeys()
expectedMessage := Created + " " + i.GetType() + ": " + i.GetAuditName() + " keys: { id:" + strconv.Itoa(keys["id"].(int)) + " }"
+ mock.ExpectBegin()
mock.ExpectExec("INSERT").WithArgs(ApiChange, expectedMessage, 1).WillReturnResult(sqlmock.NewResult(1, 1))
user := auth.CurrentUser{ID: 1}
- err = CreateChangeLog(ApiChange, Created, &i, user, db)
+ err = CreateChangeLog(ApiChange, Created, &i, &user, db.MustBegin())
if err != nil {
t.Fatal(err)
}
diff --git a/traffic_ops/traffic_ops_golang/api/shared_handlers.go b/traffic_ops/traffic_ops_golang/api/shared_handlers.go
index fc0e6bb..b01eb85 100644
--- a/traffic_ops/traffic_ops_golang/api/shared_handlers.go
+++ b/traffic_ops/traffic_ops_golang/api/shared_handlers.go
@@ -238,7 +238,7 @@ func UpdateHandler(typeFactory func(reqInfo *APIInfo) CRUDer) http.HandlerFunc {
// if the object has tenancy enabled, check that user is able to access the tenant
if t, ok := u.(Tenantable); ok {
- authorized, err := t.IsTenantAuthorized(*user)
+ authorized, err := t.IsTenantAuthorized(user)
if err != nil {
handleErrs(http.StatusBadRequest, err)
return
@@ -256,7 +256,7 @@ func UpdateHandler(typeFactory func(reqInfo *APIInfo) CRUDer) http.HandlerFunc {
return
}
//auditing here
- err = CreateChangeLog(ApiChange, Updated, u, *inf.User, inf.Tx)
+ err = CreateChangeLog(ApiChange, Updated, u, inf.User, inf.Tx)
if err != nil {
HandleErr(w,r,http.StatusInternalServerError,tc.DBError,errors.New("inserting changelog: " + err.Error()))
return
@@ -327,7 +327,7 @@ func DeleteHandler(typeFactory func(reqInfo *APIInfo) CRUDer) http.HandlerFunc {
// if the object has tenancy enabled, check that user is able to access the tenant
if t, ok := d.(Tenantable); ok {
- authorized, err := t.IsTenantAuthorized(*inf.User)
+ authorized, err := t.IsTenantAuthorized(inf.User)
if err != nil {
handleErrs(http.StatusBadRequest, err)
return
@@ -347,7 +347,7 @@ func DeleteHandler(typeFactory func(reqInfo *APIInfo) CRUDer) http.HandlerFunc {
}
//audit here
log.Debugf("changelog for delete on object")
- err = CreateChangeLog(ApiChange, Deleted, d, *inf.User, inf.Tx)
+ err = CreateChangeLog(ApiChange, Deleted, d, inf.User, inf.Tx)
if err != nil {
HandleErr(w,r,http.StatusInternalServerError,tc.DBError,errors.New("inserting changelog: " + err.Error()))
return
@@ -402,7 +402,7 @@ func CreateHandler(typeConstructor func(reqInfo *APIInfo) CRUDer) http.HandlerFu
// if the object has tenancy enabled, check that user is able to access the tenant
if t, ok := i.(Tenantable); ok {
- authorized, err := t.IsTenantAuthorized(*inf.User)
+ authorized, err := t.IsTenantAuthorized(inf.User)
if err != nil {
handleErrs(http.StatusBadRequest, err)
return
@@ -419,7 +419,7 @@ func CreateHandler(typeConstructor func(reqInfo *APIInfo) CRUDer) http.HandlerFu
return
}
- err = CreateChangeLog(ApiChange, Created, i, *inf.User, inf.Tx)
+ err = CreateChangeLog(ApiChange, Created, i, inf.User, inf.Tx)
if err != nil {
HandleErr(w,r,http.StatusInternalServerError,tc.DBError,errors.New("inserting changelog: " + err.Error()))
return
diff --git a/traffic_ops/traffic_ops_golang/api/shared_handlers_test.go b/traffic_ops/traffic_ops_golang/api/shared_handlers_test.go
index d0827ba..56880d4 100644
--- a/traffic_ops/traffic_ops_golang/api/shared_handlers_test.go
+++ b/traffic_ops/traffic_ops_golang/api/shared_handlers_test.go
@@ -30,6 +30,7 @@ import (
"github.com/apache/trafficcontrol/lib/go-tc"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
+ "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/config"
"github.com/jmoiron/sqlx"
sqlmock "gopkg.in/DATA-DOG/go-sqlmock.v1"
@@ -41,7 +42,14 @@ type tester struct {
errorType tc.ApiErrorType //only for testing
}
-type emptyTester tester
+func GetTypeSingleton() func(apiInfo *APIInfo) CRUDer{
+ return func(apiInfo *APIInfo) CRUDer {
+ tester := tester{}
+ return &tester
+ }
+}
+
+var cfg = config.Config{}
func (i tester) GetKeyFieldsInfo() []KeyFieldInfo {
return []KeyFieldInfo{{"id", GetIntKey}}
@@ -66,7 +74,7 @@ func (i *tester) GetAuditName() string {
}
//Validator interface function
-func (v *tester) Validate(db *sqlx.DB) []error {
+func (v *tester) Validate() []error {
if v.ID < 1 {
return []error{errors.New("ID is too low")}
}
@@ -74,27 +82,22 @@ func (v *tester) Validate(db *sqlx.DB) []error {
}
//Creator interface functions
-func (i *tester) Create(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
+func (i *tester) Create() (error, tc.ApiErrorType) {
return i.error, i.errorType
}
//Reader interface functions
-func (i *tester) Read(db *sqlx.DB, v map[string]string, user auth.CurrentUser) ([]interface{}, []error, tc.ApiErrorType) {
+func (i *tester) Read(v map[string]string) ([]interface{}, []error, tc.ApiErrorType) {
return []interface{}{tester{ID: 1}}, nil, tc.NoError
}
-//Reader interface functions
-func (i *emptyTester) Read(db *sqlx.DB, v map[string]string, user auth.CurrentUser) ([]interface{}, []error, tc.ApiErrorType) {
- return []interface{}{}, nil, tc.NoError
-}
-
//Updater interface functions
-func (i *tester) Update(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
+func (i *tester) Update() (error, tc.ApiErrorType) {
return i.error, i.errorType
}
//Deleter interface functions
-func (i *tester) Delete(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
+func (i *tester) Delete() (error, tc.ApiErrorType) {
return i.error, i.errorType
}
@@ -123,16 +126,23 @@ func TestCreateHandler(t *testing.T) {
ctx := r.Context()
ctx = context.WithValue(ctx, auth.CurrentUserKey,
auth.CurrentUser{UserName: "username", ID: 1, PrivLevel: auth.PrivLevelAdmin})
+ ctx = context.WithValue(ctx, DBContextKey, db)
+ ctx = context.WithValue(ctx, ConfigContextKey, &cfg)
+ ctx = context.WithValue(ctx, ReqIDContextKey, uint64(0))
+ ctx = context.WithValue(ctx, PathParamsKey, map[string]string{"id":"1"})
// Add our context to the request
r = r.WithContext(ctx)
- typeRef := tester{}
- createFunc := CreateHandler(&typeRef, db)
+ typeRef := tester{ID:1}
+
+ createFunc := CreateHandler(GetTypeSingleton())
//verifies we get the right changelog insertion
- expectedMessage := Created + " " + typeRef.GetType() + ": " + typeRef.GetAuditName() + " id: 1"
+ expectedMessage := Created + " " + typeRef.GetType() + ": " + typeRef.GetAuditName() + " keys: { id:1 }"
+ mock.ExpectBegin()
mock.ExpectExec("INSERT").WithArgs(ApiChange, expectedMessage, 1).WillReturnResult(sqlmock.NewResult(1, 1))
+ mock.ExpectCommit()
createFunc(w, r)
@@ -143,43 +153,8 @@ func TestCreateHandler(t *testing.T) {
}
}
-func TestEmptyReadHandler(t *testing.T) {
- mockDB, _, err := sqlmock.New()
- if err != nil {
- t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
- }
- defer mockDB.Close()
-
- db := sqlx.NewDb(mockDB, "sqlmock")
- defer db.Close()
-
- w := httptest.NewRecorder()
- r, err := http.NewRequest("", "", nil)
- if err != nil {
- t.Error("Error creating new request")
- }
-
- ctx := r.Context()
- ctx = context.WithValue(ctx, auth.CurrentUserKey,
- auth.CurrentUser{UserName: "username", ID: 1, PrivLevel: auth.PrivLevelAdmin})
- ctx = context.WithValue(ctx, PathParamsKey, map[string]string{})
- // Add our context to the request
- r = r.WithContext(ctx)
-
- typeRef := emptyTester{}
- readFunc := ReadHandler(&typeRef, db)
-
- readFunc(w, r)
-
- //verifies the body is in the expected format
- body := `{"response":[]}`
- if w.Body.String() != body {
- t.Error("Expected body", body, "got", w.Body.String())
- }
-}
-
func TestReadHandler(t *testing.T) {
- mockDB, _, err := sqlmock.New()
+ mockDB, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
@@ -198,11 +173,17 @@ func TestReadHandler(t *testing.T) {
ctx = context.WithValue(ctx, auth.CurrentUserKey,
auth.CurrentUser{UserName: "username", ID: 1, PrivLevel: auth.PrivLevelAdmin})
ctx = context.WithValue(ctx, PathParamsKey, map[string]string{"id": "1"})
+ ctx = context.WithValue(ctx, DBContextKey, db)
+ ctx = context.WithValue(ctx, ConfigContextKey, &cfg)
+ ctx = context.WithValue(ctx, ReqIDContextKey, uint64(0))
+
// Add our context to the request
r = r.WithContext(ctx)
- typeRef := tester{}
- readFunc := ReadHandler(&typeRef, db)
+ readFunc := ReadHandler(GetTypeSingleton())
+
+ mock.ExpectBegin()
+ mock.ExpectCommit()
readFunc(w, r)
@@ -233,15 +214,21 @@ func TestUpdateHandler(t *testing.T) {
ctx = context.WithValue(ctx, auth.CurrentUserKey,
auth.CurrentUser{UserName: "username", ID: 1, PrivLevel: auth.PrivLevelAdmin})
ctx = context.WithValue(ctx, PathParamsKey, map[string]string{"id": "1"})
+ ctx = context.WithValue(ctx, DBContextKey, db)
+ ctx = context.WithValue(ctx, ConfigContextKey, &cfg)
+ ctx = context.WithValue(ctx, ReqIDContextKey, uint64(0))
+
// Add our context to the request
r = r.WithContext(ctx)
- typeRef := tester{}
- updateFunc := UpdateHandler(&typeRef, db)
+ typeRef := tester{ID:1}
+ updateFunc := UpdateHandler(GetTypeSingleton())
//verifies we get the right changelog insertion
- expectedMessage := Updated + " " + typeRef.GetType() + ": " + typeRef.GetAuditName() + " id: 1"
+ expectedMessage := Updated + " " + typeRef.GetType() + ": " + typeRef.GetAuditName() + " keys: { id:1 }"
+ mock.ExpectBegin()
mock.ExpectExec("INSERT").WithArgs(ApiChange, expectedMessage, 1).WillReturnResult(sqlmock.NewResult(1, 1))
+ mock.ExpectCommit()
updateFunc(w, r)
@@ -272,16 +259,20 @@ func TestDeleteHandler(t *testing.T) {
ctx = context.WithValue(ctx, auth.CurrentUserKey,
auth.CurrentUser{UserName: "username", ID: 1, PrivLevel: auth.PrivLevelAdmin})
ctx = context.WithValue(ctx, PathParamsKey, map[string]string{"id": "1"})
+ ctx = context.WithValue(ctx, DBContextKey, db)
+ ctx = context.WithValue(ctx, ConfigContextKey, &cfg)
+ ctx = context.WithValue(ctx, ReqIDContextKey, uint64(0))
// Add our context to the request
r = r.WithContext(ctx)
- typeRef := tester{}
- deleteFunc := DeleteHandler(&typeRef, db)
+ typeRef := tester{ID:1}
+ deleteFunc := DeleteHandler(GetTypeSingleton())
//verifies we get the right changelog insertion
- expectedMessage := Deleted + " " + typeRef.GetType() + ": " + typeRef.GetAuditName() + " id: 1"
+ expectedMessage := Deleted + " " + typeRef.GetType() + ": " + typeRef.GetAuditName() + " keys: { id:1 }"
+ mock.ExpectBegin()
mock.ExpectExec("INSERT").WithArgs(ApiChange, expectedMessage, 1).WillReturnResult(sqlmock.NewResult(1, 1))
-
+ mock.ExpectCommit()
deleteFunc(w, r)
//verifies the body is in the expected format
diff --git a/traffic_ops/traffic_ops_golang/api/shared_interfaces.go b/traffic_ops/traffic_ops_golang/api/shared_interfaces.go
index 515a1d1..a8df96f 100644
--- a/traffic_ops/traffic_ops_golang/api/shared_interfaces.go
+++ b/traffic_ops/traffic_ops_golang/api/shared_interfaces.go
@@ -39,7 +39,6 @@ type Updater interface {
type Identifier interface {
GetKeys() (map[string]interface{}, bool)
- SetKeys(map[string]interface{})
GetType() string
GetAuditName() string
GetKeyFieldsInfo() []KeyFieldInfo
@@ -47,6 +46,7 @@ type Identifier interface {
type Creator interface {
Create() (error, tc.ApiErrorType)
+ SetKeys(map[string]interface{})
}
type Deleter interface {
@@ -58,7 +58,7 @@ type Validator interface {
}
type Tenantable interface {
- IsTenantAuthorized(user auth.CurrentUser) (bool, error)
+ IsTenantAuthorized(user *auth.CurrentUser) (bool, error)
}
type Reader interface {
diff --git a/traffic_ops/traffic_ops_golang/asn/asns_test.go b/traffic_ops/traffic_ops_golang/asn/asns_test.go
index 12e8de4..5ad859a 100644
--- a/traffic_ops/traffic_ops_golang/asn/asns_test.go
+++ b/traffic_ops/traffic_ops_golang/asn/asns_test.go
@@ -27,11 +27,11 @@ import (
"github.com/apache/trafficcontrol/lib/go-tc"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
- "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/test"
"github.com/jmoiron/sqlx"
sqlmock "gopkg.in/DATA-DOG/go-sqlmock.v1"
+ "github.com/apache/trafficcontrol/lib/go-util"
)
func getTestASNs() []tc.ASNNullable {
@@ -65,7 +65,7 @@ func TestGetASNs(t *testing.T) {
defer db.Close()
testCase := getTestASNs()
- cols := test.ColsFromStructByTag("db", TOASNV11{})
+ cols := test.ColsFromStructByTag("db", tc.ASNNullable{})
rows := sqlmock.NewRows(cols)
for _, ts := range testCase {
@@ -76,10 +76,12 @@ func TestGetASNs(t *testing.T) {
*ts.LastUpdated,
)
}
+ mock.ExpectBegin()
mock.ExpectQuery("SELECT").WillReturnRows(rows)
+ mock.ExpectCommit()
v := map[string]string{"dsId": "1"}
-
- asns, errs, _ := GetTypeSingleton(db)().Read(v, auth.CurrentUser{})
+ reqInfo := api.APIInfo{Tx:db.MustBegin(),CommitTx:util.BoolPtr(false)}
+ asns, errs, _ := GetTypeSingleton()(&reqInfo).Read(v)
if len(errs) > 0 {
t.Errorf("asn.Read expected: no errors, actual: %v", errs)
diff --git a/traffic_ops/traffic_ops_golang/cachegroup/cachegroups.go b/traffic_ops/traffic_ops_golang/cachegroup/cachegroups.go
index a43df6f..03da6d2 100644
--- a/traffic_ops/traffic_ops_golang/cachegroup/cachegroups.go
+++ b/traffic_ops/traffic_ops_golang/cachegroup/cachegroups.go
@@ -42,7 +42,7 @@ type TOCacheGroup struct{
v13.CacheGroupNullable
}
-func GetV11TypeSingleton() func(reqInfo *api.APIInfo) api.CRUDer {
+func GetTypeSingleton() func(reqInfo *api.APIInfo) api.CRUDer {
return func(reqInfo *api.APIInfo) api.CRUDer {
toReturn := TOCacheGroup{reqInfo, v13.CacheGroupNullable{}}
return &toReturn
diff --git a/traffic_ops/traffic_ops_golang/cachegroup/cachegroups_test.go b/traffic_ops/traffic_ops_golang/cachegroup/cachegroups_test.go
index 0bd2066..1c4eaff 100644
--- a/traffic_ops/traffic_ops_golang/cachegroup/cachegroups_test.go
+++ b/traffic_ops/traffic_ops_golang/cachegroup/cachegroups_test.go
@@ -28,8 +28,8 @@ import (
"github.com/apache/trafficcontrol/lib/go-tc"
"github.com/apache/trafficcontrol/lib/go-tc/v13"
+ "github.com/apache/trafficcontrol/lib/go-util"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
- "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/test"
"github.com/jmoiron/sqlx"
@@ -79,7 +79,6 @@ func TestReadCacheGroups(t *testing.T) {
db := sqlx.NewDb(mockDB, "sqlmock")
defer db.Close()
- refType := GetRefType()
testCGs := getTestCacheGroups()
cols := test.ColsFromStructByTag("db", v13.CacheGroup{})
@@ -99,10 +98,13 @@ func TestReadCacheGroups(t *testing.T) {
ts.LastUpdated,
)
}
+ mock.ExpectBegin()
mock.ExpectQuery("SELECT").WillReturnRows(rows)
+ mock.ExpectCommit()
v := map[string]string{"id": "1"}
- cachegroups, errs, _ := refType.Read(db, v, auth.CurrentUser{})
+ reqInfo := api.APIInfo{Tx:db.MustBegin(),CommitTx:util.BoolPtr(false)}
+ cachegroups, errs, _ := GetTypeSingleton()(&reqInfo).Read(v)
if len(errs) > 0 {
t.Errorf("cdn.Read expected: no errors, actual: %v", errs)
}
@@ -158,7 +160,7 @@ func TestValidate(t *testing.T) {
ty := "EDGE_LOC"
ti := 6
lu := tc.TimeNoMod{Time: time.Now()}
- c := TOCacheGroup{ID: &id,
+ c := TOCacheGroup{CacheGroupNullable: v13.CacheGroupNullable{ID: &id,
Name: &nm,
ShortName: &sn,
Latitude: &la,
@@ -166,8 +168,8 @@ func TestValidate(t *testing.T) {
Type: &ty,
TypeID: &ti,
LastUpdated: &lu,
- }
- errs := test.SortErrors(c.Validate(nil))
+ }}
+ errs := test.SortErrors(c.Validate())
expectedErrs := []error{
errors.New(`'latitude' Must be a floating point number within the range +-90`),
@@ -185,7 +187,7 @@ func TestValidate(t *testing.T) {
sn = `awesome-cachegroup`
la = 90.0
lo = 90.0
- c = TOCacheGroup{ID: &id,
+ c = TOCacheGroup{CacheGroupNullable: v13.CacheGroupNullable{ID: &id,
Name: &nm,
ShortName: &sn,
Latitude: &la,
@@ -193,9 +195,9 @@ func TestValidate(t *testing.T) {
Type: &ty,
TypeID: &ti,
LastUpdated: &lu,
- }
+ }}
expectedErrs = []error{}
- errs = c.Validate(nil)
+ errs = c.Validate()
if !reflect.DeepEqual(expectedErrs, errs) {
t.Errorf("expected %s, got %s", expectedErrs, errs)
}
diff --git a/traffic_ops/traffic_ops_golang/cachegroup/queueupdate.go b/traffic_ops/traffic_ops_golang/cachegroup/queueupdate.go
index 7ef8d1c..30bc947 100644
--- a/traffic_ops/traffic_ops_golang/cachegroup/queueupdate.go
+++ b/traffic_ops/traffic_ops_golang/cachegroup/queueupdate.go
@@ -92,7 +92,7 @@ func QueueUpdates(db *sql.DB) http.HandlerFunc {
CDN: *reqObj.CDN,
CacheGroupID: cgID,
})
- api.CreateChangeLogRaw(api.ApiChange, "Server updates "+reqObj.Action+"d for "+string(cgName), *user, db)
+ api.CreateChangeLogRaw(api.ApiChange, "Server updates "+reqObj.Action+"d for "+string(cgName), user, db)
}
}
diff --git a/traffic_ops/traffic_ops_golang/cdn/cdns_test.go b/traffic_ops/traffic_ops_golang/cdn/cdns_test.go
index f4910e9..c09529e 100644
--- a/traffic_ops/traffic_ops_golang/cdn/cdns_test.go
+++ b/traffic_ops/traffic_ops_golang/cdn/cdns_test.go
@@ -27,9 +27,9 @@ import (
"time"
"github.com/apache/trafficcontrol/lib/go-tc"
+ "github.com/apache/trafficcontrol/lib/go-util"
"github.com/apache/trafficcontrol/lib/go-tc/v13"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
- "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/test"
"github.com/jmoiron/sqlx"
@@ -65,8 +65,6 @@ func TestReadCDNs(t *testing.T) {
db := sqlx.NewDb(mockDB, "sqlmock")
defer db.Close()
- refType := GetRefType()
-
testCDNs := getTestCDNs()
cols := test.ColsFromStructByTag("db", v13.CDN{})
rows := sqlmock.NewRows(cols)
@@ -80,10 +78,13 @@ func TestReadCDNs(t *testing.T) {
ts.Name,
)
}
+ mock.ExpectBegin()
mock.ExpectQuery("SELECT").WillReturnRows(rows)
- v := map[string]string{"dsId": "1"}
+ mock.ExpectCommit()
- servers, errs, _ := refType.Read(db, v, auth.CurrentUser{})
+ v := map[string]string{"dsId": "1"}
+ reqInfo := api.APIInfo{Tx:db.MustBegin(),CommitTx:util.BoolPtr(false)}
+ servers, errs, _ := GetTypeSingleton()(&reqInfo).Read(v)
if len(errs) > 0 {
t.Errorf("cdn.Read expected: no errors, actual: %v", errs)
}
@@ -132,8 +133,8 @@ func TestInterfaces(t *testing.T) {
func TestValidate(t *testing.T) {
// invalid name, empty domainname
n := "not_a_valid_cdn"
- c := TOCDN{Name: &n}
- errs := test.SortErrors(c.Validate(nil))
+ c := TOCDN{CDNNullable: v13.CDNNullable{Name: &n}}
+ errs := test.SortErrors(c.Validate())
expectedErrs := []error{
errors.New(`'domainName' cannot be blank`),
@@ -147,11 +148,10 @@ func TestValidate(t *testing.T) {
// name, domainname both valid
n = "This.is.2.a-Valid---CDNNAME."
d := `awesome-cdn.example.net`
- c = TOCDN{Name: &n, DomainName: &d}
+ c = TOCDN{CDNNullable: v13.CDNNullable{Name: &n, DomainName: &d}}
expectedErrs = []error{}
- errs = c.Validate(nil)
+ errs = c.Validate()
if !reflect.DeepEqual(expectedErrs, errs) {
t.Errorf("expected %s, got %s", expectedErrs, errs)
}
-
}
diff --git a/traffic_ops/traffic_ops_golang/cdn/queue.go b/traffic_ops/traffic_ops_golang/cdn/queue.go
index 4e7cc6e..b8a4b82 100644
--- a/traffic_ops/traffic_ops_golang/cdn/queue.go
+++ b/traffic_ops/traffic_ops_golang/cdn/queue.go
@@ -64,7 +64,7 @@ func Queue(db *sql.DB) http.HandlerFunc {
return
}
api.WriteResp(w, r, QueueResp{Action: reqObj.Action, CDNID: int64(intParams["id"])})
- api.CreateChangeLogRaw(api.ApiChange, "Server updates "+reqObj.Action+"d for cdn "+params["id"], *user, db)
+ api.CreateChangeLogRaw(api.ApiChange, "Server updates "+reqObj.Action+"d for cdn "+params["id"], user, db)
}
}
diff --git a/traffic_ops/traffic_ops_golang/coordinate/coordinates.go b/traffic_ops/traffic_ops_golang/coordinate/coordinates.go
index 4b852d7..2707519 100644
--- a/traffic_ops/traffic_ops_golang/coordinate/coordinates.go
+++ b/traffic_ops/traffic_ops_golang/coordinate/coordinates.go
@@ -30,7 +30,6 @@ import (
"github.com/apache/trafficcontrol/lib/go-tc/tovalidate"
"github.com/apache/trafficcontrol/lib/go-tc/v13"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
- "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/dbhelpers"
validation "github.com/go-ozzo/ozzo-validation"
@@ -39,13 +38,16 @@ import (
)
//we need a type alias to define functions on
-type TOCoordinate v13.CoordinateNullable
-
-//the refType is passed into the handlers where a copy of its type is used to decode the json.
-var refType = TOCoordinate{}
+type TOCoordinate struct{
+ ReqInfo *api.APIInfo `json:"-"`
+ v13.CoordinateNullable
+}
-func GetRefType() *TOCoordinate {
- return &refType
+func GetTypeSingleton() func(reqInfo *api.APIInfo)api.CRUDer {
+ return func(reqInfo *api.APIInfo)api.CRUDer {
+ toReturn := TOCoordinate{reqInfo, v13.CoordinateNullable{}}
+ return &toReturn
+ }
}
func (coordinate TOCoordinate) GetKeyFieldsInfo() []api.KeyFieldInfo {
@@ -102,7 +104,7 @@ func IsValidCoordinateName(str string) bool {
}
// Validate fulfills the api.Validator interface
-func (coordinate TOCoordinate) Validate(db *sqlx.DB) []error {
+func (coordinate TOCoordinate) Validate() []error {
validName := validation.NewStringRule(IsValidCoordinateName, "invalid characters found - Use alphanumeric . or - or _ .")
latitudeErr := "Must be a floating point number within the range +-90"
longitudeErr := "Must be a floating point number within the range +-180"
@@ -121,24 +123,8 @@ func (coordinate TOCoordinate) Validate(db *sqlx.DB) []error {
//generic error message returned
//The insert sql returns the id and lastUpdated values of the newly inserted coordinate and have
//to be added to the struct
-func (coordinate *TOCoordinate) Create(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
- 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)
- return tc.DBError, tc.SystemError
- }
- resultRows, err := tx.NamedQuery(insertQuery(), coordinate)
+func (coordinate *TOCoordinate) Create() (error, tc.ApiErrorType) {
+ resultRows, err := coordinate.ReqInfo.Tx.NamedQuery(insertQuery(), coordinate)
if err != nil {
if pqErr, ok := err.(*pq.Error); ok {
err, eType := dbhelpers.ParsePQUniqueConstraintError(pqErr)
@@ -174,16 +160,10 @@ func (coordinate *TOCoordinate) Create(db *sqlx.DB, user auth.CurrentUser) (erro
}
coordinate.SetKeys(map[string]interface{}{"id": id})
coordinate.LastUpdated = &lastUpdated
- err = tx.Commit()
- if err != nil {
- log.Errorln("Could not commit transaction: ", err)
- return tc.DBError, tc.SystemError
- }
- rollbackTransaction = false
return nil, tc.NoError
}
-func (coordinate *TOCoordinate) Read(db *sqlx.DB, parameters map[string]string, user auth.CurrentUser) ([]interface{}, []error, tc.ApiErrorType) {
+func (coordinate *TOCoordinate) Read(parameters map[string]string) ([]interface{}, []error, tc.ApiErrorType) {
var rows *sqlx.Rows
// Query Parameters to Database Query column mappings
@@ -200,7 +180,7 @@ func (coordinate *TOCoordinate) Read(db *sqlx.DB, parameters map[string]string,
query := selectQuery() + where + orderBy
log.Debugln("Query is ", query)
- rows, err := db.NamedQuery(query, queryValues)
+ rows, err := coordinate.ReqInfo.Tx.NamedQuery(query, queryValues)
if err != nil {
log.Errorf("Error querying Coordinate: %v", err)
return nil, []error{tc.DBError}, tc.SystemError
@@ -225,25 +205,9 @@ func (coordinate *TOCoordinate) Read(db *sqlx.DB, parameters map[string]string,
//ParsePQUniqueConstraintError is used to determine if a coordinate with conflicting values exists
//if so, it will return an errorType of DataConflict and the type should be appended to the
//generic error message returned
-func (coordinate *TOCoordinate) Update(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
- 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)
- return tc.DBError, tc.SystemError
- }
+func (coordinate *TOCoordinate) Update() (error, tc.ApiErrorType) {
log.Debugf("about to run exec query: %s with coordinate: %++v", updateQuery(), coordinate)
- resultRows, err := tx.NamedQuery(updateQuery(), coordinate)
+ resultRows, err := coordinate.ReqInfo.Tx.NamedQuery(updateQuery(), coordinate)
if err != nil {
if pqErr, ok := err.(*pq.Error); ok {
err, eType := dbhelpers.ParsePQUniqueConstraintError(pqErr)
@@ -276,36 +240,14 @@ func (coordinate *TOCoordinate) Update(db *sqlx.DB, user auth.CurrentUser) (erro
return fmt.Errorf("this update affected too many rows: %d", rowsAffected), tc.SystemError
}
}
- err = tx.Commit()
- if err != nil {
- log.Errorln("Could not commit transaction: ", err)
- return tc.DBError, tc.SystemError
- }
- rollbackTransaction = false
return nil, tc.NoError
}
//The Coordinate implementation of the Deleter interface
//all implementations of Deleter should use transactions and return the proper errorType
-func (coordinate *TOCoordinate) Delete(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
- 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)
- return tc.DBError, tc.SystemError
- }
+func (coordinate *TOCoordinate) Delete() (error, tc.ApiErrorType) {
log.Debugf("about to run exec query: %s with coordinate: %++v", deleteQuery(), coordinate)
- result, err := tx.NamedExec(deleteQuery(), coordinate)
+ result, err := coordinate.ReqInfo.Tx.NamedExec(deleteQuery(), coordinate)
if err != nil {
log.Errorf("received error: %++v from delete execution", err)
return tc.DBError, tc.SystemError
@@ -321,12 +263,6 @@ func (coordinate *TOCoordinate) Delete(db *sqlx.DB, user auth.CurrentUser) (erro
return fmt.Errorf("this delete affected too many rows: %d", rowsAffected), tc.SystemError
}
}
- err = tx.Commit()
- if err != nil {
- log.Errorln("Could not commit transaction: ", err)
- return tc.DBError, tc.SystemError
- }
- rollbackTransaction = false
return nil, tc.NoError
}
diff --git a/traffic_ops/traffic_ops_golang/coordinate/coordinates_test.go b/traffic_ops/traffic_ops_golang/coordinate/coordinates_test.go
index 16b3837..6d3275b 100644
--- a/traffic_ops/traffic_ops_golang/coordinate/coordinates_test.go
+++ b/traffic_ops/traffic_ops_golang/coordinate/coordinates_test.go
@@ -26,10 +26,10 @@ import (
"testing"
"time"
+ "github.com/apache/trafficcontrol/lib/go-util"
"github.com/apache/trafficcontrol/lib/go-tc"
"github.com/apache/trafficcontrol/lib/go-tc/v13"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
- "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/test"
"github.com/jmoiron/sqlx"
@@ -69,8 +69,6 @@ func TestReadCoordinates(t *testing.T) {
db := sqlx.NewDb(mockDB, "sqlmock")
defer db.Close()
- refType := GetRefType()
-
testCoords := getTestCoordinates()
cols := test.ColsFromStructByTag("db", v13.Coordinate{})
rows := sqlmock.NewRows(cols)
@@ -84,10 +82,13 @@ func TestReadCoordinates(t *testing.T) {
ts.LastUpdated,
)
}
+ mock.ExpectBegin()
mock.ExpectQuery("SELECT").WillReturnRows(rows)
+ mock.ExpectCommit()
v := map[string]string{"id": "1"}
- coordinates, errs, _ := refType.Read(db, v, auth.CurrentUser{})
+ reqInfo := api.APIInfo{Tx:db.MustBegin(),CommitTx:util.BoolPtr(false)}
+ coordinates, errs, _ := GetTypeSingleton()(&reqInfo).Read(v)
if len(errs) > 0 {
t.Errorf("coordinate.Read expected: no errors, actual: %v", errs)
}
@@ -140,13 +141,13 @@ func TestValidate(t *testing.T) {
la := -190.0
lo := -190.0
lu := tc.TimeNoMod{Time: time.Now()}
- c := TOCoordinate{ID: &id,
- Name: &nm,
- Latitude: &la,
- Longitude: &lo,
+ c := TOCoordinate{ CoordinateNullable: v13.CoordinateNullable{ID: &id,
+ Name: &nm,
+ Latitude: &la,
+ Longitude: &lo,
LastUpdated: &lu,
- }
- errs := test.SortErrors(c.Validate(nil))
+ }}
+ errs := test.SortErrors(c.Validate())
expectedErrs := []error{
errors.New(`'latitude' Must be a floating point number within the range +-90`),
@@ -162,14 +163,14 @@ func TestValidate(t *testing.T) {
nm = "This.is.2.a-Valid---Coordinate."
la = 90.0
lo = 90.0
- c = TOCoordinate{ID: &id,
- Name: &nm,
- Latitude: &la,
- Longitude: &lo,
+ c = TOCoordinate{ CoordinateNullable: v13.CoordinateNullable{ID: &id,
+ Name: &nm,
+ Latitude: &la,
+ Longitude: &lo,
LastUpdated: &lu,
- }
+ }}
expectedErrs = []error{}
- errs = c.Validate(nil)
+ errs = c.Validate()
if !reflect.DeepEqual(expectedErrs, errs) {
t.Errorf("expected %s, got %s", expectedErrs, errs)
}
diff --git a/traffic_ops/traffic_ops_golang/crconfig/handler.go b/traffic_ops/traffic_ops_golang/crconfig/handler.go
index b1cafa1..646fe13 100644
--- a/traffic_ops/traffic_ops_golang/crconfig/handler.go
+++ b/traffic_ops/traffic_ops_golang/crconfig/handler.go
@@ -191,7 +191,7 @@ func SnapshotHandler(db *sqlx.DB, cfg config.Config) http.HandlerFunc {
handleErrs(http.StatusInternalServerError, err)
return
}
- api.CreateChangeLogRaw(api.ApiChange, "Snapshot of CRConfig performed for "+cdn, *user, db.DB)
+ api.CreateChangeLogRaw(api.ApiChange, "Snapshot of CRConfig performed for "+cdn, user, db.DB)
w.WriteHeader(http.StatusOK) // TODO change to 204 No Content in new version
}
}
@@ -236,7 +236,7 @@ func SnapshotOldGUIHandler(db *sqlx.DB, cfg config.Config) http.HandlerFunc {
writePerlHTMLErr(w, r, err)
return
}
- api.CreateChangeLogRaw(api.ApiChange, "Snapshot of CRConfig performed for "+cdn, *user, db.DB)
+ api.CreateChangeLogRaw(api.ApiChange, "Snapshot of CRConfig performed for "+cdn, user, db.DB)
http.Redirect(w, r, "/tools/flash_and_close/"+url.PathEscape("Successfully wrote the CRConfig.json!"), http.StatusFound)
}
}
diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservicesv12.go b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservicesv12.go
index 09c4f3c..a783a90 100644
--- a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservicesv12.go
+++ b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservicesv12.go
@@ -126,7 +126,7 @@ func GetXMLID(tx *sql.Tx, id int) (string, bool, error) {
// IsTenantAuthorized checks that the user is authorized for both the delivery service's existing tenant, and the new tenant they're changing it to (if different).
-func (ds *TODeliveryServiceV12) IsTenantAuthorized(user auth.CurrentUser, tx *sqlx.Tx) (bool, error) {
+func (ds *TODeliveryServiceV12) IsTenantAuthorized(user *auth.CurrentUser, tx *sqlx.Tx) (bool, error) {
return isTenantAuthorized(user, tx, &ds.DeliveryServiceNullableV12)
}
@@ -144,7 +144,7 @@ func getTenantID(tx *sql.Tx, ds *tc.DeliveryServiceNullableV12) (*int, error) {
return existingID, err
}
-func isTenantAuthorized(user auth.CurrentUser, tx *sqlx.Tx, ds *tc.DeliveryServiceNullableV12) (bool, error) {
+func isTenantAuthorized(user *auth.CurrentUser, tx *sqlx.Tx, ds *tc.DeliveryServiceNullableV12) (bool, error) {
existingID, err := getTenantID(tx.Tx, ds)
if err != nil {
return false, errors.New("getting tenant ID: " + err.Error())
@@ -197,7 +197,7 @@ func CreateV12() http.HandlerFunc {
return
}
dsv13 := tc.NewDeliveryServiceNullableV13FromV12(ds)
- if authorized, err := isTenantAuthorized(*inf.User, inf.Tx, &ds); err != nil {
+ if authorized, err := isTenantAuthorized(inf.User, inf.Tx, &ds); err != nil {
api.HandleErr(w, r, http.StatusInternalServerError, nil, errors.New("checking tenant: "+err.Error()))
return
} else if !authorized {
@@ -317,14 +317,14 @@ func UpdateV12() http.HandlerFunc {
return
}
dsv13 := tc.NewDeliveryServiceNullableV13FromV12(ds)
- if authorized, err := isTenantAuthorized(*inf.User, inf.Tx, &ds); err != nil {
+ if authorized, err := isTenantAuthorized(inf.User, inf.Tx, &ds); err != nil {
api.HandleErr(w, r, http.StatusInternalServerError, nil, errors.New("checking tenant: "+err.Error()))
return
} else if !authorized {
api.HandleErr(w, r, http.StatusForbidden, errors.New("not authorized on this tenant"), nil)
return
}
- dsv13, errCode, userErr, sysErr = update(inf.Tx.Tx, *inf.Config, *inf.User, &dsv13)
+ dsv13, errCode, userErr, sysErr = update(inf.Tx.Tx, *inf.Config, inf.User, &dsv13)
if userErr != nil || sysErr != nil {
api.HandleErr(w, r, errCode, userErr, sysErr)
return
diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservicesv13.go b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservicesv13.go
index 12d7312..994d498 100644
--- a/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservicesv13.go
+++ b/traffic_ops/traffic_ops_golang/deliveryservice/deliveryservicesv13.go
@@ -133,7 +133,7 @@ func CreateV13() http.HandlerFunc {
return
}
- if authorized, err := isTenantAuthorized(*inf.User, inf.Tx, &ds.DeliveryServiceNullableV12); err != nil {
+ if authorized, err := isTenantAuthorized(inf.User, inf.Tx, &ds.DeliveryServiceNullableV12); err != nil {
api.HandleErr(w, r, http.StatusInternalServerError, nil, errors.New("checking tenant: "+err.Error()))
return
} else if !authorized {
@@ -240,7 +240,7 @@ func create(tx *sql.Tx, cfg config.Config, user *auth.CurrentUser, ds tc.Deliver
}
ds.LastUpdated = &lastUpdated
- if err := api.CreateChangeLogRawErr(api.ApiChange, "Created ds: "+*ds.XMLID+" id: "+strconv.Itoa(*ds.ID), *user, tx); err!= nil {
+ if err := api.CreateChangeLogRawErr(api.ApiChange, "Created ds: "+*ds.XMLID+" id: "+strconv.Itoa(*ds.ID), user, tx); err!= nil {
return tc.DeliveryServiceNullableV13{}, http.StatusInternalServerError, nil, errors.New("error writing to audit log: " + err.Error())
}
return ds, http.StatusOK, nil, nil
@@ -410,7 +410,7 @@ func UpdateV13() http.HandlerFunc {
return
}
- if authorized, err := isTenantAuthorized(*inf.User, inf.Tx, &ds.DeliveryServiceNullableV12); err != nil {
+ if authorized, err := isTenantAuthorized(inf.User, inf.Tx, &ds.DeliveryServiceNullableV12); err != nil {
api.HandleErr(w, r, http.StatusInternalServerError, nil, errors.New("checking tenant: "+err.Error()))
return
} else if !authorized {
@@ -418,7 +418,7 @@ func UpdateV13() http.HandlerFunc {
return
}
- ds, errCode, userErr, sysErr = update(inf.Tx.Tx, *inf.Config, *inf.User, &ds)
+ ds, errCode, userErr, sysErr = update(inf.Tx.Tx, *inf.Config, inf.User, &ds)
if userErr != nil || sysErr != nil {
api.HandleErr(w, r, errCode, userErr, sysErr)
return
@@ -440,7 +440,7 @@ func getDSType(tx *sql.Tx, xmlid string) (tc.DSType, bool, error) {
return tc.DSTypeFromString(name), true, nil
}
-func update(tx *sql.Tx, cfg config.Config, user auth.CurrentUser, ds *tc.DeliveryServiceNullableV13) (tc.DeliveryServiceNullableV13, int, error, error) {
+func update(tx *sql.Tx, cfg config.Config, user *auth.CurrentUser, ds *tc.DeliveryServiceNullableV13) (tc.DeliveryServiceNullableV13, int, error, error) {
if ds.XMLID == nil {
return tc.DeliveryServiceNullableV13{}, http.StatusBadRequest, errors.New("missing xml_id"), nil
}
@@ -560,7 +560,7 @@ func update(tx *sql.Tx, cfg config.Config, user auth.CurrentUser, ds *tc.Deliver
return tc.DeliveryServiceNullableV13{}, http.StatusInternalServerError, nil, errors.New("creating mid cacheurl parameters: " + err.Error())
}
- if err := updatePrimaryOrigin(tx, &user, *ds); err != nil {
+ if err := updatePrimaryOrigin(tx, user, *ds); err != nil {
return tc.DeliveryServiceNullableV13{}, http.StatusInternalServerError, nil, errors.New("updating delivery service: " + err.Error())
}
@@ -579,11 +579,11 @@ func (ds *TODeliveryServiceV13) Delete() (error, tc.ApiErrorType) {
}
// IsTenantAuthorized implements the Tenantable interface to ensure the user is authorized on the deliveryservice tenant
-func (ds *TODeliveryServiceV13) IsTenantAuthorized(user auth.CurrentUser, tx *sqlx.Tx) (bool, error) {
+func (ds *TODeliveryServiceV13) IsTenantAuthorized(user *auth.CurrentUser, tx *sqlx.Tx) (bool, error) {
return ds.V12().IsTenantAuthorized(user, tx)
}
-func filterAuthorized(dses []tc.DeliveryServiceNullableV13, user auth.CurrentUser, db *sqlx.DB) ([]tc.DeliveryServiceNullableV13, error) {
+func filterAuthorized(dses []tc.DeliveryServiceNullableV13, user *auth.CurrentUser, db *sqlx.DB) ([]tc.DeliveryServiceNullableV13, error) {
newDSes := []tc.DeliveryServiceNullableV13{}
for _, ds := range dses {
// TODO add/use a helper func to make a single SQL call, for performance
diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/request/comment/comments.go b/traffic_ops/traffic_ops_golang/deliveryservice/request/comment/comments.go
index 5824af1..50ca589 100644
--- a/traffic_ops/traffic_ops_golang/deliveryservice/request/comment/comments.go
+++ b/traffic_ops/traffic_ops_golang/deliveryservice/request/comment/comments.go
@@ -28,7 +28,6 @@ import (
"github.com/apache/trafficcontrol/lib/go-tc"
"github.com/apache/trafficcontrol/lib/go-tc/tovalidate"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
- "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/dbhelpers"
"github.com/go-ozzo/ozzo-validation"
@@ -38,13 +37,13 @@ import (
//we need a type alias to define functions on
type TODeliveryServiceRequestComment struct{
- DB *sqlx.DB `json:"-"`
+ ReqInfo *api.APIInfo `json:"-"`
tc.DeliveryServiceRequestCommentNullable
}
-func GetTypeSingleton(db *sqlx.DB) func()api.CRUDer {
- return func()api.CRUDer {
- toReturn := TODeliveryServiceRequestComment{db, tc.DeliveryServiceRequestCommentNullable{}}
+func GetTypeSingleton() func(reqInfo *api.APIInfo)api.CRUDer {
+ return func(reqInfo *api.APIInfo)api.CRUDer {
+ toReturn := TODeliveryServiceRequestComment{reqInfo, tc.DeliveryServiceRequestCommentNullable{}}
return &toReturn
}
}
@@ -77,7 +76,7 @@ func (comment TODeliveryServiceRequestComment) GetType() string {
return "deliveryservice_request_comment"
}
-func (comment TODeliveryServiceRequestComment) Validate(db *sqlx.DB) []error {
+func (comment TODeliveryServiceRequestComment) Validate() []error {
errs := validation.Errors{
"deliveryServiceRequestId": validation.Validate(comment.DeliveryServiceRequestID, validation.NotNil),
"value": validation.Validate(comment.Value, validation.NotNil),
@@ -85,28 +84,11 @@ func (comment TODeliveryServiceRequestComment) Validate(db *sqlx.DB) []error {
return tovalidate.ToErrors(errs)
}
-func (comment *TODeliveryServiceRequestComment) Create(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
- 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)
- return tc.DBError, tc.SystemError
- }
-
- userID := tc.IDNoMod(user.ID)
+func (comment *TODeliveryServiceRequestComment) Create() (error, tc.ApiErrorType) {
+ userID := tc.IDNoMod(comment.ReqInfo.User.ID)
comment.AuthorID = &userID
- resultRows, err := tx.NamedQuery(insertQuery(), comment)
+ resultRows, err := comment.ReqInfo.Tx.NamedQuery(insertQuery(), comment)
if err != nil {
if pqErr, ok := err.(*pq.Error); ok {
@@ -143,16 +125,11 @@ func (comment *TODeliveryServiceRequestComment) Create(db *sqlx.DB, user auth.Cu
}
comment.SetKeys(map[string]interface{}{"id": id})
comment.LastUpdated = &lastUpdated
- err = tx.Commit()
- if err != nil {
- log.Errorln("Could not commit transaction: ", err)
- return tc.DBError, tc.SystemError
- }
- rollbackTransaction = false
+
return nil, tc.NoError
}
-func (comment *TODeliveryServiceRequestComment) Read(db *sqlx.DB, parameters map[string]string, user auth.CurrentUser) ([]interface{}, []error, tc.ApiErrorType) {
+func (comment *TODeliveryServiceRequestComment) Read(parameters map[string]string) ([]interface{}, []error, tc.ApiErrorType) {
var rows *sqlx.Rows
// Query Parameters to Database Query column mappings
@@ -171,7 +148,7 @@ func (comment *TODeliveryServiceRequestComment) Read(db *sqlx.DB, parameters map
query := selectQuery() + where + orderBy
log.Debugln("Query is ", query)
- rows, err := db.NamedQuery(query, queryValues)
+ rows, err := comment.ReqInfo.Tx.NamedQuery(query, queryValues)
if err != nil {
log.Errorf("Error querying delivery service request comments: %v", err)
return nil, []error{tc.DBError}, tc.SystemError
@@ -191,38 +168,22 @@ func (comment *TODeliveryServiceRequestComment) Read(db *sqlx.DB, parameters map
return comments, []error{}, tc.NoError
}
-func (comment *TODeliveryServiceRequestComment) Update(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
+func (comment *TODeliveryServiceRequestComment) Update() (error, tc.ApiErrorType) {
var current TODeliveryServiceRequestComment
- err := db.QueryRowx(selectQuery() + `WHERE dsrc.id=` + strconv.Itoa(*comment.ID)).StructScan(¤t)
+ err := comment.ReqInfo.Tx.QueryRowx(selectQuery() + `WHERE dsrc.id=` + strconv.Itoa(*comment.ID)).StructScan(¤t)
if err != nil {
log.Errorf("Error querying DeliveryServiceRequestComments: %v", err)
return err, tc.SystemError
}
- userID := tc.IDNoMod(user.ID)
+ userID := tc.IDNoMod(comment.ReqInfo.User.ID)
if *current.AuthorID != userID {
return errors.New("Comments can only be updated by the author"), tc.DataConflictError
}
- 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)
- return tc.DBError, tc.SystemError
- }
log.Debugf("about to run exec query: %s with comment: %++v", updateQuery(), comment)
- resultRows, err := tx.NamedQuery(updateQuery(), comment)
+ resultRows, err := comment.ReqInfo.Tx.NamedQuery(updateQuery(), comment)
if err != nil {
if pqErr, ok := err.(*pq.Error); ok {
err, eType := dbhelpers.ParsePQUniqueConstraintError(pqErr)
@@ -255,47 +216,25 @@ func (comment *TODeliveryServiceRequestComment) Update(db *sqlx.DB, user auth.Cu
return fmt.Errorf("this update affected too many rows: %d", rowsAffected), tc.SystemError
}
}
- err = tx.Commit()
- if err != nil {
- log.Errorln("Could not commit transaction: ", err)
- return tc.DBError, tc.SystemError
- }
- rollbackTransaction = false
return nil, tc.NoError
}
-func (comment *TODeliveryServiceRequestComment) Delete(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
+func (comment *TODeliveryServiceRequestComment) Delete() (error, tc.ApiErrorType) {
var current TODeliveryServiceRequestComment
- err := db.QueryRowx(selectQuery() + `WHERE dsrc.id=` + strconv.Itoa(*comment.ID)).StructScan(¤t)
+ err :=comment.ReqInfo.Tx.QueryRowx(selectQuery() + `WHERE dsrc.id=` + strconv.Itoa(*comment.ID)).StructScan(¤t)
if err != nil {
log.Errorf("Error querying DeliveryServiceRequestComments: %v", err)
return err, tc.SystemError
}
- userID := tc.IDNoMod(user.ID)
+ userID := tc.IDNoMod(comment.ReqInfo.User.ID)
if *current.AuthorID != userID {
return errors.New("Comments can only be deleted by the author"), tc.DataConflictError
}
- 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)
- return tc.DBError, tc.SystemError
- }
log.Debugf("about to run exec query: %s with comment: %++v", deleteQuery(), comment)
- result, err := tx.NamedExec(deleteQuery(), comment)
+ result, err := comment.ReqInfo.Tx.NamedExec(deleteQuery(), comment)
if err != nil {
log.Errorf("received error: %++v from delete execution", err)
return tc.DBError, tc.SystemError
@@ -311,12 +250,6 @@ func (comment *TODeliveryServiceRequestComment) Delete(db *sqlx.DB, user auth.Cu
return fmt.Errorf("this delete affected too many rows: %d", rowsAffected), tc.SystemError
}
}
- err = tx.Commit()
- if err != nil {
- log.Errorln("Could not commit transaction: ", err)
- return tc.DBError, tc.SystemError
- }
- rollbackTransaction = false
return nil, tc.NoError
}
diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/request/comment/comments_test.go b/traffic_ops/traffic_ops_golang/deliveryservice/request/comment/comments_test.go
index b785536..17b436c 100644
--- a/traffic_ops/traffic_ops_golang/deliveryservice/request/comment/comments_test.go
+++ b/traffic_ops/traffic_ops_golang/deliveryservice/request/comment/comments_test.go
@@ -27,6 +27,7 @@ import (
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/test"
+ "github.com/apache/trafficcontrol/lib/go-tc"
)
func TestFuncs(t *testing.T) {
@@ -67,7 +68,7 @@ func TestInterfaces(t *testing.T) {
func TestValidate(t *testing.T) {
c := TODeliveryServiceRequestComment{}
- errs := test.SortErrors(c.Validate(nil))
+ errs := test.SortErrors(c.Validate())
expectedErrs := []error{
errors.New(`'deliveryServiceRequestId' is required`),
@@ -80,9 +81,9 @@ func TestValidate(t *testing.T) {
v := "the comment value"
d := 1
- c = TODeliveryServiceRequestComment{DeliveryServiceRequestID: &d, Value: &v}
+ c = TODeliveryServiceRequestComment{DeliveryServiceRequestCommentNullable: tc.DeliveryServiceRequestCommentNullable{DeliveryServiceRequestID: &d, Value: &v}}
expectedErrs = []error{}
- errs = c.Validate(nil)
+ errs = c.Validate()
if !reflect.DeepEqual(expectedErrs, errs) {
t.Errorf("expected %s, got %s", expectedErrs, errs)
}
diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go b/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go
index 753127d..00a3d9d 100644
--- a/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go
+++ b/traffic_ops/traffic_ops_golang/deliveryservice/request/requests.go
@@ -122,7 +122,7 @@ func (req *TODeliveryServiceRequest) Read(parameters map[string]string) ([]inter
}
// TODO: combine tenancy with the query above so there's a single db call
- t, err := s.IsTenantAuthorized(*req.ReqInfo.User)
+ t, err := s.IsTenantAuthorized(req.ReqInfo.User)
if err != nil {
log.Errorf("error checking tenancy: %v", err)
return nil, []error{tc.DBError}, tc.SystemError
@@ -161,7 +161,7 @@ LEFT OUTER JOIN tm_user e ON r.last_edited_by_id = e.id
}
// IsTenantAuthorized implements the Tenantable interface to ensure the user is authorized on the deliveryservice tenant
-func (req TODeliveryServiceRequest) IsTenantAuthorized(user auth.CurrentUser) (bool, error) {
+func (req TODeliveryServiceRequest) IsTenantAuthorized(user *auth.CurrentUser) (bool, error) {
ds := req.DeliveryService
if ds == nil {
diff --git a/traffic_ops/traffic_ops_golang/deliveryservice/request/requests_test.go b/traffic_ops/traffic_ops_golang/deliveryservice/request/requests_test.go
index b4aa80e..b69b9b9 100644
--- a/traffic_ops/traffic_ops_golang/deliveryservice/request/requests_test.go
+++ b/traffic_ops/traffic_ops_golang/deliveryservice/request/requests_test.go
@@ -58,7 +58,7 @@ func TestGetDeliveryServiceRequest(t *testing.T) {
b := true
u := "UPDATE"
st := tc.RequestStatusSubmitted
- r := &TODeliveryServiceRequest{
+ r := &TODeliveryServiceRequest{DeliveryServiceRequestNullable: tc.DeliveryServiceRequestNullable{
ChangeType: &u,
Status: &st,
DeliveryService: &tc.DeliveryServiceNullableV13{
@@ -74,7 +74,7 @@ func TestGetDeliveryServiceRequest(t *testing.T) {
},
},
},
- }
+ }}
expectedErrors := []string{
/*
diff --git a/traffic_ops/traffic_ops_golang/deliveryservicesregexes/deliveryservicesregexes.go b/traffic_ops/traffic_ops_golang/deliveryservicesregexes/deliveryservicesregexes.go
index 20e6485..b091ea9 100644
--- a/traffic_ops/traffic_ops_golang/deliveryservicesregexes/deliveryservicesregexes.go
+++ b/traffic_ops/traffic_ops_golang/deliveryservicesregexes/deliveryservicesregexes.go
@@ -72,7 +72,7 @@ JOIN type as rt ON r.type = rt.id
handleErrs(http.StatusInternalServerError, errors.New("querying: "+err.Error()))
return
}
- if ok, err := tenant.IsResourceAuthorizedToUser(dsTenantID, *user, dbx); !ok {
+ if ok, err := tenant.IsResourceAuthorizedToUser(dsTenantID, user, dbx); !ok {
continue
} else if err != nil {
handleErrs(http.StatusInternalServerError, errors.New("checking tenancy: "+err.Error()))
@@ -153,7 +153,7 @@ ORDER BY dsr.set_number ASC
handleErrs(http.StatusInternalServerError, errors.New("querying: "+err.Error()))
return
}
- if ok, err := tenant.IsResourceAuthorizedToUser(dsTenantID, *user, dbx); !ok {
+ if ok, err := tenant.IsResourceAuthorizedToUser(dsTenantID, user, dbx); !ok {
continue
} else if err != nil {
handleErrs(http.StatusInternalServerError, errors.New("checking tenancy: "+err.Error()))
@@ -245,7 +245,7 @@ ORDER BY dsr.set_number ASC
handleErrs(http.StatusInternalServerError, errors.New("querying: "+err.Error()))
return
}
- if ok, err := tenant.IsResourceAuthorizedToUser(dsTenantID, *user, dbx); !ok {
+ if ok, err := tenant.IsResourceAuthorizedToUser(dsTenantID, user, dbx); !ok {
continue
} else if err != nil {
handleErrs(http.StatusInternalServerError, errors.New("checking tenancy: "+err.Error()))
@@ -301,7 +301,7 @@ func Post(dbx *sqlx.DB) http.HandlerFunc {
handleErrs(http.StatusInternalServerError, err)
return
}
- if ok, err := tenant.IsResourceAuthorizedToUser(dsTenantID, *user, dbx); !ok {
+ if ok, err := tenant.IsResourceAuthorizedToUser(dsTenantID, user, dbx); !ok {
handleErrs(http.StatusInternalServerError, errors.New("unauthorized"))
return
} else if err != nil {
@@ -403,7 +403,7 @@ func Put(dbx *sqlx.DB) http.HandlerFunc {
handleErrs(http.StatusInternalServerError, err)
return
}
- if ok, err := tenant.IsResourceAuthorizedToUser(dsTenantID, *user, dbx); !ok {
+ if ok, err := tenant.IsResourceAuthorizedToUser(dsTenantID, user, dbx); !ok {
handleErrs(http.StatusInternalServerError, errors.New("unauthorized"))
return
} else if err != nil {
@@ -525,7 +525,7 @@ func Delete(dbx *sqlx.DB) http.HandlerFunc {
handleErrs(http.StatusInternalServerError, err)
return
}
- if ok, err := tenant.IsResourceAuthorizedToUser(dsTenantID, *user, dbx); !ok {
+ if ok, err := tenant.IsResourceAuthorizedToUser(dsTenantID, user, dbx); !ok {
handleErrs(http.StatusUnauthorized, errors.New("unauthorized"))
return
} else if err != nil {
@@ -557,7 +557,7 @@ func Delete(dbx *sqlx.DB) http.HandlerFunc {
}
log.Debugf("changelog for delete on object")
- api.CreateChangeLogRaw(api.ApiChange,fmt.Sprintf(`deleted deliveryservice_regex {"ds": %d, "regex": %d}`, dsID, regexID), *user, dbx.DB)
+ api.CreateChangeLogRaw(api.ApiChange,fmt.Sprintf(`deleted deliveryservice_regex {"ds": %d, "regex": %d}`, dsID, regexID), user, dbx.DB)
resp := struct {
tc.Alerts
}{tc.CreateAlerts(tc.SuccessLevel, "deliveryservice_regex was deleted.")}
diff --git a/traffic_ops/traffic_ops_golang/division/divisions.go b/traffic_ops/traffic_ops_golang/division/divisions.go
index 70f864e..fa9d3a3 100644
--- a/traffic_ops/traffic_ops_golang/division/divisions.go
+++ b/traffic_ops/traffic_ops_golang/division/divisions.go
@@ -29,22 +29,23 @@ import (
"github.com/apache/trafficcontrol/lib/go-tc"
"github.com/apache/trafficcontrol/lib/go-tc/tovalidate"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
- "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/dbhelpers"
validation "github.com/go-ozzo/ozzo-validation"
- "github.com/jmoiron/sqlx"
"github.com/lib/pq"
)
//we need a type alias to define functions on
-type TODivision tc.DivisionNullable
-
-//the refType is passed into the handlers where a copy of its type is used to decode the json.
-var refType = TODivision(tc.DivisionNullable{})
+type TODivision struct{
+ ReqInfo *api.APIInfo `json:"-"`
+ tc.DivisionNullable
+}
-func GetRefType() *TODivision {
- return &refType
+func GetTypeSingleton() func(reqInfo *api.APIInfo)api.CRUDer {
+ return func(reqInfo *api.APIInfo)api.CRUDer {
+ toReturn := TODivision{reqInfo, tc.DivisionNullable{}}
+ return &toReturn
+ }
}
func (division TODivision) GetAuditName() string {
@@ -78,7 +79,7 @@ func (division TODivision) GetType() string {
return "division"
}
-func (division TODivision) Validate(db *sqlx.DB) []error {
+func (division TODivision) Validate() []error {
errs := validation.Errors{
"name": validation.Validate(division.Name, validation.NotNil, validation.Required),
}
@@ -92,24 +93,8 @@ func (division TODivision) Validate(db *sqlx.DB) []error {
//generic error message returned
//The insert sql returns the id and lastUpdated values of the newly inserted division and have
//to be added to the struct
-func (division *TODivision) Create(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
- 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)
- return tc.DBError, tc.SystemError
- }
- resultRows, err := tx.NamedQuery(insertQuery(), division)
+func (division *TODivision) Create() (error, tc.ApiErrorType) {
+ resultRows, err := division.ReqInfo.Tx.NamedQuery(insertQuery(), division)
if err != nil {
if pqErr, ok := err.(*pq.Error); ok {
err, eType := dbhelpers.ParsePQUniqueConstraintError(pqErr)
@@ -145,16 +130,10 @@ func (division *TODivision) Create(db *sqlx.DB, user auth.CurrentUser) (error, t
}
division.SetKeys(map[string]interface{}{"id": id})
division.LastUpdated = &lastUpdated
- err = tx.Commit()
- if err != nil {
- log.Errorln("Could not commit transaction: ", err)
- return tc.DBError, tc.SystemError
- }
- rollbackTransaction = false
return nil, tc.NoError
}
-func (division *TODivision) Read(db *sqlx.DB, parameters map[string]string, user auth.CurrentUser) ([]interface{}, []error, tc.ApiErrorType) {
+func (division *TODivision) Read(parameters map[string]string) ([]interface{}, []error, tc.ApiErrorType) {
if strings.HasSuffix(parameters["name"], ".json") {
parameters["name"] = parameters["name"][:len(parameters["name"])-len(".json")]
}
@@ -172,7 +151,7 @@ func (division *TODivision) Read(db *sqlx.DB, parameters map[string]string, user
query := selectQuery() + where + orderBy
log.Debugln("Query is ", query)
- rows, err := db.NamedQuery(query, queryValues)
+ rows, err := division.ReqInfo.Tx.NamedQuery(query, queryValues)
if err != nil {
log.Errorf("Error querying Divisions: %v", err)
return nil, []error{tc.DBError}, tc.SystemError
@@ -197,25 +176,9 @@ func (division *TODivision) Read(db *sqlx.DB, parameters map[string]string, user
//ParsePQUniqueConstraintError is used to determine if a division with conflicting values exists
//if so, it will return an errorType of DataConflict and the type should be appended to the
//generic error message returned
-func (division *TODivision) Update(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
- 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)
- return tc.DBError, tc.SystemError
- }
+func (division *TODivision) Update() (error, tc.ApiErrorType) {
log.Debugf("about to run exec query: %s with division: %++v", updateQuery(), division)
- resultRows, err := tx.NamedQuery(updateQuery(), division)
+ resultRows, err := division.ReqInfo.Tx.NamedQuery(updateQuery(), division)
if err != nil {
if pqErr, ok := err.(*pq.Error); ok {
err, eType := dbhelpers.ParsePQUniqueConstraintError(pqErr)
@@ -248,84 +211,14 @@ func (division *TODivision) Update(db *sqlx.DB, user auth.CurrentUser) (error, t
return fmt.Errorf("this update affected too many rows: %d", rowsAffected), tc.SystemError
}
}
- err = tx.Commit()
- if err != nil {
- log.Errorln("Could not commit transaction: ", err)
- return tc.DBError, tc.SystemError
- }
- rollbackTransaction = false
return nil, tc.NoError
}
-func getDivisionsResponse(params map[string]string, db *sqlx.DB) (*tc.DivisionsResponse, []error, tc.ApiErrorType) {
- divisions, errs, errType := getDivisions(params, db)
- if len(errs) > 0 {
- return nil, errs, errType
- }
-
- resp := tc.DivisionsResponse{
- Response: divisions,
- }
- return &resp, nil, tc.NoError
-}
-
-func getDivisions(params map[string]string, db *sqlx.DB) ([]tc.Division, []error, tc.ApiErrorType) {
- var rows *sqlx.Rows
- var err error
-
- // Query Parameters to Database Query column mappings
- // see the fields mapped in the SQL query
- queryParamsToSQLCols := map[string]dbhelpers.WhereColumnInfo{
- "id": dbhelpers.WhereColumnInfo{"id", api.IsInt},
- "name": dbhelpers.WhereColumnInfo{"name", nil},
- }
-
- where, orderBy, queryValues, errs := dbhelpers.BuildWhereAndOrderBy(params, queryParamsToSQLCols)
- if len(errs) > 0 {
- return nil, errs, tc.DataConflictError
- }
-
- query := selectQuery() + where + orderBy
- log.Debugln("Query is ", query)
-
- rows, err = db.NamedQuery(query, queryValues)
- if err != nil {
- return nil, []error{err}, tc.SystemError
- }
- defer rows.Close()
-
- o := []tc.Division{}
- for rows.Next() {
- var d tc.Division
- if err = rows.StructScan(&d); err != nil {
- return nil, []error{fmt.Errorf("getting divisions: %v", err)}, tc.SystemError
- }
- o = append(o, d)
- }
- return o, nil, tc.NoError
-}
-
//The Division implementation of the Deleter interface
//all implementations of Deleter should use transactions and return the proper errorType
-func (division *TODivision) Delete(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
- 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)
- return tc.DBError, tc.SystemError
- }
+func (division *TODivision) Delete() (error, tc.ApiErrorType) {
log.Debugf("about to run exec query: %s with division: %++v", deleteQuery(), division)
- result, err := tx.NamedExec(deleteQuery(), division)
+ result, err := division.ReqInfo.Tx.NamedExec(deleteQuery(), division)
if err != nil {
log.Errorf("received error: %++v from delete execution", err)
return tc.DBError, tc.SystemError
@@ -341,12 +234,6 @@ func (division *TODivision) Delete(db *sqlx.DB, user auth.CurrentUser) (error, t
return fmt.Errorf("this create affected too many rows: %d", rowsAffected), tc.SystemError
}
}
- err = tx.Commit()
- if err != nil {
- log.Errorln("Could not commit transaction: ", err)
- return tc.DBError, tc.SystemError
- }
- rollbackTransaction = false
return nil, tc.NoError
}
diff --git a/traffic_ops/traffic_ops_golang/division/divisions_test.go b/traffic_ops/traffic_ops_golang/division/divisions_test.go
index ce2e99d..eedcbba 100644
--- a/traffic_ops/traffic_ops_golang/division/divisions_test.go
+++ b/traffic_ops/traffic_ops_golang/division/divisions_test.go
@@ -25,6 +25,7 @@ import (
"time"
"github.com/apache/trafficcontrol/lib/go-tc"
+ "github.com/apache/trafficcontrol/lib/go-util"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/test"
"github.com/jmoiron/sqlx"
@@ -69,10 +70,13 @@ func TestGetDivisions(t *testing.T) {
ts.Name,
)
}
+ mock.ExpectBegin()
mock.ExpectQuery("SELECT").WillReturnRows(rows)
+ mock.ExpectCommit()
v := map[string]string{"dsId": "1"}
- servers, errs, errType := getDivisions(v, db)
+ reqInfo := api.APIInfo{Tx:db.MustBegin(),CommitTx:util.BoolPtr(false)}
+ servers, errs, errType := GetTypeSingleton()(&reqInfo).Read(v)
if len(errs) > 0 {
t.Errorf("getDivisions expected: no errors, actual: %v with error type: %s", errs, errType.String())
}
@@ -106,7 +110,7 @@ func TestInterfaces(t *testing.T) {
func TestValidation(t *testing.T) {
div := TODivision{}
- errs := test.SortErrors(div.Validate(nil))
+ errs := test.SortErrors(div.Validate())
expected := []error{}
if reflect.DeepEqual(expected, errs) {
diff --git a/traffic_ops/traffic_ops_golang/origin/origins.go b/traffic_ops/traffic_ops_golang/origin/origins.go
index a9b9ee7..73f4a4a 100644
--- a/traffic_ops/traffic_ops_golang/origin/origins.go
+++ b/traffic_ops/traffic_ops_golang/origin/origins.go
@@ -41,13 +41,16 @@ import (
)
//we need a type alias to define functions on
-type TOOrigin v13.Origin
-
-//the refType is passed into the handlers where a copy of its type is used to decode the json.
-var refType = TOOrigin{}
+type TOOrigin struct{
+ ReqInfo *api.APIInfo `json:"-"`
+ v13.Origin
+}
-func GetRefType() *TOOrigin {
- return &refType
+func GetTypeSingleton() func(reqInfo *api.APIInfo)api.CRUDer {
+ return func(reqInfo *api.APIInfo)api.CRUDer {
+ toReturn := TOOrigin{reqInfo, v13.Origin{}}
+ return &toReturn
+ }
}
func (origin *TOOrigin) SetID(i int) {
@@ -85,7 +88,7 @@ func (origin *TOOrigin) GetType() string {
return "origin"
}
-func (origin *TOOrigin) Validate(db *sqlx.DB) []error {
+func (origin *TOOrigin) Validate() []error {
noSpaces := validation.NewStringRule(tovalidate.NoSpaces, "cannot contain spaces")
validProtocol := validation.NewStringRule(tovalidate.IsOneOfStringICase("http", "https"), "must be http or https")
@@ -108,10 +111,10 @@ func (origin *TOOrigin) Validate(db *sqlx.DB) []error {
}
// GetTenantID returns a pointer to the Origin's tenant ID from the Tx and any error encountered
-func (origin *TOOrigin) GetTenantID(db *sqlx.DB) (*int, error) {
+func (origin *TOOrigin) GetTenantID(tx *sqlx.Tx) (*int, error) {
if origin.ID != nil {
var tenantID *int
- if err := db.QueryRow(`SELECT tenant FROM origin where id = $1`, *origin.ID).Scan(&tenantID); err != nil {
+ if err := tx.QueryRow(`SELECT tenant FROM origin where id = $1`, *origin.ID).Scan(&tenantID); err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
@@ -122,21 +125,21 @@ func (origin *TOOrigin) GetTenantID(db *sqlx.DB) (*int, error) {
return nil, nil
}
-func (origin *TOOrigin) IsTenantAuthorized(user auth.CurrentUser, db *sqlx.DB) (bool, error) {
- currentTenantID, err := origin.GetTenantID(db)
+func (origin *TOOrigin) IsTenantAuthorized(user *auth.CurrentUser) (bool, error) {
+ currentTenantID, err := origin.GetTenantID(origin.ReqInfo.Tx)
if err != nil {
return false, err
}
- if currentTenantID != nil && tenant.IsTenancyEnabled(db) {
- return tenant.IsResourceAuthorizedToUser(*currentTenantID, user, db)
+ if currentTenantID != nil && tenant.IsTenancyEnabledTx(origin.ReqInfo.Tx) {
+ return tenant.IsResourceAuthorizedToUserTx(*currentTenantID, user, origin.ReqInfo.Tx.Tx)
}
return true, nil
}
// filterAuthorized will filter a slice of Origins based upon tenant. It assumes that tenancy is enabled
-func filterAuthorized(origins []v13.Origin, user auth.CurrentUser, db *sqlx.DB) ([]v13.Origin, error) {
+func filterAuthorized(origins []v13.Origin, user *auth.CurrentUser, tx *sqlx.Tx) ([]v13.Origin, error) {
newOrigins := []v13.Origin{}
for _, origin := range origins {
if origin.TenantID == nil {
@@ -147,7 +150,7 @@ func filterAuthorized(origins []v13.Origin, user auth.CurrentUser, db *sqlx.DB)
}
}
// TODO add/use a helper func to make a single SQL call, for performance
- ok, err := tenant.IsResourceAuthorizedToUser(*origin.TenantID, user, db)
+ ok, err := tenant.IsResourceAuthorizedToUserTx(*origin.TenantID, user, tx.Tx)
if err != nil {
if origin.ID == nil {
return nil, errors.New("isResourceAuthorized for origin with nil ID: " + err.Error())
@@ -163,19 +166,19 @@ func filterAuthorized(origins []v13.Origin, user auth.CurrentUser, db *sqlx.DB)
return newOrigins, nil
}
-func (origin *TOOrigin) Read(db *sqlx.DB, params map[string]string, user auth.CurrentUser) ([]interface{}, []error, tc.ApiErrorType) {
+func (origin *TOOrigin) Read(params map[string]string) ([]interface{}, []error, tc.ApiErrorType) {
returnable := []interface{}{}
- privLevel := user.PrivLevel
+ privLevel := origin.ReqInfo.User.PrivLevel
- origins, errs, errType := getOrigins(params, db, privLevel)
+ origins, errs, errType := getOrigins(params, origin.ReqInfo.Tx, privLevel)
if len(errs) > 0 {
return nil, errs, errType
}
var err error
- if tenant.IsTenancyEnabled(db) {
- origins, err = filterAuthorized(origins, user, db)
+ if tenant.IsTenancyEnabledTx(origin.ReqInfo.Tx) {
+ origins, err = filterAuthorized(origins, origin.ReqInfo.User, origin.ReqInfo.Tx)
if err != nil {
log.Errorln("Checking tenancy: " + err.Error())
return nil, []error{errors.New("Error checking tenancy.")}, tc.SystemError
@@ -189,7 +192,7 @@ func (origin *TOOrigin) Read(db *sqlx.DB, params map[string]string, user auth.Cu
return returnable, nil, tc.NoError
}
-func getOrigins(params map[string]string, db *sqlx.DB, privLevel int) ([]v13.Origin, []error, tc.ApiErrorType) {
+func getOrigins(params map[string]string, tx *sqlx.Tx, privLevel int) ([]v13.Origin, []error, tc.ApiErrorType) {
var rows *sqlx.Rows
var err error
@@ -214,7 +217,7 @@ func getOrigins(params map[string]string, db *sqlx.DB, privLevel int) ([]v13.Ori
query := selectQuery() + where + orderBy
log.Debugln("Query is ", query)
- rows, err = db.NamedQuery(query, queryValues)
+ rows, err = tx.NamedQuery(query, queryValues)
if err != nil {
return nil, []error{fmt.Errorf("querying: %v", err)}, tc.SystemError
}
@@ -266,12 +269,12 @@ LEFT JOIN tenant t ON o.tenant = t.id`
return selectStmt
}
-func checkTenancy(originTenantID, deliveryserviceID *int, db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
- if tenant.IsTenancyEnabled(db) {
+func checkTenancy(originTenantID, deliveryserviceID *int, tx *sqlx.Tx, user *auth.CurrentUser) (error, tc.ApiErrorType) {
+ if tenant.IsTenancyEnabledTx(tx) {
if originTenantID == nil {
return tc.NilTenantError, tc.ForbiddenError
}
- authorized, err := tenant.IsResourceAuthorizedToUser(*originTenantID, user, db)
+ authorized, err := tenant.IsResourceAuthorizedToUserTx(*originTenantID, user, tx.Tx)
if err != nil {
return err, tc.SystemError
}
@@ -281,7 +284,7 @@ func checkTenancy(originTenantID, deliveryserviceID *int, db *sqlx.DB, user auth
if deliveryserviceID != nil {
var deliveryserviceTenantID *int
- if err := db.QueryRow(`SELECT tenant_id FROM deliveryservice where id = $1`, *deliveryserviceID).Scan(&deliveryserviceTenantID); err != nil {
+ if err := tx.QueryRow(`SELECT tenant_id FROM deliveryservice where id = $1`, *deliveryserviceID).Scan(&deliveryserviceTenantID); err != nil {
if err == sql.ErrNoRows {
return errors.New("checking tenancy: requested delivery service does not exist"), tc.DataConflictError
}
@@ -289,7 +292,7 @@ func checkTenancy(originTenantID, deliveryserviceID *int, db *sqlx.DB, user auth
return err, tc.SystemError
}
if deliveryserviceTenantID != nil {
- authorized, err := tenant.IsResourceAuthorizedToUser(*deliveryserviceTenantID, user, db)
+ authorized, err := tenant.IsResourceAuthorizedToUserTx(*deliveryserviceTenantID, user, tx.Tx)
if err != nil {
return err, tc.SystemError
}
@@ -307,34 +310,17 @@ func checkTenancy(originTenantID, deliveryserviceID *int, db *sqlx.DB, user auth
//ParsePQUniqueConstraintError is used to determine if an origin with conflicting values exists
//if so, it will return an errorType of DataConflict and the type should be appended to the
//generic error message returned
-func (origin *TOOrigin) Update(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
+func (origin *TOOrigin) Update() (error, tc.ApiErrorType) {
// TODO: enhance tenancy framework to handle this in isTenantAuthorized()
- err, errType := checkTenancy(origin.TenantID, origin.DeliveryServiceID, db, user)
+ err, errType := checkTenancy(origin.TenantID, origin.DeliveryServiceID, origin.ReqInfo.Tx, origin.ReqInfo.User)
if err != nil {
return err, errType
}
- 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)
- return tc.DBError, tc.SystemError
- }
-
isPrimary := false
ds := 0
q := `SELECT is_primary, deliveryservice FROM origin WHERE id = $1`
- if err := tx.QueryRow(q, *origin.ID).Scan(&isPrimary, &ds); err != nil {
+ if err := origin.ReqInfo.Tx.QueryRow(q, *origin.ID).Scan(&isPrimary, &ds); err != nil {
log.Errorf("updating origin %d, received error in select: %v", *origin.ID, err)
return tc.DBError, tc.SystemError
}
@@ -343,7 +329,7 @@ func (origin *TOOrigin) Update(db *sqlx.DB, user auth.CurrentUser) (error, tc.Ap
}
log.Debugf("about to run exec query: %s with origin: %++v", updateQuery(), origin)
- resultRows, err := tx.NamedQuery(updateQuery(), origin)
+ resultRows, err := origin.ReqInfo.Tx.NamedQuery(updateQuery(), origin)
if err != nil {
if pqErr, ok := err.(*pq.Error); ok {
err, eType := dbhelpers.ParsePQUniqueConstraintError(pqErr)
@@ -378,12 +364,6 @@ func (origin *TOOrigin) Update(db *sqlx.DB, user auth.CurrentUser) (error, tc.Ap
return tc.DBError, tc.SystemError
}
origin.LastUpdated = &lastUpdated
- err = tx.Commit()
- if err != nil {
- log.Errorln("Could not commit transaction: ", err)
- return tc.DBError, tc.SystemError
- }
- rollbackTransaction = false
return nil, tc.NoError
}
@@ -412,31 +392,14 @@ WHERE id=:id RETURNING last_updated`
//generic error message returned
//The insert sql returns the id and lastUpdated values of the newly inserted origin and have
//to be added to the struct
-func (origin *TOOrigin) Create(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
+func (origin *TOOrigin) Create() (error, tc.ApiErrorType) {
// TODO: enhance tenancy framework to handle this in isTenantAuthorized()
- err, errType := checkTenancy(origin.TenantID, origin.DeliveryServiceID, db, user)
+ err, errType := checkTenancy(origin.TenantID, origin.DeliveryServiceID, origin.ReqInfo.Tx, origin.ReqInfo.User)
if err != nil {
return err, errType
}
- 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)
- return tc.DBError, tc.SystemError
- }
-
- resultRows, err := tx.NamedQuery(insertQuery(), origin)
+ resultRows, err := origin.ReqInfo.Tx.NamedQuery(insertQuery(), origin)
if err != nil {
if pqErr, ok := err.(*pq.Error); ok {
err, eType := dbhelpers.ParsePQUniqueConstraintError(pqErr)
@@ -472,12 +435,7 @@ func (origin *TOOrigin) Create(db *sqlx.DB, user auth.CurrentUser) (error, tc.Ap
}
origin.SetKeys(map[string]interface{}{"id": id})
origin.LastUpdated = &lastUpdated
- err = tx.Commit()
- if err != nil {
- log.Errorln("Could not commit transaction: ", err)
- return tc.DBError, tc.SystemError
- }
- rollbackTransaction = false
+
return nil, tc.NoError
}
@@ -510,27 +468,10 @@ tenant) VALUES (
//The Origin implementation of the Deleter interface
//all implementations of Deleter should use transactions and return the proper errorType
-func (origin *TOOrigin) Delete(db *sqlx.DB, user auth.CurrentUser) (error, tc.ApiErrorType) {
- 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)
- return tc.DBError, tc.SystemError
- }
-
+func (origin *TOOrigin) Delete() (error, tc.ApiErrorType) {
isPrimary := false
q := `SELECT is_primary FROM origin WHERE id = $1`
- if err := tx.QueryRow(q, *origin.ID).Scan(&isPrimary); err != nil {
+ if err := origin.ReqInfo.Tx.QueryRow(q, *origin.ID).Scan(&isPrimary); err != nil {
log.Errorf("deleting origin %d, received error selecting is_primary: %v", *origin.ID, err)
return tc.DBError, tc.SystemError
}
@@ -539,7 +480,7 @@ func (origin *TOOrigin) Delete(db *sqlx.DB, user auth.CurrentUser) (error, tc.Ap
}
log.Debugf("about to run exec query: %s with origin: %++v", deleteQuery(), origin)
- result, err := tx.NamedExec(deleteQuery(), origin)
+ result, err := origin.ReqInfo.Tx.NamedExec(deleteQuery(), origin)
if err != nil {
log.Errorf("received error: %++v from delete execution", err)
return tc.DBError, tc.SystemError
@@ -555,12 +496,7 @@ func (origin *TOOrigin) Delete(db *sqlx.DB, user auth.CurrentUser) (error, tc.Ap
return fmt.Errorf("this delete affected too many rows: %d", rowsAffected), tc.SystemError
}
}
- err = tx.Commit()
- if err != nil {
- log.Errorln("Could not commit transaction: ", err)
- return tc.DBError, tc.SystemError
- }
- rollbackTransaction = false
+
return nil, tc.NoError
}
diff --git a/traffic_ops/traffic_ops_golang/origin/origins_test.go b/traffic_ops/traffic_ops_golang/origin/origins_test.go
index 7036171..ed5db33 100644
--- a/traffic_ops/traffic_ops_golang/origin/origins_test.go
+++ b/traffic_ops/traffic_ops_golang/origin/origins_test.go
@@ -113,10 +113,11 @@ func TestReadOrigins(t *testing.T) {
to.TenantID,
)
}
+ mock.ExpectBegin()
mock.ExpectQuery("SELECT").WillReturnRows(rows)
v := map[string]string{}
- origins, errs, errType := getOrigins(v, db, auth.PrivLevelAdmin)
+ origins, errs, errType := getOrigins(v, db.MustBegin(), auth.PrivLevelAdmin)
log.Debugln("%v-->", origins)
if len(errs) > 0 {
t.Errorf("getOrigins expected: no errors, actual: %v with error type: %s", errs, errType.String())
@@ -175,13 +176,13 @@ func TestValidate(t *testing.T) {
const ip6Err = `'ip6Address' must be a valid IPv6 address`
// verify that non-null fields are invalid
- c := TOOrigin{ID: nil,
+ c := TOOrigin{Origin: v13.Origin{ID: nil,
Name: nil,
DeliveryServiceID: nil,
FQDN: nil,
Protocol: nil,
- }
- errs := test.SortErrors(c.Validate(nil))
+ }}
+ errs := test.SortErrors(c.Validate())
expectedErrs := []error{
errors.New(`'deliveryServiceId' is required`),
@@ -203,7 +204,7 @@ func TestValidate(t *testing.T) {
port := 65535
pro := "http"
lu := tc.TimeNoMod{Time: time.Now()}
- c = TOOrigin{ID: &id,
+ c = TOOrigin{Origin:v13.Origin{ID: &id,
Name: &nm,
DeliveryServiceID: &id,
FQDN: &fqdn,
@@ -212,9 +213,9 @@ func TestValidate(t *testing.T) {
Port: &port,
Protocol: &pro,
LastUpdated: &lu,
- }
+ }}
expectedErrs = []error{}
- errs = c.Validate(nil)
+ errs = c.Validate()
if !reflect.DeepEqual(expectedErrs, errs) {
t.Errorf("expected %s, got %s", expectedErrs, errs)
}
@@ -319,7 +320,7 @@ func TestValidate(t *testing.T) {
c.IP6Address = &tc.Str
value = tc.Str
}
- errs = test.SortErrors(c.Validate(nil))
+ errs = test.SortErrors(c.Validate())
if !reflect.DeepEqual(tc.ExpectedErrors, errs) {
t.Errorf("given: '%v', expected %s, got %s", value, tc.ExpectedErrors, errs)
}
diff --git a/traffic_ops/traffic_ops_golang/routes.go b/traffic_ops/traffic_ops_golang/routes.go
index 67fe91c..ed93d74 100644
--- a/traffic_ops/traffic_ops_golang/routes.go
+++ b/traffic_ops/traffic_ops_golang/routes.go
@@ -36,16 +36,16 @@ import (
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/cachegroup"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/cdn"
- //"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/coordinate"
+ "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/coordinate"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/crconfig"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/deliveryservice"
dsrequest "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/deliveryservice/request"
- //"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/deliveryservice/request/comment"
+ "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/deliveryservice/request/comment"
dsserver "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/deliveryservice/servers"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/deliveryservicesregexes"
- //"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/division"
+ "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/division"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/hwinfo"
- //"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/origin"
+ "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/origin"
//"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/parameter"
//"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/physlocation"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/ping"
@@ -93,11 +93,11 @@ func Routes(d ServerData) ([]Route, []RawRoute, http.Handler, error) {
//CacheGroup: CRUD
{1.1, http.MethodGet, `cachegroups/trimmed/?(\.json)?$`, cachegroup.TrimmedHandler(d.DB.DB), auth.PrivLevelReadOnly, Authenticated, nil},
- {1.1, http.MethodGet, `cachegroups/?(\.json)?$`, api.ReadHandler(cachegroup.GetV11TypeSingleton()), auth.PrivLevelReadOnly, Authenticated, nil},
- {1.1, http.MethodGet, `cachegroups/{id}$`, api.ReadHandler(cachegroup.GetV11TypeSingleton()), auth.PrivLevelReadOnly, Authenticated, nil},
- {1.1, http.MethodPut, `cachegroups/{id}$`, api.UpdateHandler(cachegroup.GetV11TypeSingleton()), auth.PrivLevelOperations, Authenticated, nil},
- {1.1, http.MethodPost, `cachegroups/?$`, api.CreateHandler(cachegroup.GetV11TypeSingleton()), auth.PrivLevelOperations, Authenticated, nil},
- {1.1, http.MethodDelete, `cachegroups/{id}$`, api.DeleteHandler(cachegroup.GetV11TypeSingleton()), auth.PrivLevelOperations, Authenticated, nil},
+ {1.1, http.MethodGet, `cachegroups/?(\.json)?$`, api.ReadHandler(cachegroup.GetTypeSingleton()), auth.PrivLevelReadOnly, Authenticated, nil},
+ {1.1, http.MethodGet, `cachegroups/{id}$`, api.ReadHandler(cachegroup.GetTypeSingleton()), auth.PrivLevelReadOnly, Authenticated, nil},
+ {1.1, http.MethodPut, `cachegroups/{id}$`, api.UpdateHandler(cachegroup.GetTypeSingleton()), auth.PrivLevelOperations, Authenticated, nil},
+ {1.1, http.MethodPost, `cachegroups/?$`, api.CreateHandler(cachegroup.GetTypeSingleton()), auth.PrivLevelOperations, Authenticated, nil},
+ {1.1, http.MethodDelete, `cachegroups/{id}$`, api.DeleteHandler(cachegroup.GetTypeSingleton()), auth.PrivLevelOperations, Authenticated, nil},
{1.1, http.MethodPost, `cachegroups/{id}/queue_update$`, cachegroup.QueueUpdates(d.DB.DB), auth.PrivLevelOperations, Authenticated, nil},
@@ -125,12 +125,12 @@ func Routes(d ServerData) ([]Route, []RawRoute, http.Handler, error) {
{1.1, http.MethodGet, `cdns/{name}/configs/monitoring(\.json)?$`, monitoringHandler(d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
//Division: CRUD
- //{1.1, http.MethodGet, `divisions/?(\.json)?$`, api.ReadHandler(division.GetRefType(), d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
- //{1.1, http.MethodGet, `divisions/{id}$`, api.ReadHandler(division.GetRefType(), d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
- //{1.1, http.MethodPut, `divisions/{id}$`, api.UpdateHandler(division.GetRefType(), d.DB), auth.PrivLevelOperations, Authenticated, nil},
- //{1.1, http.MethodPost, `divisions/?$`, api.CreateHandler(division.GetRefType(), d.DB), auth.PrivLevelOperations, Authenticated, nil},
- //{1.1, http.MethodDelete, `divisions/{id}$`, api.DeleteHandler(division.GetRefType(), d.DB), auth.PrivLevelOperations, Authenticated, nil},
- //{1.1, http.MethodGet, `divisions/name/{name}/?(\.json)?$`, api.ReadHandler(division.GetRefType(), d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
+ {1.1, http.MethodGet, `divisions/?(\.json)?$`, api.ReadHandler(division.GetTypeSingleton()), auth.PrivLevelReadOnly, Authenticated, nil},
+ {1.1, http.MethodGet, `divisions/{id}$`, api.ReadHandler(division.GetTypeSingleton()), auth.PrivLevelReadOnly, Authenticated, nil},
+ {1.1, http.MethodPut, `divisions/{id}$`, api.UpdateHandler(division.GetTypeSingleton()), auth.PrivLevelOperations, Authenticated, nil},
+ {1.1, http.MethodPost, `divisions/?$`, api.CreateHandler(division.GetTypeSingleton()), auth.PrivLevelOperations, Authenticated, nil},
+ {1.1, http.MethodDelete, `divisions/{id}$`, api.DeleteHandler(division.GetTypeSingleton()), auth.PrivLevelOperations, Authenticated, nil},
+ {1.1, http.MethodGet, `divisions/name/{name}/?(\.json)?$`, api.ReadHandler(division.GetTypeSingleton()), auth.PrivLevelReadOnly, Authenticated, nil},
//HWInfo
{1.1, http.MethodGet, `hwinfo-wip/?(\.json)?$`, hwinfo.HWInfoHandler(d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
@@ -220,11 +220,11 @@ func Routes(d ServerData) ([]Route, []RawRoute, http.Handler, error) {
{1.3, http.MethodGet, `about/?(\.json)?$`, about.Handler(), auth.PrivLevelReadOnly, Authenticated, nil},
//Coordinates
- //{1.3, http.MethodGet, `coordinates/?(\.json)?$`, api.ReadHandler(coordinate.GetRefType(), d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
- //{1.3, http.MethodGet, `coordinates/?$`, api.ReadHandler(coordinate.GetRefType(), d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
- //{1.3, http.MethodPut, `coordinates/?$`, api.UpdateHandler(coordinate.GetRefType(), d.DB), auth.PrivLevelOperations, Authenticated, nil},
- //{1.3, http.MethodPost, `coordinates/?$`, api.CreateHandler(coordinate.GetRefType(), d.DB), auth.PrivLevelOperations, Authenticated, nil},
- //{1.3, http.MethodDelete, `coordinates/?$`, api.DeleteHandler(coordinate.GetRefType(), d.DB), auth.PrivLevelOperations, Authenticated, nil},
+ {1.3, http.MethodGet, `coordinates/?(\.json)?$`, api.ReadHandler(coordinate.GetTypeSingleton()), auth.PrivLevelReadOnly, Authenticated, nil},
+ {1.3, http.MethodGet, `coordinates/?$`, api.ReadHandler(coordinate.GetTypeSingleton()), auth.PrivLevelReadOnly, Authenticated, nil},
+ {1.3, http.MethodPut, `coordinates/?$`, api.UpdateHandler(coordinate.GetTypeSingleton()), auth.PrivLevelOperations, Authenticated, nil},
+ {1.3, http.MethodPost, `coordinates/?$`, api.CreateHandler(coordinate.GetTypeSingleton()), auth.PrivLevelOperations, Authenticated, nil},
+ {1.3, http.MethodDelete, `coordinates/?$`, api.DeleteHandler(coordinate.GetTypeSingleton()), auth.PrivLevelOperations, Authenticated, nil},
//Servers
// explicitly passed to legacy system until fully implemented. Auth handled by legacy system.
@@ -261,10 +261,10 @@ func Routes(d ServerData) ([]Route, []RawRoute, http.Handler, error) {
{1.3, http.MethodPut, `deliveryservice_requests/{id}/status$`, api.UpdateHandler(dsrequest.GetStatusTypeSingleton()), auth.PrivLevelPortal, Authenticated, nil},
//Delivery service request comment: CRUD
- //{1.3, http.MethodGet, `deliveryservice_request_comments/?(\.json)?$`, api.ReadHandler(comment.GetRefType(), d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
- //{1.3, http.MethodPut, `deliveryservice_request_comments/?$`, api.UpdateHandler(comment.GetRefType(), d.DB), auth.PrivLevelPortal, Authenticated, nil},
- //{1.3, http.MethodPost, `deliveryservice_request_comments/?$`, api.CreateHandler(comment.GetRefType(), d.DB), auth.PrivLevelPortal, Authenticated, nil},
- //{1.3, http.MethodDelete, `deliveryservice_request_comments/?$`, api.DeleteHandler(comment.GetRefType(), d.DB), auth.PrivLevelPortal, Authenticated, nil},
+ {1.3, http.MethodGet, `deliveryservice_request_comments/?(\.json)?$`, api.ReadHandler(comment.GetTypeSingleton()), auth.PrivLevelReadOnly, Authenticated, nil},
+ {1.3, http.MethodPut, `deliveryservice_request_comments/?$`, api.UpdateHandler(comment.GetTypeSingleton()), auth.PrivLevelPortal, Authenticated, nil},
+ {1.3, http.MethodPost, `deliveryservice_request_comments/?$`, api.CreateHandler(comment.GetTypeSingleton()), auth.PrivLevelPortal, Authenticated, nil},
+ {1.3, http.MethodDelete, `deliveryservice_request_comments/?$`, api.DeleteHandler(comment.GetTypeSingleton()), auth.PrivLevelPortal, Authenticated, nil},
//Delivery service uri signing keys: CRUD
{1.3, http.MethodGet, `deliveryservices/{xmlID}/urisignkeys$`, getURIsignkeysHandler, auth.PrivLevelAdmin, Authenticated, nil},
@@ -273,11 +273,11 @@ func Routes(d ServerData) ([]Route, []RawRoute, http.Handler, error) {
{1.3, http.MethodDelete, `deliveryservices/{xmlID}/urisignkeys$`, removeDeliveryServiceURIKeysHandler, auth.PrivLevelAdmin, Authenticated, nil},
//Origins
- //{1.3, http.MethodGet, `origins/?(\.json)?$`, api.ReadHandler(origin.GetRefType(), d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
- //{1.3, http.MethodGet, `origins/?$`, api.ReadHandler(origin.GetRefType(), d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
- //{1.3, http.MethodPut, `origins/?$`, api.UpdateHandler(origin.GetRefType(), d.DB), auth.PrivLevelOperations, Authenticated, nil},
- //{1.3, http.MethodPost, `origins/?$`, api.CreateHandler(origin.GetRefType(), d.DB), auth.PrivLevelOperations, Authenticated, nil},
- //{1.3, http.MethodDelete, `origins/?$`, api.DeleteHandler(origin.GetRefType(), d.DB), auth.PrivLevelOperations, Authenticated, nil},
+ {1.3, http.MethodGet, `origins/?(\.json)?$`, api.ReadHandler(origin.GetTypeSingleton()), auth.PrivLevelReadOnly, Authenticated, nil},
+ {1.3, http.MethodGet, `origins/?$`, api.ReadHandler(origin.GetTypeSingleton()), auth.PrivLevelReadOnly, Authenticated, nil},
+ {1.3, http.MethodPut, `origins/?$`, api.UpdateHandler(origin.GetTypeSingleton()), auth.PrivLevelOperations, Authenticated, nil},
+ {1.3, http.MethodPost, `origins/?$`, api.CreateHandler(origin.GetTypeSingleton()), auth.PrivLevelOperations, Authenticated, nil},
+ {1.3, http.MethodDelete, `origins/?$`, api.DeleteHandler(origin.GetTypeSingleton()), auth.PrivLevelOperations, Authenticated, nil},
//Roles
//{1.3, http.MethodGet, `roles/?(\.json)?$`, api.ReadHandler(role.GetRefType(), d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
diff --git a/traffic_ops/traffic_ops_golang/tenant/tenancy.go b/traffic_ops/traffic_ops_golang/tenant/tenancy.go
index abd3209..fad4cdc 100644
--- a/traffic_ops/traffic_ops_golang/tenant/tenancy.go
+++ b/traffic_ops/traffic_ops_golang/tenant/tenancy.go
@@ -49,7 +49,7 @@ func (dsInfo DeliveryServiceTenantInfo) IsTenantAuthorized(user *auth.CurrentUse
if dsInfo.TenantID == nil {
return false, errors.New("TenantID is nil")
}
- return IsResourceAuthorizedToUserTx(*dsInfo.TenantID, *user, tx)
+ return IsResourceAuthorizedToUserTx(*dsInfo.TenantID, user, tx)
}
// returns tenant information for a deliveryservice
@@ -233,7 +233,7 @@ func IsTenancyEnabledTx(tx *sql.Tx) (bool, error) {
// returns a boolean value describing if the user has access to the provided resource tenant id and an error
// if use_tenancy is set to false (0 in the db) this method will return true allowing access.
-func IsResourceAuthorizedToUser(resourceTenantID int, user auth.CurrentUser, db *sqlx.DB) (bool, error) {
+func IsResourceAuthorizedToUser(resourceTenantID int, user *auth.CurrentUser, db *sqlx.DB) (bool, error) {
// $1 is the user tenant ID and $2 is the resource tenant ID
query := `WITH RECURSIVE q AS (SELECT id, active FROM tenant WHERE id = $1
UNION SELECT t.id, t.active FROM TENANT t JOIN q ON q.id = t.parent_id),
@@ -264,7 +264,7 @@ func IsResourceAuthorizedToUser(resourceTenantID int, user auth.CurrentUser, db
// returns a boolean value describing if the user has access to the provided resource tenant id and an error
// if use_tenancy is set to false (0 in the db) this method will return true allowing access.
-func IsResourceAuthorizedToUserTx(resourceTenantID int, user auth.CurrentUser, tx *sql.Tx) (bool, error) {
+func IsResourceAuthorizedToUserTx(resourceTenantID int, user *auth.CurrentUser, tx *sql.Tx) (bool, error) {
// $1 is the user tenant ID and $2 is the resource tenant ID
query := `WITH RECURSIVE q AS (SELECT id, active FROM tenant WHERE id = $1
UNION SELECT t.id, t.active FROM TENANT t JOIN q ON q.id = t.parent_id),